Skip to content

Read thread head state without building a timeline window - #7238

Merged
ymichael merged 4 commits into
mainfrom
bb/timeline-head-state
Nov 9, 2026
Merged

ymichael merged 4 commits into
mainfrom
bb/timeline-head-state

Conversation

@ymichael

@ymichael ymichael commented Nov 7, 2026 •

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

A thread's head state (its to-dos, provider slash commands, session options, extension states such as goals, plan prompt mode, model fallback, and context usage) only existed as a by-product of building the latest timeline page. bb thread show, bb thread commands, bb thread options and sdk.status read it with threads.timeline({ summaryOnly: "true" }). summaryOnly only dropped the rows from the response: the server still selected, decoded and projected the whole latest page, and on a thread with a long open turn that meant every event of the turn, on the event loop. Its separate cache key meant it never reused a page the app had already built. On an active thread every poll was a rebuild. A self-hosted 0.49.0 user's server stalled and dropped every device this way. This is one trigger of #4674; #6499 is the same symptom.

What changed

  • One head-state read. readThreadHeadState (apps/server/src/services/threads/thread-head-state.ts) reads each field from its latest stored state events. The latest timeline page embeds that result instead of deriving these fields from its selected rows, so page selection no longer fetches head-only state rows, and the build no longer runs its own context-usage query. With head state outside the projection, the projection cache no longer keys on those rows.
    • Model fallback: new getLatestModelFallbackRowSinceTurnRequest reads the latest fallback event after the latest turn request. It pins events_thread_type_sequence_idx; SQLite otherwise picks the sequence index for the ORDER BY and walks the whole turn (2.8 ms → 0.14 ms on a 20k-event turn). A query-plan test covers it.
    • Plan prompt mode reuses the sidebar's open-turn query (listOpenTurnRequestRows), now shared by both.
    • GET /threads/:id/context uses the same context-usage read.
  • Route and SDK. GET /threads/:id/head-state / threads.experimental_headState returns the full set, with an entry in docs/api_to_audit.md and the Plugin Guide. bb thread show, bb thread commands, bb thread options and sdk.status use it.
  • summaryOnly removed. The query field, SDK argument, separate cache key and build branch are gone. The query schema is not strict, so a caller that still sends it gets the full latest page (same head-state values, rows included) instead of an error. No caller in this repo uses it.
  • Docs: docs/timeline-pagination.md, the plugin-authoring backend-sdk reference, and the bb guide thread-inspection chapter (cheap ways to poll a child thread).
  • Plugin SDK bumped to 0.6.136. No daemon wire change.

Active thinking, active workflows, and active background commands are not head state: they still come from projecting the latest page.

How you verified

  • Repro on main: a thread with a 20,005-event open turn. One bb thread show built a timeline window over 20,010 events (21.7 MB) in 2.15 s and the server logged "Event loop stalled". With an event appended before each read, every summaryOnly request took 220–300 ms.
  • After: GET /head-state took 2–3 ms on the same thread; bb thread show, commands, options and context built no timeline windows; output matches main.
  • Equivalence on a copy of the production database: for 374 threads (the heaviest with 143,060 events), each as its real status and as active, readThreadHeadState matched every field extracted from the thread's full event history: 748 comparisons, 0 mismatches. Read time p50 0.7 ms, max 4.5 ms. No production thread had an open plan turn; plan mode is covered by the sidebar banner tests that use the same query.
  • Tests: timeline-head-state.test.ts pins expected values far behind a long turn, model fallback clearing on the next turn request (fails if the reset is removed), and todos clearing when the thread is idle. query-plans.test.ts pins the fallback index (fails without it).
  • pnpm exec turbo run typecheck --filter='...[origin/main]' (102 packages) and lint pass. Tests pass for @bb/thread-view, @bb/db, @bb/cli, @bb/sdk, @bb/server-contract, and 331 targeted apps/server tests (test/services/threads, timeline, context, banner, pruning).

Refs #4674, #6499

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 4 commits November 9, 2026 10:50
…window

`bb thread show`, `bb thread commands`, `bb thread options`, and
`sdk.status` read their fields through `threads.timeline({ summaryOnly })`.
That builds and projects the whole latest page, which on a thread with a
long open turn decodes thousands of events on the event loop, and then
returns no rows. Agents polling child threads with `bb thread show`
repeated that build on every check (Discord report; #4674, #6499).

Add `GET /threads/:id/head-state` (`sdk.threads.experimental_headState`),
which decodes only the latest to-do snapshot and provider state events,
and switch those callers to it. On a production snapshot the summaryOnly
read took 4-174 ms per thread and the head-state read 0.2-0.9 ms, with
identical values on all 16 runs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Head state (to-dos, provider commands, session options, extension states,
plan prompt mode, model fallback, and context usage) is now computed by
readThreadHeadState from the latest stored state events. The latest
timeline page embeds that result instead of deriving the fields from its
selected rows, and GET /threads/:id/head-state returns the same values.

- Page selection no longer fetches head-only state rows, and the build no
  longer runs its own context-usage query.
- Model fallback reads the latest fallback event since the latest turn
  request; plan prompt mode reuses the sidebar's open-turn query.
- GET /threads/:id/context shares the same context-usage read.
- threads.timeline's summaryOnly is deprecated in the SDK types; it still
  works at runtime.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
summaryOnly built the whole latest page and only dropped its rows, so it
cost as much as a full read. Head state now comes from
GET /threads/:id/head-state, and no caller needs summaryOnly. The query
field, SDK argument, separate cache key, and build branch are gone; the
server ignores the parameter and returns the full page.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael force-pushed the bb/timeline-head-state branch from c7a4151 to 98414ad Compare November 9, 2026 18:51
@ymichael ymichael changed the title Read thread todos, commands, and options without building a timeline window Read thread head state without building a timeline window Nov 9, 2026
@ymichael
ymichael merged commit 458aedc into main Nov 9, 2026
52 checks passed
@ymichael
ymichael deleted the bb/timeline-head-state branch November 9, 2026 19:11
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 9, 2026
… thread (#7288)

## Human comments

## What was wrong

Five events queries filter on `type` (and sometimes `turn_id`), but
SQLite walks the thread or turn in `sequence` order instead. The
database has no `sqlite_stat1`, so the planner guesses that `thread_id =
?` matches about 10 rows. It then picks `events_thread_sequence_idx` to
skip a sort, or a type index that ignores `turn_id`, and reads every
event in a long turn or thread. This is the same class as the miss #7238
fixed in `getLatestModelFallbackRowSinceTurnRequest`. A prototype
query-plan guard (commit 33ad7275b7, local only, not in this PR) flagged
all five.

## What changed

Each query now names its index with `INDEXED BY`, the pattern #7238 and
the rest of `events.ts` use. The selected columns become `sql` fields
because Drizzle rejects plain columns when `from` is a `sql` fragment.

| Function | Plan on main | Plan now |
|---|---|---|
| `getLatestStoredThreadEventOfTypes` (`packages/db/src/data/events.ts`)
| `events_thread_sequence_idx (thread_id=? AND sequence>?)` |
`events_thread_type_sequence_idx (thread_id=? AND type=? AND
sequence>?)` |
| `listStoredClientTurnRequestIdsInRange` | `events_thread_sequence_idx
(thread_id=? AND sequence>? AND sequence<?)` |
`events_thread_type_sequence_idx (thread_id=? AND type=? AND sequence>?
AND sequence<?)` |
| `findLastCompletedRootStoredTurn` | outer `events_thread_sequence_idx
(thread_id=?)`; `completed` by `(thread_id, type)` | outer
`events_thread_type_sequence_idx (thread_id=? AND type=?)`; `completed`
by covering `events_thread_turn_type_item_sequence_idx (thread_id=? AND
turn_id=? AND type=?)` |
| `isStoredTurnContextCompactionOnly` |
`events_thread_type_item_kind_sequence_idx (thread_id=? AND type=?)`,
which reads every `item/completed` in the thread |
`events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=?
AND type=?)` |
| `getTurnInterruption` (`apps/server/src/internal/events.ts`) |
interruption lookup on `events_thread_sequence_idx`; `turn/completed`
lookup by `(thread_id, type)` | `events_thread_type_sequence_idx`;
`turn/completed` by `events_thread_turn_type_item_sequence_idx` |

`getLatestStoredThreadEventOfTypes` keeps its `type IN (...)` list. It
now reads only rows of the requested types and sorts them.
`failureCategory` passes `afterSequence: 0` with `turn/started`, so that
is one row per turn. On a 391-turn thread it takes 0.074 ms, below
main's walk even on a short turn. I also measured one seek per type
(0.20 ms, from three Drizzle builds) and a `UNION ALL` of per-type seeks
(0.047 ms, raw SQL). The `IN` list is the simplest of the three and
matches #7238.

No wire, schema or migration changes.

## How you verified

**Before/after.** These are real function calls on a production-subset
database (325k events). The thread is `thr_gtbhvapit2`, with 73k events,
391 turns and a synthetic 20k-event open turn appended. Each number is
the median of 51 runs, from the same script on main and on this branch,
and results match. Script and raw JSONL are in this thread's storage
(`scripts/bench.ts`, `bench-before.jsonl`, `bench-after.jsonl`).

| Query | Main | This PR |
|---|---|---|
| `getLatestStoredThreadEventOfTypes` (`failureCategory` types, after 0)
| 2.87 ms | 0.074 ms |
| `listStoredClientTurnRequestIdsInRange` (open turn) | 1.00 ms | 0.058
ms |
| `findLastCompletedRootStoredTurn` | 2.61 ms | 0.11 ms |
| `isStoredTurnContextCompactionOnly` (open turn) | 5.92 ms | 0.82 ms |
| `getTurnInterruption`: interruption lookup | 2.51 ms | 0.043 ms |
| `getTurnInterruption`: `turn/completed` lookup | 0.10 ms | 0.038 ms |

Without the synthetic turn (same thread, real latest turn), nothing
regresses:
- `getLatestStoredThreadEventOfTypes`: 0.088 → 0.078 ms
- `listStoredClientTurnRequestIdsInRange`: 0.071 → 0.052 ms
- `findLastCompletedRootStoredTurn`: 0.12 → 0.11 ms
- `isStoredTurnContextCompactionOnly`: 4.2 → 0.050 ms
- `getTurnInterruption` lookups: 0.070 → 0.054 ms and 0.049 → 0.040 ms

The single-type `provider/error` lookup in `turn-failed.ts` stays at
0.07–0.08 ms; that time is mostly building the query in Drizzle.

**Query-plan guard.** On a scratch branch I cherry-picked 33ad7275b7 and
deleted these five entries from `query-plan-allowlist.ts`. Then I ran
the `@bb/db` suite (685 tests) and 12 targeted `@bb/server` files (226
tests): turn telemetry, child outcomes, turn-failed retry, fork history,
compaction, turn details, send dispatch, restart-resume and dispatcher
paths. Both passed with no violations. With this PR's source changes
reverted, the same runs fail with `weaker-index` violations for all five
functions. The scratch branch is deleted, and nothing from the guard is
in this PR.

**Tests.** `packages/db/test/query-plans.test.ts` pins the plans of the
four `@bb/db` functions. They fail on main (they show the walks in the
table above) and pass here. `turbo run typecheck` and `lint` pass for
`@bb/db` and `@bb/server`. I ran only targeted tests locally; CI runs
the full suites.

> 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
## Human comments

## What was wrong

Slow query plans were caught one at a time, after the fact.
`packages/db/test/query-plans.test.ts` holds 43 hand-written plan tests,
each added after a slow query surfaced, against about 420 query
functions. The production slow log is no substitute: only 109 of 4,438
logged slow statements were mostly CPU time, so plan regressions in the
1–10 ms range never reach it.

The miss behind this work is #7238. An events query filtered `type IN
(...)` with `ORDER BY sequence DESC LIMIT 1` walked a whole 20k-event
turn through `events_thread_sequence_idx` instead of seeking
`events_thread_type_sequence_idx`. That plan is an indexed SEARCH, so a
"no full scan" rule can't see it. Without `sqlite_stat1`, which
production never creates, SQLite assumes `thread_id = ?` matches about
10 rows, so walking a thread to skip a sort looks cheap.

## What changed

**Guard.** A Vitest setup file in `@bb/db` and `@bb/server`
(`@bb/db/query-plan-guard`) patches better-sqlite3's `prepare` in test
workers.
- **What it checks.** Every statement a non-test `src/` function
prepares; migrations are skipped. On execution it is explained with its
real bound values against a pristine migrated schema. With no stats,
that is the plan production gets from the same SQLite build.
- **Partial indexes.** Bound values matter for partial indexes, so each
distinct parameter shape is planned. Strings that appear in a
partial-index predicate keep their value; everything else collapses to
its type.

**Rules** (`packages/db/src/query-plan-audit.ts`). Large tables are
those over 20k rows in production: `events`, `thread_search_segments`,
`prompt_history_entries` and `terminal_sessions`.
- **weaker-index.** For each plan step on a large table, the statement
is re-planned with `INDEXED BY` for every other index on that table. The
step is flagged when another index uses more equality terms without
losing range terms. This flags the #7238 SQL; there is a unit test.
- **full-scan** of a large table.
- **automatic index.**
- Temp B-trees are not checked: 126 statements use one, and the plan
alone can't say which matter.

**Allowlist** (`packages/db/src/query-plan-allowlist.ts`). Entries are
keyed by rule, table and `file#function`, each with a measured reason,
18 in total.
- Seven are known-slow with fixes in flight: #7287, #7288 and #7289.
Those entries go once the fixes merge.
- Two are new findings: the timeline backfill reads walk the thread,
about 10 ms per call on a 53k-event thread.
- Any finding not in the allowlist fails the test file, printing the
function, plan and SQL.

**Report mode.** `BB_QUERY_PLAN_REPORT=<file>` writes every finding,
including allowed ones, instead of failing.
- `pnpm --filter @bb/db check:query-plan-allowlist <report>...` fails on
missing entries and on entries no run reported. Feed it reports from an
unsharded db + server run.
- Turbo hashes the variable so report runs never replay a cached result.

**New test.** `packages/db/test/data/timeline-item-backfill.test.ts`
exercises the timeline backfill reads, which no suite ran before.

**Limits.**
- It only sees statements tests execute.
- It doesn't judge result volume.
- It's inactive on Windows shards, because the stack-path matching is
POSIX-only.

## How you verified

- **Full report run.** db + server in report mode gave 84 finding rows,
all allowlisted, and `check:query-plan-allowlist` reported no stale
entries.
- **Negative check.** Removing one allowlist entry fails `@bb/db` with a
readable violation.
- **Measured findings.** On a production-data subset with a seeded
20k-event turn:
- the weaker-index findings ranged from real 17–245× slowdowns to one
case where the chosen index was faster;
- `getUnfinishedCommandItemData` took 2–6 s on production turns (#7289).
- **Unit tests.** `query-plan-audit.test.ts` covers the #7238 shape,
planning partial indexes with bound values, and unique-key lookups.
- **Cost.** The guard adds about 5 s to a local `@bb/db` run: 13.3 s and
15.9 s with it, 8.8 s and 10.2 s without (two runs each, `vitest run` in
`packages/db`). The `@bb/server` CI shards took about as long as on main
(server-1 165 s vs 156 s, server-2 121 s vs 179 s).
- **Checks.** `turbo run typecheck lint` passes for `@bb/db` and
`@bb/server`.

> 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
…hem on extension state kinds (#7297)

## Human comments

## What was wrong

Two inputs to a latest timeline window were missing from the server
response cache (`apps/server/src/services/threads/timeline-cache.ts`),
so the cache kept serving a window those inputs had made stale. Both
holes are on main and predate the Nov 9 landings. They were found by the
landed-perf cache-key audit (rows H1 and H2).

- **H1, retained-output availability.** A command or tool output
truncated for storage reports `experimental_fullOutputAvailability:
"available"` until its 7-day retention deadline (`truncatedAt`) and
`"retention-expired"` after it. The window build compares the deadline
with `Date.now()`, but the cache revision has no time component, so a
cached window keeps saying `available` past the deadline. On main this
is short-lived: the `retained-event-output-expiry` sweep (10 s tick)
deletes the expired output and notifies `history-compacted`, which
invalidates the thread's cached windows. Measured live on main, the
window kept saying `available` for about 4 s after the deadline. During
that gap, expanding the output still resolves to the expired preview,
because turn details compute expiry themselves. This PR makes the cache
correct by itself instead of relying on the sweep, following the
`expiresAt` pattern the turn-details cache already uses.
- **H2, head-state extension states.** `extensionStates` in the head
state is filtered to the kinds that the thread's provider declares with
`state: true`. That list comes from the provider registry and changes
when a provider plugin is installed or updated. `surface.cacheKey` only
had `cursorKey`, `planCommand` and `compactionOfferEnabled`. After an
update that declares a new state kind, a thread with no new events kept
serving `extensionStates: {}`.

## What changed

- `timeline.ts`: `retainedOutputPreviewsByCallId` and
`nextRetainedOutputPreviewExpiry` scanned the same events twice. They
are now a single pass, `readRetainedOutputPreviews`, which returns both
the previews and the earliest future deadline. The deadline semantics
are unchanged. The window build returns that deadline as `expiresAt`,
taking the earliest one across the empty-window skip loop. The
turn-details projection uses the same function.
- `timeline-cache.ts`: entries store `expiresAt`. A hit requires a
matching revision and either no expiry or `Date.now() < expiresAt`.
`Date.now()` is called only for entries that hold an unexpired retained
output.
- `resolveThreadTimelineSurface` adds `extensionStateKinds` to
`cacheKey`. `buildWindow` already resolves these kinds on every request
through `resolveThreadHeadStateOptions`, so the key adds no extra
registry work. I did not use
`providerRegistry.getRegistrationRevision()` because it changes on any
provider's registration and would invalidate every thread's windows.
- Other caches that embed head state: `GET /threads/:id/head-state` from
#7238 calls `readThreadHeadState` on every request and does not cache.
After #7238 the projection cache no longer holds head state. The
stored-event decode cache is keyed by row content, not by kinds. That
leaves the response cache as the only cache with this input.
- No wire, CLI, or doc changes.

## How you verified

- New
`apps/server/test/services/threads/timeline-window-cache-inputs.test.ts`,
run against a real migrated DB through `withTestHarness`:
- *rebuilds a cached window once a retained output passes its retention
deadline*: before the deadline, a repeat read returns the same cached
object. At the deadline (`Date.now` mocked) the read must show
`retention-expired`. With the expiry check removed it fails: `expected
'available' to be 'retention-expired'`.
- *re-reads head extension states after a provider update declares a new
state kind*: registers a plugin provider with no state kinds, reads,
then disposes and re-registers it declaring `goal` with `state`. The
registry is real; nothing is mocked. With the cache-key change removed
it fails: `expected {} to deeply equal { 'provider-goals/goal': … }`.
- Hit-path cost: a scratch benchmark (not committed) seeded a thread
with 60 commands, warmed one latest window, and timed 7 rounds of 20,000
cached `windows.read()` calls each. Main and the branch were run
alternately, twice each, with the windows holding either no retained
output or 60 unexpired ones. Median µs per cached read:

  | | no retained output | 60 retained outputs |
  |---|---|---|
  | main (run 1 / 2) | 28.05 / 27.67 | 27.81 / 27.83 |
  | branch (run 1 / 2) | 27.83 / 27.63 | 27.58 / 27.83 |

Extra work per hit is one null check, plus one `Date.now()` when the
window holds an unexpired retained output, plus the state-kind array in
the key string (usually empty). The window build does no extra scan. The
turn-details build now does one scan instead of two.
- `pnpm exec turbo run typecheck lint --filter=@bb/server` passes, and
`pnpm exec turbo run test --filter=@bb/server -- test/services/threads`
passes (38 files, 311 tests).
- Live check of H1 on a `pnpm start:worktree` server: a real Codex turn
ran `seq 1 20000` (108,894 chars, retained). I moved its deadline a few
minutes out in the DB, restarted, and polled `GET
/threads/:id/timeline?includeNestedRows=true` every second across the
deadline. Main reported `available` until t=+4 s, then
`retention-expired` after the sweep ran. The branch reported
`retention-expired` from t=0.
- Not verified: H2 in a live app (it needs a runtime provider-plugin
update that adds a state kind), and no check against the production
snapshot. A subscriber that is idle at the deadline is not pushed a
refreshed window by this change; the existing sweep notification still
reaches it within one sweep tick, as on main.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
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