Skip to content

Catch and fix queries and responses whose cost grows with data - #7535

Merged
ymichael merged 13 commits into
mainfrom
bb/query-plan-audit-catch-correlated-subqueries-and-thr_nhhrfssmyj
Nov 14, 2026
Merged

ymichael merged 13 commits into
mainfrom
bb/query-plan-audit-catch-correlated-subqueries-and-thr_nhhrfssmyj

Conversation

@ymichael

@ymichael ymichael commented Nov 13, 2026 •

Copy link
Copy Markdown
Collaborator

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

  1. Plan rules (packages/db/src/query-plan-audit.ts, query-plan-guard.ts). Plan rules run in every @bb/db and @bb/server test, and in dev servers with BB_QUERY_PLAN_AUDIT.

    • correlated-subquery flags a search on a large table that runs once per outer row. That covers correlated subqueries and EXISTS subqueries 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-loop flags an unindexed loop over a CTE or subquery that runs once per history row of a large table. That was the shape of the old getFirstParentedTimelineBoundarySequence join. json_each and other virtual tables are ignored.
    • Expression-index terms (<expr>=?) now count as equality terms. Without this, the guard called faster expression-index plans "weaker".
    • On the full @bb/db and @bb/server suites, the new rules flag 15 callers. All are fixed or allowlisted with a measured reason.
  2. Coverage now includes wrappers (packages/db/scripts/query-functions.ts).

    • A query function is now an exported function that queries directly, or calls a function in the same file that does. That raises the count from 360 to 429.
    • The same list drives the "query functions run in tests" checks, and all 429 run in tests. test/query-functions.test.ts covers the helper-following.
  3. Cost check across every data file, on two growth axes (check:query-costs).

    • Thread history: 2,500 vs 10,000 turns, with 100-step long turns.
    • Turn size: 500 turns with 375-step vs 1,500-step long turns. One thread also has an open long turn, and 25 cases target it: active-turn checks, unfinished commands, the live timeline window, item spans and lifecycle, buffered deltas, and appending into the open turn.
    • Every case runs on both axes, and a failure names the axis.
    • Each axis grows 4× between its smaller and larger world.
    • Base thread: a 10,000-turn thread written through the real event write path.
    • Seeded tables: one case group per area seeds its own tables at about twice the largest real install, and grows them with the same scale:
      • 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.
    • Timing: each call is timed by CPU time, not wall time, so other work on a busy runner doesn't count against it. That's the thread's CPU time on macOS and the process's on Linux, where a thread's CPU time only advances at scheduler ticks.
    • Blocking rules (CI fails): only signals timing noise can't produce.
      • Quadratic growth: cost grows faster than size^2 (more than 16×) when the data grows 4×, once the full-scale time reaches 2 ms.
      • Kill: a single call runs past 5 s of wall time.
      • Error: a case throws.
    • Warnings (GitHub Actions annotations, not failing): growth past size^1.5 (8×), and full-scale time over a case's ceiling (250 ms by default). A case that crosses size^1.5 is measured up to 8 times before it's reported.
    • Why two tiers:
      • Over 21 CI runs on one commit, listTimelineOrderingContext measured 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.
      • Quadratics measure about size^2: the old plugin GC query at 2.10, so it blocks. The old closed-sessions query measures 1.60, so it only warns.
      • The exact request-path statement-count test stays blocking.
    • It also fails when any exported query function has no case.
    • It covers 436 query functions in 461 cases, and takes about 45 s locally.
    • Fixture timestamps: events are spread 30 s apart over each thread's history, ending an hour before the build. Predicates on 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.
    • New flags:
      • --group <names> runs a subset.
      • --db <copy> migrates a VACUUM INTO copy 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.
  4. Server events queries moved into @bb/db.

    • The server used to build SQL against events directly 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.
    • Five call sites reuse existing data functions.
    • Seven are new: findStoredEditMessageOperationRow, findLatestEditableUserTurnRequestRow, hasStoredThreadInterruptedSince, hasStoredProviderTurnCompletedSince, hasStoredCancelledThreadProvisioning, listTurnStartDeadlineCandidates and isThreadAwaitingTurnStartPastDeadline.
    • No server code queries events directly any more. The remaining server queries run against small tables (environments, machines, projects, sessions), where the plan guard is enough.
  5. Statement counts and response size on request paths (apps/server/test/perf/request-path-statements.test.ts).

    • It runs on both axes: history (100 vs 200 turns) and turn size (750 vs 1,500 steps).
    • Paths against the running thread include detail, timeline open, outline, context, head state, turn details, a timeline delta while the open turn streams, daemon ingestion into it, send and stop.
    • A response-size check fails when a response grows more than 1.5× (plus 4 KiB) when the data doubles.
    • The test runs two servers. The larger has twice the history (100 vs 200 turns) and twice as many other threads (20 vs 40).
    • It counts statements per path at the better-sqlite3 layer, with full SQL and IN (...) lists collapsed. A path fails if any statement runs more often in the larger server.
    • It covers 24 paths, including thread list, search and count, timeline, outline, turn details, events, prompt history, read/unread, pin, daemon event ingestion, send with a queued retry, edit, stop, fork and periodic sweeps.
    • Fork and the sweeps are declared linear (copying every event, and budgeted per-thread work) and may grow at most 2.5×.
    • Counts are exact, so the result doesn't depend on machine speed.
  6. CI. The Query Plan Audit workflow also runs on PRs that change packages/db. It has two jobs:

    • the plan report: stale allowlist entries and untested query functions;
    • the cost check.

Fixes the checks found

No new indexes and no migration: every fix uses an index that already exists.

Query Problem Fix Before → after (full scale)
listGarbageCollectablePluginArtifacts artifacts × snapshots: correlated NOT EXISTS over unindexed columns, joined with OR non-correlated NOT IN sets, built once per query 81.8 ms, 4.2× growth → 1.15 ms, linear
listLatestClosedSessionsForHosts (every thread list) rewalked the global closed-session index for every session row one lookup per host through the existing host_daemon_sessions_host_status_idx 2.34 ms, 3.5× growth → 0.13 ms, flat
Usage snapshot pruning the delete for each 16-row chunk walked every usage row of the type the delete seeks the candidate ids through the primary key quadratic per thread pass → bounded per chunk
listThreadEnvironmentAssignmentsOnHost (every daemon event batch) read every thread on the host (with 50 ids, SQLite drove the join from the host) looks up the batch's thread ids grew with the threads on the host; now bounded by the batch size
getFirstParentedTimelineBoundarySequence requests × delegation spans each span's first matching request through a range seek 2.9× growth → under 1 ms
getStoredTurnRequestEventForTurn json_extract over every request in the thread searches backwards from the accepted input's sequence 7.6 ms → 0.08 ms
findLatestUnresolvedClientTurnRequestIdAfterSequence scanned the whole thread per pending request starts at the request's sequence on the type index 12.8 ms → 0.06 ms
listCommandItemDataByItemIds scanned the whole thread seeks by item through the item-lifecycle index 11 ms → 0.02 ms
Edit message loaded every user request with .all() reads one candidate at a time; the acceptance lookup starts at the request's sequence linear → one row in the common case
Latest timeline page with a long open turn (found by the turn-size axis) the page reported every older row of the open turn as olderRowUpdates, and every streamed delta re-sent them reports rows from the first returned leaf when the window cuts inside a segment delta 266 KB (750 steps) → 1.55 MB (1,500 steps) became 2.3 KB at both sizes; cold open 2.6 MB → 1.03 MB
listTimelineOrderingContext (cold timeline open) drizzle mapping, and the json_each check on every request raw rows, a fast path for the first input part, JSON columns only where used 106 ms → 41 ms (still linear by design)

listEvents returned 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:

Query Full scale
listStoredClientTurnRequestRowsByKeys 6.7 ms
hasStoredTerminalClientTurnRequestEvent 3.4 ms
listStoredTurnInputAcceptedRowsByClientRequestIds 3.2 ms

They 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)

Query Full-scale time Where it runs
Conversation outline readers about 106 ms (117 ms on the real copy) cold outline cache and bb thread show message views
Thread search about 48 ms synthetic, 99 ms on the real copy grows with matching threads
Cold timeline ordering about 41 ms cold timeline open
advanceLiveEventPruning resume about 30 ms background sweep; grows with how far the cursor is behind
The turn-start deadline sweep per active thread sweep

docs/debugging-and-qa.md documents 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.
  • Noise margin for the cost check:
    • Five quiet runs and one with every core saturated (load ~30) all passed.
    • The highest healthy exponent was 1.33, against the 1.5 limit. With wall time and a 2× step, the same load pushed linear queries past the limit.
  • check:query-costs --db on a fresh VACUUM INTO copy of a real 8.8 GB database (4.6M events after seeding): all 429 within limits. The copy was deleted afterwards.
  • BB_QUERY_PLAN_REPORT across all @bb/db and @bb/server tests, then check:query-plan-report: "matches the allowlist (309 findings) and runs all 436 query functions".
  • The request-path and timeline-pagination tests pass (86). With the pagination fix reverted, the response-size check fails on live timeline open and on the streaming delta.

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. One builtin-plugins test failed once under load and passed when rerun on its own.

Static checks: typecheck and lint for @bb/db and @bb/server, oxfmt --check, and the provider-literal ratchet.

AGENT GENERATED

🤖 Generated with Claude Code

ymichael and others added 6 commits November 13, 2026 13:28
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]>
@ymichael ymichael changed the title Catch query costs that grow with thread history before they ship Catch and fix queries whose cost grows with data Nov 13, 2026
ymichael and others added 4 commits November 13, 2026 15:05
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]>
…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]>
@ymichael ymichael changed the title Catch and fix queries whose cost grows with data Catch and fix queries and responses whose cost grows with data Nov 14, 2026
ymichael and others added 3 commits November 13, 2026 17:58
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
ymichael merged commit eb43faa into main Nov 14, 2026
94 checks passed
@ymichael
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]>
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]>
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