Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions test/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ When a test file spawns a Bun process, we like for that file to end in `*-fixtur

Generally, `await using` or `using` is a good idea to ensure proper resource cleanup. This works in most Bun APIs like Bun.listen, Bun.connect, Bun.spawn, Bun.serve, etc.

On Windows, a spawned process that can outlive the test (`detached: true`, daemons, crash-reporter children) must not keep the temp dir as its working directory: give it `cwd: os.tmpdir()`, or kill it and await its exit before the test ends. A terminating process releases its cwd handle asynchronously, so `tempDir` disposal races it and fails with EBUSY. The same applies to the test process itself: after a `process.chdir()` into the temp dir, restore the cwd before the test ends (declare `using cwd = cwdScope(dir)` after `using dir = tempDir(...)` so it is undone first, or chdir back in a `finally`).

#### Async/await in tests

Prefer async/await over callbacks.
Expand Down
49 changes: 45 additions & 4 deletions test/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { ChildProcess, execSync, fork } from "child_process";
import { readdir, rm, writeFile } from "fs/promises";
import fs, { closeSync, openSync, rmSync } from "node:fs";
import os from "node:os";
import { dirname, isAbsolute, join } from "path";
import { dirname, isAbsolute, join, sep } from "path";

export const BREAKING_CHANGES_BUN_1_2 = false;

Expand Down Expand Up @@ -457,12 +457,49 @@ export function tempDirWithFiles(
return base;
}

/**
* On Windows, EBUSY/EPERM from removing a test directory almost always means a
* process holds the directory as its cwd or has an open handle inside it:
* either the test process itself after a process.chdir(), or a process spawned
* by the test that is still alive (or still terminating; handles are released
* asynchronously after TerminateProcess). Several tests have independently
* re-discovered this the hard way, so say it in the error instead of making the
* next author bisect it again. The error is still thrown: a held directory is a
* real leak that the test must fix.
*/
function rethrowWithRmDiagnostic(error: unknown, path: string): never {
const code = (error as NodeJS.ErrnoException)?.code;
if (process.platform === "win32" && (code === "EBUSY" || code === "EPERM") && error instanceof Error) {
let cwdInside = false;
try {
const cwd = process.cwd().toLowerCase();
const held = path.toLowerCase();
cwdInside = cwd === held || cwd.startsWith(held.endsWith(sep) ? held : held + sep);
} catch {}
error.message += cwdInside
? `\nThis test process's own working directory is inside '${path}', which keeps the directory from being ` +
`removed. Restore the original cwd before cleanup runs: chdir back in a finally, or declare the cwd ` +
`change after the directory (e.g. \`using cwd = cwdScope(dir)\` after \`using dir = tempDir(...)\`) so ` +
`it is undone first.`
: `\nA process is likely still holding '${path}' 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()).`;
}
throw error;
}

class DisposableString extends String {
[Symbol.dispose]() {
fs.rmSync(this + "", { recursive: true, force: true });
try {
fs.rmSync(this + "", { recursive: true, force: true });
} catch (error) {
rethrowWithRmDiagnostic(error, this + "");
}
}
[Symbol.asyncDispose]() {
return fs.promises.rm(this + "", { recursive: true, force: true });
return fs.promises.rm(this + "", { recursive: true, force: true }).catch(error => {
rethrowWithRmDiagnostic(error, this + "");
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

Expand Down Expand Up @@ -1863,7 +1900,11 @@ export function cwdScope(cwd: string) {
export function rmScope(path: string) {
return {
[Symbol.dispose]() {
fs.rmSync(path, { recursive: true, force: true });
try {
fs.rmSync(path, { recursive: true, force: true });
} catch (error) {
rethrowWithRmDiagnostic(error, path);
}
},
};
}
Expand Down
146 changes: 146 additions & 0 deletions test/internal/harness-rm-diagnostic.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows, rmScope, tempDir } from "harness";
import * as fs from "node:fs";

// The disposal paths in harness.ts (tempDir's DisposableString and rmScope)
// append a diagnostic to EBUSY/EPERM on Windows so test authors don't have to
// re-bisect "a process spawned by the test still holds the temp dir" (see
// #31688, #36971). These tests pin that behavior: the diagnostic is appended,
// the original error still propagates with its code intact, and everything
// else passes through unchanged.

const DIAGNOSTIC = "as its working directory or has an open handle inside it";

test.skipIf(!isWindows)("temp dir removal failures name the likely process hold on Windows", async () => {
// Deliberately no `using`: the disposal calls are the subject under test.
const dir = tempDir("rm-diagnostic", { "a.txt": "x" });
const held = String(dir);

// A live child whose cwd is inside the dir holds it open for as long as the
// child exists, so every removal attempt below fails deterministically. The
// cwd handle is established by the child-side loader after CreateProcess
// returns, so wait for the child to print before touching the dir.
const child = Bun.spawn({
cmd: [bunExe(), "-e", "console.log('ready'); setInterval(() => {}, 1000)"],
env: bunEnv,
cwd: held,
stdin: "ignore",
stdout: "pipe",
stderr: "ignore",
});

try {
const reader = child.stdout.getReader();
let started = "";
while (!started.includes("ready")) {
const { value, done } = await reader.read();
if (done) break;
started += new TextDecoder().decode(value);
}
expect(started).toContain("ready");

let syncError: NodeJS.ErrnoException | undefined;
try {
dir[Symbol.dispose]();
} catch (error) {
syncError = error as NodeJS.ErrnoException;
}
expect(syncError).toBeDefined();
expect(["EBUSY", "EPERM"]).toContain(syncError!.code);
expect(syncError!.message).toContain(DIAGNOSTIC);
expect(syncError!.message).toContain(held);

let asyncError: NodeJS.ErrnoException | undefined;
try {
await dir[Symbol.asyncDispose]();
} catch (error) {
asyncError = error as NodeJS.ErrnoException;
}
expect(asyncError).toBeDefined();
expect(["EBUSY", "EPERM"]).toContain(asyncError!.code);
expect(asyncError!.message).toContain(DIAGNOSTIC);

let scopeError: NodeJS.ErrnoException | undefined;
try {
rmScope(held)[Symbol.dispose]();
} catch (error) {
scopeError = error as NodeJS.ErrnoException;
}
expect(scopeError).toBeDefined();
expect(["EBUSY", "EPERM"]).toContain(scopeError!.code);
expect(scopeError!.message).toContain(DIAGNOSTIC);
} finally {
child.kill();
await child.exited;
// Clean the dir up for real. Handle release after exit is asynchronous,
// which is the whole point of the diagnostic, so poll with a deadline.
for (let attempt = 0; ; attempt++) {
try {
dir[Symbol.dispose]();
break;
} catch (error) {
if (attempt >= 100) throw error;
await Bun.sleep(50);
}
}
}
expect(fs.existsSync(held)).toBe(false);
});

test.skipIf(!isWindows)("temp dir removal failures name the test process's own cwd hold on Windows", () => {
const dir = tempDir("rm-diagnostic-cwd", { "a.txt": "x" });
const held = String(dir);
const original = process.cwd();
try {
process.chdir(held);
let error: NodeJS.ErrnoException | undefined;
try {
dir[Symbol.dispose]();
} catch (thrown) {
error = thrown as NodeJS.ErrnoException;
}
expect(error).toBeDefined();
expect(["EBUSY", "EPERM"]).toContain(error!.code);
expect(error!.message).toContain("This test process's own working directory");
expect(error!.message).not.toContain(DIAGNOSTIC);
} finally {
process.chdir(original);
}
// chdir is synchronous in this process, so disposal succeeds immediately.
dir[Symbol.dispose]();
expect(fs.existsSync(held)).toBe(false);
});

test("non-matching removal errors pass through unchanged", () => {
// A path with a NUL byte fails validation before any syscall, on every
// platform, with no `code` matching the diagnostic guard: the error must
// come through the disposal catch untouched.
let error: Error | undefined;
try {
rmScope("\0")[Symbol.dispose]();
} catch (thrown) {
error = thrown as Error;
}
expect(error).toBeDefined();
expect(error!.message).not.toContain(DIAGNOSTIC);
});

test("tempDir sync dispose removes the dir when nothing holds it", () => {
let p: string = "";
{
using dir = tempDir("rm-diagnostic-sync", { "a.txt": "x" });
p = String(dir);
expect(fs.existsSync(p)).toBe(true);
}
expect(fs.existsSync(p)).toBe(false);
});

test("tempDir async dispose removes the dir when nothing holds it", async () => {
let p: string = "";
{
await using dir = tempDir("rm-diagnostic-async", { "a.txt": "x" });
p = String(dir);
expect(fs.existsSync(p)).toBe(true);
}
expect(fs.existsSync(p)).toBe(false);
});