From 0445be927db56fd4057d4d5ae8eb073b97c0105f Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 13 Aug 2026 02:52:27 +0000 Subject: [PATCH 01/10] test --isolate: end the outgoing file's process stdio sinks at the global swap Each isolate context lazily re-creates process.stdout/process.stderr over a fresh dup of the stdio fd registered with the event loop, and nothing closed the previous context's sink, so the dups and their epoll registrations accumulated one per test file. A stale registration whose fd number is later reused over the same pipe makes the next context's registration fail with EEXIST from epoll_ctl while process.stderr is being created. Track the sinks (only when isolation is enabled) in the active-handle registry and end them in the stop phase that runs before each swap. Fixes #37968 --- src/jsc/bindings/BunProcess.cpp | 11 ++++++-- src/runtime/jsc_hooks.rs | 10 +++++++ src/runtime/webcore/FileSink.rs | 50 +++++++++++++++++++++++++++++++++ test/cli/test/isolation.test.ts | 38 ++++++++++++++++++++++++- 4 files changed, 105 insertions(+), 4 deletions(-) diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index 57f1b66e0eda..dface178ca90 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -2950,6 +2950,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. @@ -3017,10 +3018,14 @@ 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()); + // Under `bun test --isolate`, each test file's global re-creates these + // sinks over a fresh dup of the stdio fd; track them so the isolation swap + // can end the outgoing file's sinks. No-op otherwise. + Bun__trackProcessStdioSinkForTestIsolation(globalObject, sink); if (forceSync) { - JSValue sink = resultObject->getIndex(globalObject, 1); - RETURN_IF_EXCEPTION(scope, jsUndefined()); - Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(globalObject, JSValue::encode(sink)); + Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(globalObject, sink); } JSValue stream = resultObject->getIndex(globalObject, 0); diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 029b356845de..ff3563baec47 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -133,6 +133,11 @@ pub(crate) enum ActiveHandle { Bundle(ptr::NonNull), /// A `dns.Resolver` (or the VM-global one) with a live c-ares channel. DnsResolver(ptr::NonNull), + /// A `process.stdout`/`process.stderr` FileSink under `bun test --isolate`: + /// each isolate global lazily re-creates it over a fresh dup of the stdio + /// fd, so the swap must end the outgoing one (closing the dup and its + /// poll registration). Only registered when isolation is enabled. + ProcessStdioSink(ptr::NonNull), } pub(crate) type ActiveHandles = bun_collections::ArrayHashMap; @@ -1824,6 +1829,11 @@ fn stop_active_handles(vm: &mut VirtualMachine, reason: StopReason) -> SweepResu ActiveHandle::DnsResolver(r) => unsafe { let _ = crate::dns_jsc::Resolver::close_channel_for_terminate(r.as_ptr()); }, + // SAFETY: the registry's +1 (taken at registration) keeps it live; + // the call releases that ref and may free the sink. + ActiveHandle::ProcessStdioSink(s) => unsafe { + crate::webcore::FileSink::stop_tracked_stdio_sink(s.as_ptr()) + }, } } for handle in kept { diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index 35b03b1a059d..bd6daf70d703 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -272,6 +272,56 @@ pub(crate) extern "C" fn Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio( } } +/// `constructStdioWriteStream` just created a `process.stdout`/`process.stderr` +/// sink. Under `bun test --isolate` each test file's fresh global re-creates +/// these lazily over a new dup of the stdio fd (registered with the event +/// loop), and nothing ends the outgoing file's sink at the global swap — the +/// dups and their poll registrations accumulate per file, and a stale epoll +/// entry whose fd number gets reused over the same pipe makes a later +/// registration fail with EEXIST. Track the sink so +/// `stop_active_handles_for_test_isolation` ends it at the swap. +#[unsafe(no_mangle)] +pub(crate) extern "C" fn Bun__trackProcessStdioSinkForTestIsolation( + global: &JSGlobalObject, + jsvalue: JSValue, +) { + if !global.bun_vm().test_isolation_enabled { + return; + } + let Some(this_ptr) = JSSink::from_js(jsvalue) else { + return; + }; + // SAFETY: `from_js` returned a live `*mut JSSink`; the wrapper is + // `repr(transparent)` over `sink: FileSink`, so this recovers the canonical + // `*mut FileSink`. + let this: *mut FileSink = unsafe { &raw mut (*this_ptr).sink }; + // The registry's +1, released by `stop_tracked_stdio_sink`. + // SAFETY: `this` is live — the JS wrapper holds its own +1. + unsafe { (*this).ref_() }; + crate::jsc_hooks::ActiveHandle::ProcessStdioSink(core::ptr::NonNull::new(this).expect("sink")) + .register(); +} + +impl FileSink { + /// Ends a sink tracked by `ActiveHandle::ProcessStdioSink` (the + /// `--isolate` global swap or VM teardown), flushing buffered output, + /// closing the dup'd fd with its poll registration, and releasing the + /// registration's +1. + /// + /// # Safety + /// `this` must be the canonical live `*mut FileSink` whose registration + /// ref is still held; it must not be used after the call, which may free + /// it. + pub(crate) unsafe fn stop_tracked_stdio_sink(this: *mut FileSink) { + // SAFETY: caller contract — the registry's +1 keeps `this` live until + // the trailing `deref`, which is its last use. + unsafe { + let _ = (*this).end(None); + FileSink::deref(this); + } + } +} + impl FileSink { /// `bun.spawn`'s subprocess exited while this `FileSink` was its stdin. /// diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index 7678f5d99b7c..e923b177652b 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -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"; @@ -72,6 +72,42 @@ describe.concurrent("bun test --isolate", () => { expect(exitCode).toBe(0); }); + // Each isolate context lazily re-creates process.stderr/stdout over a fresh + // dup() of the stdio fd plus an epoll registration; the global swap must end + // the outgoing file's sinks or the dups accumulate per file and a stale + // registration can later collide with a reused fd number (EEXIST from + // epoll_ctl, #37968). Counts fds that share fd 2's pipe via /proc, Linux-only. + 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 { readdirSync, readlinkSync } from "node:fs"; + test("count dups of stderr", () => { + process.stderr.write(""); + process.stdout.write(""); + const target = readlinkSync("/proc/self/fd/2"); + let count = 0; + for (const fd of readdirSync("/proc/self/fd")) { + try { + if (readlinkSync("/proc/self/fd/" + fd) === target) count++; + } catch {} + } + 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])); + 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": ` From 1d6af6ecae3fefef083edb9d77255be80dceccec Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 18 Aug 2026 22:59:47 +0000 Subject: [PATCH 02/10] Tighten comments on the stdio sink tracking path --- src/jsc/bindings/BunProcess.cpp | 4 +--- src/runtime/jsc_hooks.rs | 7 +++---- src/runtime/webcore/FileSink.rs | 20 ++++++-------------- 3 files changed, 10 insertions(+), 21 deletions(-) diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index dface178ca90..931b503200fd 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -3020,9 +3020,7 @@ static JSValue constructStdioWriteStream(JSC::JSGlobalObject* globalObject, JSC: #endif JSC::EncodedJSValue sink = JSValue::encode(resultObject->getIndex(globalObject, 1)); RETURN_IF_EXCEPTION(scope, jsUndefined()); - // Under `bun test --isolate`, each test file's global re-creates these - // sinks over a fresh dup of the stdio fd; track them so the isolation swap - // can end the outgoing file's sinks. No-op otherwise. + // No-op outside `bun test --isolate`, where the swap must end this sink. Bun__trackProcessStdioSinkForTestIsolation(globalObject, sink); if (forceSync) { Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio(globalObject, sink); diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index ff3563baec47..abc4b5d3334b 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -133,10 +133,9 @@ pub(crate) enum ActiveHandle { Bundle(ptr::NonNull), /// A `dns.Resolver` (or the VM-global one) with a live c-ares channel. DnsResolver(ptr::NonNull), - /// A `process.stdout`/`process.stderr` FileSink under `bun test --isolate`: - /// each isolate global lazily re-creates it over a fresh dup of the stdio - /// fd, so the swap must end the outgoing one (closing the dup and its - /// poll registration). Only registered when isolation is enabled. + /// A `process.stdout`/`process.stderr` FileSink, registered only under + /// `bun test --isolate`, where each global dups the stdio fd anew and the + /// swap must close the outgoing dup and its poll registration. ProcessStdioSink(ptr::NonNull), } diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index bd6daf70d703..a02592f6cbdb 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -272,14 +272,9 @@ pub(crate) extern "C" fn Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio( } } -/// `constructStdioWriteStream` just created a `process.stdout`/`process.stderr` -/// sink. Under `bun test --isolate` each test file's fresh global re-creates -/// these lazily over a new dup of the stdio fd (registered with the event -/// loop), and nothing ends the outgoing file's sink at the global swap — the -/// dups and their poll registrations accumulate per file, and a stale epoll -/// entry whose fd number gets reused over the same pipe makes a later -/// registration fail with EEXIST. Track the sink so -/// `stop_active_handles_for_test_isolation` ends it at the swap. +/// Registers a just-created `process.stdout`/`process.stderr` sink so the +/// `--isolate` swap ends it. Each isolate global dups the stdio fd anew; an +/// unclosed dup leaks its epoll registration (EEXIST on fd-number reuse). #[unsafe(no_mangle)] pub(crate) extern "C" fn Bun__trackProcessStdioSinkForTestIsolation( global: &JSGlobalObject, @@ -303,15 +298,12 @@ pub(crate) extern "C" fn Bun__trackProcessStdioSinkForTestIsolation( } impl FileSink { - /// Ends a sink tracked by `ActiveHandle::ProcessStdioSink` (the - /// `--isolate` global swap or VM teardown), flushing buffered output, - /// closing the dup'd fd with its poll registration, and releasing the - /// registration's +1. + /// Ends a sink tracked by `ActiveHandle::ProcessStdioSink` and releases + /// the registration's +1. /// /// # Safety /// `this` must be the canonical live `*mut FileSink` whose registration - /// ref is still held; it must not be used after the call, which may free - /// it. + /// ref is still held; the call may free it. pub(crate) unsafe fn stop_tracked_stdio_sink(this: *mut FileSink) { // SAFETY: caller contract — the registry's +1 keeps `this` live until // the trailing `deref`, which is its last use. From 17016a6771d60b35744bb39477aa64a425e0e6e3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 18 Aug 2026 23:51:02 +0000 Subject: [PATCH 03/10] ci: retrigger From d9a71d5b7acc1ad60602ded3b0ca00de75526565 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Tue, 18 Aug 2026 23:58:54 +0000 Subject: [PATCH 04/10] Address review: rethrow non-ENOENT in fd count, check exception after sink lookup --- test/cli/test/isolation.test.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index e923b177652b..3b883422156a 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -72,11 +72,9 @@ describe.concurrent("bun test --isolate", () => { expect(exitCode).toBe(0); }); - // Each isolate context lazily re-creates process.stderr/stdout over a fresh - // dup() of the stdio fd plus an epoll registration; the global swap must end - // the outgoing file's sinks or the dups accumulate per file and a stale - // registration can later collide with a reused fd number (EEXIST from - // epoll_ctl, #37968). Counts fds that share fd 2's pipe via /proc, Linux-only. + // 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"; @@ -89,7 +87,10 @@ describe.concurrent("bun test --isolate", () => { for (const fd of readdirSync("/proc/self/fd")) { try { if (readlinkSync("/proc/self/fd/" + fd) === target) count++; - } catch {} + } catch (error) { + // An fd can vanish between readdir and readlink. + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } } console.log("FDCOUNT:" + count); }); From 17ea9b83f90dba84c9b1f31e733d71cf40c72e4a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 18 Sep 2026 16:20:57 +0000 Subject: [PATCH 05/10] FileSink: one-line notes on the isolate stdio tracking --- src/runtime/webcore/FileSink.rs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index 95057acd6ea3..edf13774ced8 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -66,8 +66,7 @@ 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, - /// Armed while a file this sink opened for a `Bun.ModuleGraph`'s script is open, - /// and for `process.stdout`/`process.stderr` under `bun test --isolate`. + /// 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, @@ -276,9 +275,7 @@ pub(crate) extern "C" fn Bun__ForceFileSinkToBeSynchronousForProcessObjectStdio( } } -/// Arms a just-created `process.stdout`/`process.stderr` sink on the realm's -/// context so the `--isolate` swap ends it. Each isolate global dups the stdio -/// fd anew; an unclosed dup leaks its epoll registration (EEXIST on fd-number reuse). +/// 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, From ab8e1807a447da7920b05ab3fd54bd8d03df4aa7 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:13:22 +0000 Subject: [PATCH 06/10] Flush stdio sinks only at the isolate swap; make the fd-count fixture wait for the deferred close The abort handler took the graceful end() for every stop cause. At VmTeardown a backpressured end() can go Pending with no loop left to drain it, leaving the poll registered and a keep-alive ref across VM destruction. Limit the graceful path to StopReason::Disposed (the isolate swap); teardown keeps the native close. The fd-count fixture raced the work-pool close(2) of the previous file's dup. The first file records a baseline and later files poll, with a deadline, until their count drops to it. --- src/runtime/webcore/FileSink.rs | 11 +++++++++-- test/cli/test/isolation.test.ts | 22 ++++++++++++++++++---- 2 files changed, 27 insertions(+), 6 deletions(-) diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index 054dfb8386b3..31b7ba25ea9f 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -1686,7 +1686,7 @@ impl FileSink { } } -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`. @@ -1694,7 +1694,14 @@ bun_jsc::impl_abort_handle_owner!(FileSink, abort_handle, |this, _cause| { // write+dealloc provenance; the guard keeps it so across `close()` and `run_pending`. unsafe { let _guard = RefPtr::init_ref(this); - if (*this).flush_on_abort.get() { + // 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. + if (*this).flush_on_abort.get() + && matches!( + cause, + bun_jsc::AbortCause::ContextStopped(bun_jsc::StopReason::Disposed) + ) + { let _ = (*this).end(None); return; } diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index 48868b0bd690..857a3ed78beb 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -79,10 +79,8 @@ describe.concurrent("bun test --isolate", () => { 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 { readdirSync, readlinkSync } from "node:fs"; - test("count dups of stderr", () => { - process.stderr.write(""); - process.stdout.write(""); + import { existsSync, readdirSync, readFileSync, readlinkSync, writeFileSync } from "node:fs"; + function countStderrDups() { const target = readlinkSync("/proc/self/fd/2"); let count = 0; for (const fd of readdirSync("/proc/self/fd")) { @@ -93,6 +91,22 @@ describe.concurrent("bun test --isolate", () => { 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); }); `; From 483210b29160b7cd3138d14e6cd1759bee7fac26 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 05:20:01 +0000 Subject: [PATCH 07/10] FileSink: one-line note on the abort cause gate --- src/runtime/webcore/FileSink.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index 31b7ba25ea9f..f30746328880 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -1694,8 +1694,7 @@ bun_jsc::impl_abort_handle_owner!(FileSink, abort_handle, |this, cause| { // 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. + // Only the isolate swap drains a backpressured `end()`: VM teardown has no loop left. if (*this).flush_on_abort.get() && matches!( cause, From 0c8f3581db42ed264e79fb3ab794f71affc278fe Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:53:07 +0000 Subject: [PATCH 08/10] test --isolate: end stdio sinks at retire, after the file's close handlers; count both stdio fds The sweep before the swap ended process.stdout/process.stderr while the file's socket close handlers could still run, so a write from one was dropped. Those sinks now decline that sweep (on_abort records them and stop_active_handles_for_test_isolation re-arms them on the root context) and the swap's sweep after retireForTestIsolation ends them, once nothing enters the file's script again. The fd-count fixture now counts dups of fd 1 and fd 2. --- src/runtime/jsc_hooks.rs | 31 ++++++++++++ src/runtime/webcore/FileSink.rs | 41 +++++++++++++++- test/cli/test/isolation.test.ts | 84 +++++++++++++++++++++++++++------ 3 files changed, 140 insertions(+), 16 deletions(-) diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index c7577a110e40..8b2476c82960 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -97,6 +97,10 @@ pub(crate) struct RuntimeState { /// The resolver's PackageManager wake-handler context (module queue + VM /// handle); the resolver holds a raw pointer to it. Freed with the state. pub(crate) wake_ctx: Option>, + /// `Some` only while the `--isolate` sweep before the swap runs: the + /// `process.stdout`/`process.stderr` sinks it reaches (one ref each), to + /// re-arm after it. See [`stop_active_handles_for_test_isolation`]. + pub(crate) stdio_sinks_kept_for_retire: Option>>, /// In-process `Bun.cron()` jobs that `--hot` reload / worker teardown must /// stop; one ref per entry, released by `CronJob::remove_from_list` / /// `clear_all_for_vm`. @@ -370,6 +374,7 @@ unsafe fn init_runtime_state( } }, wake_ctx: None, + stdio_sinks_kept_for_retire: None, cron_jobs: Vec::new(), lint: core::cell::OnceCell::new(), })); @@ -1735,9 +1740,35 @@ fn stop_dns_for_vm_teardown() -> SweepResult { /// handles when it runs, so drain first so they are armed before the sweep, /// then stop. (VM teardown must *not* drain here — its /// prepareForDestruction discards the pre-exit queues.) +/// +/// The file's socket close handlers still run after this sweep, and may write to +/// `process.stdout`/`process.stderr`. Those sinks decline this sweep (their +/// `on_abort` records them instead) and are re-armed here, so the swap's sweep +/// after it retires the realm is the one that ends them. pub(crate) fn stop_active_handles_for_test_isolation(vm: &mut VirtualMachine) { let _ = vm.event_loop_mut().drain_microtasks(); + let state = runtime_state(); + // SAFETY: live boxed per-thread `RuntimeState`; the sweep's callbacks + // reach the field through `runtime_state()` again, never through this + // borrow, which ends at each statement. + unsafe { + if !state.is_null() { + (*state).stdio_sinks_kept_for_retire = Some(Vec::new()); + } + } let _ = stop_active_handles(vm, bun_jsc::StopReason::Disposed); + // SAFETY: as above. + let kept = unsafe { + if state.is_null() { + None + } else { + (*state).stdio_sinks_kept_for_retire.take() + } + }; + for sink in kept.into_iter().flatten() { + // SAFETY: `on_abort` took a ref on each entry; the call releases it. + unsafe { crate::webcore::FileSink::rearm_for_retire(sink.as_ptr(), vm) }; + } } pub(crate) fn stop_active_handles_for_vm_teardown(vm: &mut VirtualMachine) -> SweepResult { diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index f30746328880..28765dc5676a 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -303,6 +303,43 @@ pub(crate) extern "C" fn Bun__trackProcessStdioSinkForTestIsolation( } impl FileSink { + /// The `--isolate` sweep before the swap reached this stdio sink. The file's socket close + /// handlers still run after that sweep and may write here, so it stays open: it is recorded + /// for [`rearm_for_retire`](Self::rearm_for_retire). Returns false outside that sweep. + /// + /// # Safety + /// `this` must be the canonical live `*mut FileSink`. + unsafe fn keep_for_retire(this: *mut FileSink) -> bool { + let state = crate::jsc_hooks::runtime_state(); + if state.is_null() { + return false; + } + // SAFETY: live boxed per-thread `RuntimeState`; the borrow ends here. + let Some(kept) = (unsafe { &mut (*state).stdio_sinks_kept_for_retire }) else { + return false; + }; + // SAFETY: caller contract. The ref keeps `this` live until `rearm_for_retire`. + unsafe { (*this).ref_() }; + kept.push(core::ptr::NonNull::new(this).expect("sink")); + true + } + + /// Arms a sink [`keep_for_retire`](Self::keep_for_retire) recorded on the root context again, + /// for the swap's sweep after it retires the realm, and releases the record's ref. + /// + /// # Safety + /// `this` came from `keep_for_retire` in this sweep; it must not be used after the call. + pub(crate) unsafe fn rearm_for_retire( + this: *mut FileSink, + vm: &bun_jsc::virtual_machine::VirtualMachine, + ) { + // SAFETY: caller contract; the ref taken in `keep_for_retire` keeps `this` live + // until the trailing `deref`, its last use. + unsafe { + bun_jsc::AbortHandle::arm_owner(this, vm.root_context()); + FileSink::deref(this); + } + } /// `bun.spawn`'s subprocess exited while this `FileSink` was its stdin. /// /// Takes the canonical `*mut FileSink` (not `&mut self`): `writer.close()` @@ -1701,7 +1738,9 @@ bun_jsc::impl_abort_handle_owner!(FileSink, abort_handle, |this, cause| { bun_jsc::AbortCause::ContextStopped(bun_jsc::StopReason::Disposed) ) { - let _ = (*this).end(None); + if !FileSink::keep_for_retire(this) { + let _ = (*this).end(None); + } return; } (*this).done.set(true); diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index 857a3ed78beb..e73580cadb81 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -80,34 +80,40 @@ describe.concurrent("bun test --isolate", () => { 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"); - let count = 0; + // Dups of stdout and stderr: [fd 1 count, fd 2 count]. + function countDups() { + const targets = [readlinkSync("/proc/self/fd/1"), readlinkSync("/proc/self/fd/2")]; + const counts = [0, 0]; for (const fd of readdirSync("/proc/self/fd")) { try { - if (readlinkSync("/proc/self/fd/" + fd) === target) count++; + const link = readlinkSync("/proc/self/fd/" + fd); + for (let i = 0; i < 2; i++) if (link === targets[i]) counts[i]++; } catch (error) { // An fd can vanish between readdir and readlink. if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } } - return count; + return counts; } - test("count dups of stderr", () => { + test("count dups of stdout and 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; + // file's dups on a work-pool thread, so later files poll until those + // closes land. A leaked dup never closes, so the poll then times out. + const baseline = existsSync("baseline.json") ? JSON.parse(readFileSync("baseline.json", "utf8")) : null; const deadline = Date.now() + 5000; - let count = countStderrDups(); - while (baseline !== null && count > baseline && Date.now() < deadline) { + let counts = countDups(); + while ( + baseline !== null && + (counts[0] > baseline[0] || counts[1] > baseline[1]) && + Date.now() < deadline + ) { Bun.sleepSync(1); - count = countStderrDups(); + counts = countDups(); } - if (baseline === null) writeFileSync("baseline.txt", String(count)); - console.log("FDCOUNT:" + count); + if (baseline === null) writeFileSync("baseline.json", JSON.stringify(counts)); + console.log("FDCOUNT:" + counts.join(",")); }); `; const names = ["a", "b", "c", "d"].map(c => `${c}-stdio-fds.test.ts`); @@ -117,13 +123,61 @@ describe.concurrent("bun test --isolate", () => { ["--isolate"], names.map(name => `./${name}`), ); - const counts = [...stdout.matchAll(/FDCOUNT:(\d+)/g)].map(m => Number(m[1])); + const counts = [...stdout.matchAll(/FDCOUNT:(\d+),(\d+)/g)].map(m => [Number(m[1]), Number(m[2])]); expect(counts).toHaveLength(4); expect(counts).toEqual(Array(4).fill(counts[0])); expect(normalizeBunSnapshot(stderr, dir)).toContain("4 pass"); expect(exitCode).toBe(0); }); + // The swap closes the file's leaked sockets after the sweep that stops its + // handles, and their close handlers still run. A write to process.stderr + // from one must reach the fd, so the stdio sinks end only once the realm + // is retired. + test("with --isolate, a socket close handler can still write to process.stderr at the swap", async () => { + await using server = Bun.listen({ + hostname: "127.0.0.1", + port: 0, + socket: { data() {} }, + }); + using dir = tempDir("isolate-stdio-close-handler", { + "a-leaks-socket.test.ts": ` + import { test, expect } from "bun:test"; + test("leaves a socket open", async () => { + process.stderr.write(""); + const sock = await Bun.connect({ + hostname: "127.0.0.1", + port: Number(process.env.SERVER_PORT), + socket: { + data() {}, + close() { + process.stderr.write("CLOSE-HANDLER-WROTE\\n"); + }, + }, + }); + expect(sock.localPort).toBeGreaterThan(0); + }); + `, + "b-next.test.ts": ` + import { test, expect } from "bun:test"; + test("next file", () => { + expect(1).toBe(1); + }); + `, + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "test", "--isolate", "./a-leaks-socket.test.ts", "./b-next.test.ts"], + env: { ...bunEnv, SERVER_PORT: String(server.port) }, + cwd: String(dir), + stderr: "pipe", + stdout: "pipe", + }); + const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + expect(stderr).toContain("CLOSE-HANDLER-WROTE"); + expect(normalizeBunSnapshot(stderr, dir)).toContain("2 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": ` From dcbfa3c9e8f363f5edbaeb764d35dbb5d9b752cb Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 09:08:10 +0000 Subject: [PATCH 09/10] Tighten the notes on the stdio sink re-arm --- src/runtime/jsc_hooks.rs | 12 +++++------- src/runtime/webcore/FileSink.rs | 10 +++++----- 2 files changed, 10 insertions(+), 12 deletions(-) diff --git a/src/runtime/jsc_hooks.rs b/src/runtime/jsc_hooks.rs index 8b2476c82960..e13d504647bb 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -97,9 +97,8 @@ pub(crate) struct RuntimeState { /// The resolver's PackageManager wake-handler context (module queue + VM /// handle); the resolver holds a raw pointer to it. Freed with the state. pub(crate) wake_ctx: Option>, - /// `Some` only while the `--isolate` sweep before the swap runs: the - /// `process.stdout`/`process.stderr` sinks it reaches (one ref each), to - /// re-arm after it. See [`stop_active_handles_for_test_isolation`]. + /// `Some` while the `--isolate` sweep before the swap runs: the stdio sinks it + /// reached, one ref each, re-armed after it (see [`stop_active_handles_for_test_isolation`]). pub(crate) stdio_sinks_kept_for_retire: Option>>, /// In-process `Bun.cron()` jobs that `--hot` reload / worker teardown must /// stop; one ref per entry, released by `CronJob::remove_from_list` / @@ -1741,10 +1740,9 @@ fn stop_dns_for_vm_teardown() -> SweepResult { /// then stop. (VM teardown must *not* drain here — its /// prepareForDestruction discards the pre-exit queues.) /// -/// The file's socket close handlers still run after this sweep, and may write to -/// `process.stdout`/`process.stderr`. Those sinks decline this sweep (their -/// `on_abort` records them instead) and are re-armed here, so the swap's sweep -/// after it retires the realm is the one that ends them. +/// The file's socket close handlers still run after this sweep and may write to +/// `process.stdout`/`process.stderr`, so those sinks decline it (`on_abort` records +/// them) and are re-armed here for the swap's sweep after it retires the realm. pub(crate) fn stop_active_handles_for_test_isolation(vm: &mut VirtualMachine) { let _ = vm.event_loop_mut().drain_microtasks(); let state = runtime_state(); diff --git a/src/runtime/webcore/FileSink.rs b/src/runtime/webcore/FileSink.rs index 28765dc5676a..18fe951f105a 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -303,9 +303,9 @@ pub(crate) extern "C" fn Bun__trackProcessStdioSinkForTestIsolation( } impl FileSink { - /// The `--isolate` sweep before the swap reached this stdio sink. The file's socket close - /// handlers still run after that sweep and may write here, so it stays open: it is recorded - /// for [`rearm_for_retire`](Self::rearm_for_retire). Returns false outside that sweep. + /// The `--isolate` sweep before the swap reached this stdio sink: the file's close handlers + /// may still write here, so record it for [`rearm_for_retire`](Self::rearm_for_retire) + /// instead of ending it. False outside that sweep. /// /// # Safety /// `this` must be the canonical live `*mut FileSink`. @@ -324,8 +324,8 @@ impl FileSink { true } - /// Arms a sink [`keep_for_retire`](Self::keep_for_retire) recorded on the root context again, - /// for the swap's sweep after it retires the realm, and releases the record's ref. + /// Re-arms a sink [`keep_for_retire`](Self::keep_for_retire) recorded, for the swap's sweep + /// after it retires the realm, and releases the record's ref. /// /// # Safety /// `this` came from `keep_for_retire` in this sweep; it must not be used after the call. From 3382edabbc5f6bf698364f2f9dfbed65b39f8ba3 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:10:57 +0000 Subject: [PATCH 10/10] test: use the runTests helper in the close-handler case --- test/cli/test/isolation.test.ts | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index e73580cadb81..a7f886aa25c6 100644 --- a/test/cli/test/isolation.test.ts +++ b/test/cli/test/isolation.test.ts @@ -165,14 +165,12 @@ describe.concurrent("bun test --isolate", () => { }); `, }); - await using proc = Bun.spawn({ - cmd: [bunExe(), "test", "--isolate", "./a-leaks-socket.test.ts", "./b-next.test.ts"], - env: { ...bunEnv, SERVER_PORT: String(server.port) }, - cwd: String(dir), - stderr: "pipe", - stdout: "pipe", - }); - const [stderr, exitCode] = await Promise.all([proc.stderr.text(), proc.exited]); + const { stderr, exitCode } = await runTests( + String(dir), + ["--isolate"], + ["./a-leaks-socket.test.ts", "./b-next.test.ts"], + { ...bunEnv, SERVER_PORT: String(server.port) }, + ); expect(stderr).toContain("CLOSE-HANDLER-WROTE"); expect(normalizeBunSnapshot(stderr, dir)).toContain("2 pass"); expect(exitCode).toBe(0);