Skip to content

Seek the type and turn indexes in five events queries that walked the thread - #7288

Merged
ymichael merged 1 commit into
mainfrom
bb/fix-five-events-queries-that-skip-the-type-index-thr_pg4wukeyqh
Nov 9, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/fix-five-events-queries-that-skip-the-type-index-thr_pg4wukeyqh

Conversation

@ymichael

@ymichael ymichael commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

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

@ymichael
ymichael merged commit 11175a0 into main Nov 9, 2026
32 checks passed
@ymichael
ymichael deleted the bb/fix-five-events-queries-that-skip-the-type-index-thr_pg4wukeyqh branch November 9, 2026 20:19
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
…thread (#7295)

## Human comments

## What was wrong

When a timeline window starts in the middle of an item,
`apps/server/src/services/threads/timeline.ts` backfills that item with
two reads in `packages/db/src/data/events.ts`:
`listStoredItemLifecycleRowsByItems` and
`listStoredBufferedTextDeltaRowsByItems`. Both put `thread_id` and the
event type outside the per-scope `OR` that matches `(scope_kind,
turn_id, item_id)`. The database has no `sqlite_stat1`, so SQLite picks
`events_thread_sequence_idx (thread_id=?)` (the deltas read also uses
`sequence<?`) to avoid a sort, then filters every earlier event in the
thread. That costs 7–8 ms per call on a 53k-event production thread. The
query-plan guard prototype (#7292) flagged both functions once
`timeline-item-backfill.test.ts` exercised them.

## What changed

- Both reads now name `events_thread_turn_type_item_sequence_idx` with
`INDEXED BY`, like #7288. They pass `thread_id`, the type list and (for
deltas) the `sequence <` cutoff into `scopedItemRefsPredicate` as shared
predicates, the same way `listItemEventSpansByItems` already does. Each
scope group now seeks `(thread_id, turn_id, type, item_id[,
sequence<])`. Items from several turns use a `MULTI-INDEX OR` with one
seek per group. Thread-scoped items seek `turn_id IS NULL`.
- The selected columns switch to the existing `storedEventRowSqlFields`,
because Drizzle needs `sql` fields when `from` is a `sql` fragment. Rows
and their order (`ORDER BY sequence`) are unchanged.
- `packages/db/test/query-plans.test.ts` pins both plans, for one item
and for items from two turns plus a thread-scoped item.
- `packages/db/test/data/timeline-item-backfill.test.ts` is copied
unchanged from #7292. It covers turn scoping, type filtering and the
`beforeSequence` cutoff, and adding an identical file merges cleanly
whichever PR lands first. Once both PRs land, the two allowlist entries
#7292 adds for these functions are stale and should be deleted.

No schema, migration or wire changes.

## How you verified

**Before/after on real data.** I called the real functions on the
production-subset database from #7292's investigation (325k events). The
heavy thread is `thr_gtbhvapit2` (53k events, max sequence 117k). The
reasoning case uses `thr_6e9knccemi` (26k events), because the heavy
thread has no reasoning deltas. Inputs are real items from those
threads: recent delegations, the latest agent message with stored
deltas, and a mix of two turns. The script and the `EXPLAIN QUERY PLAN`
were the same on main and on this branch. Each number is the median of
51 runs. Returned rows are identical (ids, sequences and data lengths
compared).

| Call | Main | This PR |
|---|---|---|
| lifecycle, 1 delegation | 7.39 ms | 0.20 ms |
| lifecycle, 3 delegations in one turn | 8.47 ms | 0.22 ms |
| lifecycle, 2 items in two turns | 8.11 ms | 0.21 ms |
| buffered deltas, agent message | 7.29 ms | 0.11 ms |
| buffered deltas, reasoning (26k-event thread) | 1.18 ms | 0.12 ms |
| buffered deltas, 2 items in two turns | 8.27 ms | 0.13 ms |

Plans on that database:
- Main: `SEARCH events USING INDEX events_thread_sequence_idx
(thread_id=?)` (lifecycle), or `(thread_id=? AND sequence<?)` (deltas).
- This PR: `SEARCH events USING INDEX
events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND
type=? AND item_id=?)`, with `AND sequence<?` added for deltas, once per
scope group, followed by a temp B-tree for `ORDER BY sequence`.

**Tests.**
- The new plan tests fail on main with the `events_thread_sequence_idx`
plans above and pass here.
- `query-plans.test.ts` and `timeline-item-backfill.test.ts`: 56 tests
pass.
- The 22 `apps/server/test/services/threads/timeline*` files (185 tests)
pass.
- `turbo run typecheck lint --filter=@bb/db --filter=@bb/server` passes.
- I ran only these 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
…7299)

## Root cause
The slow-query-plan guard (#7292) landed with seven `knownSlow`
allowlist entries for queries that had fixes in flight. Those fixes have
since merged: #7289 (getUnfinishedCommandItemData), #7288 (five
type-index queries plus getTurnInterruption), and #7287
(listThreadEventSuffixBackgroundSettlementRows). While the entries stay
in the allowlist, the guard would not catch a regression to the slow
plan for any of those queries.

## Change
Delete the seven entries and the now-unused `knownSlow` helper. The
accepted entries, which carry measurements, are unchanged.

## Verification
- `BB_QUERY_PLAN_REPORT=… pnpm exec turbo run test --filter=@bb/db
--filter=@bb/server --force`, then `pnpm --filter @bb/db
check:query-plan-allowlist <report>`: "Query plan allowlist matches the
report (46 findings)", meaning no finding is unallowed and no entry is
stale.
- That run hit two failures in `builtin-plugins.test.ts` hot-reload
timing tests (40 s and 22 s under load). Re-running the file alone
passed 27/27, and nothing in that file touches the allowlist.

> 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
…and diagnostics servers (#7302)

## Human comments

## What was wrong

The slow-query-plan guard from #7292 only judges queries that tests run,
and nothing noticed when an allowlist entry outlived its fix. #7288 and
#7289 merged just before #7292 and #7287 just after it, so main carries
seven entries for queries that are no longer slow.

## What changed

**Nightly coverage and stale-entry check.**
- A new `Query Plan Audit` workflow
(`.github/workflows/query-plan-audit.yml`, nightly on main and runnable
by hand) runs `@bb/db` and `@bb/server` tests unsharded in report mode.
It is not part of PR CI: an unsharded run took 5.2 min per PR push. PRs
still fail on new slow plans through the per-file guard in their
existing test shards.
- `check:query-plan-report` (renamed from `check:query-plan-allowlist`)
fails on:
  - findings missing from the allowlist;
  - allowlist entries no test reported;
- exported query functions in `packages/db/src/data` that no test runs.
- `packages/db/scripts/query-functions.ts` finds those functions with
the TypeScript AST: exported functions that call a query builder or
`prepare` on a connection. In report mode, the guard records the data
functions on each prepared statement's stack.
- Four functions never ran:
  - `getEarlyAdopter` had no callers and is deleted.
- `updateProject`, `getSkippedAppUpdate` and
`setPluginArtifactGitCheckoutRoot` gain tests.
- The seven fixed entries are removed.

**Per-PR check for changed query functions.**
- The Linux test shards set
`BB_QUERY_PLAN_EXECUTED=.query-plan/executed.jsonl`. The `@bb/db` and
`@bb/server` test guards record the data functions on each prepared
statement's stack while still failing on slow plans as before.
- The file is a Turbo test output (`.query-plan/**`), so a cached run
restores it.
- The shard that runs `@bb/db` also writes the query function list.
- A new `Query functions run in tests` job
(`scripts/check-pr-query-functions.mjs`) downloads both, installs
nothing, and fails when an exported query function in a
`packages/db/src/data` file the PR changed never ran. On this PR it took
11 s, and the server and packages-host shards showed no measurable
change.
- Untouched files and stale allowlist entries stay with the nightly
audit. Their tests may replay from cache, and a stale entry only
over-permits.

**Runtime audit on dev and diagnostics servers.**
- When `BB_QUERY_PLAN_AUDIT=1` or the `performanceDiagnostics`
experiment is on, the server logs `Slow SQLite query plan` once per
rule, table and caller for unallowed findings.
- `pnpm dev`, `pnpm start:worktree` and `pnpm desktop:worktree` default
`BB_QUERY_PLAN_AUDIT` to `1`. `start:worktree` runs its server with
`NODE_ENV=production`, so `NODE_ENV` can't identify dev servers.
- The connection's existing statement instrumentation
(`packages/db/src/connection.ts`) hands each new statement and parameter
shape to the auditor, which also covers cached statements. The auditor
captures the stack synchronously. It plans the statement on
`setImmediate` against a read-only connection to the same file
(`apps/server/src/services/system/query-plan-audit.ts`).
- Bundled frames are attributed through the `// path` module comments
esbuild writes into `apps/server/dist`, resolved against `apps/server`.
The bundle's 17 MB source map took about 0.9 s and 122 MB of heap to
load. Resolving against the filesystem would also misattribute an
npm-installed bb-app, whose bundle sits under `node_modules`.

**Test guard.**
- Audits are queued and run in each test file's `afterAll`, so EXPLAIN
work no longer runs inside time-budgeted code.
- The guard core now lives in `query-plan-guard.ts`, shared by tests and
the server. The prototype patch, report rows and report comparison live
in `query-plan-test-guard.ts`, exported as
`@bb/db/query-plan-test-guard`.

**Docs.**
- `docs/configuration.md`: the env var row and the
`performanceDiagnostics` description.
- `docs/debugging-and-qa.md`: a new "Slow SQLite query plans" section.
- The `bb guide` customization chapter.

**Windows.** Callers are read from POSIX stack paths, as in #7292, so
the runtime audit logs nothing on Windows and the bundle test skips
there.

**Server/daemon wire.** No daemon wire change.

## How you verified

- **Full report run** (db then server, report mode):
`check:query-plan-report` printed "Query plan report matches the
allowlist (45 findings) and runs all 362 query functions."
- Before removing the seven entries, the same check listed them as
unreported.
  - Before the new tests, it listed the four untested functions.
- **Live, `pnpm start:worktree` (ESM `dist` bundle):** with the
`listThreadSearchMatchRows` allowlist entry temporarily removed, `GET
/api/v1/threads/search?query=hello` logged `Slow SQLite query plan` with
`caller: "packages/db/src/data/threads.ts#listThreadSearchMatchRows"`.
  - A repeat search logged nothing more.
- **Experiment gate**, with `BB_QUERY_PLAN_AUDIT=0 pnpm start:worktree
--perf-diagnostics`: a search logged nothing while the experiment was
off. After `bb settings experiment performanceDiagnostics true`, the
same search logged the finding without a restart.
- **Overhead:** a microbenchmark of a cached lookup on a real connection
measured 1.2 µs per query with the audit off and 1.5 µs with it on, for
an already-audited shape (+0.33 µs across 3 rounds of 200k). Off, the
hook is one call that returns null.
- **Per-PR check, locally:** a temporary commit added an untested
`countAppSettingsRows` to `app-settings.ts`. The check named only that
function, given the db record plus server records. Against this PR's
real diff it passed: "Every query function in 1 changed data file(s)
runs in a test."
- **Per-PR check, on CI:** the job downloaded the packages-host,
server-1 and server-2 records and passed in 11 s.
- **Cache replay:** deleting `packages/db/.query-plan` and rerunning the
cached `@bb/db` test task restored all 603 rows.
- **Tests:**
- `query-plan-guard.test.ts` bundles a query function with esbuild and
loads it with Node's native `require`. It asserts the audit is deferred
until `flush()` and that the caller is attributed to
`apps/demo/src/latest-event.ts`. It fails when bundle-marker resolution
is disabled.
  - `ci-selection.test.mjs` covers the job selection.
  - The run-dev and run-desktop env tests cover the new default.
- `pnpm exec turbo run typecheck lint --filter=@bb/db
--filter=@bb/server --filter=@bb/config --filter=@bb/scripts` passes.
- **Local timing flakes:** under load averages above 100 on this
machine, `thread-pruning.test.ts` (with or without the guard) and
`builtin-plugins.test.ts` hot-reload failed once each. Both pass on
their own. #7298 since removed the pruning tests' dependence on the 20
ms budget.

> 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