| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http/httptest" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | |
| 10 | "amadan.net/oficina/suite" |
| 11 | "gorm.io/gorm" |
| 12 | |
| 13 | "amadan.net/oficina/memoria/internal/memoria/sibling" |
| 14 | ) |
| 15 | |
| 16 | // CURSOR_RESET, memoria's half (suite doctrine §6.6, revision 11): a |
| 17 | // sibling restored from a backup answers 409 to the cursor memoria holds, |
| 18 | // and memoria hides everything it holds from that sibling on every |
| 19 | // surface, reads the feed again from the start, and at the tip deletes |
| 20 | // whatever the re-read did not list. |
| 21 | // |
| 22 | // The search is the surface asked here; every other surface goes through |
| 23 | // the same rule() (TestEverySurfaceAsksTheAppOfRecord), which is where the |
| 24 | // withholding is. |
| 25 | // |
| 26 | // MUTATION-TESTED 2026-11-02, each seen red and reverted: |
| 27 | // |
| 28 | // rule() not withholding a reconciling source |
| 29 | // -> "shown while being re-read" |
| 30 | // cursorReset not discarding the cursor |
| 31 | // -> the sibling is asked for the disowned cursor again ("unscripted") |
| 32 | // cursorReset not marking documents pending |
| 33 | // -> "survived the re-read" |
| 34 | // unpend removed from applyRow |
| 35 | // -> "the re-listed document was retired" |
| 36 | // finishReread not clearing Reconciling |
| 37 | // -> "still withheld after the re-read" |
| 38 | // finishReread run on every page, not only at the tip |
| 39 | // -> "retired before the re-read reached the tip" |
| 40 | // a listed row S3 refuses unpended (Fable's R06) |
| 41 | // -> "survived the re-read" |
| 42 | // retirement by deleting the document row, not Store.Delete (R03) |
| 43 | // -> "passages outlived their retired documents" |
| 44 | // the sources page not reading Reconciling |
| 45 | // -> "does not say Docs is being re-read" |
| 46 | func TestACursorResetHidesThenReReadsThenRetires(t *testing.T) { |
| 47 | ctx := context.Background() |
| 48 | s := storeForTest(t) |
| 49 | s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| 50 | asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| 51 | |
| 52 | f := &feedServer{ |
| 53 | t: t, |
| 54 | pages: map[string]suite.Feed{ |
| 55 | "": {Cursor: "old-1", Rows: []suite.FeedRow{row("keep", 5, false), row("drop", 7, false), row("unserved", 9, false)}}, |
| 56 | "old-1": {Cursor: "old-1", Rows: []suite.FeedRow{}}, |
| 57 | }, |
| 58 | bodies: map[string]string{"keep": "The nebula plan is kept.", "drop": "The nebula budget was dropped.", "unserved": "The nebula draft."}, |
| 59 | } |
| 60 | sib, client := f.start(t) |
| 61 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 62 | t.Fatalf("first poll: %v", err) |
| 63 | } |
| 64 | if got := nebula(t, s, asker); got.n != 3 { |
| 65 | t.Fatalf("before the reset the search found %d, want 3 (the presence half)", got.n) |
| 66 | } |
| 67 | |
| 68 | // The sibling is restored: memoria's cursor names nothing in its log. |
| 69 | // The restored log has "keep" and not "drop", and two pages, so the |
| 70 | // tip is not reached on the first. It lists "unserved" and then will |
| 71 | // not serve it: memoria cannot show its copy is one the restored log |
| 72 | // still has, so the tip retires it too. |
| 73 | f.reset = map[string]bool{"old-1": true} |
| 74 | f.failS3 = map[string]bool{"unserved": true} |
| 75 | f.pages[""] = suite.Feed{Cursor: "new-1", Rows: []suite.FeedRow{row("keep", 5, false), row("unserved", 9, false)}} |
| 76 | f.pages["new-1"] = suite.Feed{Cursor: "new-2", Rows: []suite.FeedRow{}} |
| 77 | f.pages["new-2"] = suite.Feed{Cursor: "new-2", Rows: []suite.FeedRow{}} |
| 78 | |
| 79 | res, err := s.Poll(ctx, client, sib) |
| 80 | if err != nil || !res.Reset { |
| 81 | t.Fatalf("reset poll = %+v, %v; want Reset and no error", res, err) |
| 82 | } |
| 83 | if got := cursorOf(t, s, "Docs"); got != "" { |
| 84 | t.Errorf("cursor after a reset = %q, want discarded", got) |
| 85 | } |
| 86 | got := nebula(t, s, asker) |
| 87 | if got.n != 0 { |
| 88 | t.Fatalf("shown while being re-read: %d results", got.n) |
| 89 | } |
| 90 | if !strings.Contains(got.notices, "Docs is being re-read") { |
| 91 | t.Errorf("withheld without saying so: notices %q", got.notices) |
| 92 | } |
| 93 | if heldCount(t, s, "Docs") != 3 { |
| 94 | t.Errorf("the reset deleted something; it may only hide (step 1 is a soft drop)") |
| 95 | } |
| 96 | if line := sourcesLine(t, s, sib); !strings.Contains(line, "Being re-read") { |
| 97 | t.Errorf("the owner's sources page does not say Docs is being re-read: %q", line) |
| 98 | } |
| 99 | |
| 100 | // The re-read, stopped after its first page: nothing is retired yet, |
| 101 | // and the source stays hidden. |
| 102 | f.failS1 = map[string]bool{"new-1": true} |
| 103 | if _, err := s.Poll(ctx, client, sib); err == nil { |
| 104 | t.Fatal("the scripted failure did not fail") |
| 105 | } |
| 106 | if heldCount(t, s, "Docs") != 3 { |
| 107 | t.Fatal("retired before the re-read reached the tip") |
| 108 | } |
| 109 | if got := nebula(t, s, asker); got.n != 0 { |
| 110 | t.Fatalf("shown while being re-read (after a partial re-read): %d", got.n) |
| 111 | } |
| 112 | |
| 113 | // The re-read completes. |
| 114 | f.failS1 = nil |
| 115 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 116 | t.Fatalf("re-read: %v", err) |
| 117 | } |
| 118 | if heldCount(t, s, "Docs") != 1 { |
| 119 | t.Errorf("%d Docs documents after the re-read, want 1: \"drop\" or \"unserved\" survived the re-read, or the re-listed document was retired", heldCount(t, s, "Docs")) |
| 120 | } |
| 121 | assertHeld(t, s, "Docs", "keep", 5) |
| 122 | got = nebula(t, s, asker) |
| 123 | if got.n != 1 || got.notices != "" { |
| 124 | t.Errorf("still withheld after the re-read: %d results, notices %q", got.n, got.notices) |
| 125 | } |
| 126 | // Retired through Store.Delete: the in-memory index holds exactly the |
| 127 | // passages the database does. (The chunk rows cascade with their |
| 128 | // document whatever deletes it; the index is what a raw delete leaves |
| 129 | // behind.) |
| 130 | var stored int64 |
| 131 | if err := s.db.G.Model(&Chunk{}).Count(&stored).Error; err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | indexed, err := s.ix.Count() |
| 135 | if err != nil { |
| 136 | t.Fatal(err) |
| 137 | } |
| 138 | if int64(indexed) != stored { |
| 139 | t.Errorf("passages outlived their retired documents: %d indexed, %d stored", indexed, stored) |
| 140 | } |
| 141 | if line := sourcesLine(t, s, sib); !strings.HasPrefix(line, "Current as of") { |
| 142 | t.Errorf("the sources page after the re-read: %q", line) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // A retirement that fails leaves the source hidden and the feed not |
| 147 | // called current: §6.6's step 1 exists so that a consumer is never left |
| 148 | // showing a mix of two logs, and clearing Reconciling before the deletes |
| 149 | // (or stamping PolledAt before them) is how a crash would leave one. |
| 150 | // |
| 151 | // MUTATION-TESTED 2026-11-02, each seen red and reverted: Reconciling |
| 152 | // cleared before the deletes → "shown after a failed retirement"; |
| 153 | // markPolled before finishReread → "called current". |
| 154 | func TestAFailedRetirementStaysHidden(t *testing.T) { |
| 155 | ctx := context.Background() |
| 156 | s := storeForTest(t) |
| 157 | s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| 158 | asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| 159 | f := &feedServer{ |
| 160 | t: t, |
| 161 | pages: map[string]suite.Feed{ |
| 162 | "": {Cursor: "old-1", Rows: []suite.FeedRow{row("keep", 1, false), row("drop", 2, false)}}, |
| 163 | "old-1": {Cursor: "old-1", Rows: []suite.FeedRow{}}, |
| 164 | }, |
| 165 | bodies: map[string]string{"keep": "nebula keep", "drop": "nebula drop"}, |
| 166 | } |
| 167 | sib, client := f.start(t) |
| 168 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 169 | t.Fatal(err) |
| 170 | } |
| 171 | before := polledAt(t, s, "Docs") |
| 172 | f.reset = map[string]bool{"old-1": true} |
| 173 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | f.pages[""] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{row("keep", 1, false)}} |
| 177 | f.pages["end"] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{}} |
| 178 | |
| 179 | failing := true |
| 180 | if err := s.db.G.Callback().Delete().Before("gorm:delete").Register("test:fail_retire", func(tx *gorm.DB) { |
| 181 | if failing && tx.Statement.Table == "documents" { |
| 182 | tx.AddError(errors.New("the disk went away")) |
| 183 | } |
| 184 | }); err != nil { |
| 185 | t.Fatal(err) |
| 186 | } |
| 187 | if _, err := s.Poll(ctx, client, sib); err == nil { |
| 188 | t.Fatal("the retirement did not fail, so nothing below is about a failed one") |
| 189 | } |
| 190 | if got := nebula(t, s, asker); got.n != 0 { |
| 191 | t.Fatalf("shown after a failed retirement: %d results", got.n) |
| 192 | } |
| 193 | if !polledAt(t, s, "Docs").Equal(before) { |
| 194 | t.Error("a re-read whose retirement failed was called current") |
| 195 | } |
| 196 | // Next wake, the disk is back: the tip finishes the job. |
| 197 | failing = false |
| 198 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 199 | t.Fatalf("the retry: %v", err) |
| 200 | } |
| 201 | if got := nebula(t, s, asker); got.n != 1 || heldCount(t, s, "Docs") != 1 { |
| 202 | t.Errorf("after the retry: %d results, %d held; want 1 and 1", got.n, heldCount(t, s, "Docs")) |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | // rule() withholds every sibling passage when it cannot read which |
| 207 | // sources are being re-read, rather than guess that none is (Fable, |
| 208 | // 2026-11-02: this branch was unreachable). MUTATION-TESTED 2026-11-02: |
| 209 | // the read error ignored → "shown". |
| 210 | func TestAnUnreadableReReadStateWithholds(t *testing.T) { |
| 211 | ctx := context.Background() |
| 212 | s := storeForTest(t) |
| 213 | s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| 214 | asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| 215 | if _, err := s.Ingest(systemWrite(ctx), IngestSpec{Source: "Docs", Key: "a", Title: "A", Body: "nebula a", ItemID: "a", SiblingRevision: 1}); err != nil { |
| 216 | t.Fatal(err) |
| 217 | } |
| 218 | if got := nebula(t, s, asker); got.n != 1 { |
| 219 | t.Fatalf("presence: %d results", got.n) |
| 220 | } |
| 221 | if err := s.db.G.Exec("ALTER TABLE sibling_feeds RENAME TO sibling_feeds_away").Error; err != nil { |
| 222 | t.Fatal(err) |
| 223 | } |
| 224 | got := nebula(t, s, asker) |
| 225 | if got.n != 0 { |
| 226 | t.Fatalf("shown with the re-read state unreadable: %d results", got.n) |
| 227 | } |
| 228 | if !strings.Contains(got.notices, "Docs") { |
| 229 | t.Errorf("withheld silently: %q", got.notices) |
| 230 | } |
| 231 | // And the owner's sources page says it could not tell, rather than |
| 232 | // falling through to another line (Fable's N03, 2026-11-02; that case |
| 233 | // disabled → red). |
| 234 | sib := docsRoster()["Docs"] |
| 235 | if line := sourcesLine(t, s, sib); !strings.Contains(line, "whether this source is being re-read") { |
| 236 | t.Errorf("the sources page with the re-read state unreadable: %q", line) |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | // sourcesLine is the owner's sources-page freshness line for sib. |
| 241 | func sourcesLine(t *testing.T, s *Store, sib sibling.Sibling) string { |
| 242 | t.Helper() |
| 243 | keep := s.custody |
| 244 | s.custody = &Siblings{client: sibling.NewForTest(), byName: map[string]sibling.Sibling{sib.Name: sib}} |
| 245 | defer func() { s.custody = keep }() |
| 246 | rows := (&app{store: s}).siblingRows(httptest.NewRequest("GET", "/connectors", nil)) |
| 247 | if len(rows) != 1 { |
| 248 | t.Fatalf("%d sources rows, want 1", len(rows)) |
| 249 | } |
| 250 | return rows[0].Current |
| 251 | } |
| 252 | |
| 253 | // At most one reset per re-read (§6.6, Fable's M1): a second reset before |
| 254 | // the tip is a failure, everything stays hidden, and only a later re-read |
| 255 | // that completes decides what survives — including a document the |
| 256 | // abandoned re-read had already fetched again. |
| 257 | // |
| 258 | // MUTATION-TESTED 2026-11-02, each seen red and reverted: cursorReset |
| 259 | // returning nil on a second reset -> "a second reset was not a failure"; |
| 260 | // the second reset not re-marking pending -> "survived". |
| 261 | func TestASecondResetBeforeTheTipIsAFailure(t *testing.T) { |
| 262 | ctx := context.Background() |
| 263 | s := storeForTest(t) |
| 264 | s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| 265 | asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| 266 | f := &feedServer{ |
| 267 | t: t, |
| 268 | pages: map[string]suite.Feed{ |
| 269 | "": {Cursor: "old-1", Rows: []suite.FeedRow{row("a", 1, false), row("b", 2, false)}}, |
| 270 | "old-1": {Cursor: "old-1", Rows: []suite.FeedRow{}}, |
| 271 | }, |
| 272 | bodies: map[string]string{"a": "nebula a", "b": "nebula b"}, |
| 273 | } |
| 274 | sib, client := f.start(t) |
| 275 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 276 | t.Fatal(err) |
| 277 | } |
| 278 | f.reset = map[string]bool{"old-1": true} |
| 279 | if res, err := s.Poll(ctx, client, sib); err != nil || !res.Reset { |
| 280 | t.Fatalf("first reset = %+v, %v", res, err) |
| 281 | } |
| 282 | |
| 283 | // The re-read lists "b", then resets again on its own cursor. |
| 284 | f.pages[""] = suite.Feed{Cursor: "mid", Rows: []suite.FeedRow{row("b", 2, false)}} |
| 285 | f.reset["mid"] = true |
| 286 | _, err := s.Poll(ctx, client, sib) |
| 287 | if !errors.Is(err, errResetTwice) { |
| 288 | t.Fatalf("a second reset was not a failure: %v", err) |
| 289 | } |
| 290 | if got := nebula(t, s, asker); got.n != 0 { |
| 291 | t.Fatalf("shown after a failed re-read: %d", got.n) |
| 292 | } |
| 293 | |
| 294 | // A later re-read lists only "a" and completes: "b", fetched by the |
| 295 | // abandoned re-read, must not survive on that re-read's word. |
| 296 | f.reset = nil |
| 297 | f.pages[""] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{row("a", 1, false)}} |
| 298 | f.pages["end"] = suite.Feed{Cursor: "end", Rows: []suite.FeedRow{}} |
| 299 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 300 | t.Fatalf("later re-read: %v", err) |
| 301 | } |
| 302 | if heldCount(t, s, "Docs") != 1 { |
| 303 | t.Fatalf("\"b\" survived: %d Docs documents, want 1", heldCount(t, s, "Docs")) |
| 304 | } |
| 305 | assertHeld(t, s, "Docs", "a", 1) |
| 306 | } |
| 307 | |
| 308 | // A reset answered to the start of the feed is a broken producer, not an |
| 309 | // instruction: nothing is hidden or dropped on its word. |
| 310 | // |
| 311 | // MUTATION-TESTED 2026-11-02: the cursor == "" check removed -> "hidden". |
| 312 | func TestAResetAtTheStartDropsNothing(t *testing.T) { |
| 313 | ctx := context.Background() |
| 314 | s := storeForTest(t) |
| 315 | s.custody = &fixedCustody{apps: docsRoster(), give: suite.VISIBLE} |
| 316 | asker := suite.Subject{Kind: suite.SubjectAddress, Value: "paul@tito.io"} |
| 317 | f := &feedServer{ |
| 318 | t: t, |
| 319 | pages: map[string]suite.Feed{"": {Cursor: "c", Rows: []suite.FeedRow{row("a", 1, false)}}, "c": {Cursor: "c", Rows: []suite.FeedRow{}}}, |
| 320 | bodies: map[string]string{"a": "nebula a"}, |
| 321 | } |
| 322 | sib, client := f.start(t) |
| 323 | if _, err := s.Poll(ctx, client, sib); err != nil { |
| 324 | t.Fatal(err) |
| 325 | } |
| 326 | // The stored cursor is lost (say, a fresh row), and the producer |
| 327 | // answers reset to "". |
| 328 | if err := s.db.G.Model(&SiblingFeed{}).Where("app = ?", "Docs").Update("sealed_cursor", nil).Error; err != nil { |
| 329 | t.Fatal(err) |
| 330 | } |
| 331 | f.reset = map[string]bool{"": true} |
| 332 | if _, err := s.Poll(ctx, client, sib); !errors.Is(err, errResetAtStart) { |
| 333 | t.Fatalf("a reset to the start = %v, want errResetAtStart", err) |
| 334 | } |
| 335 | if got := nebula(t, s, asker); got.n != 1 { |
| 336 | t.Fatalf("hidden on a broken producer's word: %d results", got.n) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | type found struct { |
| 341 | n int |
| 342 | notices string |
| 343 | } |
| 344 | |
| 345 | func nebula(t *testing.T, s *Store, asker suite.Subject) found { |
| 346 | t.Helper() |
| 347 | page, err := s.Search(context.Background(), asker, "nebula", 10) |
| 348 | if err != nil { |
| 349 | t.Fatalf("search: %v", err) |
| 350 | } |
| 351 | return found{len(page.Results), strings.Join(page.Notices, " | ")} |
| 352 | } |
| 353 | |