Skip to content

Fail tests on slow SQLite query plans - #7292

Merged
ymichael merged 3 commits into
mainfrom
bb/query-plan-guard
Nov 9, 2026
Merged

ymichael merged 3 commits into
mainfrom
bb/query-plan-guard

Conversation

@ymichael

@ymichael ymichael commented Nov 9, 2026 •

Copy link
Copy Markdown
Collaborator

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 Read thread head state without building a timeline window #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.

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:
  • Unit tests. query-plan-audit.test.ts covers the Read thread head state without building a timeline window #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

ymichael and others added 3 commits November 9, 2026 12:00
The db and server test suites now explain every statement a src function
prepares, using its first-execution parameters, against a pristine
migrated schema. Without sqlite_stat1, which production never creates,
those plans match production. A weaker-index rule re-plans with each
other index on large tables via INDEXED BY and flags plans that leave
equality terms unused. This is the class behind the model-fallback miss.
Full scans of large tables and automatic indexes are also flagged.
Findings fail the test file unless listed with a reason in
packages/db/src/query-plan-allowlist.ts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tale entries

The guard planned a statement once, with its first-execution parameters,
so a statement first run with a value that misses a partial index planned
differently from one that hits it, depending on test order. It now plans
every distinct shape of the parameters: strings that appear as literals in
a partial index predicate keep their value, and everything else collapses
to its type.

Report mode writes every finding with whether it is allowed, and
check:query-plan-allowlist reads one or more reports and fails on findings
missing from the allowlist and on entries no run reported. Turbo now hashes
BB_QUERY_PLAN_REPORT so report runs never replay a cached test result.

Also exercise the timeline backfill reads, which no suite ran; the guard
flags both as walking the thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit c9c5016 into main Nov 9, 2026
95 of 96 checks passed
@ymichael
ymichael deleted the bb/query-plan-guard branch November 9, 2026 21:07
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