Repository navigation
Make slow real-subprocess tests cheaper and report tests near their time limit - #7745
Merged
Merged
Conversation
…ime limit Co-Authored-By: Claude Opus 5.5 <[email protected]>
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
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]>
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
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.
packages/dbresolved-item-pruning-resume.test.ts› seed 1 (15 s)mainruns; seed 1 failed twiceprepare(Drizzle re-prepares each query) it captures a 40-frame stack in CI'sBB_QUERY_PLAN_EXECUTEDmode and re-resolves every frame. Without the guard, 16.6k prepares cost 124 ms. (2) 400-step runs grow superlinearly.apps/servertimeline-in-turn-window.test.ts:1140(15 s)apps/serverplugin-update.test.ts› nested git plugin (Windows, 15 s)npm installon 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-hostworkspace-git-fetch.test.ts:194(Windows, 15 s)remote add/fetch/pushper 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-hostworkspace-git.test.ts:215beforeAll(Windows, 10 s hook)git configcalls per repo and afetchright after apush -uthat had already updatedorigin/main.process-utilsvcs-process-admission.test.ts:59(Windows, 20 s)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,execPortableFilekeeps waiting on pipes the grandchild still holds.process-utilsworkload-priority.test.ts:38(Windows, 5 s)loggerlogger.test.ts:215and:243(Windows, 15 s)node --import tsx, which transforms@bb/loggerand@bb/configTypeScript, again inside pino's worker thread (it inherits--import tsx).@bb/weboauth.test.ts:1137(Windows, 5 s)Starting serverand never answered/health. The smoke printed only stdout, so the log cannot show why.timeline-in-turn-window.test.ts:1357mainit falls inside the image-generation test, which takes 65 ms locally.What changed
Fixes, at the cause:
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 everyprepare. 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/dband@bb/servertest.apps/server/src/services/plugins/git-plugin-dependencies.ts): skipnpm installwhenpackage.jsondeclares nodependenciesorpeerDependencies. With--omit=dev --omit=optional, those are all npm would install..npmrc/.yarnrcare still removed. Tests pin the skip (nopackage-lock.jsonwritten) and that a peer-only plugin still runs npm.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:beforeAllbuilds 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/configdirectly, as@bb/test-helpers'initRepoalready does, and the redundant post-pushfetchis dropped.beforeAllgoes 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 isexec 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 withkilled: true, signal: SIGTERM, then six recoveries) are unchanged.workload-priority: the lowered child spawns the grandchild and reports its PID. The test readsgetPriority(grandchild)directly, since Windows and POSIX fix the inherited priority at process creation. The grandchild never has to boot Node at low priority.logger:beforeAllbundles@bb/loggeronce with esbuild's in-process API, keepingpino/pino-pretty/pino-rollexternal; the server ships it bundled too. The subprocess runs plainnode -ewith no tsx, in the main thread or the transport worker. Addsesbuildas a logger devDependency.oauth: the retention test refreshes everyOAUTH_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.logs/, so the next hang shows what the server was doing.Class policy:
vitest.test-durations.ts, added bydefineWorkspaceTestConfigwhenBB_TEST_DURATIONS_DIRis set. It records every test that used ≥25% of its effective timeout (testCase.options.timeout, else the project'stestTimeout).test-timings-*artifacts. Foundation gains an upload step.CI Healthstep downloads those artifacts from the last 20mainpush runs.scripts/report-test-headroom.mjs(pure logic inscripts/lib/test-headroom.mjs, tested inpackages/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/ci-performance.mdgains "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.
resolved-item-pruning-resumeslowest testresolved-item-pruning-resumefile, CPU in CI's guard mode (3 rounds)resolved-item-pruning-resumefile, test time (guard + split)timeline› delegated byte-budget slicestimeline› finished turn over byte budgettimelinefile, test timeplugin-update› nested git pluginplugin-updatefile, test time (npm skipped for every git fixture)workspace-git-fetch› prunes only origin (×2)workspace-git-fetch› only remote / several remotesworkspace-gitfile, test timelogger› worker mode / plain fileoauth› bounded refresh rows / reuse in windowworkload-priority› lowers a running processvcs-process-admission› releases admissionvcs-process-admissionshows 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.
vcs-process-admissionworkload-priorityoauthloggerworkspace-git-fetchworkspace-gitplugin-updatetimeline-in-turn-window(Linux)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%), andhost-toolchain› kills a shell that ignores SIGTERM (60%). They are the next work list, not part of this PR.@bb/dbfull suite passes. Also passing: process-utils, logger, web, environment-provider-host and scripts full suites, and the touched@bb/serverfiles (147 tests).typecheck,lintandlint:type-awarepass for the 8 changed packages; rootlint:type-awarepasses;actionlintpasses.BB_TEST_DURATIONS_DIR=/tmp/tdur turbo run test --filter=@bb/db -- … --testTimeout=1000writes one JSONL record per qualifying test, with the resolved timeout. In CI, all 30test-timings-*artifacts of run 44212664696, includingwindows-foundation, contain records;report-test-headroom.mjsover them produced the table above.Past fixes on these files
workspace-git-fetch/workspace-git: Reuse private Git fixture topology to reduce refresh and branch-test setup #7687 (shared fixture topology), Keep SSH wrapper compatibility test independent of fetch deadline #7145 (SSH wrapper independent of the fetch deadline).query-plan-guard.ts: Reduce query-plan test instrumentation cost with structured call sites #7323 (structured call sites), Avoid formatting and reparsing structured query audit frames #7711 (no reparsing of audit frames), Catch and fix queries and responses whose cost grows with data #7535.plugin-update.test.ts: Wait for admitted test work and share native plugin startup #7685 (shared native plugin startup), Give the native plugin loading tests 60 s on slow Windows runners #7688 (open: proposes 60 s for native loading).timeline-in-turn-window.test.ts: Make paged timeline reads match a full build, with equivalence and cost guards #7541, Build test databases from one template, share test setup, and move DOM-free tests out of jsdom #5261.vcs-process-admission.test.ts: Bound git and gh subprocesses with shared priority admission #5630.smoke-tarball.mjs: Overlap independent Windows tarball smoke checks #7202.Decisions for review
Git plugins with no runtime or peer dependencies no longer run
npm installon install or update. It's faster, and nopackage-lock.jsonornode_modulesis 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
mainruns, which is a stable signal. The two numbers are policy constants, not per-test budgets:Turbo cache hits replay results without running, so they add no records. Hook timeouts (as in
workspace-gitbeforeAll) 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,
stopWindowsProcessTreecapstaskkill /Tat 2 s, and a tree it fails to kill keeps inherited pipes open. Thevcs-process-admissionfix stops the test from depending on that, but the production behaviour under load deserves its own issue.🤖 Generated with Claude Code