Skip to content
Closed
Show file tree
Hide file tree
Changes from 8 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
9 changes: 6 additions & 3 deletions src/jsc/bindings/BunProcess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2967,6 +2967,7 @@ enum class BunProcessStdinFdType : int32_t {
extern "C" BunProcessStdinFdType Bun__Process__getStdinFdType(void*, int fd);

extern "C" void Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(JSC::JSGlobalObject*, JSC::EncodedJSValue);
extern "C" void Bun__trackProcessStdioSinkForTestIsolation(JSC::JSGlobalObject*, JSC::EncodedJSValue);
// node:worker_threads worker: process.stdout/stderr forward to the parent Worker's
// worker.stdout/stderr over a MessagePort; process.stdin is port-fed for { stdin: true }
// and otherwise an already-ended Readable (never the process-wide fd 0). fd 0/1/2 selects the port.
Expand Down Expand Up @@ -3034,10 +3035,12 @@ static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, JSC:
// Until then, we have to force it to be sync EVEN for sockets or else console.log() may flush at a different time than process.stdout.write.
forceSync = true;
#endif
JSC::EncodedJSValue sink = JSValue::encode(resultObject->getIndex(globalObject, 1));
RETURN_IF_EXCEPTION(scope, jsUndefined());
// No-op outside `bun test --isolate`, where the swap must end this sink.
Bun__trackProcessStdioSinkForTestIsolation(globalObject, sink);
Comment thread
robobun marked this conversation as resolved.
Resolved
if (forceSync) {
JSValue sink = resultObject->getIndex(globalObject, 1);
RETURN_IF_EXCEPTION(scope, jsUndefined());
Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(globalObject, JSValue::encode(sink));
Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(globalObject, sink);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

JSValue stream = resultObject->getIndex(globalObject, 0);
Expand Down
41 changes: 39 additions & 2 deletions src/runtime/webcore/FileSink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,10 @@ pub struct FileSink {
/// while an async operation is pending. This is set when endFromJS returns a
/// pending Promise and cleared when the operation completes.
pub(crate) js_sink_ref: JsCell<bun_jsc::strong::Optional>,
/// Armed while a file this sink opened for a `Bun.ModuleGraph`'s script is open.
/// Armed for a file opened for a `Bun.ModuleGraph`'s script, and for process stdio under `bun test --isolate`.
abort_handle: bun_jsc::AbortHandle,
/// `process.stdout`/`process.stderr` under `bun test --isolate`: the stop flushes before it closes.
flush_on_abort: Cell<bool>,
}

// `bun.ptr.RefCount(FileSink, "ref_count", deinit, .{})` — intrusive single-thread
Expand Down Expand Up @@ -277,6 +279,29 @@ pub(crate) extern "C" fn Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(
}
}

/// Under `bun test --isolate`, arms a new `process.stdout`/`process.stderr` sink on the root context so the global swap ends it.
#[unsafe(no_mangle)]
pub(crate) extern "C" fn Bun__trackProcessStdioSinkForTestIsolation(
global: &JSGlobalObject,
jsvalue: JSValue,
) {
let vm = global.bun_vm();
if !vm.test_isolation_enabled {
return;
}
let Some(this_ptr) = JSSink::from_js(jsvalue) else {
return;
};
// SAFETY: `from_js` returned a live `*mut JSSink<FileSink>`; the wrapper is
// `repr(transparent)` over `sink: FileSink`, so this recovers the canonical
// `*mut FileSink`. A started sink is heap-allocated; it leaves its context in `on_close`.
unsafe {
let this: *mut FileSink = &raw mut (*this_ptr).sink;
(*this).flush_on_abort.set(true);
bun_jsc::AbortHandle::arm_owner(this, vm.root_context());
}
}

impl FileSink {
/// `bun.spawn`'s subprocess exited while this `FileSink` was its stdin.
///
Expand Down Expand Up @@ -1656,18 +1681,30 @@ impl FileSink {
pump_promise_ref: Cell::new(false),
js_sink_ref: JsCell::new(bun_jsc::strong::Optional::empty()),
abort_handle: bun_jsc::AbortHandle::for_owner::<FileSink>(),
flush_on_abort: Cell::new(false),
}
}
}

bun_jsc::impl_abort_handle_owner!(FileSink, abort_handle, |this, _cause| {
bun_jsc::impl_abort_handle_owner!(FileSink, abort_handle, |this, cause| {
// What is buffered is dropped with the graph: the writer closes without draining (a reader
// that never reads would keep it open for ever), and a parked write gives up its promise and
// the wrapper it pins, as when an attached process exits. `on_close` may free `this`.
// SAFETY: trait contract — `this` is live (armed ⇒ `on_close` has not run) with
// write+dealloc provenance; the guard keeps it so across `close()` and `run_pending`.
unsafe {
let _guard = RefPtr::init_ref(this);
// The isolate swap flushes stdio first; a backpressured `end()` then drains on the live
// loop. VM teardown has no loop left to drain on, so it takes the native close below.
Comment thread
robobun marked this conversation as resolved.
Resolved
if (*this).flush_on_abort.get()
&& matches!(
cause,
bun_jsc::AbortCause::ContextStopped(bun_jsc::StopReason::Disposed)
)
{
let _ = (*this).end(None);
return;
}
(*this).done.set(true);
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
#[cfg(windows)]
if !(*this).writer.get().owns_fd {
Expand Down
53 changes: 52 additions & 1 deletion test/cli/test/isolation.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, setDefaultTimeout, test } from "bun:test";
import { bunEnv, bunExe, isASAN, normalizeBunSnapshot, tempDir, tls } from "harness";
import { bunEnv, bunExe, isASAN, isLinux, normalizeBunSnapshot, tempDir, tls } from "harness";
import fs from "node:fs";
import net from "node:net";
import { join } from "node:path";
Expand Down Expand Up @@ -73,6 +73,57 @@ describe.concurrent("bun test --isolate", () => {
expect(exitCode).toBe(0);
});

// The swap must end each file's process.stderr/stdout sinks (a fresh dup of
// the stdio fd per isolate global) or the dups and their epoll registrations
// accumulate. https://github.com/oven-sh/bun/issues/37968
test.skipIf(!isLinux)("with --isolate, stdio sinks do not leak a dup'd fd per file", async () => {
const countFixture = `
import { test } from "bun:test";
import { existsSync, readdirSync, readFileSync, readlinkSync, writeFileSync } from "node:fs";
function countStderrDups() {
const target = readlinkSync("/proc/self/fd/2");
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
let count = 0;
for (const fd of readdirSync("/proc/self/fd")) {
try {
if (readlinkSync("/proc/self/fd/" + fd) === target) count++;
} catch (error) {
// An fd can vanish between readdir and readlink.
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
}
}
return count;
}
test("count dups of stderr", () => {
process.stderr.write("");
process.stdout.write("");
// The first file records the baseline. The swap closes the previous
// file's dup on a work-pool thread, so later files poll until that
// close lands. A leaked dup never closes, so the poll then times out.
const baseline = existsSync("baseline.txt") ? Number(readFileSync("baseline.txt", "utf8")) : null;
const deadline = Date.now() + 5000;
let count = countStderrDups();
while (baseline !== null && count > baseline && Date.now() < deadline) {
Bun.sleepSync(1);
count = countStderrDups();
}
if (baseline === null) writeFileSync("baseline.txt", String(count));
console.log("FDCOUNT:" + count);
});
`;
const names = ["a", "b", "c", "d"].map(c => `${c}-stdio-fds.test.ts`);
using dir = tempDir("isolate-stdio-fds", Object.fromEntries(names.map(name => [name, countFixture])));
const { stdout, stderr, exitCode } = await runTests(
String(dir),
["--isolate"],
names.map(name => `./${name}`),
);
const counts = [...stdout.matchAll(/FDCOUNT:(\d+)/g)].map(m => Number(m[1]));
expect(counts).toHaveLength(4);
expect(counts).toEqual(Array(4).fill(counts[0]));
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
expect(normalizeBunSnapshot(stderr, dir)).toContain("4 pass");
expect(exitCode).toBe(0);
});

test("with --isolate, a file's process.chdir() is undone before the next file", async () => {
const cwdFixtures = {
"a-chdir.test.ts": `
Expand Down
Loading