Skip to content

Read finished collapsed turns through one stored per-turn summary (alternative to #7247) - #7331

Closed
ymichael wants to merge 4 commits into
mainfrom
bb/per-turn-summaries-for-collapsed-turns-reshaped-thr_v5rh98dc7y
Closed

ymichael wants to merge 4 commits into
mainfrom
bb/per-turn-summaries-for-collapsed-turns-reshaped-thr_v5rh98dc7y

Conversation

@ymichael

@ymichael ymichael commented Nov 10, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A finished turn under the collapse display (Codex's default) shows one or more "Worked for" summary rows plus the messages that stay visible. Working that out needs the whole turn projected, so every timeline page that touched such a turn read and projected all of its events: avim9t7kpe's 6-row latest page read the whole 5,888-event turn. The conversation outline could not afford that, so it read only messages, tool calls and background tasks and guessed which agent messages a collapsed turn shows. It cannot see the commands, edits, reasoning or plan updates between two agent messages, so in collapse mode it over-lists. On the Nov 7 snapshot, 800 sampled threads list 69,384 collapse-mode outline entries where the collapsed timeline shows 22,533. Clicking an over-listed entry looks for a row that is not on screen.

This is the alternative to #7247 (now closed). #7247 stored a plan only for turns of 1,000+ events, only after a first whole read, and kept the whole-turn read as a second path.

What changed

One stored summary per finished collapsed turn. Timeline pages and the outline both read finished collapsed turns through it.

  • thread_turn_summaries (migration 0157, one row per thread and turn) holds the turn's summary rows with their counts, status and times, its external user boundaries, its turn/started sequence, and the id and source range of each message it shows ungrouped. It also records the turn's background tasks, delegations and still-open tool calls, and the nested turns its delegations pulled in. Each row stores the sequence it was last validated through.

  • Read path (selectTimelineTurnRows in timeline.ts): when a page under the collapse display touches a summarized finished root turn, it reads only that turn's lifecycle, accepted-input, compaction, provider and error rows, the events of the messages it shows, its open items and related nested turns. The summary rows come from the record (planTimelineRows in @bb/thread-view). The flat display, running turns and includeNestedRows reads still read turns whole.

  • When summaries are written: there is no background job.

    • The push that completes a watched turn stores the summary from the projection it already holds.
    • A page that finds no summary for a finished turn reads that turn whole, even when its window only partly covers it. It also reads the thread-scoped approval, permission and question lifecycle rows inside the turn's span, and stores the summary from its own projection. Each turn is projected once.
    • Older turns get their summary on the first page read that reaches them.
  • Staleness: a read checks only the events appended since the summary was validated, using events_thread_sequence_idx. A summary is stale when one of those events belongs to the turn or names one of its recorded items as its item or parent. Background tasks and delegations finish after their turn, so they are always recorded. Validated summaries are kept in memory per connection (64 threads, 16M chars). The key holds the summary version, the context-clear boundary and the diagnostic-events setting.

  • Rewrites: suffix deletes, and inserts below the high-water mark, delete the thread's summaries and stored outline in the same transaction, so a restart cannot serve either. Pruning does not touch them: since Stop pruning from making apps refetch, and keep older cursors valid after pruning #7284 it only removes rows the timeline never displays.

  • Selection memo: if an event arrives for a summarized turn, the next push selects again with that turn read whole. Later events then extend the kept selection.

  • Outline: under the collapse display it reads the same summaries, so it lists exactly the collapsed timeline's messages. It no longer reads background tasks. What I kept for turns without a summary:

    • main's existing rule, unchanged: list every agent message not followed by a tool call;
    • a bounded build of missing summaries, at most 2,000 sequences of turns per load, through the same selection code. It costs at most about 11 ms per load (table below).
    • An outline that still has unsummarized turns is not cached or persisted.

    Flat mode and running turns are unchanged. The route passes showDiagnosticEvents, so the outline and the app share summaries. Outline projection version 2 → 3.

Not in this PR: windowed reads of flat and running turns, and grid cuts inside long running turns. Those are in #7327 (see the combination test below). No wire or cursor change. Docs: docs/timeline-pagination.md has a new "Collapsed turn summaries" section and an updated outline caching section.

How you verified

All runs are in-process against an APFS clone of the Nov 7 production snapshot (/tmp/tl-audit-db), migrated first. No server was started.

Parity with main (9cc701a). Main's timeline and this branch's timeline give identical merged rows on every walk, and olderRowsSourceSeqEnd matches on every page. Two passes were run: the first with nothing stored and in forward order, the second with the summaries the first pass stored and in reverse order.

  • 14 heavy threads, app/CLI/nested/phone/active variants: 140/140 walks
  • 104 Codex threads, app/CLI/phone/active: 832/832 walks
  • every 8th thread over 1,000 events, app/CLI/nested/active: 952/952 walks
  • 1,924/1,924 in total

Outline equals the collapsed timeline. Each sampled thread's collapse-mode outline was compared with an outline built from all of its events (1,600 outlines, 800 threads × collapse/flat):

  • this branch: 1,596/1,600 identical, and 22,533 collapse entries against 22,533 in the truth outline
  • main: 800/1,600, with 69,384 collapse entries against 22,533

The 4 mismatches are a user-seed id quirk that main shows the same way in flat mode.

Turn-end capture: on 108 Codex threads, the completing push stored the summary for 106. The other 2 are steered turns that the kept page covers only partly, so the next read stores them. All 108 summaries, and the responses, are identical to a fresh build.

Combination with #7327 (495f17e), merged locally and not pushed:

Timing: median of 3 alternating rounds (main / #7247 / this PR, with the order rotated each round), 3 repeats per round. Each read is a fresh connection, in ms unless labelled. "This PR" starts from the database the parity passes left, so the summaries present are the ones written by reads. The load average was 9–29 during the rounds.

case main #7247 this PR
cold latest, avim (Codex) 104 12.4 12.7
cold latest, 9h3n (Codex) 16.8 18.1 13.3
cold latest, gtbh (Codex) 12.8 12.1 12
cold latest, kbjz (Codex) 34.1 40.3 26.7
cold latest, u738 (Claude, flat) 132 26.4 132
cold latest, d5ej (Claude, flat) 33.6 32.9 34
first read, nothing stored, avim 93.2 112 114
first read, nothing stored, kbjz 34.6 40.1 35.1
first read, nothing stored, gtbh 12.5 12 14.4
first read, nothing stored, 9h3n 16.4 18.1 18.1
phone after app, avim 2.9 9.5 0.9
phone after app, u738 4 17.1 4.2
CLI log after app, avim 3.4 0.7 1.1
nested after app, avim 30 135 119
nested after app, kbjz 7.9 12.6 30.5
app walk, avim 155 14.7 15.4
app walk, 9h3n 127 52.2 37.5
app walk, gtbh 1,174 1,099 749
app walk, kbjz 544 624 308
app walk, u738 400 317 404
app walk, d5ej 1,695 1,940 1,860
thread log --all, avim 149 15.3 15.4
thread log --all, gtbh 1,034 1,087 749
thread log --all, kbjz 500 579 275
thread log --all, u738 778 746 832
thread log --all, d5ej 3,136 4,113 3,038
push into finished turn, warm, avim 4.6 6.9 5
push into finished turn, cold, avim 107 11.9 12.8
push into finished turn, warm, 9h3n 2.7 2.3 2.5
push warm, u738 active 10.3 1.8 9.6
push cold, u738 active 131 22.8 130
push that completes the turn, avim 6.6 110 6.2
push that completes the turn, kbjz 3.5 4.3 5
push that completes the turn, gtbh 4.1 2.9 4.7
turn details, 6e9k 4.4 1,683 4.5
turn details, avim 0.7 698 0.7
outline cold (no stored outline), 6e9k 32.6 30.5 30
outline cold, gtbh 51.3 50 49
outline cold, kbjz 28.1 31.3 29.5
outline cold, d5ej 160 164 120
outline active reload, 6e9k 1.2 25.2 1.2
outline active reload, gtbh 12.8 12.5 13.7
outline active reload, kbjz 22.6 23.4 22
outline active reload, d5ej 89.8 127 64.2
outline first load, nothing stored, 6e9k 31 30.3 28.4
outline first load, nothing stored, gtbh 48.4 48.5 53.3
outline first load, nothing stored, kbjz 27.9 28.2 39.3
outline first load, nothing stored, d5ej 156 146 110
SQL rows, cold latest avim 5,897 49 27
SQL rows, cold latest kbjz 2,166 2,177 1,263
walk rows read, avim 11,777 73 37
walk rows read, kbjz 31,752 30,812 9,473
retained heap MB (14 threads walked) 129 87.9 108

Things the table can't show:

  • First read with nothing stored (avim 114 vs 93 ms) has to be read in-process. That case runs right after the stored-summary case, so its first sample is the first whole-turn decode in that process (168–185 ms in this PR). With warm-up excluded, in-process over 10 repeats: avim 95.6/96.9 ms against main 95.5/92.6, kbjz 12.7/12.3 against 11.6/12.2, 9h3n 7.0/7.1 against 6.1/6.4. The difference is the one summary write (turn-summary-store: 0.6 ms on 9h3n, 0.9 ms on kbjz, 2.5 ms on avim).
  • Flat walks (d5ej, u738) read the same rows and pages as main. In a separate quiet A/B, their medians match main apart from single-page outliers in individual rounds.

One-time costs that remain:

  • A finished turn's first read writes its summary: 0.6–2.5 ms, once per turn. For turns that finish while watched, the write happens in the completing push: +0.5–1.5 ms on kbjz/gtbh, once per turn.
  • includeNestedRows reads (bb thread log --format verbose) can no longer reuse the app's selection, because that selection no longer holds whole turns. The first such read after an app read is a cold whole-turn read: avim 119 ms vs 30 ms on main, kbjz 30.5 vs 7.9. Repeats of that read are unchanged (0.2 / 0.6 ms on both).
  • The outline's first load on a thread with unsummarized turns builds up to 2,000 sequences of them (kbjz 39 vs 28 ms, gtbh 53 vs 48). Later loads are faster than main or match it.
  • Nothing backfills old turns. Until a page reads an old turn or the outline builds it, the turn is read whole as on main, and the outline lists it by main's rule.

Code size against origin/main, excluding drizzle snapshot JSON:

Tests

  • New: timeline-turn-summaries.test.ts, 9 cases. Each fails with its change removed (checked by mutating the code). They cover:
    • the outline equals the collapsed timeline
    • a late background task
    • a gap-fill rewrite plus restart
    • a suffix rewrite that reuses the turn id
    • turn-end capture
    • the outline's existing rule plus filling across loads
    • late events absorbed into a kept selection
    • a first page that only partly covers a turn storing that turn's summary
    • the validation sequence being written back after 1,024 checked events
  • Commands, all passing:
    • pnpm exec turbo run typecheck lint lint:type-aware --filter=@bb/server --filter=@bb/db --filter=@bb/thread-view
    • pnpm exec turbo run test --filter=@bb/db --filter=@bb/thread-view: 710 + 544
    • server test/services/threads and test/routes/threads: 320

Refs #4674

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 3 commits November 16, 2026 19:45
A finished turn under the collapse display is now read through a stored
summary (thread_turn_summaries): its "Worked for" rows, external user
boundaries, turn/started sequence, and the id and source range of each
message it shows. Timeline pages read only the turn's lifecycle rows, the
events of the messages it shows, its open items and related nested turns.

A page that has no summary for a finished turn reads it whole, even when
its window only partly covers the turn, and stores the summary from its
own projection. The push that completes a watched turn stores it from the
projection it already holds. Nothing fills summaries in the background.

The conversation outline reads the same summaries, so in collapse mode it
lists exactly the collapsed timeline's messages, and it no longer reads
background tasks. It builds missing summaries for at most 2,000 sequences
of turns per load and keeps the earlier rule for the rest. Rewrites delete
summaries and the stored outline in the same transaction, so restarts
cannot serve stale ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/per-turn-summaries-for-collapsed-turns-reshaped-thr_v5rh98dc7y branch from 833094c to 46371dd Compare November 17, 2026 04:00
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]>
@ymichael

Copy link
Copy Markdown
Collaborator Author

Closing at Michael's direction. It conflicts with main, its migration number is taken, and it predates #7754 and #7795. The two problems it documents stay open: a finished collapsed turn is read whole for a few rows, and the outline lists more entries than the collapsed timeline shows. If a stored per-turn summary turns out to be needed, it will be rebuilt on current main.

AGENT GENERATED

@ymichael ymichael closed this Nov 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant