diff --git a/src/jsc/bindings/BunProcess.cpp b/src/jsc/bindings/BunProcess.cpp index adaa1a5f1831..898dfa39ba65 100644 --- a/src/jsc/bindings/BunProcess.cpp +++ b/src/jsc/bindings/BunProcess.cpp @@ -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. @@ -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); 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 c7577a110e40..e13d504647bb 100644 --- a/src/runtime/jsc_hooks.rs +++ b/src/runtime/jsc_hooks.rs @@ -97,6 +97,9 @@ 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` 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` / /// `clear_all_for_vm`. @@ -370,6 +373,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 +1739,34 @@ 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`, 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(); + // 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 1aea4c7d7fa6..18fe951f105a 100644 --- a/src/runtime/webcore/FileSink.rs +++ b/src/runtime/webcore/FileSink.rs @@ -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, - /// 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, } // `bun.ptr.RefCount(FileSink, "ref_count", deinit, .{})` — intrusive single-thread @@ -277,7 +279,67 @@ 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`; 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 { + /// 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`. + 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 + } + + /// 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. + 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()` @@ -1656,11 +1718,12 @@ 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::(), + 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`. @@ -1668,6 +1731,18 @@ 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); + // Only the isolate swap drains a backpressured `end()`: VM teardown has no loop left. + if (*this).flush_on_abort.get() + && matches!( + cause, + bun_jsc::AbortCause::ContextStopped(bun_jsc::StopReason::Disposed) + ) + { + if !FileSink::keep_for_retire(this) { + let _ = (*this).end(None); + } + return; + } (*this).done.set(true); #[cfg(windows)] if !(*this).writer.get().owns_fd { diff --git a/test/cli/test/isolation.test.ts b/test/cli/test/isolation.test.ts index 13ec4e9aae83..a7f886aa25c6 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"; @@ -73,6 +73,109 @@ 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"; + // 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 { + 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 counts; + } + 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 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 counts = countDups(); + while ( + baseline !== null && + (counts[0] > baseline[0] || counts[1] > baseline[1]) && + Date.now() < deadline + ) { + Bun.sleepSync(1); + counts = countDups(); + } + 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`); + 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+),(\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); + }); + `, + }); + 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); + }); + test("with --isolate, a file's process.chdir() is undone before the next file", async () => { const cwdFixtures = { "a-chdir.test.ts": `