Skip to content

Bound the client turn request lookup to the acceptance that consumed it - #7920

Merged
ymichael merged 1 commit into
mainfrom
bb/triage-and-resolve-issue-7899-thr_x8nhf9bjwq
Nov 20, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/triage-and-resolve-issue-7899-thr_x8nhf9bjwq

Conversation

@ymichael

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

listStoredClientTurnRequestRowsByKeys found a thread's client/turn/requested row by matching json_extract(data, '$.requestId'). No index covers that JSON field, so SQLite read and parsed every request event in each thread before filtering. Both callers (the thread runtime display / head state via listOpenTurnRequestRows, and timeline page context) run it synchronously on the main loop. On a 6.8 GB database one lookup took 26.5 s and stalled the server for 28.6 s (#7899).

What changed

  • ThreadClientTurnRequestKey now carries acceptedSequence, the sequence of the turn/input/accepted row that consumed the request. A request always precedes its acceptance.
  • The lookup joins a VALUES list of keys to a correlated subquery that walks events_thread_type_sequence_idx backwards from acceptedSequence and stops at the first matching request (ORDER BY sequence DESC LIMIT 1). Rows read are bounded by requests queued between a request and its acceptance, not by thread history. Plan: SEARCH candidate USING INDEX events_thread_type_sequence_idx (thread_id=? AND type=? AND sequence<?), with no temp B-tree.
  • The OR-chain expression-depth batch cap (995) is gone. Keys batch by the SQLite variable limit like the other VALUES lookups.
  • thread-head-state.ts and timeline.ts pass the accepted row's sequence. The query-cost case passes a bound.
  • No new index or migration, and no wire change.

How you verified

  • Repro with the real function on the history fixture plus 16 KB request payloads, fetching one request, warm cache, median of 10 runs:

    Requests in thread Before After
    251 1.13 ms 0.11 ms
    4,001 17.4 ms 0.08 ms
  • pnpm exec turbo run typecheck --filter=@bb/db --filter=@bb/server

  • packages/db/test/data/events.test.ts: 93 passed. The new test checks that only the request before the consuming acceptance is returned. The batching test now crosses the variable limit.

  • apps/server timeline, head-state and thread-route tests: 193 passed. With a wrong bound in the head-state caller, two existing runtime-display and status-change tests fail.

  • tsx scripts/check-query-costs.ts --group events passes.

Fixes #7899

AGENT GENERATED

🤖 Generated with Claude Code

listStoredClientTurnRequestRowsByKeys filtered every client/turn/requested
row of each thread by json_extract(data, '$.requestId'), so a timeline or
head-state read decoded the whole request history. On a large database that
held the event loop for 28 s (#7899).

Each key now carries the sequence of its turn/input/accepted row. The lookup
walks events_thread_type_sequence_idx backwards from that sequence and stops
at the first matching request, so rows read are bounded by requests queued
between the request and its acceptance, not by history length. No new index.

Fixes #7899

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit cffc828 into main Nov 20, 2026
35 checks passed
@ymichael
ymichael deleted the bb/triage-and-resolve-issue-7899-thr_x8nhf9bjwq branch November 20, 2026 18:08
ymichael added a commit that referenced this pull request Nov 20, 2026
…y lookups (#7923)

## Human comments

## What was wrong

`check:query-costs` times every exported query function in a small and a
4x larger world (thread history, and turn size), but it only failed past
size^2 (16x) and only warned past size^1.5 (8x). Linear growth passed at
any size. The #7899 lookup read every request event in a thread and
parsed its JSON to keep one row. It measured 1.8 → 8.5 ms (4.7x) in this
check and passed, then took 26.5 s on a 6.8 GB database. The query-plan
guard missed it too, because `SEARCH events USING INDEX (thread_id=? AND
type=?)` hides the per-row `json_extract` filter. Applying a stricter
rule showed 12 more query functions with the same shape: they read
history and keep a few rows.

## What changed

**The check**
- The smaller world is now a sixteenth of the larger: 625 against 10,000
turns, and 94 against 1,500 steps per long turn. A bounded cost measures
about 1x and a linear one about 16x.
- An undeclared query function fails if it grows faster than size^0.5
(4x) once its larger-world time reaches the growth floor.
- A case whose cost must grow declares `growsWith: { history | turnSize:
"<reason>" }`. Declared growth keeps the old limits: warn past size^1.5,
fail past size^2. An empty reason fails the coverage check.
- A declaration that measures within size^0.125 (1.4x) warns, so it is
removed once its query is bounded.
- The growth floor is 2 ms on the reference machine, scaled by a fixed
SQLite calibration workload. The calibration runs after the worlds are
built and keeps the fastest of three.
- Every case is timed at least three times. A case crossing the limit is
timed up to eight times.
- Each axis prints the five undeclared functions closest to the limit,
so CI logs show near-misses.
- I swept once with a 0.25 ms floor, so every case that grows declares
it. A case that crosses the floor on one runner and not another
therefore doesn't change the result.
- The tree and paged cases now pass fixed-size inputs (20 chain leaves,
20 descendant roots, a 1,000-row page), so they measure per-call cost
rather than input size.
- Documented in `docs/debugging-and-qa.md`.

**Queries bounded with existing indexes** (no new indexes on `events`)
- `listStoredTurnStartedRowsByTurnIdsUpToSequence` and
`listStoredTurnCompletedRowsByTurnIds` seek the requested turns on
`events_thread_turn_type_item_sequence_idx`. Before, they filtered every
started or completed row in the thread.
- `isThreadAwaitingTurnStartPastDeadline` and
`listTurnStartDeadlineCandidates` compare only the newest
`turn/completed` row's `created_at` to the deadline. This relies on
appended rows' `created_at` rising with `sequence`. Fork copies keep
older timestamps, but they are appended before any of the fork's own
rows, and the copy aborts if anything else is appended.
- `hasStoredProviderTurnCompletedSince` reads only the completions after
the newest one older than the cutoff.
- `getLastStoredTurnRequestEvent` and `listStoredTaskTurnRequestEvents`
seek each request type on `events_thread_type_sequence_idx` with its own
`LIMIT`, then merge. Before, an `OR` over the types made SQLite walk
every event of an open turn.
- `listStoredTimelineThreadWindowEventRows` reads the thread-scoped
(`turn_id IS NULL`) index entries, which carry `sequence`, instead of
every row in the window.
- `supersedeQueuedRetriesInTransaction` starts its retry-chain scans at
the retried request.
- `deleteThreadScopedPruningCursors` deletes by the indexed `thread_id`.
Before, it filtered on `scope`, the second primary-key column, and
scanned every cursor. The table's check constraint makes the two filters
select the same rows.

- `isStoredTurnProviderCompactionRunning` seeks the turn's latest root
compaction start and completion on
`events_thread_type_item_kind_sequence_idx`. Before, it read every item
start and completion in the turn.
- `isStoredTurnContextCompactionOnly` checks two things: whether a root
compaction exists, and whether any other root item exists. A normal turn
stops at its first non-compaction item. Before, it listed every
completed item's kind.
- `listLatestTurnFinalAgentMessageEventRows` walks root agent replies
newest-first. A turn's first reply in that walk is its final one, and
the walk then jumps below the turn's start. Each step is one cached
prepared statement that returns the reply along with its turn's start.
Before, every reply ran a `NOT EXISTS` over its whole turn.

**Still declared, with the reason in the case**
- `getStoredConversationOutlineProjectionState`: its nested turn's
root-request lookup now seeks back from the acceptance instead of
JSON-scanning every request. The outer scan stays as it was. I tried
starting from the nested rows, using the partial parented-row index.
That doubled its time on real threads: one thread has 46,791 delegation
rows and no nested turns. No index singles out nested `turn/started`
rows.
- `listStoredTurnInputAcceptedRowsByClientRequestIds`: no index keys
`clientRequestId`. A request that was accepted before `afterSequence`,
or never accepted, has to read every later acceptance. Stopping at the
first match would change edit-message's "accepted into exactly one turn"
check.
- `getUnfinishedCommandItemData`: to find a started command with no
completion, it has to check each command started in the turn, because
nothing records open items. It reads only command rows, through the
item-kind index, and runs only when a daemon restarts mid-turn.
- `listTimelineRootWindowTurnIds`: it must find every turn with rows in
the window. A turn's late rows can land after later turns start, so only
reading the window finds them.

51 cases are declared. Apart from the 4 above, each one returns, writes
or deletes rows the larger world has more of.

## How you verified

- `pnpm exec turbo run typecheck --filter=@bb/db` and `pnpm exec turbo
run test --filter=@bb/server` pass. All 729 `@bb/db` tests pass, with
the query-plan guard on.
- New `packages/db/test/data/bounded-history-lookups.test.ts` (7 tests)
pins the behaviour each rewrite keeps. The tests pass against both the
`origin/main` queries and the rewritten ones.
- Full `check:query-costs` with the pre-#7920
`listStoredClientTurnRequestRowsByKeys` put back exits 1 on that
function. On this branch it exits 0 with no warnings.
- **Stability:** the cost job ran four times on CI on the final changes
(the PR run plus two dispatched runs on `6d95c41`, then the PR run after
the rebase). All passed. The closest undeclared case in any run was
3.15x against the 4x limit, and most were at or below 2.2x. The
calibrated floors ranged from 2.5 to 3.4 ms. Before these changes, one
of three runs on the same commit failed.
- **Real data**: a `VACUUM INTO` copy of a production bb.db (8.8 GB). I
ran the `origin/main` and rewritten queries on its 40 largest threads
(largest: 131,244 events). Results were identical for every function and
thread. Median of 5 runs:

  | Function | Total, 40 threads | Slowest thread |
  |---|---|---|
| `listStoredTimelineThreadWindowEventRows` | 108.6 → 36.8 ms | 12.45 →
3.95 ms |
  | `listStoredTaskTurnRequestEvents` | 38.6 → 5.1 ms | 6.21 → 0.52 ms |
| `getStoredConversationOutlineProjectionState` | 22.5 → 19.7 ms | 4.04
→ 3.95 ms |
| `listStoredTurnCompletedRowsByTurnIds` | 5.5 → 3.2 ms | 0.63 → 0.18 ms
|
| `listStoredTurnStartedRowsByTurnIdsUpToSequence` | 4.4 → 2.5 ms | 0.48
→ 0.08 ms |
| `hasStoredProviderTurnCompletedSince` | 3.3 → 1.9 ms | 0.33 → 0.05 ms
|
  | `getLastStoredTurnRequestEvent` | 2.9 → 2.8 ms | 0.35 → 0.09 ms |
| `isThreadAwaitingTurnStartPastDeadline` | 1.7 → 1.5 ms | 0.09 → 0.05
ms |
  | `listTurnStartDeadlineCandidates` | 0.12 → 0.07 ms | |

- **Real data, turn helpers:** on the same copy (40 largest threads,
7,289 root turns), the `origin/main` and rewritten versions returned
identical results for every call. Worst-case times:

  | Function | Slowest call |
  |---|---|
  | `isStoredTurnProviderCompactionRunning` | 3.72 → 0.60 ms |
  | `isStoredTurnContextCompactionOnly` | 1.30 → 0.44 ms |
| `listLatestTurnFinalAgentMessageEventRows` (limit 50) | 9.40 → 2.05 ms
|

My first version of the final-reply walk was slower on real data (87 →
228 ms total at limit 50), because it rebuilt two queries per turn. The
prepared-statement version fixed that.
This database has no queued retries, so
`supersedeQueuedRetriesInTransaction` is covered by the cost check and
`queued-retry-history.test.ts` instead.

Refs #7899

> 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.

Timeline request-ID lookups scan event history and can block the server

1 participant