Skip to content

Stop test helpers leaking temp dirs into tmpdir() - #7882

Open
smsunarto wants to merge 20 commits into
get-bb:mainfrom
smsunarto:scott/bb-1-clean-up-fake-plugin-host-temp-dirs-in-test-thr_bcvgyetpsm
Open

smsunarto wants to merge 20 commits into
get-bb:mainfrom
smsunarto:scott/bb-1-clean-up-fake-plugin-host-temp-dirs-in-test-thr_bcvgyetpsm

Conversation

@smsunarto

@smsunarto smsunarto commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Human comments

What was wrong

createFakePluginHost made a bb-fake-plugin-host-* dir under os.tmpdir() for every host and removed it only in dispose(), so every test that skipped dispose() leaked one. A process.on("exit") fallback can't help. vitest stops its fork workers with SIGTERM (then SIGKILL after 500 ms), so exit never fires there.

Main's per-run TMPDIR sandbox (#6212) already contains these leaks for the packages on the shared vitest config. The 43 plugin and tunnel packages use plain defineConfig, have no sandbox, and are where the fake host still leaks: 297 dirs across 26 plugin suites in one run.

What changed

  • Fake plugin host (plugin-sdk/src/testing/fake-storage-dir.ts):
    • The host dir is created on the first storage.database() call, so a host that never opens a database writes nothing to disk.
    • dispose() still removes the host's dir right away.
    • Every host dir sits under one root per process, bb-fake-plugin-host-<pid>-*, which is removed when the process exits or receives SIGTERM.
    • A test that needs its host's dir gone sooner calls dispose(). The createFakePluginHost doc comment states this guarantee.
    • The upstream database() pragmas are unchanged. Nothing in the public API changes. The SDK is bumped to 0.6.168 because its packed content changed.
  • Process-end cleanup (plugin-sdk/src/testing/process-end-cleanup.ts, private to the testing entry):
    • Cleanups run on exit and on SIGTERM.
    • The SIGTERM listener never changes what SIGTERM does for other listeners. If another SIGTERM listener is registered when the signal arrives, or already ran for this signal (a once listener prepended later), it only cleans up and leaves termination to that listener.
    • It re-raises SIGTERM only when its own copies are the only listeners, so the process still dies of SIGTERM. Copies are recognised by a Symbol.for tag.
    • SIGINT is not intercepted.
    • On Windows, killing a process with SIGTERM terminates it without running listeners, so there only exit and dispose() clean up. The SIGTERM test cases run on POSIX only, and the exit cases run everywhere.
  • Parity replay (replayRecordingAttempt): prepareState and the wrapper write ran before the try whose finally removes the replay's state and workspace dirs, so a throwing profile left both behind. They now run inside it. No suite exercised this path in the measurement below; the regression test covers it.
  • Automations: the legacy-import test removes its bb-auto-plugin-* dir.

Leak sites from earlier rounds of this PR that main's sandbox already handles leave 0 entries on main, so this version drops their fixes:

  • agent-runtime harness
  • bb-app index.test.ts
  • process-utils
  • app bundle-budget and precompress
  • server static-shell, dev-build-problems and plugin-icons
  • host-workspace
  • host-daemon outside fixtures, which now land inside the private sandbox
  • the parity default dataDir

Left alone as production paths: bb-claude-skill-plugins-* (2 per provider-claude-code run) and bb-provider-bridge-*.

How you verified

New tests run the code in a child process with its own TMPDIR:

  • plugin-sdk/src/testing/__tests__/fake-storage-dir.test.ts:
    • a host creates its dir only when it opens a database
    • two hosts share one per-pid root, and dispose() removes only its own dir
    • a never-disposed host's dir is gone after SIGTERM
  • plugin-sdk/src/testing/__tests__/process-end-cleanup.test.ts:
    • exit
    • SIGTERM with re-raise
    • an own SIGTERM listener that exits 7
    • an earlier once listener finishing its async shutdown
    • a later SIGTERM after another listener absorbed one
    • a later prependOnceListener finishing its shutdown
    • two loaded copies
    • unregister, and a cleanup that throws
  • provider-bridge-protocol/src/testing/parity.test.ts: a throwing prepareState leaves neither replay dir. It fails on main and passes here.

To measure leaks, each of the 104 workspace test suites (all but bb, integration and qa) ran as TMPDIR=<fresh dir> pnpm exec turbo run test --filter=<pkg> --only --force --env-mode=loose, and the entries left in that dir were counted. Loose mode is needed because turbo strips TMPDIR. Counts are from main at 9f4c15646d and this series on that base. Every suite not listed left 0 test-owned entries both times.

Suite Before After
environment-modal-sandbox 41 0
simple-notes 41 0
bb--prompt-library 23 0
ask-user-question 21 0
provider-acp 19 0
concurrency-limit 18 0
secrets 15 0
github, inline-vis 14, 14 0, 0
thread-list 12 0
memory, provider-codex 11, 11 0, 0
theme-preview 8 0
bb--mcp, tasks 7, 7 0, 0
provider-claude-code 6 0
custom-instructions 5 0
drafts, environment-personal-workspace 4, 4 0, 0
agent-annotations, bb--github-star, monaco-editor, workflows 3 each 0
provider-pi, account-pool, bb-guide 2, 1, 1 0, 0, 0
automations (bb-auto-plugin-*) 1 0

Every suite's exit code is unchanged. account-pool (2 re-login tests) and provider-claude-code (1 bridge test) fail identically on main. provider-pi's bb-pi-* dir also went from 1 to 0; this series has no code for it.

On the rebased head (351cb84dc6):

  • turbo run typecheck lint test over plugin-sdk, provider-bridge-protocol, automations, domain and templates: 19/19 tasks pass.
  • plugin-api-docs: 75/75.
  • plugin-sdk lint:type-aware: 0 findings.
  • check-npm-version-guard.mjs: pass at 0.6.168.
  • simple-notes, environment-modal-sandbox and automations measured again: 0 entries left.

Fixes #7884

AGENT GENERATED

@github-actions github-actions Bot added the needs-issue PR does not close an open issue label Nov 20, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Thanks for the pull request, @smsunarto. It was closed automatically because it does not meet the requirements below yet. This is an automated check, not a review of the change.

Linked issue. Every pull request must close an open issue in this repository. The issue keeps the problem tracked even if this pull request closes or we take a different approach. Open an issue for the change, or find an existing one, and add Fixes #<number> to the pull request description. Feature requests and UI changes need a maintainer's sign-off on the issue first. This pull request reopens on its own once you save the description.

See CONTRIBUTING.md for details.

@github-actions github-actions Bot closed this Nov 20, 2026
@github-actions github-actions Bot removed the needs-issue PR does not close an open issue label Nov 20, 2026
@github-actions github-actions Bot reopened this Nov 20, 2026
@smsunarto
smsunarto force-pushed the scott/bb-1-clean-up-fake-plugin-host-temp-dirs-in-test-thr_bcvgyetpsm branch 2 times, most recently from 43b94de to 943d7f6 Compare November 20, 2026 05:00
Every createFakePluginHost dir now sits under one root per process,
shared on globalThis so every loaded copy of the SDK uses it, and the
root is removed on process exit. dispose() still removes a host's own
dir, the dir is created only on the first storage.database() call, and
one host dir failing to delete no longer keeps the others. Signals are
left alone: a process killed by SIGTERM can leave its root behind.
On Windows os.tmpdir() reads TEMP and TMP, not TMPDIR, so tests there
wrote outside the sandbox that suite teardown removes.
Replay setup ran before the try whose finally removes the replay dirs,
so a throwing prepareState or a failed workspace allocation left them
behind. The default bridge data dir of resolveProviderBridgeLaunch had
no owner at all; it is now removed on process exit.
@smsunarto
smsunarto force-pushed the scott/bb-1-clean-up-fake-plugin-host-temp-dirs-in-test-thr_bcvgyetpsm branch from 943d7f6 to 3dd8fc1 Compare November 20, 2026 05:27
Windows TEMP now points at the per-run vitest sandbox, which adds a
path segment; the git clone probe path crossed MAX_PATH.
…osed

One exit listener per process now covers every root the process creates,
so dispose cycles no longer leave empty per-worker roots behind.
@get-bb/plugin-sdk/testing/vitest-global-setup points TMPDIR, TEMP and TMP
at a bb-vt-* sandbox and deletes it at teardown in Vitest's main process.
Vitest stops workers with SIGTERM, so worker exit handlers never remove
fake plugin host roots; the sandbox removal does. The root workspace setup
now wraps the same function, adding its process sweep via beforeRemove.
Upstream main already released 0.6.168.
Keep @get-bb/plugin-sdk at 0.6.169; main took 0.6.168.
- Sandbox teardown runs every beforeRemove and the removal even when one
  throws, then rethrows (AggregateError for several failures).
- The sandbox base is resolved to an absolute path, so a relative TMPDIR
  survives a later chdir.
- A fake host keeps its dir registered until removal succeeds, so the exit
  fallback retries after a failed dispose().
- Reopening a fake host database drops closed handles.
- The API audit names the six forkable plugins not yet wired.
A relative TMPDIR made the root path relative, so the exit retry after a
failed dispose() resolved it against the cwd at exit and could delete a
same-named directory elsewhere.
Take @get-bb/plugin-sdk 0.6.172, the next free version after main's
0.6.171, and keep PLUGIN_SDK_VERSION in sync. Keep this branch's
./testing/vitest-global-setup export.
Cold tsx child startup on Windows CI exceeded the 5s default.
@smsunarto
smsunarto marked this pull request as ready for review November 20, 2026 20:21
ymichael added a commit that referenced this pull request Nov 24, 2026
## Human comments

## What was wrong

These are the still-active group D server flakes from the past week.

**`test/environments/locate.test.ts`**: "lets two Local threads share
one row" and "holds a second branch switch behind the first one's
claim…". This failed 3 times on Windows server-2, including main
`de0b6f1ccf` and today on `f9134e1c49`. Both tests always fail together,
and attempt 2 passed on the same SHA.

- `path-admission.ts` set `PATH_CLAIM_SETTLE_TIMEOUT_MS =
ENVIRONMENT_HOOK_TIMEOUT_MS` at module top level, importing the value
from `environment-hooks.ts`.
- `environment-hooks` sits on an import cycle that leads back to
`path-admission` (through `hosts/online-rpc` → `ws/hub` → … →
`threads/thread-command-environment`).
- Node test files share a worker (`isolate: false`). When a file such as
`test/app/host-shared-ports.test.ts` loads that graph from a different
entry, `path-admission` is evaluated before `environment-hooks`
finishes, and the constant is `undefined`.
- Both settle waits (`admitAfterPathClaimsSettle` and
`pathClaimDeadline` in `thread-provisioning.ts`) then compute a `NaN`
deadline. A thread that should wait behind another thread's settling
path claim either fails immediately (`'error'` instead of `'starting'`)
or never wakes (`[id, null]`).
- These two tests are the only ones in the file that wait on a settling
claim, which is why they fail as a pair.
- The production bundle orders the two `var`s safely today, but it would
get the same silent `NaN` if the bundle order changed.

**`test/server-move/coordinator.test.ts` (3 tests) and
`test/server-move/routes.test.ts` (1 test)** failed once on Windows
server-3 (run 44836680494). Attempt 2 passed on the same SHA, and that
branch only touched `install-machine.sh`.

- Each failing `expect.poll` used vitest's default 1 s budget while
waiting for the coordinator to get through real work: a real export of
the harness DB (SQLite backup, tar.gz, sha256), target RPCs, and the
200–300 ms activation retry windows the tests configure.
- On a passing Windows attempt the coordinator file takes 4.9 s, and the
"abandons…" test takes 624 ms. On the failing runner the whole file took
17.3 s, about 3.5× slower, which puts these paths at roughly 2 s, past
the 1 s budget.
- That work is inherently that slow on the slowest runner, so the budget
is raised rather than the work faked.

Checked and left out:
- **plugin-install "falls back to a full clone…"** (13 failures) and the
ubuntu "refuses a collection entry…" failure (same probe, reported
against a test running alongside it): fixed by #7951. The last failure
was 11-21 00:08 UTC, before #7951 merged at 00:30 UTC. #7951's own repro
passes 10/10 on current main.
- **plugin-install ENOENT on "resolved commit / pinned sha" tests**: the
cache path contains `127.0.0.1:<port>`, and Windows rejects a colon in a
path. This is deterministic and only on unmerged #7914.
- **plugin-install "Filename too long" on range-spec tests**: open #7882
moves test temp dirs under a deeper `bb-vt-` sandbox, which pushes git
object paths past Windows MAX_PATH. This is deterministic and only on
that branch.

## What changed

- `apps/server/src/services/environments/environment-hook-timeout.ts`
(new, no imports) owns `ENVIRONMENT_HOOK_TIMEOUT_MS`.
`environment-hooks.ts` and `path-admission.ts` import it from there. A
module with no imports always finishes evaluating before its importers,
so the settle deadline no longer depends on module load order. Behavior
is otherwise unchanged (still 15 minutes).
- `apps/server/test/helpers/server-move.ts` exports
`SERVER_MOVE_STEP_POLL = { timeout: 10_000 }`.
- Every `expect.poll` in `coordinator.test.ts` and `routes.test.ts` uses
it, since each one waits on the move pipeline.
- 10 s gives about 4× headroom over the ~2.2 s observed on the slow
runner and stays under the 15 s test timeout.
- Passing runs are unaffected; only a real failure takes longer to
report.
- No wire, CLI or doc changes.

## How you verified

- **locate, reproduced locally.** A temporary vitest sequencer ran the
failing shard's 115 shared-worker files in one worker, with locate last.
  - Both tests failed with the exact CI messages.
- Bisecting narrowed it to `test/app/host-shared-ports.test.ts`. Its
imports alone are enough (`-t KT2`, with all its tests skipped).
- Logging `PATH_CLAIM_SETTLE_TIMEOUT_MS` inside locate printed
`undefined` in that order.
- Forcing `settlingPathClaim()` to return null reproduces exactly these
two failures and no others.
- **locate, before and after,** with host-shared-ports then locate in
one worker:
  - main: **5/5 runs fail** (2 failed | 20 passed).
  - this branch: **5/5 runs pass** (22/22).
- The full 115-file single-worker order passes on this branch: 113
files, 953 tests.
- **locate, Windows CI evidence.** A diagnostic push of this PR ran both
tests 30× each on Windows server-2, and all 60 iterations passed. That
rules out an in-test race and points to worker history.
- **server-move.** I injected 800 ms of latency before the real export
(about the failing runner's 3.5× slowdown on top of the export itself):
- main: **4 failed | 25 passed**. Failing: "abandons a move in
recovery_required…", "rolls back when the target is gone…", and two
sibling recovery tests in the same class.
  - The 4 CI-failing tests alone failed 2/4 in each of 3 runs.
  - this branch: **29/29 in 3/3 runs**.
  - Without injected latency, 29/29 pass.
- `pnpm exec turbo run typecheck --filter=@bb/server` passes.
- `test/environments`, `test/server-move` and
`test/threads/thread-environment-restore.test.ts`: 23 files, 175 tests,
all pass.

> AGENT GENERATED

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
- SDK version: take 0.6.200, next after main's 0.6.199; keep
  PLUGIN_SDK_VERSION in sync and keep ./testing/vitest-global-setup.
- fake-plugin-host: main's storage.experimental_directory() now gets its
  files folder from FakeStorageDir.filesDirectory(), so it shares the
  lazy per-process host dir and is removed with it.
- automations test: keep main's experimental_BbHttpError import and this
  branch's onTestFinished cleanup.
Take @get-bb/plugin-sdk 0.6.206, next after main's 0.6.205; keep
PLUGIN_SDK_VERSION in sync and keep ./testing/vitest-global-setup.

This branch has not been deployed

No deployments
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.

Test helpers leak temp dirs into os.tmpdir() on every test run

1 participant