Skip to content

Explain Windows EBUSY from temp dir cleanup in the test harness - #36976

Closed
robobun wants to merge 3 commits into
mainfrom
farm/3440d127/tempdir-ebusy-diagnostic
Closed

robobun wants to merge 3 commits into
mainfrom
farm/3440d127/tempdir-ebusy-diagnostic

Conversation

@robobun

@robobun robobun commented Aug 5, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-up to #36971. When tempDir disposal fails with EBUSY on Windows, the harness currently surfaces a bare filesystem error:

EBUSY: resource busy or locked, rm 'C:\Windows\Temp\buntmp-Fbshlf\socket-inherit_Ev5bLB'
    at [Symbol.dispose] (C:\buildkite-agent\build\test\harness.ts:462:8)

That error has now been independently bisected to the same root cause three times, each investigation ending in a per-test fix plus a locally worded comment:

The cause is always a process holding the directory as its cwd (or an open handle inside it) when disposal runs: either a process spawned by the test, including one already killed (TerminateProcess releases handles asynchronously), or the test process itself after a process.chdir() into the dir that was not restored.

Change

  • test/harness.ts: when rmSync/rm in DisposableString's dispose paths or rmScope fails with EBUSY or EPERM on Windows, append the diagnosis to the error message and rethrow. The two holder classes get different advice: if process.cwd() is inside the directory the message says to restore the cwd before cleanup (chdir back in a finally, or declare cwdScope after tempDir so it is undone first); otherwise it points at the spawned-process fixes (await the child's exit, or spawn it with a cwd outside the temp dir). The original error object is rethrown unchanged otherwise: code, errno, syscall, path, and the stack stay intact, and the test still fails. No retry and no swallow, so a held directory remains a hard failure (a retry would mask genuine process and handle leaks, which is why Spawn the detached child outside the temp dir in the socket-inherit test #36971 rejected it).
  • test/CLAUDE.md: document both rules in the "Spawning processes" section, since the canonical multi-file example teaches cwd: String(dir) and any child that outlives the test reproduces this.
  • test/internal/harness-rm-diagnostic.test.ts: regression tests. A live child with its cwd inside the dir makes sync disposal, async disposal, and rmScope all fail with the spawned-process diagnostic and an intact EBUSY/EPERM code; a process.chdir() into the dir produces the own-cwd diagnostic instead; non-matching errors (a pre-syscall validation error, portable to all platforms) pass through untouched; and the success paths still remove their directories on every platform.

Verification (Windows 11 aarch64)

Restored the pre-#36971 fixture (detached child inheriting the temp dir cwd) to trigger the real failure through the new path; the test now fails with:

EBUSY: resource busy or locked, rm 'C:\Users\azureuser\AppData\Local\Temp\socket-inherit_lrjDJd'
A process is likely still holding 'C:\Users\azureuser\AppData\Local\Temp\socket-inherit_lrjDJd' as its working directory or has an open handle inside it. Kill that process and await its exit before the directory is cleaned up, or spawn processes that can outlive the test with a cwd outside the temp dir (e.g. cwd: os.tmpdir()).
    path: "C:\\Users\\azureuser\\AppData\\Local\\Temp\\socket-inherit_lrjDJd",
 syscall: "rm",
   errno: -4082,
    code: "EBUSY"

The regression tests pass 10/10 consecutive runs on Windows 11 aarch64 and on Linux (where the Windows-only cases skip). Success paths are unchanged: tempDir sync dispose, tempDir async dispose, and rmScope all still remove their directories, and the socket-inherit test passes 5/5 with the modified harness.

One detail the child-holder regression test encodes: a spawned child's cwd handle is established by the child-side loader after CreateProcess returns, so the test waits for the child to print before asserting removal fails. The same window is why the original flake in #36971 was intermittent rather than constant.


no test proof · iteration 0 · Platform-specific test-only change; deferring to CI.

Three separate investigations (#31688, the inspector temp-dir disposal
fix, and #36971) each re-derived the same cause for a bare EBUSY thrown
by tempDir disposal on Windows: a process spawned by the test still
holds the directory as its cwd while terminating. Augment the error in
DisposableString's dispose paths and rmScope with that diagnosis (the
error is still thrown, with code/errno intact), and document the rule
in test/CLAUDE.md.
@github-actions github-actions Bot added the claude label Aug 5, 2026
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The test harness adds Windows diagnostics for temporary-directory removal failures. Synchronous and asynchronous cleanup paths, including rmScope, use the diagnostics. Test guidance documents how long-lived child processes must manage their working directory and termination.

Changes

Windows test cleanup

Layer / File(s) Summary
Windows cleanup diagnostics and process guidance
test/harness.ts, test/CLAUDE.md
Cleanup paths add diagnostics for EBUSY and EPERM removal failures. Guidance covers child processes that outlive tests and retain temporary-directory handles.

Possibly related PRs

  • oven-sh/bun#36413: Modifies platform-specific test behavior for process-lifecycle issues.
  • oven-sh/bun#36424: Updates test/harness.ts for spawned-process handling and cleanup diagnostics.

Suggested reviewers: jarred-sumner, alii, cirospaciari

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the main change: diagnosing Windows EBUSY errors during temporary-directory cleanup in the test harness.
Description check ✅ Passed The description explains the change, root cause, affected files, behavior, and verification results, despite using different headings than the template.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@test/harness.ts`:
- Around line 471-493: Add Windows-focused regression tests for
rethrowWithRmDiagnostic and DisposableString cleanup, simulating process-handle
failures to verify the original error propagates with the appended diagnostic
text. Exercise synchronous disposal, asynchronous disposal, and rmScope, and
also verify non-matching errors retain their unchanged message and behavior.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 0ca7c677-cca8-4396-97b7-ffe7c169b51e

📥 Commits

Reviewing files that changed from the base of the PR and between 1f606e6 and 32c8af4.

📒 Files selected for processing (2)
  • test/CLAUDE.md
  • test/harness.ts

Comment thread test/harness.ts Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — test-harness-only diagnostic that appends guidance to Windows EBUSY/EPERM errors during temp-dir disposal without changing success-path behavior.

What was reviewed:

  • rethrowWithRmDiagnostic always throws (return type never), so neither the sync try/catch nor the async .catch() swallows the error — tests still fail on a held directory.
  • Non-Windows and non-EBUSY/EPERM paths rethrow the original error unchanged; code/errno/syscall/path are preserved since the same object is rethrown.
  • The path parameter name doesn't shadow any module-level import (only dirname/isAbsolute/join are imported from path).
Extended reasoning...

Overview

This PR touches two test-infrastructure files: test/harness.ts adds a rethrowWithRmDiagnostic helper wrapping the three temp-dir cleanup sites (DisposableString[Symbol.dispose], DisposableString[Symbol.asyncDispose], and rmScope), and test/CLAUDE.md gains one paragraph documenting the Windows cwd-handle behavior. No runtime, native, or user-facing code is touched.

Security risks

None. This is test-harness-only code that appends a string to an error message on the failure path. It does not touch auth, crypto, network, or any production surface.

Level of scrutiny

Low. The change is confined to error handling in test cleanup helpers. The only behavioral question is whether errors could be accidentally swallowed, and the answer is no: rethrowWithRmDiagnostic unconditionally ends with throw error, so the sync path rethrows and the async .catch(error => rethrowWithRmDiagnostic(...)) rejects the returned promise. On non-Windows or non-matching error codes the message is left untouched and the original error object is rethrown, so nothing that previously failed will now pass.

Other factors

The PR description cites three prior independent bisections of the same root cause (#31688, ecaa553, #36971), which is exactly the situation where centralizing the diagnostic in the harness is the right layer per REVIEW.md's "fix bugs at the layer that owns the violated invariant" guidance. The change deliberately does not retry or suppress (which #36971 rejected), keeping held directories a hard failure. Verification was done on Windows aarch64 by reproducing the pre-#36971 failure and confirming the new message appears, and success paths were checked on both Windows and Linux.

…test

A live child with its cwd inside the temp dir makes every disposal path
(sync, async, rmScope) fail with the appended diagnostic and an intact
error code; non-matching errors pass through unchanged. The child
prints before the dir is touched because its cwd handle is established
by the child-side loader after CreateProcess returns.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — test-infrastructure-only change that appends a diagnostic hint to an already-thrown error.

What was reviewed:

  • rethrowWithRmDiagnostic always rethrows; success paths and non-Windows/non-matching error paths are byte-identical to before.
  • Async dispose's .catch handler throws via the never-returning helper, so the returned promise still rejects — no swallowing.
  • New Windows test kills the child and polls cleanup in finally; the NUL-path pass-through test and both success-path tests run on all platforms.
Extended reasoning...

Overview

This PR touches only test infrastructure: test/harness.ts (wraps three temp-dir cleanup sites in try/catch to append a diagnostic to Windows EBUSY/EPERM before rethrowing), test/CLAUDE.md (one paragraph documenting the pattern), and a new test/internal/harness-rm-diagnostic.test.ts. No runtime code is touched.

Security risks

None. The change only mutates error.message on an error object that was already being thrown from test cleanup. No new inputs are parsed, no new syscalls, no auth/crypto/network paths.

Level of scrutiny

Moderate — test/harness.ts is loaded by every test file, so a top-level fault would break the whole suite. I checked that the additions are a function definition plus try/catch wrappers with no top-level side effects, and that the success path (rmSync returns normally) is unchanged. The failure-path change is purely additive: the same error object is rethrown with code/errno/syscall/path intact and only .message extended, gated on process.platform === 'win32' plus a specific errno match. The async-dispose wrapper uses .catch(e => rethrowWithRmDiagnostic(e, ...)) where the helper is never-returning, so the promise still rejects and await using still surfaces the failure.

Other factors

  • The regression test is well-structured: the Windows case waits for the child's readiness line before asserting, cleans up in finally with a bounded poll (the exact pattern REVIEW.md prescribes for "X eventually happens"), and the cross-platform tests cover the pass-through and success paths so non-Windows CI still exercises the new catch blocks.
  • CodeRabbit's only feedback (add tests) was addressed in cb344c9 and marked resolved.
  • The author verified on Windows 11 aarch64 (15/15) and Linux; the PR description shows the actual augmented error output.
  • The new test file lives in test/internal/ alongside other harness/internal tests, which is the right home.

Given the change is small, additive, test-only, and cannot alter behavior on the happy path, I'm approving.

…iagnostic

A process.chdir() into the temp dir that is not restored produces the
same Windows EBUSY as a child process holding the dir, but the
child-process advice misdirects that case. Detect it from process.cwd()
and point at restoring the cwd instead, document it in test/CLAUDE.md,
and pin both branches in the regression test.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — test-harness-only change that appends a diagnostic to Windows EBUSY/EPERM on temp-dir disposal and rethrows; success paths are unchanged.

What was reviewed:

  • rethrowWithRmDiagnostic always rethrows (return type never), so no failure is swallowed; async dispose's .catch handler throws → promise still rejects.
  • Non-Windows and non-EBUSY/EPERM paths short-circuit and rethrow the original error untouched; code/errno/syscall/path stay intact since only .message is appended.
  • Regression tests: child-holder test awaits the child's "ready" line before asserting (avoids the CreateProcess race), restores process.chdir in finally, cleanup polls with a bounded deadline; rmScope("\0") is a portable pre-syscall validation error that won't match the diagnostic guard.
Extended reasoning...

Overview

This PR touches three files, all in the test tree: test/harness.ts (adds rethrowWithRmDiagnostic and wraps the three temp-dir disposal call sites — DisposableString[Symbol.dispose], [Symbol.asyncDispose], and rmScope — in try/catch that rethrows through it), test/CLAUDE.md (a paragraph documenting the Windows cwd-hold pitfall), and a new test/internal/harness-rm-diagnostic.test.ts regression file. No runtime, native, or shipped code is touched.

Security risks

None. This is test-infrastructure error-message enrichment only. The diagnostic is gated behind process.platform === "win32" and specific errno codes, mutates only error.message, and always rethrows.

Level of scrutiny

Low-medium. test/harness.ts is imported by every test file, so a mistake here would break the whole suite — but the change is purely additive around already-throwing failure paths. On success (rmSync/rm completes), execution is byte-identical to before. On failure, the same error object is rethrown with an appended message on Windows only. The async-dispose wrapper returns promise.catch(handler) where the handler throws, so the returned promise still rejects — no swallow. The sep import addition is trivial.

Other factors

  • The cwd-inside check lowercases both sides and appends the platform separator before startsWith, so C:\\foo doesn't false-match C:\\foobar, and process.cwd() is wrapped in try/catch in case the cwd itself was deleted.
  • The regression tests follow harness conventions: test.skipIf(!isWindows) for the platform-specific cases, bunEnv/bunExe, awaiting the child's readiness line rather than sleeping, restoring mutated global state (process.chdir) in finally, and a bounded poll loop (100 × 50ms) for the asynchronous handle-release cleanup. The non-matching-error case uses a NUL-byte path, which fails Node's argument validation before any syscall on every platform and carries no EBUSY/EPERM code.
  • CodeRabbit's only feedback (add regression tests) was addressed in cb344c9 and marked resolved. No CODEOWNERS apply to these paths. No prior reviews from me on this PR.

@robobun

robobun commented Aug 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI note: the only hard failure in build 89258 is test/js/node/async_hooks/AsyncLocalStorage-tracking.test.ts on the x64-asan lane, a pre-existing leak on main that is unrelated to this PR (it was red in builds 89222 and 89243 as well, and predates these commits). The other failures passed on retry. Everything this PR touches is green, including the new regression tests on every Windows lane.

@github-actions

github-actions Bot commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

@github-actions github-actions Bot closed this Nov 4, 2026
@robobun

robobun commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator Author

The inactivity sweep closed this PR, and it can stay closed. Main solved the same failure in a different way after I opened this PR.

  • test: fix bake.test.ts cleanup and the --check URL on Windows #46135 made tempDir cleanup retry EBUSY on Windows for up to 5 seconds (DisposableString in test/harness.ts). That covers the case seen in CI: a child that was just killed still holds the folder.
  • This PR took the opposite approach: no retry, only a longer error message. Its regression test expects cleanup to fail at once while a child holds the folder. That test does not fit the retry.

One part is not on main. It is the message that explains the cause when a process holds the folder past the retry. If someone wants that message, a new and smaller change on top of the retry is the way to add it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant