Skip to content

Check restart-resume command completions within their turn - #7289

Merged
ymichael merged 1 commit into
mainfrom
bb/fix-getunfinishedcommanditemdata-thread-walk-thr_sh957kpjd7
Nov 9, 2026
Merged

ymichael merged 1 commit into
mainfrom
bb/fix-getunfinishedcommanditemdata-thread-walk-thr_sh957kpjd7

Conversation

@ymichael

@ymichael ymichael commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator

Human comments

What was wrong

getUnfinishedCommandItemData (packages/db/src/data/events.ts) is called by restart-resume for each thread whose turn was cut off by a restart. Its NOT EXISTS probe for a matching item/completed constrained only thread_id and then filtered on item_id/type. SQLite therefore probed events_thread_turn_type_item_sequence_idx on thread_id=? alone and walked every event in the thread once per started command. On real turns with 200 to 2,500 commands this takes 0.1–6.4 s, and it runs on the server during startup. The query-plan audit in thr_k58av3ue8x found it.

What changed

  • The probe also correlates finished_command.turn_id = events.turn_id. It now seeks events_thread_turn_type_item_sequence_idx on all four equality terms: thread_id, turn_id, type, item_id.

  • The result is unchanged if a command's item/completed always has its item/started's turn_id. I checked that read-only against production (~/.bb/bb.db, 10.9M events):

    Commands with item_id item/started with an item/completed completion only in a different turn start with NULL turn_id
    count 713,150 712,508 0 0

    There is also no completion in a different turn from its start at all: a direct cross-turn join returns zero rows. The old probe could also have matched a completion from an earlier turn that reused an item id. The new probe can't.

  • New query-plan test in packages/db/test/query-plans.test.ts. It covers the behaviour (an open command is returned, a completed one is not) and asserts the four-term seek.

No schema, index, or wire changes.

How you verified

Before/after on production (~/.bb/bb.db, read-only), the real SQL, and the 10 heaviest command turns plus the three turns from the audit report. Each time is the median of 3 runs. Both variants returned identical rows on every turn.

Thread Turn Commands Before After
thr_ymhw6pktq4 da7ca02626-t1 2,564 229.9 ms 1.6 ms
thr_u738kqjs29 dabd1c25da-t3 2,316 370.6 ms 1.8 ms
thr_kdrbtee92b da1f5fa598-t1 2,314 377.5 ms 2.0 ms
thr_m46b55x3yc da3f7f5def-t4 2,254 617.3 ms 1.3 ms
thr_d5ej4e2gtv da2e060369-t4 1,947 5,507.6 ms 7.8 ms
thr_u2gncttzuz turn_7f5e…_1 1,643 86.7 ms 1.1 ms
thr_6e9knccemi da9ab5128d-t2 1,637 2,023.2 ms 7.0 ms
thr_m46b55x3yc dab7caa9ac-t1 1,474 569.4 ms 1.2 ms
thr_gcuc46ug4j turn_a2a6…_41 1,241 2,355.5 ms 3.4 ms
thr_avim9t7kpe da15fcbc31-t1 1,144 82.8 ms 1.4 ms
thr_gtbhvapit2 da1fe7e359-t3 203 6,415.9 ms 9.9 ms
thr_gtbhvapit2 da595a89d7-t2 193 5,461.4 ms 2.6 ms
thr_gtbhvapit2 da595a89d7-t3 191 2,892.3 ms 2.2 ms

Plans (from EXPLAIN QUERY PLAN on production):

  • before: SEARCH finished_command USING COVERING INDEX events_thread_turn_type_item_sequence_idx (thread_id=?)
  • after: SEARCH finished_command USING COVERING INDEX events_thread_turn_type_item_sequence_idx (thread_id=? AND turn_id=? AND type=? AND item_id=?)

Local runs:

  • pnpm exec turbo run test --filter=@bb/db -- query-plans: 53 passed. The new test fails with the fix reverted.
  • pnpm exec turbo run test --filter=@bb/server -- test/threads/restart-resume.test.ts: 19 passed.
  • pnpm exec turbo run typecheck --filter=@bb/db: passed.

CI runs the full suites.

🤖 Generated with Claude Code

AGENT GENERATED

getUnfinishedCommandItemData's NOT EXISTS probe matched only thread_id,
so SQLite walked every event in the thread for each started command
(2.9-6.4 s on real ~200-command turns). Correlating on turn_id lets the
probe seek events_thread_turn_type_item_sequence_idx on all four
equality terms (1-10 ms). On production, every command completion
carries its start's turn_id.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 60f81b3 into main Nov 9, 2026
32 checks passed
@ymichael
ymichael deleted the bb/fix-getunfinishedcommanditemdata-thread-walk-thr_sh957kpjd7 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
…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