| 1 | package memoria |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | "time" |
| 9 | |
| 10 | "amadan.net/oficina/suite" |
| 11 | |
| 12 | "amadan.net/oficina/memoria/internal/memoria/seal" |
| 13 | "amadan.net/oficina/memoria/internal/memoria/sibling" |
| 14 | ) |
| 15 | |
| 16 | // maxFeedPages bounds one poll. |
| 17 | // |
| 18 | // A sibling whose cursor never advances, or whose feed loops, must not |
| 19 | // hold a wake open forever. A ceiling on damage rather than a |
| 20 | // measurement: at a few hundred rows a page this is far past any ordinary |
| 21 | // catch-up, and reaching it is reported as an INCOMPLETE poll rather than |
| 22 | // as a finished one — the difference between "there is no more" and "I |
| 23 | // stopped looking" is the difference this whole file is about. |
| 24 | const maxFeedPages = 50 |
| 25 | |
| 26 | // PollResult is what one poll did. Counts only: no item id, no title, no |
| 27 | // body, so it can go in a log line or on the sources page (AGENTS.md). |
| 28 | type PollResult struct { |
| 29 | Stored int |
| 30 | Deleted int |
| 31 | // Missing counts rows the sibling listed and then would not serve. |
| 32 | // |
| 33 | // **Not an error, and emphatically not a deletion.** §4.2 makes S3's |
| 34 | // 404 cover both "gone" and "not team-visible", deliberately, so |
| 35 | // memoria cannot tell which — and deleting on it would let a |
| 36 | // visibility change erase history that the sibling still has. What it |
| 37 | // feeds is §8.1's S3 breaker, which is the thing that notices when |
| 38 | // this happens wholesale. |
| 39 | Missing int |
| 40 | // Empty counts items the sibling served with no body at all. |
| 41 | // |
| 42 | // Skipped, not stored: a stub page has no passages, so there is |
| 43 | // nothing to retrieve and nothing to cite. Counted rather than passed |
| 44 | // over in silence, because a source that is suddenly all stubs is a |
| 45 | // fact about the sibling worth being able to see. |
| 46 | Empty int |
| 47 | // More means the poll stopped before the sibling ran out. What |
| 48 | // memoria holds is consistent; it is not current, and the sources |
| 49 | // page must not say it is. |
| 50 | More bool |
| 51 | // Reset means the sibling answered CURSOR_RESET (suite doctrine §6.6, |
| 52 | // revision 11) and this poll soft-dropped everything held from it. |
| 53 | // The re-read starts on the next poll, never in this one: "every |
| 54 | // re-read … waits on the consumer's ordinary backoff", and memoria's |
| 55 | // is the wake. |
| 56 | Reset bool |
| 57 | } |
| 58 | |
| 59 | // errResetTwice is §6.6's "at most one reset per re-read": a second |
| 60 | // CURSOR_RESET before the re-read reached the tip is a failure of that |
| 61 | // producer, not another reset. What was held stays pending and withheld |
| 62 | // (the source stays Reconciling); the next poll starts a later re-read. |
| 63 | var errResetTwice = errors.New("a second cursor reset before the re-read reached the tip") |
| 64 | |
| 65 | // errResetAtStart is a CURSOR_RESET answered to the empty cursor, which |
| 66 | // §6.6 says is never reset (the module's server answers 500 rather than |
| 67 | // write one). A producer doing it is broken; nothing is dropped on its |
| 68 | // word, and the poll fails. |
| 69 | var errResetAtStart = errors.New("a cursor reset answered to the start of the feed") |
| 70 | |
| 71 | // Poll brings memoria's copy of one sibling's content up to date. |
| 72 | // |
| 73 | // **The cursor advances only after a page has been fully applied**, and |
| 74 | // that ordering is the whole design. §5.1 and gate 7: a timed-out, |
| 75 | // rate-limited or half-applied enumeration returns no information rather |
| 76 | // than no documents, and a cursor moved past a page nobody applied skips |
| 77 | // changes the sibling will never offer again — silently, because the |
| 78 | // sibling has no way to know. Every failure below returns before the |
| 79 | // cursor is stored. |
| 80 | // |
| 81 | // **A failed poll deletes nothing**, which is the same rule from the other |
| 82 | // end. Deletions arrive as `gone` rows on a page that was fetched |
| 83 | // successfully; they are never inferred from an item's absence, because to |
| 84 | // a consumer that infers, a short page and a complete one look the same. |
| 85 | // |
| 86 | // Re-applying is the cheap failure and is chosen deliberately. When a row |
| 87 | // fails mid-page the cursor stays put, so the whole page comes back next |
| 88 | // time and its earlier rows are applied again — which is safe, since |
| 89 | // Ingest is keyed on (source, external id) and deleting an absent row is a |
| 90 | // no-op. The expensive failure is skipping a row nobody will mention |
| 91 | // again. |
| 92 | func (s *Store) Poll(ctx context.Context, c *sibling.Client, sib sibling.Sibling) (PollResult, error) { |
| 93 | // A poll is the instance's own derived work, not anybody's write |
| 94 | // (team_guard.go). |
| 95 | ctx = systemWrite(ctx) |
| 96 | var res PollResult |
| 97 | cursor, err := s.cursor(ctx, sib.Name) |
| 98 | if err != nil { |
| 99 | return res, err |
| 100 | } |
| 101 | |
| 102 | for page := 0; ; page++ { |
| 103 | if page >= maxFeedPages { |
| 104 | // Neither an error nor a completed poll: what memoria has is |
| 105 | // consistent, and there is more. Returning nil with More unset |
| 106 | // would let the caller call the corpus current. |
| 107 | res.More = true |
| 108 | return res, nil |
| 109 | } |
| 110 | feed, err := c.Feed(ctx, sib, cursor) |
| 111 | if errors.Is(err, suite.ErrCursorReset) { |
| 112 | // The rows already applied on earlier pages of this poll came |
| 113 | // from the log the producer has just disowned; soft-dropping |
| 114 | // marks them pending with everything else. |
| 115 | if cursor == "" { |
| 116 | return res, fmt.Errorf("poll %s: %w", sib.Name, errResetAtStart) |
| 117 | } |
| 118 | res.Reset = true |
| 119 | return res, s.cursorReset(ctx, sib.Name) |
| 120 | } |
| 121 | if err != nil { |
| 122 | return res, fmt.Errorf("poll %s: %w", sib.Name, err) |
| 123 | } |
| 124 | |
| 125 | for _, row := range feed.Rows { |
| 126 | if err := s.applyRow(ctx, c, sib, row, &res); err != nil { |
| 127 | return res, fmt.Errorf("poll %s: %w", sib.Name, err) |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | // The page is applied. Only now may the position move. |
| 132 | if feed.Cursor != "" && feed.Cursor != cursor { |
| 133 | if err := s.setCursor(ctx, sib.Name, feed.Cursor); err != nil { |
| 134 | return res, err |
| 135 | } |
| 136 | cursor = feed.Cursor |
| 137 | continue |
| 138 | } |
| 139 | |
| 140 | // The cursor did not move. If the page was empty, the sibling |
| 141 | // answered and has nothing further — **the one place an empty |
| 142 | // result may be read as "nothing", and only because Feed returns |
| 143 | // an error for every other reason it could be empty.** If the page |
| 144 | // had rows, a cursor that does not advance would loop forever, so |
| 145 | // stop and say the poll did not conclude. |
| 146 | res.More = len(feed.Rows) > 0 |
| 147 | if !res.More { |
| 148 | // The tip. A re-read after a reset ends here, and only here: |
| 149 | // §6.6 step 3 retires what the complete re-read did not list. |
| 150 | if err := s.finishReread(ctx, sib.Name, &res); err != nil { |
| 151 | return res, err |
| 152 | } |
| 153 | if err := s.markPolled(ctx, sib.Name); err != nil { |
| 154 | return res, err |
| 155 | } |
| 156 | } |
| 157 | return res, nil |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | func (s *Store) applyRow(ctx context.Context, c *sibling.Client, sib sibling.Sibling, row suite.FeedRow, res *PollResult) error { |
| 162 | // **There is no check for an empty item id here, and that is |
| 163 | // deliberate.** One was written; it could not fail. Every row reaching |
| 164 | // this function came out of `suite.DecodeS1`, which refuses the whole |
| 165 | // page — "S1 row %d has no item_id" (s1.go) — so the guard never ran, |
| 166 | // and a mutation deleting it left the suite green because the module |
| 167 | // was doing the work. A defence nothing can reach is a guard written |
| 168 | // to pass, whatever the intent. |
| 169 | // |
| 170 | // What memoria depends on is the module's refusal, and what makes that |
| 171 | // dependency visible is a test asserting the MODULE behaves that way |
| 172 | // rather than a duplicate check here pretending to. |
| 173 | if row.Gone { |
| 174 | n, err := s.deleteBySiblingItem(ctx, sib.Name, row.ItemID) |
| 175 | if err != nil { |
| 176 | return err |
| 177 | } |
| 178 | res.Deleted += n |
| 179 | return nil |
| 180 | } |
| 181 | |
| 182 | body, err := c.Content(ctx, sib, row.ItemID, row.Revision) |
| 183 | switch { |
| 184 | case errors.Is(err, suite.ErrNotAvailable): |
| 185 | // Listed, then not served. See PollResult.Missing: counted, not |
| 186 | // deleted, not failed. |
| 187 | res.Missing++ |
| 188 | return nil |
| 189 | case err != nil: |
| 190 | return err |
| 191 | } |
| 192 | |
| 193 | // **An empty item is skipped and counted, not stored and not failed.** |
| 194 | // |
| 195 | // This said `AllowTitleOnly: true` and claimed it stopped one empty |
| 196 | // document blocking a catch-up. It did the opposite: no Title is |
| 197 | // passed here — a sibling's S3 gives a body and nothing else — so |
| 198 | // Ingest refused with "neither a body nor a title", the row failed, |
| 199 | // the cursor stayed put, and **every subsequent poll of that sibling |
| 200 | // failed on the same row forever**. One stub page in Docs and nothing |
| 201 | // from Docs is ever ingested again. A review found it. |
| 202 | // |
| 203 | // Skipping is right rather than a fallback title: a stub page has no |
| 204 | // passages, so there is nothing to retrieve and nothing to cite, and |
| 205 | // inventing a title from an empty body would put a document in the |
| 206 | // corpus whose only content is its own name. The count is what keeps |
| 207 | // it from being silent. |
| 208 | if strings.TrimSpace(string(body)) == "" { |
| 209 | res.Empty++ |
| 210 | return nil |
| 211 | } |
| 212 | |
| 213 | // The item id is the stable key, so ExternalID's fingerprint is |
| 214 | // computed over it. A title would not be: a rename would make a second |
| 215 | // document and leave the first indexed under the old name. |
| 216 | _, err = s.Ingest(ctx, IngestSpec{ |
| 217 | Source: sib.Name, |
| 218 | Key: row.ItemID, |
| 219 | Body: string(body), |
| 220 | ItemID: row.ItemID, |
| 221 | SiblingRevision: row.Revision, |
| 222 | }) |
| 223 | switch { |
| 224 | case errors.Is(err, ErrIndexLag): |
| 225 | // Stored, and only the index is behind. The document is in the |
| 226 | // database, so the cursor may pass this row: re-fetching it would |
| 227 | // not fix the index either, and the app says the lag out loud. |
| 228 | case err != nil: |
| 229 | return err |
| 230 | } |
| 231 | // Listed by the re-read and fetched again, so it is no longer a |
| 232 | // leftover of the disowned log (§6.6 step 2). A row that 404s or is |
| 233 | // empty above returns before this and stays pending: memoria cannot |
| 234 | // show that its copy is one the restored log still has, so the tip |
| 235 | // retires it. |
| 236 | if err := s.unpend(ctx, sib.Name, row.ItemID); err != nil { |
| 237 | return err |
| 238 | } |
| 239 | res.Stored++ |
| 240 | return nil |
| 241 | } |
| 242 | |
| 243 | // cursorReset is §6.6 step 1, on CURSOR_RESET: every document held from |
| 244 | // app is marked pending, the source is marked Reconciling — which takes |
| 245 | // it off every surface, because rule() withholds a reconciling source |
| 246 | // wholesale — and the cursor is discarded, so the next poll reads from |
| 247 | // "". One transaction: a crash between the three must not leave a source |
| 248 | // shown with its cursor gone, or hidden with its cursor kept. |
| 249 | // |
| 250 | // A source already Reconciling is in a re-read that has not reached the |
| 251 | // tip, and this is its second reset: errResetTwice. The marking is done |
| 252 | // all the same — documents the abandoned re-read had fetched go back to |
| 253 | // pending, so only a re-read that completes decides what survives. |
| 254 | func (s *Store) cursorReset(ctx context.Context, app string) error { |
| 255 | var again bool |
| 256 | err := s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| 257 | var row SiblingFeed |
| 258 | err := tx.Where("app = ?", app).First(&row).Error |
| 259 | switch { |
| 260 | case errors.Is(err, errRecordNotFound): |
| 261 | // A reset with no stored cursor cannot happen (Poll refuses a |
| 262 | // reset on ""), but a feed row is what holds the state, so make |
| 263 | // one rather than reason about it. |
| 264 | row = SiblingFeed{App: app} |
| 265 | if err := tx.Create(&row).Error; err != nil { |
| 266 | return err |
| 267 | } |
| 268 | case err != nil: |
| 269 | return err |
| 270 | } |
| 271 | again = row.Reconciling |
| 272 | if err := tx.Model(&Document{}).Where("source = ?", app).Update("pending", true).Error; err != nil { |
| 273 | return err |
| 274 | } |
| 275 | return tx.Model(&SiblingFeed{}).Where("id = ?", row.ID). |
| 276 | Updates(map[string]any{"reconciling": true, "sealed_cursor": nil}).Error |
| 277 | }) |
| 278 | if err != nil { |
| 279 | return err |
| 280 | } |
| 281 | if again { |
| 282 | return fmt.Errorf("poll %s: %w", app, errResetTwice) |
| 283 | } |
| 284 | return nil |
| 285 | } |
| 286 | |
| 287 | // unpend clears Pending on the document a re-read has just fetched again. |
| 288 | func (s *Store) unpend(ctx context.Context, app, itemID string) error { |
| 289 | external, err := s.externalID(itemID) |
| 290 | if err != nil { |
| 291 | return err |
| 292 | } |
| 293 | return s.db.G.WithContext(ctx).Model(&Document{}). |
| 294 | Where("source = ? AND external_id = ? AND pending = ?", app, external, true). |
| 295 | Update("pending", false).Error |
| 296 | } |
| 297 | |
| 298 | // finishReread is §6.6 step 3, at the tip: if app is Reconciling, every |
| 299 | // document still pending is deleted — through Store.Delete, so the index |
| 300 | // goes first — and only then is the source shown again. A delete that |
| 301 | // fails leaves it Reconciling, and the next poll, at the tip again, |
| 302 | // finishes the job. |
| 303 | func (s *Store) finishReread(ctx context.Context, app string, res *PollResult) error { |
| 304 | var row SiblingFeed |
| 305 | err := s.db.G.WithContext(ctx).Where("app = ?", app).First(&row).Error |
| 306 | switch { |
| 307 | case errors.Is(err, errRecordNotFound): |
| 308 | return nil |
| 309 | case err != nil: |
| 310 | return err |
| 311 | } |
| 312 | if !row.Reconciling { |
| 313 | return nil |
| 314 | } |
| 315 | var docs []Document |
| 316 | if err := s.db.G.WithContext(ctx).Select("id"). |
| 317 | Where("source = ? AND pending = ?", app, true).Find(&docs).Error; err != nil { |
| 318 | return err |
| 319 | } |
| 320 | for _, d := range docs { |
| 321 | if err := s.Delete(ctx, d.ID); err != nil { |
| 322 | return err |
| 323 | } |
| 324 | res.Deleted++ |
| 325 | } |
| 326 | return s.db.G.WithContext(ctx).Model(&SiblingFeed{}).Where("id = ?", row.ID). |
| 327 | Update("reconciling", false).Error |
| 328 | } |
| 329 | |
| 330 | // cursor reads memoria's position in one sibling's feed. |
| 331 | // |
| 332 | // **A cursor that will not open is an error, never an empty cursor.** An |
| 333 | // empty cursor means "start from the beginning", which is a legitimate and |
| 334 | // very different instruction: it would re-announce the sibling's entire |
| 335 | // corpus, and — worse — it is exactly what a corrupted row would silently |
| 336 | // turn into. |
| 337 | func (s *Store) cursor(ctx context.Context, app string) (string, error) { |
| 338 | var row SiblingFeed |
| 339 | err := s.db.G.WithContext(ctx).Where("app = ?", app).First(&row).Error |
| 340 | switch { |
| 341 | case errors.Is(err, errRecordNotFound): |
| 342 | // No row yet: the first poll of a newly configured sibling starts |
| 343 | // from the beginning, which is what an empty cursor asks for. |
| 344 | return "", nil |
| 345 | case err != nil: |
| 346 | return "", err |
| 347 | } |
| 348 | if len(row.SealedCursor) == 0 { |
| 349 | return "", nil |
| 350 | } |
| 351 | raw, err := s.sealer.Open(seal.PurposeCursor, row.SealedCursor) |
| 352 | if err != nil { |
| 353 | return "", fmt.Errorf("open cursor for %s: %w", app, err) |
| 354 | } |
| 355 | return string(raw), nil |
| 356 | } |
| 357 | |
| 358 | // setCursor stores a position. **It does not touch PolledAt.** |
| 359 | // |
| 360 | // The two used to move together, and that was wrong in the direction that |
| 361 | // matters. A multi-page catch-up calls this once per page, so a poll that |
| 362 | // failed on page four — or one that stopped at the page bound with more to |
| 363 | // come — left PolledAt at the moment of the last page it managed. The |
| 364 | // sources page would then report the corpus current as of a time when it |
| 365 | // demonstrably was not, which is §8.1's rule inverted: *"a failed or stale |
| 366 | // S1 → the page states the corpus is current as of a time, rather than |
| 367 | // implying freshness."* |
| 368 | // |
| 369 | // A position is "how far I got". A timestamp is "and there was nothing |
| 370 | // after it". Only the second is a claim about completeness, and only the |
| 371 | // drained-feed branch of Poll may make it. |
| 372 | func (s *Store) setCursor(ctx context.Context, app, cursor string) error { |
| 373 | sealed, err := s.sealer.Seal(seal.PurposeCursor, []byte(cursor)) |
| 374 | if err != nil { |
| 375 | return err |
| 376 | } |
| 377 | return s.upsertFeed(ctx, app, map[string]any{"sealed_cursor": sealed}) |
| 378 | } |
| 379 | |
| 380 | // markPolled records that a poll reached the end of the feed without |
| 381 | // moving the cursor — the sibling answered and had nothing new. |
| 382 | func (s *Store) markPolled(ctx context.Context, app string) error { |
| 383 | return s.upsertFeed(ctx, app, map[string]any{"polled_at": time.Now().UTC()}) |
| 384 | } |
| 385 | |
| 386 | func (s *Store) upsertFeed(ctx context.Context, app string, fields map[string]any) error { |
| 387 | return s.db.G.WithContext(ctx).Transaction(func(tx *gormTx) error { |
| 388 | var row SiblingFeed |
| 389 | err := tx.Where("app = ?", app).First(&row).Error |
| 390 | switch { |
| 391 | case errors.Is(err, errRecordNotFound): |
| 392 | row = SiblingFeed{App: app} |
| 393 | if v, ok := fields["sealed_cursor"].([]byte); ok { |
| 394 | row.SealedCursor = v |
| 395 | } |
| 396 | if v, ok := fields["polled_at"].(time.Time); ok { |
| 397 | row.PolledAt = v |
| 398 | } |
| 399 | return tx.Create(&row).Error |
| 400 | case err != nil: |
| 401 | return err |
| 402 | } |
| 403 | // Scoped to tx, never the outer handle (AGENTS.md). |
| 404 | return tx.Model(&SiblingFeed{}).Where("id = ?", row.ID).Updates(fields).Error |
| 405 | }) |
| 406 | } |
| 407 | |
| 408 | // deleteBySiblingItem applies one `gone` row. |
| 409 | // |
| 410 | // It resolves the sibling's item id the same way Ingest stores it — the |
| 411 | // keyed fingerprint over (source, key) — because that is the only handle |
| 412 | // memoria has on a row from the outside. Returns how many documents went, |
| 413 | // which is 0 for a tombstone memoria has already applied or never held: |
| 414 | // **not an error.** A feed can legitimately re-announce a deletion, and a |
| 415 | // poll that failed mid-page re-applies the rows before the failure by |
| 416 | // design. |
| 417 | func (s *Store) deleteBySiblingItem(ctx context.Context, app, itemID string) (int, error) { |
| 418 | external, err := s.externalID(itemID) |
| 419 | if err != nil { |
| 420 | return 0, err |
| 421 | } |
| 422 | var docs []Document |
| 423 | if err := s.db.G.WithContext(ctx). |
| 424 | Where("source = ? AND external_id = ?", app, external). |
| 425 | Find(&docs).Error; err != nil { |
| 426 | return 0, err |
| 427 | } |
| 428 | for _, d := range docs { |
| 429 | // Store.Delete removes the index entries BEFORE the rows and |
| 430 | // refuses the whole delete if that fails, so a tombstone cannot |
| 431 | // leave passages indexed under a document that is gone. That |
| 432 | // ordering is AGENTS.md's rule and the reason this does not do |
| 433 | // its own deleting. |
| 434 | if err := s.Delete(ctx, d.ID); err != nil { |
| 435 | return 0, err |
| 436 | } |
| 437 | } |
| 438 | return len(docs), nil |
| 439 | } |
| 440 | |
| 441 | // polledAt reports when this sibling's feed was last drained. |
| 442 | // |
| 443 | // **A read that fails is an error, not a zero time.** A zero time means |
| 444 | // "never checked", which the page renders as its own sentence; returning |
| 445 | // it for a failed read would put a false one on the page — the same rule |
| 446 | // as everywhere else, on the value the freshness claim is built from. |
| 447 | func (s *Store) polledAt(ctx context.Context, app string) (time.Time, error) { |
| 448 | var row SiblingFeed |
| 449 | err := s.db.G.WithContext(ctx).Where("app = ?", app).First(&row).Error |
| 450 | switch { |
| 451 | case errors.Is(err, errRecordNotFound): |
| 452 | return time.Time{}, nil |
| 453 | case err != nil: |
| 454 | return time.Time{}, err |
| 455 | } |
| 456 | return row.PolledAt, nil |
| 457 | } |
| 458 | |