Repository navigation
Conversation
The plan guard now flags correlated subqueries over large tables, including EXISTS subqueries SQLite rewrites into joins, unless the inner search pins a unique key or a column bounded per value (turn_id, item_id, parent_tool_call_id). Existing findings are fixed or allowlisted with a reason. The Query Plan Audit workflow now runs on pull requests that change packages/db and adds a cost job: check:query-costs builds a 10,000-turn thread through the real event write path and times every exported query function in events.ts and queued-thread-messages.ts against it, killing calls that run past 5 seconds. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Run check:query-costs as a Turbo task that depends on //#ensure-native-modules so the job can install with --ignore-scripts, use a neutral provider id in the fixture, and allowlist the bounded correlated search in findLatestUnresolvedClientTurnRequestIdAfterSequence. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Absolute per-function budgets failed on a CI runner 2.5-4x slower than a laptop. The cost check now builds a 5,000-turn and a 10,000-turn database, times each query function against both interleaved, and fails when doubling history grows the time more than 3x (once the long time is at least 2 ms), when the long time passes a loose ceiling (250 ms by default), or when one call runs past 5 seconds. The growth check found getFirstParentedTimelineBoundarySequence growing 2.9x per doubling: its final join compared every request in history with every delegation span. It now takes each span's first matching request through a range seek on the request index, which gives the same minimum. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tory A new @bb/server test builds the history fixture (now @bb/db/history-fixture) at 100 and 200 turns in two test servers and runs hot request paths against both: thread list and detail, timeline, conversation outline, context, head state, queued messages, oldest turn details and message, send with a queued retry, edit, stop and fork. It counts executed statements through the existing slow-query logger at a 0 ms threshold and fails when any statement runs more often on the longer thread, which catches per-turn query loops that per-function timing cannot see. Counts are exact, so the test does not depend on machine speed. Fork copies history by design and may grow at most linearly. The fixture now matches what the server parses: turn/started precedes turn/input/accepted, completed turns carry a provider checkpoint, the environment is ready, and the queued retry carries the original request's input. A @bb/db test parses every fixture event with parseStoredThreadEvent. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Coverage: - The cost check now times every exported query function in packages/db/src/data (429). Case groups seed their tables into the same half- and full-scale worlds at about twice the largest real user, so growth in thread count, environments, sessions, plugin rows or prompt history shows up as well as turns. - Query functions now include exported wrappers that query through a local helper; 69 functions were invisible to coverage, including thread search and the sidebar listings. - check:query-costs --db <copy> times every case against a VACUUM INTO copy of a real database. - A nested-loop plan rule flags a loop over a CTE or subquery that runs once per history row of a large table, the shape of the old parented-boundary join. - The request-path statement test counts at the better-sqlite3 layer and covers 24 paths, including daemon event ingestion, search, sweeps and growing thread counts. Fixes: - listGarbageCollectablePluginArtifacts was quadratic in artifacts x snapshots; it now seeks snapshot and active-artifact indexes. - listLatestClosedSessionsForHosts, on every thread list, rescanned closed sessions per session row; it now seeks each host's latest closed session. - Usage snapshot pruning walked every usage row per 16-row chunk; it now seeks the candidate ids. - listThreadEnvironmentAssignmentsOnHost, on every daemon event batch, read every thread on the host; it now looks up the batch's thread ids. - Request-id lookups use partial expression indexes, listCommandItemDataByItemIds seeks by item, edit reads one candidate at a time, the cold timeline ordering read is about 2.5x cheaper, and listEvents moved to test support. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The migration built two expression indexes over every events row (12-21 s on a 4.35M-event database). Every fix now uses an index that already exists: - Plugin artifact GC excludes retained and active artifacts with non-correlated NOT IN sets, built once per query. - The latest closed session per host seeks host_daemon_sessions_host_status_idx instead of walking the global closed-session index. - Request-id lookups use events_thread_type_sequence_idx again; getStoredTurnRequestEventForTurn and the edit path start their range at the accepted input's or the request's sequence. The cost check re-measures a case that crosses the growth limit up to eight times before failing it, so one slow call on a shared runner does not fail CI. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…to @bb/db Server events queries: - Every query the server ran directly on events now goes through @bb/db, so the cost check and the "query functions run in tests" check cover it. This affects the edit path, thread-start staleness, provisioning cancellation, and the turn-start deadline sweep. - Five reuse existing data functions. Seven are new: findStoredEditMessageOperationRow, findLatestEditableUserTurnRequestRow, hasStoredThreadInterruptedSince, hasStoredProviderTurnCompletedSince, hasStoredCancelledThreadProvisioning, listTurnStartDeadlineCandidates and isThreadAwaitingTurnStartPastDeadline. Fixture realism: - The history fixture spreads each thread's events 30 s apart, ending an hour before the build, so created_at predicates such as the deadline sweep's behave as they do on a real long thread. Turn size as a second growth axis: - The fixture can make long turns, and an active thread with an open long turn. - check:query-costs runs every case on a history axis (5k to 10k turns) and a turn-size axis (750 to 1,500 steps per turn). 25 cases target the open long turn. - The request-path test runs on both axes and also bounds response bytes. Fix found by the turn-size axis: - With a long open turn, the latest timeline page reported every older row of the turn as olderRowUpdates. Every streamed delta re-sent them: 266 KB at 750 steps and 1.55 MB at 1,500. - The page now reports rows from the first returned leaf when the window cuts inside a segment. The delta is 2.3 KB at both sizes, and cold open of the running thread drops from 2.6 MB to 1.03 MB. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Wall-clock timing let other work on a busy runner inflate one side of a comparison, and a 2x step left little room between linear (2x) and the 3x limit. The cost check now times each call by its thread's CPU time, grows both axes 4x (2,500 to 10,000 turns, 375 to 1,500 steps), and fails when cost grows faster than size^1.5 (8x). Measured across all 461 cases: - With every core saturated, no case went above size^1.33; that was 1.21 or less outside one turn-axis case. Wall time at the old 2x step crossed the limit at that load. - Quadratics still fail: the old listGarbageCollectablePluginArtifacts at size^2.12, and the old listLatestClosedSessionsForHosts at size^1.66. The pre-#7474 retry check is still killed after 5 s of wall time. Three seeds keep a floor of projects, schedules and path plugins so their smaller world keeps the mix the cases need. Co-Authored-By: Claude Opus 5.5 <[email protected]>
On Linux, process.threadCpuUsage only advances at scheduler ticks, so CI read 0 or 4 ms for short calls and reported infinite growth. The cost check now uses the process's CPU time on Linux, which includes the running time slice, and the thread's CPU time on macOS. It prints which clock it used. Checked in a node:22 Linux container: all 461 cases pass, and the old listGarbageCollectablePluginArtifacts still fails at size^2.15. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Across 21 CI runs of the cost job on 9cb13b1, all passed, but listTimelineOrderingContext measured between size^1.24 and size^1.50, with the worst run exactly on the old size^1.5 limit. The same query measures size^1.09 to 1.18 in a Linux container and locally. Memory-heavy queries scale worse on shared runners under neighbouring load, and repeated measurement within a job cannot remove that. The check now blocks only on signals noise cannot produce: - growth faster than size^2 (16x on the 4x step); - a call killed after 5 s, or a case that throws. It reports GitHub Actions warnings for growth past size^1.5 and for time over a ceiling. The exact request-path statement-count test stays blocking. Checked against known regressions: - the old listGarbageCollectablePluginArtifacts fails at size^2.10; - the pre-#7474 retry query fails when it is killed; - the old listLatestClosedSessionsForHosts warns at size^1.60. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
deleted the
bb/query-plan-audit-catch-correlated-subqueries-and-thr_nhhrfssmyj
branch
November 14, 2026 06:08
ymichael
added a commit
that referenced
this pull request
Nov 14, 2026
The rebase onto #7535 left its cost case and plan allowlist entry on the old name, listThreadIdsStoppedSinceLastTurnStart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 14, 2026
The query-plan rules from #7535 flag a per-row search of the thread's refusals. Select the overtaken retries first, then read which of their originals were refused busy in one indexed query. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 14, 2026
The rebase onto #7535 left its cost case and plan allowlist entry on the old name, listThreadIdsStoppedSinceLastTurnStart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 15, 2026
Merged
Merged
ymichael
added a commit
that referenced
this pull request
Nov 17, 2026
The rebase onto #7535 left its cost case and plan allowlist entry on the old name, listThreadIdsStoppedSinceLastTurnStart. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 17, 2026
The query-plan rules from #7535 flag a per-row search of the thread's refusals. Select the overtaken retries first, then read which of their originals were refused busy in one indexed query. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ymichael
added a commit
that referenced
this pull request
Nov 18, 2026
…ime limit (#7745) ## Human comments ## What was wrong Most CI flakes logged this week came from one class: a test charges real work (Git or Node subprocesses, cold transforms, or thousands of instrumented queries) against a fixed per-test limit. On a slow, usually Windows, runner that work occasionally overruns the limit. Each item below was verified from the failing job log, then measured locally. The cause was rarely what the test is about. | Item | CI evidence | Cause found | |---|---|---| | `packages/db` `resolved-item-pruning-resume.test.ts` › seed 1 (15 s) | File took 64 s ([job](https://github.com/get-bb/bb/actions/runs/44168611379/job/134341637967)); 32–64 s in passing `main` runs; seed 1 failed twice | Two causes. (1) The query-plan test guard costs ~1.1 s per seed of ~1.7 s: on every `prepare` (Drizzle re-prepares each query) it captures a 40-frame stack in CI's `BB_QUERY_PLAN_EXECUTED` mode and re-resolves every frame. Without the guard, 16.6k prepares cost 124 ms. (2) 400-step runs grow superlinearly. | | `apps/server` `timeline-in-turn-window.test.ts:1140` (15 s) | Linux, file 41.8 s ([job](https://github.com/get-bb/bb/actions/runs/44170437386/job/134347996736)) | The verification helper loaded 1,750 content-deferred rows one by one (1,764 paged walks) to collect call ids those rows already carry. Only 7 delegation expansions were needed. | | `apps/server` `plugin-update.test.ts` › nested git plugin (Windows, 15 s) | [job](https://github.com/get-bb/bb/actions/runs/44170437386/job/134347996617) | Production runs `npm install` on every git plugin materialization, even when the plugin declares nothing npm would install. The test pays a cold npm boot three times (170–270 ms locally, seconds on Windows). Users pay it on every git plugin install and update. | | `environment-provider-host` `workspace-git-fetch.test.ts:194` (Windows, 15 s) | [job 1](https://github.com/get-bb/bb/actions/runs/44170437386/job/134347996813), [job 2](https://github.com/get-bb/bb/actions/runs/44166034127/job/134332437148) | Each case ran 9 Git commands (`remote add`/`fetch`/`push` per remote), and local transports spawn more helpers, before the one fetch under test. Every ref in the topology points at the same commit. | | `environment-provider-host` `workspace-git.test.ts:215` `beforeAll` (Windows, 10 s hook) | [job](https://github.com/get-bb/bb/actions/runs/44163251565/job/134322720725) | 9 Git spawns, including 2 `git config` calls per repo and a `fetch` right after a `push -u` that had already updated `origin/main`. | | `process-utils` `vcs-process-admission.test.ts:59` (Windows, 20 s) | 4.5 s / 8.1 s / 21.3 s (failed) on Windows ([job](https://github.com/get-bb/bb/actions/runs/44170133473/job/134346992616)) | Each timeout case started `git` → `sh` → a 30 s Node grandchild that inherited stdout/stderr. If the Windows tree kill (`taskkill /T`, 2 s cap) is slow under load, `execPortableFile` keeps waiting on pipes the grandchild still holds. | | `process-utils` `workload-priority.test.ts:38` (Windows, 5 s) | 0.45 s / 5.2 s / 7.1 s (failed) ([job](https://github.com/get-bb/bb/actions/runs/44152213676/job/134283643727)) | The child is lowered to below-normal priority, then must cold-boot a second Node process only to print that priority. A starved low-priority Node boot is the slow step. | | `logger` `logger.test.ts:215` and `:243` (Windows, 15 s) | [job](https://github.com/get-bb/bb/actions/runs/44168611379/job/134341637638) | Each test spawns `node --import tsx`, which transforms `@bb/logger` and `@bb/config` TypeScript, again inside pino's worker thread (it inherits `--import tsx`). | | `@bb/web` `oauth.test.ts:1137` (Windows, 5 s) | 5,048 ms; the 21-refresh sibling took 1,125 ms ([job](https://github.com/get-bb/bb/actions/runs/44156219534/job/134297803640)) | 72 sequential hourly refreshes, about 54 ms each on Windows PGlite, to prove a 24 h retention bound. Locally they take 2 ms each. | | macOS Package Smoke, first server start | Full stack timed out after 62.6 s ([job](https://github.com/get-bb/bb/actions/runs/44166147875/job/134333018710)); passing runs take 3.3–6.8 s | **Not a slow start; a hang.** The server printed `Starting server` and never answered `/health`. The smoke printed only stdout, so the log cannot show why. | | `timeline-in-turn-window.test.ts:1357` | **Not found.** No failure at that line in the last 60 CI runs. On `main` it falls inside the image-generation test, which takes 65 ms locally. | — | ## What changed **Fixes, at the cause:** - **Query-plan test guard** (`packages/db/src/query-plan-guard.ts`): memoizes located stack frames in nested maps keyed by script, line and function, instead of re-parsing every frame on every `prepare`. The audit dedupe key no longer concatenates the full SQL text on every execution; it uses caller → SQL → plan-signature maps. Findings and the executed-function report are unchanged. This benefits every `@bb/db` and `@bb/server` test. - **Pruning property test:** 16 seeds × 200 steps instead of 8 × 400, so the same 3,200 steps are split into shorter runs. Every seed still exercises 2–8 suffix-delete-and-compare cycles (81 in total). - **Git plugin dependencies** (`apps/server/src/services/plugins/git-plugin-dependencies.ts`): skip `npm install` when `package.json` declares no `dependencies` or `peerDependencies`. With `--omit=dev --omit=optional`, those are all npm would install. `.npmrc`/`.yarnrc` are still removed. Tests pin the skip (no `package-lock.json` written) and that a peer-only plugin still runs npm. - **Timeline helper:** `buildTimelineTurnSummaryDetails(…, "keep-deferred")` expands delegations but leaves content deferred. The two call-id-only tests use it; the 5 content-asserting callers still load. - **`workspace-git-fetch`:** `beforeAll` builds one final-state bare remote. Each case copies it and writes the remote config and tracking refs as files, so the only Git work per test is the fetch under test. - **`workspace-git`:** test identity and the remote are written into `.git/config` directly, as `@bb/test-helpers`' `initRepo` already does, and the redundant post-push `fetch` is dropped. `beforeAll` goes from 9 Git spawns to 5, the clone helper from 6 to 4, and every repo the file builds saves 2. - **`vcs-process-admission`:** the timeout case's delayed command is `exec sleep 30 </dev/null >/dev/null 2>&1`. That is no Node boot, and the command can't hold the root's pipes after the root is killed. The assertions (rejected with `killed: true, signal: SIGTERM`, then six recoveries) are unchanged. - **`workload-priority`:** the lowered child spawns the grandchild and reports its PID. The test reads `getPriority(grandchild)` directly, since Windows and POSIX fix the inherited priority at process creation. The grandchild never has to boot Node at low priority. - **`logger`:** `beforeAll` bundles `@bb/logger` once with esbuild's in-process API, keeping `pino`/`pino-pretty`/`pino-roll` external; the server ships it bundled too. The subprocess runs plain `node -e` with no tsx, in the main thread or the transport worker. Adds `esbuild` as a logger devDependency. - **`oauth`:** the retention test refreshes every `OAUTH_ROTATED_REFRESH_RETENTION_MS / 6` (4 h) over the same 72 h. That is 18 refreshes instead of 72, and the bound is derived from the constant instead of the literal 26. The reuse test spans the same 20 h in 4 steps instead of 20. A temporary break in production pruning still fails it. - **Package smoke:** on timeout it appends the tail of every log in the data directory's `logs/`, so the next hang shows what the server was doing. **Class policy:** - **Reporter:** `vitest.test-durations.ts`, added by `defineWorkspaceTestConfig` when `BB_TEST_DURATIONS_DIR` is set. It records every test that used ≥25% of its effective timeout (`testCase.options.timeout`, else the project's `testTimeout`). - **CI:** the Linux tests, Windows tests and Windows foundation jobs set the variable and upload the records with their `test-timings-*` artifacts. Foundation gains an upload step. - **Nightly report:** a new `CI Health` step downloads those artifacts from the last 20 `main` push runs. `scripts/report-test-headroom.mjs` (pure logic in `scripts/lib/test-headroom.mjs`, tested in `packages/scripts/test/test-headroom.test.mjs`) lists, per platform, every test that reached ≥50% of its timeout. Each row shows its worst duration, the number of runs near the limit and the number of failed runs. The list goes to the step summary and `.ci-health/test-headroom.md`. - **Docs:** `docs/ci-performance.md` gains "Tests near their time limit". ## How you verified Local numbers are on macOS (M-series), from interleaved before/after runs. Other agents were running suites on the same machine, so CPU time is shown where wall time was noisy. | Test | Before | After | |---|---|---| | `resolved-item-pruning-resume` slowest test | 1,680 ms | 510 ms | | `resolved-item-pruning-resume` file, CPU in CI's guard mode (3 rounds) | 15.3–16.8 s | 12.9–14.3 s | | `resolved-item-pruning-resume` file, test time (guard + split) | 10.1–13.6 s | 6.4 s | | two-seed profile, guard frames in CI mode | 4,540 ms | 2,767 ms | | `timeline` › delegated byte-budget slices | 1,542–1,651 ms | 106–115 ms | | `timeline` › finished turn over byte budget | 1,069–1,123 ms | 77–78 ms | | `timeline` file, test time | 4.2–4.4 s | 1.8 s | | `plugin-update` › nested git plugin | 1,491–1,675 ms | 1,040–1,333 ms | | `plugin-update` file, test time (npm skipped for every git fixture) | 11.9–12.7 s | 7.5–9.6 s | | `workspace-git-fetch` › prunes only origin (×2) | 414–549 ms | 111–147 ms | | `workspace-git-fetch` › only remote / several remotes | 184–213 / 277–284 ms | 94–113 / 71–106 ms | | `workspace-git` file, test time | 3.7–4.6 s | 3.3–4.0 s | | `logger` › worker mode / plain file | 619–629 / 503–507 ms | 379–398 / 365–379 ms | | `oauth` › bounded refresh rows / reuse in window | 143 / 65 ms | 49 / 29 ms | | `workload-priority` › lowers a running process | 51–54 ms | 27–29 ms | | `vcs-process-admission` › releases admission | 228–232 ms | 226–257 ms | `vcs-process-admission` shows no local difference because POSIX group kills are immediate; its fix targets the Windows pipe hold. **Windows CI, file durations.** "Before" is every sample in the failing jobs and recent logs above; "after" is this PR's full-matrix [run 44212664696](https://github.com/get-bb/bb/actions/runs/44212664696). This is one after sample, so the per-test check below is the stronger evidence. | File | Before | After | |---|---|---| | `vcs-process-admission` | 4.5 s, 8.1 s, 21.3 s (failed) | 1.5 s | | `workload-priority` | 0.45 s, 5.2 s, 7.1 s (failed) | 0.19 s | | `oauth` | 9.4–18.3 s (one failed) | 5.6 s | | `logger` | 6.1–6.8 s, 34.2 s (failed) | 5.5 s | | `workspace-git-fetch` | 21–47 s (two failed) | 20.8 s | | `workspace-git` | 28–51 s | 29.0 s | | `plugin-update` | 78.6 s (failed) | 52.3 s | | `timeline-in-turn-window` (Linux) | 41.8 s (failed) | 5.4 s | **Per-test check from the new reporter.** In that full run, across all 30 Linux and Windows test shards (37 record files, 87 tests at ≥25% of their timeout), **no test from any file fixed here reached even 25% of its timeout on any platform.** The report over that one run already lists 7 tests at ≥50% of their timeout. Several deliberately wait out a real timeout, for example `disk-usage` › kills every running du when the timeout elapses (62%), `desktop-browser-broker-client` › timed out broker (61–62%), `actions-api` › bounds recovery for timeout (55–56%), and `host-toolchain` › kills a shell that ignores SIGTERM (60%). They are the next work list, not part of this PR. - `@bb/db` full suite passes. Also passing: process-utils, logger, web, environment-provider-host and scripts full suites, and the touched `@bb/server` files (147 tests). - `typecheck`, `lint` and `lint:type-aware` pass for the 8 changed packages; root `lint:type-aware` passes; `actionlint` passes. - **Reporter end to end:** locally, `BB_TEST_DURATIONS_DIR=/tmp/tdur turbo run test --filter=@bb/db -- … --testTimeout=1000` writes one JSONL record per qualifying test, with the resolved timeout. In CI, all 30 `test-timings-*` artifacts of run 44212664696, including `windows-foundation`, contain records; `report-test-headroom.mjs` over them produced the table above. - **oauth mutation check:** with production pruning disabled, the 18-refresh test fails. ## Past fixes on these files - `workspace-git-fetch` / `workspace-git`: #7687 (shared fixture topology), #7145 (SSH wrapper independent of the fetch deadline). - `query-plan-guard.ts`: #7323 (structured call sites), #7711 (no reparsing of audit frames), #7535. - `plugin-update.test.ts`: #7685 (shared native plugin startup), #7688 (open: proposes 60 s for native loading). - `timeline-in-turn-window.test.ts`: #7541, #5261. - `vcs-process-admission.test.ts`: #5630. - `smoke-tarball.mjs`: #7202. ## Decisions for review - **Git plugins with no runtime or peer dependencies no longer run `npm install`** on install or update. It's faster, and no `package-lock.json` or `node_modules` is created in that plugin's directory. Plugins that declare dependencies are unchanged. - **The policy reports; it does not block.** A per-PR duration budget would itself fail on slow runners, the flake class this fixes. So durations are recorded in every CI test job and aggregated nightly across 20 `main` runs, which is a stable signal. The two numbers are policy constants, not per-test budgets: - 25% of timeout is the threshold for recording a test, which keeps artifacts small; - 50% is the threshold for listing it. Turbo cache hits replay results without running, so they add no records. Hook timeouts (as in `workspace-git` `beforeAll`) are not covered: Vitest does not expose hook durations to reporters. - **The pruning property test now explores shorter histories** (200 steps) across twice as many seeds. - **Not fixed: the macOS smoke hang.** The cause is unknown; the change is the diagnostic that will name it. - **Out of scope, noted:** on Windows, `stopWindowsProcessTree` caps `taskkill /T` at 2 s, and a tree it fails to kill keeps inherited pipes open. The `vcs-process-admission` fix stops the test from depending on that, but the production behaviour under load deserves its own issue. > AGENT GENERATED 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Human comments
What was wrong
The slow query in #7473 (fixed by #7474) passed the query-plan checks because every step used an index. Its cost was a correlated subquery that reread every request in the thread for each accepted turn, which is quadratic in history. Nothing measured how query cost grows with data, and nothing ran query functions against a large database.
The checks this PR adds found more of the same: two more quadratic queries (one runs on every thread list), a quadratic usage-pruning pass, a per-daemon-batch lookup that read every thread on the host, and several linear-in-history lookups. They also found a coverage hole: 69 exported query functions, including thread search and the sidebar listings, were invisible to every query-function check because they query through a private helper.
What changed
Detection
Plan rules (
packages/db/src/query-plan-audit.ts,query-plan-guard.ts). Plan rules run in every@bb/dband@bb/servertest, and in dev servers withBB_QUERY_PLAN_AUDIT.correlated-subqueryflags a search on a large table that runs once per outer row. That covers correlated subqueries andEXISTSsubqueries that SQLite turns into joins, when the search key grows with history. A search on a unique key, or on a bounded column (turn_id,item_id,parent_tool_call_id), is accepted.nested-loopflags an unindexed loop over a CTE or subquery that runs once per history row of a large table. That was the shape of the oldgetFirstParentedTimelineBoundarySequencejoin.json_eachand other virtual tables are ignored.<expr>=?) now count as equality terms. Without this, the guard called faster expression-index plans "weaker".@bb/dband@bb/serversuites, the new rules flag 15 callers. All are fixed or allowlisted with a measured reason.Coverage now includes wrappers (
packages/db/scripts/query-functions.ts).test/query-functions.test.tscovers the helper-following.Cost check across every data file, on two growth axes (
check:query-costs).threads: 10,000 threads, search segments, tabs, outlines, 50,000 prompt history entries, pruning work.hosts-environments: 50 hosts, 1,000 sessions, 4,000 environments, 15,000 terminal sessions, projects, attachments.plugins: 100 plugins, artifacts, snapshots, 5,000 storage rows, marketplaces.settings-maintenance: interactions, retained outputs, sweeps, legacy rows for the migrations.listTimelineOrderingContextmeasured between size^1.24 and size^1.50. It measures size^1.09–1.18 in a Linux container and locally. Memory-heavy queries scale worse on shared runners, and repeating the measurement within a job doesn't remove that.created_at, such as the turn-start deadline sweep's, therefore behave as they do on a real long thread rather than seeing every event as brand new.--group <names>runs a subset.--db <copy>migrates aVACUUM INTOcopy of a real database, seeds the full-scale world into it, and checks the ceiling and kill rules against real data shapes. It refuses~/.bb/bb.db.Server
eventsqueries moved into@bb/db.eventsdirectly in three files. That covered the edit path, thread-start staleness, provisioning cancellation and the turn-start deadline sweep. It now goes through@bb/db, so the cost check and the "query functions run in tests" check cover it.findStoredEditMessageOperationRow,findLatestEditableUserTurnRequestRow,hasStoredThreadInterruptedSince,hasStoredProviderTurnCompletedSince,hasStoredCancelledThreadProvisioning,listTurnStartDeadlineCandidatesandisThreadAwaitingTurnStartPastDeadline.eventsdirectly any more. The remaining server queries run against small tables (environments, machines, projects, sessions), where the plan guard is enough.Statement counts and response size on request paths (
apps/server/test/perf/request-path-statements.test.ts).IN (...)lists collapsed. A path fails if any statement runs more often in the larger server.CI. The
Query Plan Auditworkflow also runs on PRs that changepackages/db. It has two jobs:Fixes the checks found
No new indexes and no migration: every fix uses an index that already exists.
listGarbageCollectablePluginArtifactsNOT EXISTSover unindexed columns, joined withORNOT INsets, built once per querylistLatestClosedSessionsForHosts(every thread list)host_daemon_sessions_host_status_idxlistThreadEnvironmentAssignmentsOnHost(every daemon event batch)getFirstParentedTimelineBoundarySequencegetStoredTurnRequestEventForTurnjson_extractover every request in the threadfindLatestUnresolvedClientTurnRequestIdAfterSequencelistCommandItemDataByItemIds.all()olderRowUpdates, and every streamed delta re-sent themlistTimelineOrderingContext(cold timeline open)json_eachcheck on every requestlistEventsreturned a whole thread and only tests called it, so it moved to@bb/db/testing.These lookups are linear, unchanged from main, and inside every limit:
listStoredClientTurnRequestRowsByKeyshasStoredTerminalClientTurnRequestEventlistStoredTurnInputAcceptedRowsByClientRequestIdsThey have no position to start from. An expression index on the request id would make them flat, but building it reads every events row (12–21 s on a 4.35M-event database), so it isn't worth a migration.
Known linear costs (measured, under the ceiling)
bb thread showmessage viewsadvanceLiveEventPruningresumedocs/debugging-and-qa.mddocuments all the checks.How you verified
The checks fail on known-bad queries and responses:
Full runs on the final branch:
check:query-costs: 436 query functions in 461 cases, all within limits on both axes, in 43 s locally at load 16–23.check:query-costs --dbon a freshVACUUM INTOcopy of a real 8.8 GB database (4.6M events after seeding): all 429 within limits. The copy was deleted afterwards.BB_QUERY_PLAN_REPORTacross all@bb/dband@bb/servertests, thencheck:query-plan-report: "matches the allowlist (309 findings) and runs all 436 query functions".Targeted tests:
@bb/db: events, threads, sessions, hosts, plugin persistence, thread pruning, queued messages, query plans, plan audit and guard, history fixture, query functions, migrations.@bb/server: perf, event pruning, internal events, edit, restart-resume, runtime display, plugin services. Onebuiltin-pluginstest failed once under load and passed when rerun on its own.Static checks: typecheck and lint for
@bb/dband@bb/server,oxfmt --check, and the provider-literal ratchet.🤖 Generated with Claude Code