Repository navigation
Share timeline window builds across page shapes and key caches correctly - #7245
Merged
ymichael merged 2 commits intoNov 9, 2026
Merged
Conversation
Phone (segmentLimit 8) and desktop (20) windows, summaryOnly, CLI log and nested reads each paid a full build after the app's window was already built, and with both phone and desktop watching a giant-turn thread the two 13 MB selections evicted each other from the 16M-char memo, so every push rebuilt both from SQL. Older pages were revisioned on the thread head, so every append invalidated them, and no revision carried the rewrite generation, so a gap-filled event below the head was never seen. - Selection memo: a narrower window adopts a wider sibling's selection when both start at the same sequence, or trims it in memory; shared row arrays are counted once against the char budget. - Projection cache keyed by the selected rows array: the event projection is shared across deferContent, summaryOnly and includeNestedRows; rows are materialized per includeNestedRows (thread-view now exposes projectThreadTimelineEvents and buildThreadTimelineFromProjection). - Response cache: revisions include the rewrite generation; older pages are revisioned on generation and surface only (their cursor snapshot is already in the key); thread-deleted drops a thread's windows; the per-entry cap is 8 MB (was 2 MB, total cap unchanged at 64 MB). - Decode cache: one LRU of 16M chars instead of two 4M generations, so a rescan of a 13M-char turn hits. Snapshot A/B (3 alternating pairs, medians, load 17-64): - u738 phone+desktop push after an append: 864 -> 26.5 ms - older page re-read after an append: u738 230 -> 0.1, kdrb 108 -> 0.1 ms - phone8 after app: u738 294 -> 5.3, avim 138 -> 2.2, kdrb 32 -> 1.8 ms - summaryOnly after app: u738 42 -> 4.0, avim 23 -> 2.2 ms - CLI log after app: u738 40 -> 3.9, avim 23 -> 2.0 ms - nested after app: u738 46 -> 11, avim 59 -> 45 ms - wg5 CLI log / nested repeat (over 2 MB): 38 -> 0.3 ms - u738 walk pages 2-4: ~225 -> ~175 ms - cold latest builds: unchanged (15 samples each, within noise) Parity: 72 snapshot threads, 586 response hashes identical to main. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…n one pass Evicting one entry per insert from the front of the Map walked every tombstone left by earlier deletes, so each insert over budget cost O(evicted entries) and 600k inserts took 16 s instead of 85 ms. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
marked this pull request as ready for review
November 9, 2026 18:03
ymichael
deleted the
bb/timeline-s2-cache-keys-and-sharing-thr_curdrpgt2c
branch
November 9, 2026 18:12
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
## Human comments ## What was wrong Every prune that removed rows advanced the thread's rewrite generation and sent `history-compacted`. That threw away the server's timeline caches for the thread (response cache, selection memo, projection fold, grouping and outline state), and the app refetched the timeline and turn details, whatever kind of rows had gone. Two kinds of work were wasted: - **Usage and turn-diff snapshot prunes changed nothing the timeline reads.** `thread/tokenUsage/updated`, `thread/contextWindowUsage/updated` and `turn/diff/updated` are excluded from every timeline, outline and turn-detail query, and the snapshots the context indicator reads are kept. These prunes still caused full rebuilds and refetches. - **The settled sweep notified once per 10 s run, not once per thread.** After a turn ends, the sweep works through the thread over several runs (50 ms / 64 advances each), across four policies. Each run that removed rows sent its own `history-compacted`, so one turn end produced a burst of notices, refetches and rebuilds. Separately, any `history-rewritten` on one thread cleared the grouping-context cache for every thread. Replaying the production schedule (see below) also showed that live prunes on active threads rarely remove rows: 5 of 61–65 live calls on u738kqjs29 and kdrbtee92b. Their thread-scoped cursors crawl from sequence 0 through deltas that can't be pruned; production's kdrbtee92b deltas cursor sat at 505 of 13,030. The churn was at turn end, in the sweep. ## What changed - `packages/db/src/data/thread-pruning.ts`: `usage` and `turn-diffs` prunes no longer bump the rewrite generation. `advanceThreadPruning` now returns `rewroteHistory`. Rate-limit, delta and background-progress prunes are unchanged: they can move a window's budget floor, and in the replay they changed 1–14 windows per thread, so they still invalidate. - `apps/server/src/services/system/thread-pruning-sweep.ts`: the sweep notifies only for advances that rewrote history. It sends one `history-compacted` per (policy, thread) pass, when the pass ends, even if the pass spans several runs. A pass that fails still notifies straight away, as before. - The response-cache revision must include the rewrite generation: the client notice can now come later, so the server has to see the rewrite itself, or a read between sweep runs serves the pre-prune window. #7245 already added `rewriteGeneration` to the revision on main, so after the rebase this PR relies on it and no longer changes `timeline-cache.ts`. - `apps/server/src/services/threads/thread-timeline-windows.ts`: uses the per-thread forget below instead of clearing every thread's grouping contexts. - `apps/server/src/services/threads/timeline-context-order.ts`: `history-rewritten` now forgets only that thread's grouping contexts and ordering logs. - `docs/events-table-pruning.md`: new section on cache invalidation and notifications. No wire, CLI or SDK changes. `history-compacted` keeps its meaning; fewer of them are sent. ## How you verified **After rebasing onto main (78e0e28):** `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db` passes; the pruning, sweep, invalidation, timeline-cache and rewrite-generation test files pass (server 33, db 39). Live on a `start:worktree` server, a 60-command Codex turn (508 rows) sent no `history-compacted` for the settled sweep's token-usage prune (61 rows); the mid-turn rate-limit prune and the turn-end delta/rate-limit prunes still notified. **Replay of the production pruning schedule.** Snapshot `/tmp/tl-audit-db/bb.db` (Nov 7 10:48), in-process, on a fresh APFS clone per run. It covers the 5 busiest threads of the 27 h log window: kdrbtee92b, u738kqjs29, dwzy4aij2h, y6xhxw8t8w and pvd2eqmdcv. The snapshot is already fully pruned: a first replay over 76 threads found nothing left to remove. So the replay rebuilds what production deleted: - In the 27 h window, 74k rows created were later pruned, against 88.5k survivors. They show up as sequence holes. - Holes inside a completed reasoning, agentMessage or command item become that item's deltas, splitting the item's real final text. - Holes outside items become usage snapshots. The replay then re-appends each thread's rows in sequence order and runs the real code paths: - `pruneThreadEventHistoryBestEffort` on prod's live schedule: ≥30 s and ≥250 sequences while active. - The idle prune at each root `turn/completed`. - The real `threadPruningSweep` runs after each turn end. Reads follow production: a push every 20 rows, plus a desktop and phone refetch after every `history-compacted`. After every prune, the next served read (desktop and phone) is compared byte for byte with a build on a separate connection whose caches were cleared. 3 alternating A/B pairs (A = main, B = this branch), medians, load average 15–67 throughout because other benchmarks shared the machine: | | A (main) | B (this PR) | |---|---|---| | `history-compacted` notices (163 turn ends) | 344 [349, 344, 326] | 121 [121, 129, 121] | | notices per turn end | 2.1 | 0.74 | | rewrite-generation bumps | 275 | 156 | | served timeline build time, total | 133 s [133, 160, 62] | 63 s [68, 60, 63] | | refetch build time after notices | 44 s | 12 s | | u738kqjs29 notices / build time | 30 / 78.8 s | 9 / 32.5 s | | kdrbtee92b notices / build time | 44 / 20.9 s | 15 / 13.4 s | | dwzy4aij2h notices / build time | 126 / 12.6 s | 51 / 4.9 s | | post-prune reads ≠ fresh build | 0 of 275 | 0 of 239 | y6xhxw8t8w and pvd2eqmdcv show no clear change in build time (ranges overlap under load). B folds about 6% more events in total. All of the extra folding is phone-window reads made by the replay's own parity check: B checks quiet prunes at the next push, and the replay only pushes the desktop window. That inflates B, not production. A broader B-only parity replay (7-day window, 24 more threads with ≥1,000 events, including i2qj9tb7j3, fq6umiby2y and wg5iwwrezi) replayed 140,872 rows and 980 turn ends. All 1,031 post-prune reads equalled a fresh build. The other harness threads (avim9t7kpe, 6e9knccemi, d5ej4e2gtv, 9h3n4aiax8, dbcv9uurw7, ymhw6pktq4) had no events in that window, so the replay can't cover them. **Harness `push` scenario** (`tl-audit.test.ts`, u738kqjs29 active and kdrbtee92b): rows, bytes and folded counts are identical. Wall time stays within noise: - 5 low-load pairs with 40 appends each: u738 warm push median A 9.2–12.8 ms vs B 10.1–13.8 ms. - Bisecting the diff into its parts put every variant in the same 10.6–13.1 ms band; A itself measured 12.8 ms once. **Tests.** Each new test fails on main: - `apps/server/test/system/thread-pruning-invalidation.test.ts`: - Live usage and turn-diff prunes on an active thread keep the served window (same object) and send no notice. - A sweep pass split over runs (one advance per run) sends exactly one notice, in its final run. The served window equals a fresh build after every run, and the window does grow (it gains turn 1). With the generation removed from the revision (now on main via #7245), this test fails. - A `history-rewritten` on one thread keeps another thread's grouping context. - `packages/db/test/data/event-rewrite-generation.test.ts`: - Usage and turn-diff prunes keep the generation. - A rate-limit prune advances it. It replaces the old "usage prune advances it" case, which pinned the behavior this PR changes. - `apps/server/test/system/thread-pruning-sweep.test.ts`: - The notification tests now use rate-limit rows, since turn diffs no longer notify. - New case: a settled turn-diff sweep is silent. Commands: - `pnpm exec turbo run typecheck lint --filter=@bb/db --filter=@bb/server` - `pnpm exec turbo run test --filter=@bb/db --filter=@bb/server` (db 664 passed; server 3,944 passed, 1 skipped) **Not verified:** - No live server or app. The app-side refetch count is inferred from the notice count; the app's debounced handler was not exercised. - The replay reconstructs pruned rows. Their types are inferred from position: about 79% fall inside text items, the rest are treated as usage. Real turn-diff rows aren't represented. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
…tion The projection cache from #7245 keyed built rows by includeNestedRows only. Deferred reads now omit settled delegation children, so a CLI read after an app read could reuse rows with those children missing. The cache now keys rows by both flags; this test reads the app window and then the CLI window and checks the subagent's children survive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
…tion The projection cache from #7245 keyed built rows by includeNestedRows only. Deferred reads now omit settled delegation children, so a CLI read after an app read could reuse rows with those children missing. The cache now keys rows by both flags; this test reads the app window and then the CLI window and checks the subagent's children survive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
…tion The projection cache from #7245 keyed built rows by includeNestedRows only. Deferred reads now omit settled delegation children, so a CLI read after an app read could reuse rows with those children missing. The cache now keys rows by both flags; this test reads the app window and then the CLI window and checks the subagent's children survive. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 9, 2026
## Human comments ## What was wrong With the selection memo and projection fold both hitting, a push for one new event still ran several passes over the whole latest window (timeline perf audit, REPORT #5). On the snapshot threads the biggest were: - **Settled delegations.** Their child rows were built and mapped bottom-up, then thrown away by `deferSettledTimelineRow` (572 of 634 rows on kdrbtee92b). - **Sent-message detection.** `parseThreadTellCommand` scanned every command's text several times per build (2 MB per pass on u738kqjs29, about 14% of a push). - **Interrupted turns.** Once any turn in the window had been interrupted, every fold finish ran `structuredClone` on the whole projection state, because `pendingFinalizationByTurnId` is never cleared (6 of 150 sampled active threads, 1–1.8 ms per push). - **Decoding and byte counts.** Every row was decoded and its bytes counted again. - **Byte-budget pagination.** It ran `JSON.stringify` on every leaf, then on every returned segment. - **Tag and delta.** Every row object was fresh each build, so the tag and delta hashed and stringified all of them again. ## What changed - **thread-view.** `buildThreadTimelineFromEvents` takes a new `omitSettledDelegationChildRows` option. The server sets it when `deferContent` is on, and settled delegations then skip building their child rows. Emptiness is still checked lazily, so the output keeps the exact `null` vs `[]` that deferral produced. - **thread-view.** `parseThreadTellCommand` results are cached by command string, bounded the same way as `shellIntentCache` (16k entries, 8M chars), and every call returns a fresh object. - **thread-view.** `copyProjectionStateForFinish` deep-copies only when interrupted-turn finalization would actually change something: a running call, or a pending message or cell scoped to that turn. `interruptedTurnFinalizationChangesState` implements the check. - **server.** - `timeline-selection-decode.ts` / `timeline-selection-memo.ts`: when a selection extends the previous one, it reuses the decoded prefix and its byte count. The decoded rows live on the selection memo entry whose rows they decode, so they have exactly the memo's bounds (16 entries, 4 idle, 16M data chars) and go away wherever the memo drops an entry: thread delete, rewrite generation or `data_version` change, context-clear epoch change, and eviction. - `timeline-content-pagination.ts` / `timeline-pagination.ts`: JSON byte counts are cached per row object, and array and parent sizes are derived from their parts (exact for any UTF-8). - `timeline-window-reuse.ts`: unchanged latest-window rows, and window fields like todos and provider commands, are reused from the previous build when they serialize identically, key order included. The tag, delta and cache accounting then only touch rows that changed. `getOrBuild` now passes the stale response to the builder for this. - `timeline-selection-memo.ts`: the previous build's pageable rows, which the next build reuses rows from, live on the selection memo entry, one set per `deferContent`/`includeNestedRows` variant. Their JSON bytes count toward the memo's 16M budget along with the selection's data chars, and they go away wherever the memo drops an entry. Only rows whose JSON size pagination already measured are kept, so the size costs nothing extra (e515883). - **server, after rebasing onto #7245.** #7245's projection cache shares built rows between windows and keyed them only by `includeNestedRows`. Deferred reads now leave out settled delegations' child rows, so a CLI read after an app read could reuse the app's rows and lose a subagent's children. `timeline-projection-cache.ts` now keys rows by `includeNestedRows` and `omitSettledDelegationChildRows`. The first non-deferred read after an app read builds its own rows; the projection is still shared. In the selection memo, a selection shared by several entries counts its data once, and kept pageable rows count per entry. An entry that adopts a sibling's selection starts with no kept rows instead of sharing the sibling's map. - **No contract change.** No wire, CLI, SDK or plugin surface changes. Output is byte-identical to main. Not changed: - **Push pacing** still waits the last build's duration (capped at 1 s). Cheaper builds shorten it directly. - **Remaining u738kqjs29 cost.** Most of its remaining push cost is the fold finish over completed turn t3 (7.4k events). The window loads t3 only as context and the page doesn't return it. Removing that needs page-bounded reads (#4674 / S6), not hit-path work. - **kdrbtee92b grouping-context SQL.** About 10% of its push is still `getTimelineGroupingContext` running again whenever child (parented) events are appended. ## How you verified **Before/after.** Harness push scenario: warm latest read with `afterTag` after appending one `item/started`. In-process on a clone of the Nov 7 snapshot. 4 alternating main/branch pairs × 12 appends, load average 14–19 (other slices were benchmarking at the same time). Median of per-run medians: | thread | main ms | branch ms | Δ | |---|---|---|---| | kdrbtee92b (active) | 4.0 (3.5–4.4) | 2.8 (2.8–3.0) | −30% | | u738kqjs29 (forced active) | 15.4 (14.3–16.2) | 9.8 (9.4–10.6) | −36% | | 8nnix6m53a (forced active) | 5.9 | 3.0 | −48% | | gyi25h9awq (forced active) | 10.6 | 4.7 | −56% | | wg5iwwrezi (forced active) | 10.9 | 4.3 | −61% | | txqr3djnmd (forced active, interrupted turn) | 8.0 | 2.5 | −69% | | mwktgwihcc (forced active, interrupted turn) | 8.1 | 3.2 | −60% | An earlier round of 3 pairs at load average 37–58 showed the same direction, with −16% to −61% and much wider spread. **Memory.** The first version of this PR kept decoded selections in a separate per-connection cache: 4 per thread for 64 threads, bounded by count only, never dropped on thread delete, rewrite or idle. It retained rows the memo and the stored-event decode cache had already released. They now live on the memo entries (49f4151). Retained `heapUsed` after one instance reads the app, phone, CLI and nested windows of each thread, after a forced GC, on a clone of the snapshot: | scenario | main | c381f52 | 49f4151 | |---|---|---|---| | 12 harness threads | +63 MB | +321 MB (261 MB in the decoded-selection cache) | +67 MB | | 12 harness + 293 most recent threads | +109 MB | +295 MB | +108 MB | | 12 harness threads, forced active | – | – | +74 MB | Push and warm timings for 49f4151 vs c381f52: harness `push` + `warm`, 9 alternating pairs × 12 appends (3 of them reversed-order, 3 interleaved), load average 7–9. Median of per-run medians: | case | c381f52 | 49f4151 | |---|---|---| | warm push, kdrbtee92b | 2.5 ms | 2.4 ms | | warm push, u738kqjs29 (forced active) | 8.8 ms | 9.1 ms (last 3 interleaved pairs: 8.8 vs 8.8) | | cold after append, kdrbtee92b / u738kqjs29 | 33.4 / 207.8 ms | 34.0 / 207.4 ms | | warm cache hit, all 12 threads | 0.0–0.1 ms | 0.0–0.1 ms | Rows read, decoded and folded per push are identical, and `event-json-decode` stays under 0.1 ms on both, so the prefix is still reused. **Memory, kept pageable rows (e515883).** Before this commit the reused rows sat in a separate per-connection map of the last 32 windows. The bound was a count, and nothing dropped a thread's windows on rewrite, compaction or memo eviction. Same measurement as above. In brackets: heap freed by dropping the kept rows once the windows instance is gone. | read set | 49f4151 | e515883 | |---|---|---| | 12 harness threads | +66.5 MB (5.9) | +66.5 MB (1.0) | | 305 threads (12 harness + 300 most recent) | +108.3 MB (3.2) | +108.4 MB (1.2) | | the same 305, harness threads read last | +128.6 MB (5.9) | +112.4 MB (1.0) | | 318 threads, the 17 largest read last | +149.1 MB (14.4) | +140.3 MB (0.0) | On this branch alone the old map stayed small in the default read order, because the last 32 windows read were small threads. With the larger merged integration branch (#7250) it measured 33 MB at 305 threads. The first version of this commit charged every pageable row. That stringified the older context rows pagination never measures, and it doubled u738kqjs29's first CLI, nested and summary reads after an app read (27 → 57 ms). Keeping only measured rows removed that cost. Timings for e515883 vs 49f4151: harness `cold`, `warm`, `variants`, `capacity` and `push`. Push threads were kdrbtee92b plus u738kqjs29, wg5iwwrezi and txqr3djnmd forced active, 12 appends, 5 repeats. 4 alternating pairs, each started at load below 8 (4.3–6.3). Median of per-run medians: | case | 49f4151 | e515883 | |---|---|---| | warm push, kdrbtee92b / txqr3djnmd / wg5iwwrezi / u738kqjs29 | 1.9 / 2.05 / 3.55 / 8.6 ms | 1.9 / 2.1 / 3.6 / 8.15 ms | | cold after append, u738kqjs29 | 205.8 ms (202.5–212.5) | 210.8 ms (206.6–220.3) | | cold app latest, sum of 12 threads | 567.7 ms | 570.7 ms | | first variant read after app, sum of 48 | 782.8 ms | 788.5 ms | | u738kqjs29 CLI log after app | 26.85 ms | 27.15 ms | | capacity reopen | 19.3 ms | 19.35 ms | | warm cache hit, all 12 threads | 0.0–0.1 ms | 0.0–0.1 ms | Every rows-read, decoded, bytes and response-bytes metric is identical between the two. **Parity.** Responses were hashed on main and on the branch over a read-only clone of the snapshot: - All 947 threads with ≥1,000 events, six window variants each: app latest, phone (segmentLimit 8), CLI, nested, nested+deferred, summaryOnly. - Up to three older pages per thread. - A 13-step incremental replay on 112 threads (the 12 harness threads plus 100 sampled), app and CLI params. Each step compares warm memo, fold and row-reuse builds against a cold build at the same maxSeq, and also hashes the delta from the previous step. Result: 9,723 / 9,723 hashes identical to main, and warm equals cold at every replay step. Retained-output availability, which depends on `Date.now()`, was normalized before hashing. Re-run on 49f4151 with the same script on a fresh clone: 9,723 / 9,723 identical to main and to c381f52, warm equals cold at every replay step. e515883 vs 49f4151, using the integration's parity and append-replay scripts on fresh clones: - 162 threads × 8 variants, older pages, turn details and outlines: 4,652 forward-order and 2,462 reverse-order hashes, all identical. - Append replay over 64 thread-runs: 1,024 steps and 5,120 deltas, 0 warm-vs-cold mismatches on both. **Tests added.** I ran the `structuredClone` test against the old condition, where it fails. The others test code paths that don't exist on main, so they weren't run there. - `thread-view/test/settled-delegation-child-rows.test.ts`: omitted child rows equal deferring the full rows, including nested, childless and pending delegations. - `thread-view/test/event-projection-fold.test.ts`: fold matches cold after every event for an interrupted turn with nothing pending, and finishing does not call `structuredClone`. - `thread-view/test/tool-call-parsing*.test.ts`: cached results are independent objects, repeated parses are reused, and the existing linearity benchmarks now use unique commands so the cache can't mask them. - `server/test/services/threads/timeline-selection-decode.test.ts`: prefix reuse and byte count. The memo entry carries the decoded rows and a reused selection extends them. Decoded rows are dropped on history rewrite and thread forget, and when the memo evicts the entry for its data-char budget or its entry cap. - `server/test/services/threads/timeline-selection-decode.test.ts`, kept pageable rows (e515883). A build reuses no row objects after the memo forgets the thread. Kept rows count toward the memo budget, so a second thread of the same size evicts the first. Both tests fail on 49f4151, where the rebuilt rows are still the old objects. - `server/test/services/threads/timeline-window-reuse.test.ts`: unchanged rows keep identity across an append and serialize like a fresh build; reuse only happens on exact JSON equality, including key order. - `server/test/services/threads/timeline-content-pagination.test.ts`: derived byte counts equal `Buffer.byteLength(JSON.stringify(rows))` for nested multibyte rows. - `server/test/services/threads/timeline-window-sharing.test.ts`: the CLI window built after the app window keeps a settled subagent's child rows. It fails without the cache-key change (`[null]` instead of `[1]`). The existing sharing test now expects a row rebuild for each new row shape (`includeNestedRows` × `deferContent`). **Commands run.** - e515883: `turbo run typecheck lint --filter=@bb/server`, plus vitest on `test/services/threads` and `test/provider-corpus` (34 files, 293 tests pass, 1 skipped). All with `env -u BB_ACCOUNT_POOL_PARENT_URL -u BB_SERVER_URL -u BB_CLI`. - `pnpm exec turbo run typecheck test --filter=@bb/server --filter=@bb/thread-view --filter=@bb/provider-parity` - 49f4151: `turbo run typecheck lint --filter=@bb/server`, plus vitest on `test/services/threads/timeline*`, `thread-events`, `conversation-outline*`, `test/provider-corpus`, `event-pruning` and `internal-event-append-ownership` (25 files, 241 tests pass, 1 skipped) **After rebasing onto main at 226d128** (#7245, #7238, #7254, #7284): `turbo run typecheck lint --filter=@bb/server`, `turbo run typecheck test --filter=@bb/thread-view --filter=@bb/provider-parity`, and vitest on `test/services/threads` and `test/provider-corpus` (38 files, 312 tests pass, 1 skipped). Push harness, 4 threads × 12 appends, rebased branch vs main at be3ca2c: warm push −37% to −64%, identical response bytes (load average 12–38, so the exact numbers are noisy). Refs #4674 (does not fix it) > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
…heck cached reads against uncached builds (#7733) ## Human comments ## What was wrong The server had three thread-derived caches: the timeline window cache (`timeline-cache.ts`), the turn-details cache (`timeline-turn-details-cache.ts`) and the conversation-outline route LRU (`routes/threads/data.ts`). Each one hand-wrote the same code for slots, revisions, expiry, byte budget and LRU eviction, and each one hand-picked its key inputs. The bugs came back cache by cache: | Past fix | Shape | What went wrong | |---|---|---| | #6862 (outline route LRU) and #7034 (timeline cache) | revision baked into the LRU key | The same bug in two caches, fixed three days apart. Dead revisions filled the slots and evicted idle threads. | | #7245 | missing input | The timeline revision lacked `rewriteGeneration`, so a gap-filled event below the head was served stale. | | #7245 | too-specific input | Older pages were revisioned on the head `maxSeq`/status, so every append rebuilt them. | | #7297 H1 | missing input | No clock deadline: windows kept saying `available` after an output's retention deadline. | | #7297 H2 | missing input | `extensionStateKinds` was missing, so a provider update declaring a state kind kept serving `extensionStates: {}`. | | #6844 | wrong input lifetime | The stored outline row is keyed on the in-memory rewrite generation, which resets on restart. | The new table found a live instance of the #6844 shape on main. #6844 only made the rewind path drop the stored outline row. The other three paths that bump the generation still left it in place: gap-fill inserts below the high-water mark, non-preserving prunes, and completed-output migration. If any of them ran on an idle thread and the server restarted before the next outline read, the generation reset to 0, the old row's key matched again, and the outline served pre-rewrite items. Background: the C11 section of the cache-key class analysis (bb thread `thr_qchecuan6n`, `verify/data.md`). ## What changed **One cache owner.** `apps/server/src/services/threads/thread-derived-cache.ts` adds `createThreadDerivedCache({ maxEntries, bytes })`. `getOrBuild({ slot, revision, threadId, build })` keeps one entry per slot (the request shape). An entry is served while its revision matches and `Date.now() < expiresAt`. Otherwise it is rebuilt from the previous value and replaced. The cache also handles an optional byte budget, LRU eviction and `invalidateThread`. Because slot and revision are separate required fields, the #6862/#7034 mistake can't be written without visibly putting the revision into the slot. - Timeline windows: `createThreadTimelineWindowCache()` (same 512 entries / 64 MB / 8 MB). The 102-line copy in `timeline-cache.ts` is deleted; the key and revision builders stay. - Turn details: still one cache per DB connection. The 62-line hand-rolled LRU is replaced, and the clock is read inside the projection. - Outline route: replaces the `Map` + manual LRU (`CONVERSATION_OUTLINE_CACHE_MAX_ENTRIES`). Slot is the thread id; revision is `[dataVersion, projectionKey]`; 128 entries with no byte budget, as before. **Stored outline fix (`@bb/db`).** `bumpThreadEventRewriteGeneration(db, threadId)` now deletes the thread's `thread_conversation_outlines` row in the caller's transaction. All four rewrite paths get the fix from one place, and the special-case delete #6844 added to `deleteThreadEventSuffixInTransaction` is gone. In-process, a bump already made the stored row unreadable because its key embeds the generation, so this only changes what a restarted server sees. **Test-only hook.** `@bb/db/testing` exports `forgetThreadEventRewriteGenerations()`. A process restart resets the in-memory generation, and nothing else can model that in one process. It is not exported from `@bb/db`. **Deleted patches and tests.** - #6844's hand-placed outline delete in the rewind path. - #6862's hand-written outline LRU. - #7034/#7245/#7297's hand-written timeline LRU/expiry/bytes code, and the turn-details copy of it. - The circular `buildThreadTimelineCacheKey`/`buildThreadTimelineCacheRevision` "differs for every argument" tests. They could not catch an input the builder never received; the route table does. - The #6844 db test. It is now one row of the db rewrite table (see below). No wire, CLI, SDK or plugin API changes. ## The guard Five test files run every row against every thread-data surface: - `apps/server/test/helpers/thread-derived-cache-table.ts` holds the fixture, the surfaces and the row runner. - `apps/server/test/public/thread-derived-cache-equivalence.test.ts` holds the hand-written rows (history, clock, restarts), the route coverage check and the eviction rows. - Generated rows live in `thread-derived-cache-equivalence-settings.test.ts`, `-thread-columns.test.ts` and `-provider.test.ts`. **Uncached build.** The cold side runs the same `registerThreadDataRoutes` routes, with the app's error handler, over a serialized copy of the database with stored outline rows deleted. That gives it no in-memory caches, nothing persisted, and the same provider registry. **Surfaces come from the routes.** `THREAD_DATA_ROUTE_SURFACES` maps every GET route that `registerThreadDataRoutes` registers to one or more requests, or to an exclusion with a reason. A test reads Hono's registered routes and fails if a route has neither, so a new data route can't skip the table. - The requests cover: plugin metadata, context, head state, and the timeline as the latest window (deferred, with content, with nested rows) and as an older page. - They also cover: the conversation outline (all roles and `role=user`), a message with its neighbours, turn details, output, queued messages, prompt history, events, event wait and default execution options. - Only the three thread-storage routes are excluded. They read the host over RPC and use no derived cache. **Push surface.** A subscriber is attached to the WebSocket timeline push with the tag of the window it holds, which is how real clients subscribe. After the change the server is nudged with `events-appended`. The subscriber's window, with pushed deltas applied, must reach the uncached build. A deleted thread is skipped: it 404s and the server stops pushing. **Rows come from the input sources.** Each source is a compile-time exhaustive map: `{ [K in keyof X]-?: change | { excluded: reason } }`. A new key does not compile until it has a row or a stated exclusion. Boolean settings and boolean capabilities are the exception: their rows are generated (flip the value), so adding one needs no test edit. Only non-boolean fields need a hand-written change. - **Settings:** all 20 `AppSettings` keys. The 12 booleans come from `defaultAppSettings`; the 8 others have a hand-written change. - **Experiments:** all 13 `experimentKeys`, iterated directly. - **Thread columns:** all 28 `threads` table columns. A runtime check compares the map against `getTableColumns(threads)`. Only `id` is excluded. - **Provider declaration:** all 21 `PluginProviderDeclaration` fields plus all 8 capabilities. The 5 boolean capabilities come from the base declaration; the other 3 have a hand-written change. Only `id` is excluded; the `providerId` column row covers switching providers. - **Hand-written rows:** an appended event, events filled in below the head (inside a turn and between turns), the clock passing a retained-output deadline, and two server restarts. The restarts happen after a rewind that reuses sequences and after a gap fill, each on an idle thread whose stored outline was already written. Hand-written rows assert that the uncached output changed. Generated rows don't, because most settings and columns don't affect these surfaces. Each generated row asserts that its change differs from the starting value. **Fixture.** It is built so every cache-key input is observable: - an active thread with an open `/plan` turn, so the plan command shows; - context-window and token usage, with `compactExpiredCache` and `supportsManualCompaction` on, so the compaction offer shows; - a context clear; - retained command outputs in a collapsed turn and an open turn; - file changes under the workspace root; - diagnostic provider events and turn-scoped ownership rows in both turns; - a goal extension state; - one hole inside turn 1 and one between turns. **Eviction rows.** These check that entries which are still current stay cached. A hit is detected by counting prepared statements, after first checking that a hit prepares fewer statements than a miss. - An idle thread's window, turn details and outline survive another thread churning through 520 revisions (more than the largest cache's 512 entries). The window and outline rows churn by renaming the other thread, so its history stays small. Turn details churns by appends, because the title is part of its slot. - An older timeline page survives an append. 98 tests, about 15 s of test time across four files locally. `packages/db/test/data/event-rewrite-generation.test.ts` already listed every rewrite path: suffix delete, three prune policies, output migration and gap fill. Each row now also checks that the stored outline is dropped exactly when the generation bumps, and the cross-thread row checks that other threads keep theirs (the part of the deleted #6844 test the table did not cover). Removing the drop fails 6 of its 9 tests. ### Every cache-key input, dropped one at a time On this branch, I deleted each input from each cache key or revision in turn and ran the four files: | Key | Inputs whose removal a row catches | Inputs no row catches | |---|---|---| | Timeline surface (`resolveThreadTimelineSurface`) | `includeClearedContextHistory`, `includeDiagnosticOperations`, `providerDisplayName`, thread name, `workspaceRoot`, `completedTurnDisplay`, `summarizeShellCommands`, `planCommand`, `compactionOfferEnabled`, `extensionStateKinds` | `includeNestedRows` and `deferContent` (also in the slot); `maxInlineOutputChars` (a constant) | | Latest-window revision | `rewriteGeneration`, `maxSeq`, `status`, `surface` (13 rows) | none | | Older-page revision | `rewriteGeneration`, `surface` (9 rows) | none | | Turn-details surface | `includeDiagnosticOperations`, `providerDisplayName`, title, workspace root, `completedTurnDisplay`, `summarizeShellCommands` | `turnId`, `itemId`, `deferContent`, `sourceSeqStart`, `sourceSeqEnd` (the request shape; the surface is the slot) | | Turn-details revision | rewrite generation | none | | Outline projection key | rewrite generation, `outlineSequence`, `includeClearedContextHistory` | `providerId`, `providerDisplayName`, `status`, `title`, `titleFallback`, `completedTurnDisplay` | | Outline route revision | (projection key, above) | `dataVersion` | | `createThreadDerivedCache` | the expiry check | none | What the uncaught inputs mean: - **Request shape:** these parts are also in the slot, so dropping them from the surface or revision can't make a read wrong. At worst two shapes share a slot. - **Outline projection key:** the outline's output doesn't change with any of these six inputs, under any row. They only cause rebuilds. This is the over-specific key in #7399 (status and title), plus four more inputs; I left it for that fix. - **`dataVersion`:** it only moves when another connection writes, and the server writes through one connection. The test database is in memory, so no row can produce that change. The reviewer's case is now caught: dropping `includeClearedContextHistory` from the timeline key fails the latest window, and dropping it from the outline key fails the outline. Both are caught by the `keepHistoryAfterContextClear` setting row. ### The table catches each past fix on its pre-fix code Each fix's source change was reverted on main (before this PR's refactor, with the table and the db fix in place), and the table was run: | Reintroduced bug | Rows that fail | |---|---| | #7297 H1: no expiry check in the timeline cache | after the clock passing a retained-output deadline | | #7297 H2: `extensionStateKinds` dropped from the surface key | after a provider update that declares a new state kind | | #7245: `rewriteGeneration` dropped from the revision | after an event filled in below the head (now "events filled in below the head") | | #7245: older pages revisioned on `maxSeq`/status | keeps an older timeline page across appends | | #7034: `maxSeq` in the timeline cache key | keeps an idle thread's latest window while another thread streams (first churn version); keeps an older page across appends | | #6862: outline LRU keyed by the revision key | keeps an idle thread's conversation outline while another thread streams | | #6844: rewind no longer drops the stored outline | after a server restart after a rewind that reuses sequences; after a server restart after an event filled in below the head | | this PR's fix removed (main as shipped) | after a server restart after an event filled in below the head | That table was run on main before the refactor, with the first version of the guard. On the final guard and the refactored code, the same shapes are caught, as rows of the key matrix above: - Window revision inside the slot (#7034): fails "keeps an idle thread's latest timeline window". - Outline revision inside the slot (#6862): fails "keeps an idle thread's conversation outline". - Generation bump that keeps the stored outline (#6844 and the gap-fill bug): fails both restart rows. - Helper expiry check removed (#7297 H1): fails the clock row. - `extensionStateKinds` dropped (#7297 H2): fails the `extensionKinds` provider row. - `rewriteGeneration` dropped (#7245): fails the gap-fill row. ### What the shared owner would have prevented - #6862 and #7034: one implementation instead of two, with slot and revision as separate fields. Table 2 catches a regression in any of the three caches. - #7245 (generation), #7297 H1/H2 and the gap-fill/restart bug fixed here: each is a Table 1 row, so they would have failed before merge instead of being found in audits. - #6844 and the gap-fill/prune/migration paths: one drop in the generation bump instead of a per-path delete. ## Decisions for review - **Stored outlines after a prune or output migration.** Those paths now drop the stored outline row. The first outline load after a restart rebuilds that thread's outline instead of reading the row. In-process nothing changes, because the row's key already stopped matching after the bump. The user-visible effect is a fix: after a restart, the outline no longer shows items from before a gap-fill rewrite. - **Caches left on their own code.** `createThreadDerivedCache` serves a stored value when its revision matches. None of the remaining same-class caches works that way. Each one extends earlier work or shares it, and moving it onto the helper would throw away the incremental reuse that #7245 and #7541 measured: - `latestThreadStateCaches` (`packages/db/src/data/events.ts`) is a scan checkpoint per thread and kind. It is batched across many thread ids, and even a valid entry still scans newer events from `scannedThroughSequence`. It also lives in `@bb/db`, below the server package. It feeds head state, the runtime display and session options; the head-state, context and timeline surfaces reach it in every row. - `timeline-selection-memo.ts` shares row arrays between sibling windows, with a reference-counted character budget and active/idle eviction. A narrower window adopts a wider sibling's selection, or trims it (#7245). - `timeline-projection-fold.ts` resumes a fold when the new rows extend the kept rows, which is a prefix check, not a revision match. - `timeline-context-order.ts` has two caches. Ordering-context logs are extended up to `maxSeq`. Grouping contexts keep up to 4 entries per key, reused within a 1,024-sequence span. - `timeline-projection-cache.ts` is a `WeakMap` keyed by the selected row array, so an entry lives exactly as long as the memo's rows. It has no LRU. - `conversation-outline-cache.ts` extends an incremental outline checkpoint with new events. - Excluded as delta baselines: the served-windows cache and `lastPushedByTarget`. All of these are now reached by every row through the routes and the push. #7331's summary memo, still open, is a revision-equality memo and can use `createThreadDerivedCache` when it lands. ## How you verified - Guard: 98/98 pass across the four files. The key-drop matrix (45 cases) is above. - `pnpm exec turbo run check:query-costs --filter=@bb/db` passes, with a new case for `bumpThreadEventRewriteGeneration`. - `pnpm exec turbo run typecheck --filter=@bb/server --filter=@bb/db` and `lint:type-aware` (0 warnings), plus `oxfmt --check` on the changed files. - `pnpm exec turbo run test --filter=@bb/server -- test/public/thread-derived-cache-equivalence test/services/threads/ test/public/public-thread-data.test.ts test/public/public-thread-timeline-push.test.ts`, after merging main (#7541's equivalence and read-cost guards are in `test/services/threads/`): 572 tests pass. - `pnpm exec turbo run test --filter=@bb/db -- test/data/events.test.ts test/data/event-rewrite-generation.test.ts test/data/thread-pruning.test.ts test/data/resolved-item-pruning-resume.test.ts test/data/sweeps.test.ts`: all pass. - Real restart, two processes over one on-disk database (save the outline of an idle thread, fill a missing turn into a gap below the head, restart, read the outline). On main the restarted server serves 4 items, without the filled-in turn, while an uncached build has 6. On this branch it serves the same 6 items. - After generating the boolean rows (6cfad40): `pnpm exec turbo run test --filter=@bb/server -- test/public/thread-derived-cache-equivalence test/services/threads/thread-derived-cache.test.ts` (105 pass), `@bb/db`'s `test/data/events.test.ts` and `test/data/event-rewrite-generation.test.ts` (111 pass), plus typecheck and lint for `@bb/server` and `@bb/db`. Mutation checks on that head: - `summarizeShellCommands` dropped from the timeline key: fails the generated `summarizeShellCommands` setting row. - `compactionOfferEnabled` dropped from the timeline key: fails the generated `capabilities.supportsManualCompaction` row. - the generation bump without the outline delete (main's behaviour): fails both restart rows. - the outline delete without its thread filter: fails the cross-thread db row. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
Timeline window caches were keyed on the request's page shape and on the thread head, not on what actually determines the output. The selection memo was keyed by
segmentLimit. So the phone (8) and desktop (20) windows each ran their own SQL selection, decode and projection, even when both started at the same sequence. On a giant-turn thread the two ~13M-char selections could not both fit the memo's 16M-char budget: with phone and desktop both watching, every push evicted the other entry and rebuilt both windows from SQL. summaryOnly, CLI log and nested reads shared the selection but re-ran the whole projection. In the response cache, older pages used the currentmaxSeq/status as their revision, even though their content is fixed by the cursor's snapshot, so every append on an active thread invalidated them. No revision carried the rewrite generation, so an event gap-filled below the head (samemaxSeq) was served stale.thread-deletednever dropped cached windows. Windows over 2 MB were never cached. The decode cache's two 4M-char generations thrash on a rescan of any turn larger than one generation (the largest recent turns are 11–13M chars).What changed
timeline-selection-memo.ts: a narrower window adopts a wider sibling's selection (same thread, budget, epoch, head and generation) when its computed start equals the sibling's. If the start is later, it trims the sibling's rows in memory instead of running SQL. A wider window whose start equals a narrower sibling's adopts that selection too. Row arrays shared between entries count once against the char budget. A memo hit with no appended rows keeps the same row array.timeline-projection-cache.ts(new),timeline.ts: the projection is cached per selected row array (aWeakMap, so it lives exactly as long as the memo's rows). The event projection is shared acrossdeferContent,summaryOnlyandincludeNestedRows, and rows are materialized perincludeNestedRows. Output after projection (previews, deferral, pagination, shortening, tag) is still computed per request.@bb/thread-viewnow exportsprojectThreadTimelineEventsandbuildThreadTimelineFromProjection;buildThreadTimelineFromEventscomposes them. Profiles have a newthread-view-rowsstage for materialization.timeline-cache.ts,thread-timeline-windows.ts: revisions include the rewrite generation. Older pages are revisioned on generation and surface only, because the anchor id in the key already encodes the cursor snapshot.thread-deletedinvalidates the thread's windows. The per-entry cap is now 8 MB (was 2 MB). The 64 MB total is unchanged, and cached responses measured 1.3–1.6× their JSON size in heap.stored-event-decode-cache.ts: one LRU of 16M chars replaces two 4M-char generations, so a rescan of a turn up to 16M chars hits. Once the cache goes over either cap, it evicts the oldest entries down to 90% of both caps in one pass. Evicting one entry per insert from the front of theMapwould walk every slot deleted before it (V8 keeps deleted slots until the next rehash): 600k inserts take 14.6 s that way and 82 ms with batch eviction.No wire, CLI or SDK changes. Every response is byte-identical to main (parity below).
How you verified
Benchmarked on a prod snapshot clone with the shared in-process harness (cold/variants/walk/push) plus S2 scenarios (older pages after an append, phone+desktop push, parity, memory). Three alternating base/new pairs, medians of medians. Load average was 17–64 because other benchmarks shared the host; row and parity metrics are deterministic.
The extra heap is mostly the decode cache (16M vs 8M chars, about 3.1 heap bytes per cached char when it holds the only copy of the row data).
Parity. On 72 snapshot threads (the 12 harness threads plus 60 threads with ≥1,000 events), each of 6 variants (app, summaryOnly, CLI log, nested, phone8, CLI log at segment limit 100) was built cold, plus the latest and up to three older pages. All 586 response hashes, including rows, tags and cursors, are identical to main. On this branch, 1,008 reads in two warm sharing orders (wide first and narrow first) each equal the cold build. After appends, the older-page and phone/desktop scenarios showed zero mismatches against fresh builds.
Decode-cache eviction (23d0283, found by the integration branch #7250). Per-insert front eviction made the
capacityscenario (one instance opens 712 threads, then re-reads them) 14–17% slower than main. Harnesscapacity,cold, 9 repeats, three alternating pairs on fresh snapshot clones, load 4–8:The PR's other bounded
Maps are fine. The response cache (512 entries) and the selection memo (16 entries) also evict from the front, but at those sizes 600k inserts take 108 ms and 49 ms (vs 45 / 44 ms with batch eviction). Both predate this PR. The projection cache is aWeakMapwith at most 4 entries per selection.Parity of the fix: the 162-thread parity replay (12 harness threads plus 150 sampled threads with ≥1,000 events, 8 latest variants, older pages, repeats, turn details, outline), with one connection per arm so the decode cache evicts. All 4,652 response hashes are identical between dc75c40 and 23d0283 (and against a second dc75c40 run). The 8 errors are the same on both arms: details requests for 2 turns that the route rejects on main too.
Tests (they fail on main, pass here):
test/services/threads/timeline-window-sharing.test.ts: a gap-filled event below the head is served. Older pages stay cached while the thread grows and are rebuilt after a rewrite. Phone reuses desktop's selection and projection. summaryOnly, CLI and nested reuse the app's projection.thread-deleteddrops cached windows. All 5 fail on main.stored-event-decode-cache.test.ts: a rescan of a turn at 75% of the cap hits on every row. Going over the cap evicts down to 90% at once, so the next inserts evict nothing; this one fails on dc75c40 (expected 15987023 to be less than or equal to 14400000).timeline-cache.test.ts: older-page revision ignores the head and includes the generation; a 3 MB window is cached by default.timeline-selection-memo.test.ts: the randomized warm-equals-cold replay also builds a narrower window before and after the wider one.Commands:
pnpm exec turbo run typecheck lint --filter=@bb/server --filter=@bb/thread-viewpasses.pnpm exec turbo run test --filter=@bb/server --filter=@bb/thread-view: thread-view 510/510; server 3,947 passed and 1 failed, intest/app/install-machine-script.test.ts. That file also fails on main on this host (a different test each run, timing under load) and is unrelated.🤖 Generated with Claude Code