Skip to content

Make slow real-subprocess tests cheaper and report tests near their time limit - #7745

Merged
ymichael merged 2 commits into
mainfrom
bb/slow-subprocess-test-costs
Nov 18, 2026
Merged

ymichael merged 2 commits into
mainfrom
bb/slow-subprocess-test-costs

Conversation

@ymichael

@ymichael ymichael commented Nov 18, 2026 •

Copy link
Copy Markdown
Collaborator

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); 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) 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 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, job 2 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 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) 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) 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 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) 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); 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. 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

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

ymichael and others added 2 commits November 17, 2026 17:01
Setting reporters in the shared config replaced Vitest's defaults, so CI
jobs with BB_TEST_DURATIONS_DIR lost the github-actions reporter.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@ymichael
ymichael merged commit 2625899 into main Nov 18, 2026
54 checks passed
@ymichael
ymichael deleted the bb/slow-subprocess-test-costs branch November 18, 2026 04:14
ymichael added a commit that referenced this pull request Nov 24, 2026
…races (#8079)

## Human comments

## What was wrong

Each of these tests failed on CI in the past week, then passed on a
rerun of the same SHA, or failed on `main` with no relevant change. I
checked every failing job log and traced the cause. Most are the same
class as #7745: real work charged against a fixed deadline on a loaded
Windows runner. In each case the expensive step was not what the test is
about.

| Test | CI evidence | Root cause |
|---|---|---|
| `process-utils` `workload-priority.test.ts` › lowers a running process
so the processes it starts later inherit the priority (Windows, 5 s) | 5
timeouts at 5.0 s, 4 of them after #7745, one on `main`
([job](https://github.com/get-bb/bb/actions/runs/44798992406/job/136506064404));
passing runs 2.8–4.9 s | #7745 stopped the grandchild from booting Node
at low priority. The child still does. The test lowered the child right
after `spawn`, so its whole Node bootstrap ran at below-normal priority.
It then needed a second lowered wake-up (`"done"`) to kill the
grandchild and exit. On a saturated Windows runner a below-normal thread
can wait about 4 s for the anti-starvation boost, once for each burst. |
| `agent-runtime` `runtime.process-lifecycle.test.ts` › does not wait
for stalled replacement initialization during full shutdown (Windows) |
`Timed out after 1000ms waiting for the replacement bridge to begin
initialization`, twice
([job](https://github.com/get-bb/bb/actions/runs/44386079401/job/135091227510))
| The setup step polled for a marker file with the helper's 1 s budget.
That window covers retiring one Node bridge and spawning another. The
sibling test that does exactly that took 2.8 s in the same failing job.
|
| `local-open-targets` `workspace-open-targets.test.ts` › discovers and
opens JetBrains Toolbox applications through bundled executables
(Windows, 5 s) | 5.05 s and 5.08 s
([job](https://github.com/get-bb/bb/actions/runs/44814274981/job/136558617339));
passing runs 0.49 s and 1.07 s | The macOS listing walked the JetBrains
Toolbox tree once for every JetBrains product (8), one readdir at a
time: 54 readdirs in this test. In the same failing job, fs ops cost
about 100 ms each (the TextMate test, about 8 fs ops, took 805 ms). The
cost is in the product: every "Open in" listing on a Mac with Toolbox
walks the tree 8 times. |
| `thread-view` `tool-call-parsing-performance.test.ts` › bounds intent
parsing work after a script's disqualifying write (Windows) | `expected
4.80 to be less than 4.77` on `main`
([job](https://github.com/get-bb/bb/actions/runs/45242326493/job/137930150703)),
plus 2 more | The `/ 8` bound sits on the healthy ratio. Both commands
pay the same O(n) cost to build, hash and cache the command string, so a
correct early exit is only 6.5–8× cheaper on Windows (10–12× on an
M-series Mac). The regression the test guards, scanning on after the
write, gives a ratio of about 1. |
| `desktop` `server-moved.test.ts` › closes the watcher and polls after
a watch error (Linux) | `expected "vi.fn()" to be called once`
([job](https://github.com/get-bb/bb/actions/runs/44847337211/job/136670291512))
| A race in the test's manual scheduler. The first `flush()` starts the
initial lock read. If that read is still in flight when the second
`flush()` fires the poll, the poll only marks a recheck. The in-flight
read then sees no lock and schedules a debounced check on the manual
scheduler, which the test never flushed again. |
| Windows app smoke on `main`: `bb plugin list failed with 1` / `bb-app
SDK status failed with 1`, with no output
([run](https://github.com/get-bb/bb/actions/runs/44443547241),
[run](https://github.com/get-bb/bb/actions/runs/44790721793)) | Both
after "daemon join" | `waitForProcessExit` resolved on `'exit'`, which
Node fires before the child's stdio is drained. The SDK step is a `node
-e` script, and one that exits 1 always writes a stack trace to stderr,
yet both failure messages were empty. Why the commands exited 1 is still
unknown. This change makes the next occurrence show it. |

Looked at and left alone:
- `tool-call-parsing-performance` › scans long quoted thread messages in
chunks: all 4 failures were on SHAs without #7680, which moved these
benchmarks to thread CPU time. No failure since.
- `plugin-sdk` `vendor-plugin-roots.test.ts` (Windows, 5 s, 3 failures):
a victim of runner saturation, not of its own work. The resolver does
14–39 fs ops per test, none redundant. In the failing jobs every test in
the file slowed from 5–100 ms to 2–6 s during one window, while
`shared-declaration-emit` (9–16 s), `runtime-entries` (5–16 s) and
`api-index` (5.7 s) were running too. In the last 19 `main` runs it
reached 50% of its limit once. A larger timeout would only move the
deadline. The real fix is Windows-shard oversubscription (unbounded
`VITEST_MAX_WORKERS` × turbo concurrency on 8 vCPUs), which belongs in
its own change.
- `scripts` `ci-performance.test.mjs` › ENOTEMPTY removing the fixture's
`.git` (Linux, once): I found no concurrent writer. Each `git commit`
does leave a detached `git maintenance run --auto` behind. An strace
(git 2.56) shows it only unlinks `objects/maintenance.lock`, and it
creates nothing in `.git` after `commit` returns. 750 Linux iterations
of the exact fixture sequence, under CPU contention, produced no
failure. A retry would only hide whatever caused it.

## What changed

- `packages/process-utils/test/workload-priority.test.ts`: the child
prints `ready` after booting at normal priority, and only then is it
lowered. The lowered work is now one wake-up and one `spawn`, the
minimum the claim needs. The test reads the grandchild's priority, and
`stop()` tears down the tree at normal priority (`taskkill /T`, or the
process group). The child no longer has to be scheduled again to exit.
The test gets a 15 s budget. That one wake-up can still wait about 4 s
for Windows' anti-starvation boost on a saturated runner, and the
inherent worst case of about 4 s + about 1 s bootstrap + taskkill is
above 5 s.
- `packages/agent-runtime/src/runtime.process-lifecycle.test.ts`: the
stalled bridge writes a line to stderr when it receives `initialize`,
and the test awaits it through the manager's `onStderr`. There is no
polling budget. The real assertion is unchanged: shutdown completes
within 1 s instead of waiting for the bridge's 3 s stall.
- `packages/local-open-targets/src/index.ts`: the Toolbox `apps` tree is
walked once per runtime, and each JetBrains adapter matches its prefixes
against the collected bundles. Traversal order, depth limit and the
executable check are unchanged, so results are the same. The daemon
builds a new runtime for every request
(`apps/host-daemon/src/local-api.ts`), so the walk is never stale across
requests. In this test: 54 readdirs down to 12, 6 for the listing and 6
for the open.
- `packages/thread-view/test/tool-call-parsing-performance.test.ts`: the
bound is `readOnly / 3`. It sits between the healthy ratio (6.5–12×) and
the regressed ratio (about 1×), with more than 2× margin on each side.
- `apps/desktop/test/server-moved.test.ts`: the `waitFor` flushes the
manual scheduler on each attempt, so a recheck that the in-flight
initial read schedules also runs.
- `packages/bb-app/scripts/smoke-tarball.mjs`: `runCommand` and the
bridge `model/list` step wait for `'close'` (new
`waitForProcessOutput`), after the process has exited and its stdio has
closed, so a failing command's stdout and stderr reach the error. The
forked plugin-host worker keeps `waitForProcessExit` (`'exit'`). Node
never emits `'close'` once the parent disconnects the IPC channel, which
I checked with a minimal fork/disconnect script, and the first local
smoke run with `'close'` everywhere hung at that step.

No wire, CLI or doc changes.

## How you verified

All local numbers are from an M-series Mac. Other agents' suites were
running on the same machine, with load averages of 100–700.

| Test | Before (`origin/main`) | After |
|---|---|---|
| `workload-priority`, with the lowered child also put in macOS
background QoS (`taskpolicy -b -p`) and 32 CPU burners, to model
Windows' strict below-normal scheduling | Spawn to grandchild pid:
13.5–25.1 s, then another 1.7–11.2 s to exit (5 s limit) | Ready 26–102
ms at normal priority, lowered burst 48–913 ms, `stop()` about 105 ms
(16 timed runs). macOS background QoS can starve a process indefinitely,
which Windows does not: in a 50-run batch under this model a few runs
still waited 30 s or more for that one burst. |
| `workload-priority`, unmodified, 30 repeats | 30/30 | 30/30, about 160
ms per run instead of 65 ms, because `stop()` polls the process group at
normal priority. No leaked grandchildren afterwards. |
| `runtime.process-lifecycle` stalled-replacement test, with a preload
that delays every child Node start by 1 s to model Windows spawn cost |
Fails with the CI error, `Timed out after 1000ms waiting for the
replacement bridge to begin initialization` | 20/20 |
| Same test, unmodified, 30 repeats with 48 CPU burners, and with
background QoS | passes | passes |
| JetBrains Toolbox test, fs calls counted by wrapping `fs/promises` |
54 readdirs (46 listing + 8 open) | 12 readdirs (6 + 6). 100/100 repeats
pass. |
| Parser bound, 40 repeats | — | 40/40. Injected regression (keep
scanning after the write, same result): `expected 57.0 to be less than
18.5`, still caught. |
| `server-moved` watch-error test, with the first lock read delayed by
200 ms | Fails with the CI error, `expected "vi.fn()" to be called once
with arguments` | Passes, and 500/500 unmodified. With `schedulePoll()`
removed from the watch-error fallback it still fails. |
| Smoke `waitForProcessExit` | Can't reproduce the lost output on macOS
or Linux (Node's `'exit'`-before-stdio ordering shows up on Windows
IOCP). | Local `turbo run smoke:tarball --filter=bb-app`: every step
passes, including full stack, daemon join and plugin host worker |

`pnpm exec turbo run lint typecheck --filter=@bb/process-utils
--filter=@bb/thread-view --filter=@bb/agent-runtime
--filter=@bb/local-open-targets --filter=@bb/desktop --filter=bb-app`
passes. `pnpm exec turbo run test` for the same packages passes except
`process-utils` `process-tree.test.ts` › finds and kills processes whose
cwd is inside a directory. That file is untouched and also fails alone
on this machine, which had about 1,020 processes running at the time.

> 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