Repository navigation
Keep one timeline cache revision per request shape - #7034
Merged
Merged
Conversation
Key the timeline response cache by request shape and store the maxSeq each entry was built at, so a streaming thread replaces its own entry instead of evicting idle threads' windows. Fixes get-bb#2066 Co-Authored-By: Claude Opus 5.5 <[email protected]>
The cache key still carried the thread's status and surface (title, workspace and display settings), so a turn starting or ending, a generated title or a settings change left the previous entry behind until LRU eviction. The key now holds only the request shape (thread, page, summaryOnly, deferContent, includeNestedRows) and the revision stamp holds maxSeq, status and surface, so each request shape keeps exactly one entry. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 4, 2026
## Human comments ## What was wrong The timeline response cache skipped every window over 200 rows. Row count is a poor proxy for size: on a live database, the latest window of 72 of the 150 most recently updated threads was over 200 rows (Claude Code's finished turns stay flat, so one busy turn gives 140 command rows), while those windows were only modestly larger, median 318 KiB and at most 732 KiB, against 130 KiB for the cached ones. Switching back to any busy thread therefore always rebuilt its window. Follows #7034. ## What changed `apps/server/src/services/threads/timeline-cache.ts`: - A window is cacheable up to 2 MiB, measured with `timelineWindowJsonLength`, the same measure the served-windows cache uses. It reads the row digests `timelineWindowTag` already computed, so measuring adds no serialization. - The cache holds at most 64 MiB in total and evicts least-recently-used entries past it. - With bytes bounding memory, the entry limit rises from 128 to 512. Once busy windows are cacheable, a rotation of more than 128 threads otherwise evicts every entry just before it is reopened (measured below). ## How you verified - Tests: a 500-row window is cached, a window over the entry byte limit is not (and drops the stale revision), the total byte budget evicts the least-recently-used entry, and byte accounting stays exact across revision replacement and invalidation. Removing the byte subtraction fails three of them. - Benchmark on a `VACUUM INTO` copy of a live database (8.4 GB): `createThreadTimelineWindows().read` for the latest window (`deferContent`, as the app requests) of the N most recently updated threads, once cold, then three reopen passes. | threads in rotation | instant reopens, row limit | instant reopens, this PR | total reopen time | |---|---|---|---| | 30 | 20 / 30 | 30 / 30 | 223 ms → 4 ms | | 100 | 54 / 100 | 100 / 100 | 1,054 ms → 17 ms | | 150 | 77–81 / 150 | 150 / 150 | 1.5–3.1 s → 27–33 ms | - With a 128-entry limit the 150-thread rotation dropped to 2–4 instant reopens out of 150, which is why the entry limit rises. - Heap after a forced GC with all 150 threads cached: 191 MiB with the row limit, 217–223 MiB with this PR, about 30 MiB more, matching the measured JSON size of the windows. - `pnpm exec turbo run typecheck lint --filter=@bb/server`, and the server `test/services/threads` and `test/public/public-thread-timeline*` suites (38 files, 343 tests) pass. > 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
The timeline response cache keyed entries by
maxSeq, so every new event left a dead entry behind. One streaming thread fills the 128 slots with revisions nobody can hit again and evicts every idle thread. Switching back to an idle thread then rebuilds its window from scratch. The key also carried the thread's status and surface (title, workspace and display settings), so a turn starting or ending, a generated title or a settings change left the previous entry behind as well. Tracked in #2066.What changed
apps/server/src/services/threads/timeline-cache.ts,thread-timeline-windows.ts:summaryOnly,deferContent,includeNestedRows.maxSeq, status and surface. A request with the same stamp hits the cache; anything else rebuilds and replaces the entry, so each request shape keeps exactly one entry.How you verified
timeline-cache.test.ts: a maxSeq advance replaces the entry, a status or title change replaces the entry, an idle thread stays cached while another thread streams revisions, and the stale revision is dropped when the rebuilt window is not cacheable. The key and revision builders each differ for every one of their inputs./api/v1/threads/:id/timeline, seeded DB): 6 idle threads were opened, then another thread appended N events with a timeline read after each, then the idle threads were reopened. Median idle reopen:pnpm exec turbo run typecheck lint --filter=@bb/server, and the servertest/services/threadsandtest/public/public-thread-timeline*suites (38 files, 341 tests) pass after merging current main.Fixes #2066
🤖 Generated with Claude Code