oficina / memoria Public

Clone
git clone https://amadan.net/oficina/memoria

Plain git — no account needed to clone.

Download

Download this file

1package memoria
2
3import (
4 "context"
5 "encoding/json"
6 "fmt"
7 "net/http"
8 "net/http/httptest"
9 "strings"
10 "testing"
11 "time"
12
13 "amadan.net/oficina/suite"
14
15 "amadan.net/oficina/memoria/internal/memoria/sibling"
16)
17
18// feedServer is a sibling that serves a scripted sequence of S1 pages and
19// an S3 body per item.
20type feedServer struct {
21 t *testing.T
22 // pages is consulted by cursor: the empty string is the first page.
23 pages map[string]suite.Feed
24 bodies map[string]string
25 failS1 map[string]bool
26 failS3 map[string]bool
27 // brokeS3 is a 5xx rather than a 404: an ERROR, where failS3 is a
28 // refusal. The two must not be confused — a 404 is counted and moves
29 // on, a 500 stops the page — and no fixture distinguished them until
30 // a mutation showed the cursor could advance mid-page unnoticed.
31 brokeS3 map[string]bool
32 // forbidS3 answers 403, which is a CONTRACT BREACH and a third thing
33 // again: the sibling is telling callers which ids exist.
34 forbidS3 map[string]bool
35 // reset answers CURSOR_RESET to these cursors (suite doctrine §6.6).
36 reset map[string]bool
37 s1Calls int
38 s3Calls int
39}
40
41func (f *feedServer) start(t *testing.T) (sibling.Sibling, *sibling.Client) {
42 t.Helper()
43 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
44 switch {
45 case r.URL.Path == suite.RouteS1:
46 f.s1Calls++
47 cur := r.URL.Query().Get("cursor")
48 if f.failS1[cur] {
49 w.WriteHeader(http.StatusInternalServerError)
50 // A well-formed empty feed with a bad status: the shape
51 // that would authorise a purge if the status were ignored.
52 _, _ = w.Write([]byte(`{"cursor":"","rows":[]}`))
53 return
54 }
55 if f.reset[cur] {
56 w.WriteHeader(suite.CursorResetStatus)
57 _, _ = w.Write([]byte(suite.CursorResetBody))
58 return
59 }
60 page, ok := f.pages[cur]
61 if !ok {
62 f.t.Errorf("sibling asked for an unscripted cursor %q", cur)
63 w.WriteHeader(http.StatusInternalServerError)
64 return
65 }
66 _ = json.NewEncoder(w).Encode(page)
67 case strings.HasPrefix(r.URL.Path, suite.RouteS3+"/"):
68 f.s3Calls++
69 id := strings.TrimPrefix(r.URL.Path, suite.RouteS3+"/")
70 if f.forbidS3[id] {
71 w.WriteHeader(http.StatusForbidden)
72 return
73 }
74 if f.brokeS3[id] {
75 w.WriteHeader(http.StatusInternalServerError)
76 return
77 }
78 if f.failS3[id] {
79 w.WriteHeader(http.StatusNotFound)
80 return
81 }
82 body, ok := f.bodies[id]
83 if !ok {
84 w.WriteHeader(http.StatusNotFound)
85 return
86 }
87 _, _ = w.Write([]byte(body))
88 default:
89 f.t.Errorf("sibling asked for %s %s", r.Method, r.URL.Path)
90 w.WriteHeader(http.StatusNotFound)
91 }
92 }))
93 t.Cleanup(srv.Close)
94 s := sibling.Sibling{Name: "Docs", BaseURL: srv.URL, Token: "consumer-token"}
95 return s, sibling.NewForTest()
96}
97
98func row(id string, rev int64, gone bool) suite.FeedRow {
99 return suite.FeedRow{ItemID: id, Revision: rev, Gone: gone, TouchedAt: time.Unix(0, 0).UTC()}
100}
101
102// Gate 7 where it actually bites: **a failed poll advances nothing and
103// deletes nothing.**
104//
105// The clients already refuse to turn a failure into an empty feed. This is
106// the layer above, where the consequences live: a cursor moved past a page
107// nobody applied skips changes the sibling will never offer again, and it
108// does so silently, because the sibling has no way to know its consumer
109// stopped listening.
110//
111// TWO-SIDED, and the first subtest is what makes the rest mean anything: a
112// Poll that never stores would satisfy every "nothing was deleted"
113// assertion below.
114//
115// MUTATION-TESTED 2026-09-07, each verified red then reverted:
116//
117// setCursor called before the rows are applied
118// -> the mid-page-failure case red (the cursor moved)
119// the S1 error swallowed and the loop continued
120// -> the failed-poll case red
121// a `gone` row applied by deleting on a failed S3 instead
122// -> the missing case red (the document went)
123// Missing counted as Deleted
124// -> the missing case red
125// the empty final page treated as More
126// -> the completion case red
127func TestAFailedPollAdvancesNothing(t *testing.T) {
128 ctx := context.Background()
129
130 t.Run("a good poll stores the sibling's documents", func(t *testing.T) {
131 f := &feedServer{
132 t: t,
133 pages: map[string]suite.Feed{
134 // Revisions 7 and 9, not 1: the sibling issues these and
135 // memoria stores what it was given. With a fixture at
136 // revision 1, hard-coding `SiblingRevision: 1` passes —
137 // a mutation did.
138 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 7, false), row("b", 9, false)}},
139 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
140 },
141 bodies: map[string]string{
142 "a": "The quarterly planning process runs in March.",
143 "b": "Expenses are filed monthly.",
144 },
145 }
146 sib, client := f.start(t)
147 s := storeForTest(t)
148
149 res, err := s.Poll(ctx, client, sib)
150 if err != nil {
151 t.Fatalf("poll: %v", err)
152 }
153 if res.Stored != 2 || res.Deleted != 0 || res.Missing != 0 || res.More {
154 t.Errorf("result = %+v, want 2 stored and nothing else", res)
155 }
156 // Stored WITH their coordinates, or the ruling has nothing to ask
157 // about and every one of them withholds forever.
158 assertHeld(t, s, "Docs", "a", 7)
159 assertHeld(t, s, "Docs", "b", 9)
160 })
161
162 t.Run("a row failing mid-page leaves the cursor before that page", func(t *testing.T) {
163 // **This is the file's central claim, and nothing reached it.**
164 // The other failure cases fail at the S1 fetch, where no row has
165 // been applied yet and storing the cursor first is indisitinguishable
166 // from storing it last. A mutation that moved setCursor above the
167 // apply loop passed every one of them.
168 //
169 // Here the page is fetched fine and a row inside it fails. With
170 // the cursor stored first, page one is marked done while document
171 // "b" was never stored — and the sibling will not mention it
172 // again, because from its side the consumer read that page.
173 f := &feedServer{
174 t: t,
175 pages: map[string]suite.Feed{
176 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false), row("b", 1, false)}},
177 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
178 },
179 bodies: map[string]string{"a": "Applied.", "b": "Never fetched."},
180 brokeS3: map[string]bool{"b": true},
181 }
182 sib, client := f.start(t)
183 s := storeForTest(t)
184
185 if _, err := s.Poll(ctx, client, sib); err == nil {
186 t.Fatal("a 500 from S3 mid-page came back as a completed poll")
187 }
188 if got := cursorOf(t, s, "Docs"); got != "" {
189 t.Errorf("cursor = %q, want empty: a page with an unapplied row in "+
190 "it must not be marked read, or the sibling never offers it "+
191 "again and the document is lost silently", got)
192 }
193 // Row "a" was applied before the failure and stands — re-applying
194 // it next time is the cheap failure, and the point of the
195 // assertion is that the page will be re-offered at all.
196 assertHeld(t, s, "Docs", "a", 1)
197 if heldCount(t, s, "Docs") != 1 {
198 t.Errorf("%d documents held; the row that failed must not be "+
199 "stored", heldCount(t, s, "Docs"))
200 }
201
202 // Let it work, and the whole page arrives.
203 f.brokeS3 = nil
204 if _, err := s.Poll(ctx, client, sib); err != nil {
205 t.Fatalf("second poll: %v", err)
206 }
207 assertHeld(t, s, "Docs", "b", 1)
208 })
209
210 t.Run("a page carrying a row that names nothing is refused whole", func(t *testing.T) {
211 // A row with no item id can neither be stored nor deleted, and
212 // passing over it would advance the cursor past a change memoria
213 // never applied.
214 //
215 // **The refusal is the MODULE's**, and this test says so on
216 // purpose. memoria had its own check; it could not fail, because
217 // DecodeS1 rejects the page before applyRow sees a row — a
218 // mutation deleting memoria's guard left the suite green. So the
219 // guard is gone and this asserts the thing memoria actually
220 // depends on. It goes red if the module ever softens, which is
221 // the day memoria owes a check of its own.
222 f := &feedServer{
223 t: t,
224 pages: map[string]suite.Feed{
225 "": {Cursor: "c1", Rows: []suite.FeedRow{row("", 1, false)}},
226 // A clean second page, so SKIPPING the malformed row would
227 // produce a completely successful poll. Without it the
228 // poll fails anyway — on an unscripted cursor — and the
229 // assertion passes for the wrong reason.
230 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
231 },
232 bodies: map[string]string{},
233 }
234 sib, client := f.start(t)
235 s := storeForTest(t)
236
237 if _, err := s.Poll(ctx, client, sib); err == nil {
238 t.Fatal("a feed row with no item id was passed over silently")
239 }
240 if got := cursorOf(t, s, "Docs"); got != "" {
241 t.Errorf("cursor = %q, want empty: a page memoria could not apply "+
242 "whole must not be marked read", got)
243 }
244 })
245
246 t.Run("a failed page leaves the cursor where it was", func(t *testing.T) {
247 f := &feedServer{
248 t: t,
249 pages: map[string]suite.Feed{
250 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false)}},
251 "c1": {Cursor: "c2", Rows: []suite.FeedRow{row("b", 1, false)}},
252 },
253 bodies: map[string]string{"a": "First document.", "b": "Second document."},
254 failS1: map[string]bool{"c1": true},
255 }
256 sib, client := f.start(t)
257 s := storeForTest(t)
258
259 if _, err := s.Poll(ctx, client, sib); err == nil {
260 t.Fatal("a 500 from S1 came back as a completed poll")
261 }
262 // Page one was applied and stands.
263 assertHeld(t, s, "Docs", "a", 1)
264 // And the position is page one's, so page two is offered again
265 // rather than skipped forever.
266 if got := cursorOf(t, s, "Docs"); got != "c1" {
267 t.Errorf("cursor = %q, want c1: a poll that failed on the second "+
268 "page must leave the position at the first", got)
269 }
270
271 // Now let it succeed, and the page it could not read arrives.
272 f.failS1 = nil
273 f.pages["c2"] = suite.Feed{Cursor: "c2", Rows: []suite.FeedRow{}}
274 if _, err := s.Poll(ctx, client, sib); err != nil {
275 t.Fatalf("second poll: %v", err)
276 }
277 assertHeld(t, s, "Docs", "b", 1)
278 })
279
280 t.Run("a listed item the sibling will not serve is counted, not deleted", func(t *testing.T) {
281 f := &feedServer{
282 t: t,
283 pages: map[string]suite.Feed{
284 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false)}},
285 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
286 },
287 bodies: map[string]string{"a": "Held already."},
288 }
289 sib, client := f.start(t)
290 s := storeForTest(t)
291 if _, err := s.Poll(ctx, client, sib); err != nil {
292 t.Fatalf("first poll: %v", err)
293 }
294 assertHeld(t, s, "Docs", "a", 1)
295
296 // The sibling now lists it at a new revision and refuses to serve
297 // it. §4.2 makes that 404 cover both "gone" and "not
298 // team-visible", so memoria cannot tell which — and deleting on it
299 // would let a visibility change erase history the sibling still
300 // has.
301 f.pages[""] = suite.Feed{Cursor: "c2", Rows: []suite.FeedRow{row("a", 2, false)}}
302 f.pages["c2"] = suite.Feed{Cursor: "c2", Rows: []suite.FeedRow{}}
303 f.failS3 = map[string]bool{"a": true}
304
305 // The store under test is already at cursor "c1", so it is page
306 // "c1" that must now carry the re-announced row — not page "".
307 // Both are set: the first line above is what a sibling starting
308 // fresh would serve, and this is what ours will actually ask for.
309 f.pages["c1"] = suite.Feed{Cursor: "c2", Rows: []suite.FeedRow{row("a", 2, false)}}
310 res, err := s.Poll(ctx, client, sib)
311 if err != nil {
312 t.Fatalf("second poll: %v", err)
313 }
314 if res.Missing != 1 {
315 t.Errorf("result = %+v, want 1 missing", res)
316 }
317 if res.Deleted != 0 {
318 t.Errorf("a 404 on S3 deleted %d documents: an item that is not "+
319 "team-visible is indistinguishable from one that is gone, and "+
320 "acting on that erases history the sibling still has", res.Deleted)
321 }
322 // Still held, at the revision memoria could actually fetch.
323 assertHeld(t, s, "Docs", "a", 1)
324 })
325
326 t.Run("a gone row deletes, so the case above is not vacuous", func(t *testing.T) {
327 f := &feedServer{
328 t: t,
329 pages: map[string]suite.Feed{
330 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false)}},
331 "c1": {Cursor: "c2", Rows: []suite.FeedRow{row("a", 2, true)}},
332 "c2": {Cursor: "c2", Rows: []suite.FeedRow{}},
333 },
334 bodies: map[string]string{"a": "Here for now."},
335 }
336 sib, client := f.start(t)
337 s := storeForTest(t)
338 if _, err := s.Poll(ctx, client, sib); err != nil {
339 t.Fatalf("poll: %v", err)
340 }
341 // One poll walks both pages: stored, then tombstoned.
342 if held := heldCount(t, s, "Docs"); held != 0 {
343 t.Errorf("%d documents survived a tombstone", held)
344 }
345 })
346}
347
348// A sibling whose cursor never advances must not loop forever, and the
349// poll must say it did not finish.
350//
351// "Stopped looking" and "there is no more" are the same value to a caller
352// that only checks the error, which is why More exists.
353//
354// MUTATION-TESTED 2026-09-07: drop the maxFeedPages bound and the test
355// hangs rather than failing — which is itself the finding, so the bound is
356// asserted by the call count as well. Reverted.
357func TestAFeedThatNeverAdvancesStopsAndSaysSo(t *testing.T) {
358 f := &feedServer{
359 t: t,
360 // A page that hands back the cursor it was asked with. The module
361 // will not serve an empty cursor at all, so this — not a blank —
362 // is what "the feed did not advance" looks like on the wire.
363 pages: map[string]suite.Feed{
364 "": {Cursor: "same", Rows: []suite.FeedRow{row("a", 1, false)}},
365 "same": {Cursor: "same", Rows: []suite.FeedRow{row("a", 1, false)}},
366 },
367 bodies: map[string]string{"a": "Going nowhere."},
368 }
369 sib, client := f.start(t)
370 s := storeForTest(t)
371
372 res, err := s.Poll(context.Background(), client, sib)
373 if err != nil {
374 t.Fatalf("poll: %v", err)
375 }
376 if !res.More {
377 t.Error("a feed that never advanced its cursor reported a complete " +
378 "poll; the corpus would be called current")
379 }
380 // Two: the first page advanced the cursor, the second handed back the
381 // same one and the poll stopped. Bounded, not walked to maxFeedPages.
382 if f.s1Calls != 2 {
383 t.Errorf("%d S1 calls for a feed that stops advancing, want 2: a feed "+
384 "repeating itself must not be walked to the page bound", f.s1Calls)
385 }
386}
387
388func assertHeld(t *testing.T, s *Store, app, itemID string, revision int64) {
389 t.Helper()
390 external, err := s.externalID(itemID)
391 if err != nil {
392 t.Fatalf("externalID: %v", err)
393 }
394 var d Document
395 if err := s.db.G.Where("source = ? AND external_id = ?", app, external).First(&d).Error; err != nil {
396 t.Fatalf("%s/%s not held: %v", app, itemID, err)
397 }
398 if d.SiblingRevision != revision {
399 t.Errorf("%s/%s held at revision %d, want %d", app, itemID, d.SiblingRevision, revision)
400 }
401 if len(d.SiblingItemID) == 0 {
402 t.Errorf("%s/%s stored without its coordinate, so nothing can be "+
403 "asked about it and it withholds forever", app, itemID)
404 }
405}
406
407func heldCount(t *testing.T, s *Store, app string) int {
408 t.Helper()
409 var n int64
410 if err := s.db.G.Model(&Document{}).Where("source = ?", app).Count(&n).Error; err != nil {
411 t.Fatalf("count: %v", err)
412 }
413 return int(n)
414}
415
416func cursorOf(t *testing.T, s *Store, app string) string {
417 t.Helper()
418 got, err := s.cursor(context.Background(), app)
419 if err != nil {
420 t.Fatalf("cursor: %v", err)
421 }
422 return got
423}
424
425// The cursor is sealed at rest, and a cursor that will not open is an
426// error rather than an empty one.
427//
428// An empty cursor is not a degraded value: it is the instruction "start
429// from the beginning", which would re-announce the sibling's whole corpus.
430// Reading a corrupted row as that instruction is the plausible-empty-list
431// failure wearing its other face — a confident restart rather than a
432// confident absence.
433//
434// MUTATION-TESTED 2026-09-07: return ("", nil) when Open fails, and the
435// second half goes red. Reverted.
436func TestACursorIsSealedAndACorruptOneIsAnError(t *testing.T) {
437 ctx := context.Background()
438 s := storeForTest(t)
439 if err := s.setCursor(ctx, "Docs", "opaque-cursor-value"); err != nil {
440 t.Fatalf("setCursor: %v", err)
441 }
442
443 var stored SiblingFeed
444 if err := s.db.G.Where("app = ?", "Docs").First(&stored).Error; err != nil {
445 t.Fatalf("read back: %v", err)
446 }
447 // The presence assertion: it round-trips, so the absence check below
448 // is about sealing rather than about an empty column.
449 if got := cursorOf(t, s, "Docs"); got != "opaque-cursor-value" {
450 t.Fatalf("cursor round-tripped as %q", got)
451 }
452 if strings.Contains(string(stored.SealedCursor), "opaque-cursor-value") {
453 t.Error("the cursor is at rest in plaintext")
454 }
455
456 // Corrupt it. The row is present and unreadable, which must not read
457 // as "never polled".
458 if err := s.db.G.Model(&SiblingFeed{}).Where("id = ?", stored.ID).
459 Update("sealed_cursor", []byte("not a sealed value at all")).Error; err != nil {
460 t.Fatalf("corrupt: %v", err)
461 }
462 if got, err := s.cursor(ctx, "Docs"); err == nil {
463 t.Errorf("an unreadable cursor came back as %q with no error: that is "+
464 "the instruction to re-announce the sibling's entire corpus", got)
465 }
466}
467
468// PolledAt says when the corpus was last known current, so a poll that
469// failed must not move it. §8.1: a failed or stale S1 makes the page state
470// what it is current as of, rather than implying freshness.
471//
472// MUTATION-TESTED 2026-09-07: set polled_at before walking the pages and
473// this goes red. Reverted.
474func TestAFailedPollDoesNotClaimFreshness(t *testing.T) {
475 f := &feedServer{
476 t: t,
477 pages: map[string]suite.Feed{"": {Cursor: "c1", Rows: []suite.FeedRow{}}},
478 failS1: map[string]bool{"": true},
479 }
480 sib, client := f.start(t)
481 s := storeForTest(t)
482
483 if _, err := s.Poll(context.Background(), client, sib); err == nil {
484 t.Fatal("a failing S1 reported a completed poll")
485 }
486 var row SiblingFeed
487 err := s.db.G.Where("app = ?", "Docs").First(&row).Error
488 if err == nil && !row.PolledAt.IsZero() {
489 t.Errorf("a poll that never read a page recorded PolledAt=%v; the "+
490 "sources page would report the corpus current as of a moment "+
491 "nothing was read", row.PolledAt)
492 }
493 if err != nil && !strings.Contains(fmt.Sprint(err), "record not found") {
494 t.Fatalf("read back: %v", err)
495 }
496}
497
498// **An empty item is skipped, and the feed keeps moving.**
499//
500// This was the opposite: `AllowTitleOnly` was passed with no Title, so
501// Ingest refused with "neither a body nor a title", the row failed, the
502// cursor stayed, and every subsequent poll of that sibling failed on the
503// same row. One stub page in Docs and nothing from Docs was ever ingested
504// again — a permanent, silent halt with only "sibling poll failed" to show
505// for it. A review found it by putting a stub first in a page.
506//
507// TWO-SIDED: the real document after the stub must arrive, or "refuse
508// everything" satisfies the count.
509//
510// MUTATION-TESTED 2026-09-07, each verified red then reverted:
511//
512// restore AllowTitleOnly and drop the empty check
513// -> red: the poll errors and the real document is not held
514// skip the empty row without counting it
515// -> red on Empty
516// treat whitespace as a body
517// -> red: Ingest refuses " " the same way
518func TestAnEmptyItemIsSkippedNotWedged(t *testing.T) {
519 ctx := context.Background()
520 f := &feedServer{
521 t: t,
522 pages: map[string]suite.Feed{
523 "": {Cursor: "c1", Rows: []suite.FeedRow{
524 row("stub", 1, false),
525 row("blank", 1, false),
526 row("real", 1, false),
527 }},
528 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
529 },
530 bodies: map[string]string{
531 "stub": "",
532 "blank": " \n\t ",
533 "real": "The quarterly planning process runs in March.",
534 },
535 }
536 sib, client := f.start(t)
537 s := storeForTest(t)
538
539 res, err := s.Poll(ctx, client, sib)
540 if err != nil {
541 t.Fatalf("a stub page stopped the poll: %v", err)
542 }
543 if res.Empty != 2 {
544 t.Errorf("result = %+v, want 2 empty", res)
545 }
546 if res.Stored != 1 {
547 t.Errorf("result = %+v, want 1 stored", res)
548 }
549 // The document after the stubs arrived, which is the whole point.
550 assertHeld(t, s, "Docs", "real", 1)
551 if heldCount(t, s, "Docs") != 1 {
552 t.Errorf("%d documents held; an empty item has no passages to "+
553 "retrieve and must not become one", heldCount(t, s, "Docs"))
554 }
555 // And the feed moved on, so the next poll does not re-read this page.
556 if got := cursorOf(t, s, "Docs"); got != "c1" {
557 t.Errorf("cursor = %q, want c1", got)
558 }
559}
560
561// **A revision bump with an identical body must still be recorded.**
562//
563// The two revisions answer different questions. memoria's counts its own
564// edits; the sibling's is the token S2 is asked about, and a sibling
565// issues a new one for reasons memoria cannot see — a permissions change,
566// a metadata edit, a re-save that touched no bytes.
567//
568// Ingest's unchanged branch returned without touching it, and the failure
569// was permanent and invisible: the sibling announces revision 8 of a body
570// identical to 7, memoria keeps 7, and every query thereafter asks S2
571// about `(item, 7)`. The sibling answers STALE — correctly, it has moved
572// on — so the passage is withheld loudly on every page forever, and
573// re-polling cannot fix it because the body never changes. Found by a
574// review, 2026-09-07.
575//
576// MUTATION-TESTED 2026-09-07, each verified red then reverted:
577//
578// restore the bare `unchanged = true; return nil`
579// -> red, the row stays at 7
580// update sibling_revision but also bump Revision
581// -> red: memoria's own counter must not move for a body that did
582// not, or §5.2's provenance invalidates artefacts for nothing
583func TestARevisionBumpOnAnIdenticalBodyIsRecorded(t *testing.T) {
584 ctx := context.Background()
585 const body = "The quarterly planning process runs in March."
586 f := &feedServer{
587 t: t,
588 pages: map[string]suite.Feed{
589 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 7, false)}},
590 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
591 },
592 bodies: map[string]string{"a": body},
593 }
594 sib, client := f.start(t)
595 s := storeForTest(t)
596 if _, err := s.Poll(ctx, client, sib); err != nil {
597 t.Fatalf("first poll: %v", err)
598 }
599 assertHeld(t, s, "Docs", "a", 7)
600 before := documentOf(t, s, "Docs", "a")
601
602 // The sibling moves to 8. Same bytes.
603 f.pages["c1"] = suite.Feed{Cursor: "c2", Rows: []suite.FeedRow{row("a", 8, false)}}
604 f.pages["c2"] = suite.Feed{Cursor: "c2", Rows: []suite.FeedRow{}}
605 if _, err := s.Poll(ctx, client, sib); err != nil {
606 t.Fatalf("second poll: %v", err)
607 }
608
609 after := documentOf(t, s, "Docs", "a")
610 if after.SiblingRevision != 8 {
611 t.Errorf("held at sibling revision %d after the sibling announced 8: "+
612 "S2 is asked about %d, the sibling answers STALE, and the passage "+
613 "is withheld on every query forever — re-polling cannot fix it "+
614 "because the body never changes",
615 after.SiblingRevision, after.SiblingRevision)
616 }
617 if after.Revision != before.Revision {
618 t.Errorf("memoria's own revision moved from %d to %d for a body that "+
619 "did not change; §5.2 would invalidate every artefact built from "+
620 "it for nothing", before.Revision, after.Revision)
621 }
622}
623
624// PolledAt is a claim about COMPLETENESS, and only a drained feed may make
625// it.
626//
627// A position is "how far I got"; a timestamp is "and there was nothing
628// after it". These were written together, once per page, so a multi-page
629// catch-up that failed on page four — or stopped at the page bound with
630// more to come — left PolledAt at the moment of the last page it managed.
631// The sources page would then report the corpus current as of a time it
632// demonstrably was not. §8.1: *a failed or stale S1 states what the corpus
633// is current as of, rather than implying freshness.*
634//
635// **The presence half is the one that was missing.** The existing test
636// only ever failed on page one, so "PolledAt was not set" passed against a
637// Poll that never set it at all — and a mutation deleting the write
638// entirely stayed green. This asserts a good poll DOES set it first.
639//
640// MUTATION-TESTED 2026-09-07, each verified red then reverted:
641//
642// setCursor writes polled_at again
643// -> the second-page failure case red, and the More case red
644// the drained branch stops writing polled_at
645// -> the presence case red
646func TestPolledAtMeansTheFeedWasDrained(t *testing.T) {
647 ctx := context.Background()
648
649 t.Run("a completed poll records when", func(t *testing.T) {
650 f := &feedServer{
651 t: t,
652 pages: map[string]suite.Feed{
653 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false)}},
654 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
655 },
656 bodies: map[string]string{"a": "Held."},
657 }
658 sib, client := f.start(t)
659 s := storeForTest(t)
660 if _, err := s.Poll(ctx, client, sib); err != nil {
661 t.Fatalf("poll: %v", err)
662 }
663 if polledAt(t, s, "Docs").IsZero() {
664 t.Error("a poll that drained the feed recorded no time; the sources " +
665 "page has nothing to say the corpus is current as of")
666 }
667 })
668
669 t.Run("a poll failing on a later page claims nothing", func(t *testing.T) {
670 f := &feedServer{
671 t: t,
672 pages: map[string]suite.Feed{
673 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false)}},
674 "c1": {Cursor: "c2", Rows: []suite.FeedRow{row("b", 1, false)}},
675 },
676 bodies: map[string]string{"a": "First.", "b": "Second."},
677 failS1: map[string]bool{"c1": true},
678 }
679 sib, client := f.start(t)
680 s := storeForTest(t)
681 if _, err := s.Poll(ctx, client, sib); err == nil {
682 t.Fatal("a 500 on page two came back as a completed poll")
683 }
684 // Page one WAS applied and the cursor moved — so the row exists,
685 // and this is an assertion about the column rather than about the
686 // row's absence.
687 if got := cursorOf(t, s, "Docs"); got != "c1" {
688 t.Fatalf("cursor = %q, want c1", got)
689 }
690 if at := polledAt(t, s, "Docs"); !at.IsZero() {
691 t.Errorf("a poll that failed on page two recorded PolledAt=%v: the "+
692 "sources page would call the corpus current as of a moment "+
693 "there was demonstrably more to read", at)
694 }
695 })
696
697 t.Run("a poll that stopped short claims nothing", func(t *testing.T) {
698 f := &feedServer{
699 t: t,
700 pages: map[string]suite.Feed{
701 "": {Cursor: "same", Rows: []suite.FeedRow{row("a", 1, false)}},
702 "same": {Cursor: "same", Rows: []suite.FeedRow{row("a", 1, false)}},
703 },
704 bodies: map[string]string{"a": "Going nowhere."},
705 }
706 sib, client := f.start(t)
707 s := storeForTest(t)
708 res, err := s.Poll(ctx, client, sib)
709 if err != nil {
710 t.Fatalf("poll: %v", err)
711 }
712 if !res.More {
713 t.Fatal("the fixture did not produce a short poll")
714 }
715 if at := polledAt(t, s, "Docs"); !at.IsZero() {
716 t.Errorf("a poll reporting More recorded PolledAt=%v", at)
717 }
718 })
719}
720
721// Two siblings in one store keep their own position and their own
722// documents.
723//
724// Neither scoping had a fixture: a review dropped `source = ?` from the
725// tombstone lookup and `app = ?` from the cursor read, and both stayed
726// green. In production the first means Docs' tombstone for item "42"
727// deletes Sheets' item "42"; the second means Sheets polls from Docs'
728// cursor and silently skips everything before it.
729//
730// MUTATION-TESTED 2026-09-07, each verified red then reverted:
731//
732// deleteBySiblingItem without `source = ?`
733// -> red, the other sibling's document goes
734// cursor()/upsertFeed without `app = ?`
735// -> red, the positions collide
736func TestTwoSiblingsKeepTheirOwnPositionAndDocuments(t *testing.T) {
737 ctx := context.Background()
738 s := storeForTest(t)
739
740 // The same item id in both apps, which is the collision that matters:
741 // item ids are the siblings' own and nothing makes them unique across
742 // apps.
743 docs := &feedServer{
744 t: t,
745 pages: map[string]suite.Feed{
746 "": {Cursor: "docs-1", Rows: []suite.FeedRow{row("42", 1, false)}},
747 "docs-1": {Cursor: "docs-1", Rows: []suite.FeedRow{}},
748 },
749 bodies: map[string]string{"42": "Docs' document forty-two."},
750 }
751 sheets := &feedServer{
752 t: t,
753 pages: map[string]suite.Feed{
754 "": {Cursor: "sheets-9", Rows: []suite.FeedRow{row("42", 1, false)}},
755 "sheets-9": {Cursor: "sheets-9", Rows: []suite.FeedRow{}},
756 },
757 bodies: map[string]string{"42": "Sheets' document forty-two."},
758 }
759 dSib, client := docs.start(t)
760 sSib, _ := sheets.start(t)
761 sSib.Name = "Sheets"
762
763 if _, err := s.Poll(ctx, client, dSib); err != nil {
764 t.Fatalf("poll Docs: %v", err)
765 }
766 if _, err := s.Poll(ctx, client, sSib); err != nil {
767 t.Fatalf("poll Sheets: %v", err)
768 }
769
770 // Separate positions, or one app resumes from the other's place.
771 if got := cursorOf(t, s, "Docs"); got != "docs-1" {
772 t.Errorf("Docs cursor = %q, want docs-1", got)
773 }
774 if got := cursorOf(t, s, "Sheets"); got != "sheets-9" {
775 t.Errorf("Sheets cursor = %q, want sheets-9", got)
776 }
777 assertHeld(t, s, "Docs", "42", 1)
778 assertHeld(t, s, "Sheets", "42", 1)
779
780 // Docs tombstones its "42". Sheets' must survive.
781 docs.pages["docs-1"] = suite.Feed{Cursor: "docs-2", Rows: []suite.FeedRow{row("42", 2, true)}}
782 docs.pages["docs-2"] = suite.Feed{Cursor: "docs-2", Rows: []suite.FeedRow{}}
783 res, err := s.Poll(ctx, client, dSib)
784 if err != nil {
785 t.Fatalf("tombstone poll: %v", err)
786 }
787 if res.Deleted != 1 {
788 t.Errorf("result = %+v, want 1 deleted", res)
789 }
790 if heldCount(t, s, "Docs") != 0 {
791 t.Error("Docs' document survived its own tombstone")
792 }
793 assertHeld(t, s, "Sheets", "42", 1)
794}
795
796// A tombstone memoria has already applied deletes nothing and says so.
797//
798// A feed can legitimately re-announce a deletion, and a poll that failed
799// mid-page re-applies the rows before the failure by design — so the count
800// has to be of documents that actually went, not of rows that mentioned
801// one. Counting rows makes the sources page report deletions that did not
802// happen, on exactly the days something went wrong.
803//
804// MUTATION-TESTED 2026-09-07: `res.Deleted++` per tombstone row rather
805// than per document removed. Red. Reverted.
806func TestAReAnnouncedTombstoneDeletesNothing(t *testing.T) {
807 ctx := context.Background()
808 f := &feedServer{
809 t: t,
810 pages: map[string]suite.Feed{
811 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 2, true)}},
812 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
813 },
814 bodies: map[string]string{},
815 }
816 sib, client := f.start(t)
817 s := storeForTest(t)
818
819 // memoria never held "a" at all.
820 res, err := s.Poll(ctx, client, sib)
821 if err != nil {
822 t.Fatalf("poll: %v", err)
823 }
824 if res.Deleted != 0 {
825 t.Errorf("result = %+v: a tombstone for a document memoria does not "+
826 "hold removed nothing, and the count must say so", res)
827 }
828}
829
830// A sibling answering 403 on S3 is a contract breach, not a missing item,
831// and it must not be quietly folded into the count that means "gone or
832// not visible".
833//
834// 403 says "this exists and you may not have it" — the one fact custody
835// hides — so a sibling emitting one is leaking, and the module keeps it
836// distinguishable on purpose. Counting it as Missing would hide a leaking
837// sibling behind a number that means something else.
838//
839// MUTATION-TESTED 2026-09-07: fold ErrContractBreach into the Missing
840// branch. Red. Reverted.
841func TestA403OnS3IsNotAMissingItem(t *testing.T) {
842 f := &feedServer{
843 t: t,
844 pages: map[string]suite.Feed{
845 "": {Cursor: "c1", Rows: []suite.FeedRow{row("a", 1, false)}},
846 "c1": {Cursor: "c1", Rows: []suite.FeedRow{}},
847 },
848 bodies: map[string]string{},
849 forbidS3: map[string]bool{"a": true},
850 }
851 sib, client := f.start(t)
852 s := storeForTest(t)
853
854 res, err := s.Poll(context.Background(), client, sib)
855 if err == nil {
856 t.Fatalf("a 403 from S3 came back as a completed poll: %+v", res)
857 }
858 if res.Missing != 0 {
859 t.Errorf("a 403 was counted as a missing item: %+v — that number "+
860 "means 'gone or not team-visible', and a 403 means the sibling "+
861 "is telling callers which ids exist", res)
862 }
863}
864
865func documentOf(t *testing.T, s *Store, app, itemID string) Document {
866 t.Helper()
867 external, err := s.externalID(itemID)
868 if err != nil {
869 t.Fatalf("externalID: %v", err)
870 }
871 var d Document
872 if err := s.db.G.Where("source = ? AND external_id = ?", app, external).First(&d).Error; err != nil {
873 t.Fatalf("%s/%s not held: %v", app, itemID, err)
874 }
875 return d
876}
877
878func polledAt(t *testing.T, s *Store, app string) time.Time {
879 t.Helper()
880 var row SiblingFeed
881 if err := s.db.G.Where("app = ?", app).First(&row).Error; err != nil {
882 return time.Time{}
883 }
884 return row.PolledAt
885}
886