diff --git a/packages/bun-types/bun.d.ts b/packages/bun-types/bun.d.ts index 59aa530c8e58..7d7954e3415e 100644 --- a/packages/bun-types/bun.d.ts +++ b/packages/bun-types/bun.d.ts @@ -7918,11 +7918,10 @@ declare module "bun" { * - This callback indicates that the pipe is closed; it is not an error * by itself. Use {@link onExit} or {@link Subprocess.exited} to * determine why the process ended. - * - It may occur before or after {@link onExit} depending on timing; do - * not rely on ordering. Typically, if you or the child call - * `disconnect()` first, this fires before {@link onExit}; if the - * process exits without an explicit disconnect, either may happen - * first. + * - When the process exits, this fires before {@link onExit}. The + * exceptions are a channel with input that is still unread at that + * moment, and a channel that another process still holds open: they + * are closed, and reported, after {@link onExit}. * - Only runs when {@link ipc} is enabled and runs at most once per * subprocess. * - If the child becomes a zombie (exited but not yet reaped), the IPC is diff --git a/src/runtime/api/bun/subprocess.rs b/src/runtime/api/bun/subprocess.rs index b709da579918..42e503f1bfdd 100644 --- a/src/runtime/api/bun/subprocess.rs +++ b/src/runtime/api/bun/subprocess.rs @@ -1023,6 +1023,10 @@ impl Subprocess<'_> { // The exit is reported to the script that spawned the child. let _context = (*jsc_vm).enter_context(self.context); if !is_sync { + // The channel reports its end before this exit is reported. + if let Some(ipc_data) = self.ipc() { + ipc_data.close_after_peer_exit(); + } if !this_jsvalue.is_empty() { if let Some(promise) = js::exited_promise_take_cached(this_jsvalue, global_this) { // SAFETY: event_loop points into the live VM and outlives this scope. diff --git a/src/runtime/ipc.rs b/src/runtime/ipc.rs index a87586280ffd..7e30fc4c34a0 100644 --- a/src/runtime/ipc.rs +++ b/src/runtime/ipc.rs @@ -1196,32 +1196,83 @@ impl SendQueue { // SAFETY: caller contract — the queued task owns a ref on `this`. let sq = unsafe { &*this }; sq.deferred_scheduled.set(false); - if sq.pending_close.replace(false) { - log!("SendQueue#closeSocketTask"); - sq.close_socket(CloseReason::Normal, CloseFrom::User); - } - if sq.pending_after_close.replace(false) { - log!("SendQueue#_onAfterIPCClosed"); - if !sq.close_event_sent.replace(true) { - let global = sq.get_global_this(); - if let Some(item) = sq.waiting_for_ack.with_mut(|w| w.take()) { - item.complete(&global); - } - // on_write_complete already dequeued everything fully written; the rest was never delivered. - for item in sq.queue.with_mut(std::mem::take) { - item.abort_unsent(&global); - } - if let Some(owner) = sq.owner.get() { - owner.handle_ipc_close(); - } - } - } + sq.run_pending(); } // Release the task's ref; the SendQueue may be freed here. // SAFETY: `this` is live and owns the ref taken at schedule. unsafe { ::deref(this) }; } + /// Does now what the queued task would do. A pending flag means that task is still queued, and its ref keeps `self` alive through the callbacks. + pub(crate) fn run_pending(&self) { + if self.pending_close.replace(false) { + log!("SendQueue#closeSocketTask"); + self.close_socket(CloseReason::Normal, CloseFrom::User); + } + if self.pending_after_close.replace(false) { + log!("SendQueue#_onAfterIPCClosed"); + if !self.close_event_sent.replace(true) { + let global = self.get_global_this(); + if let Some(item) = self.waiting_for_ack.with_mut(|w| w.take()) { + item.complete(&global); + } + // on_write_complete already dequeued everything fully written; the rest was never delivered. + for item in self.queue.with_mut(std::mem::take) { + item.abort_unsent(&global); + } + if let Some(owner) = self.owner.get() { + owner.handle_ipc_close(); + } + } + } + } + + /// The peer process has exited. A channel whose other end is closed, with nothing left to read, + /// is closed here, so that `run_pending` reports its end before the owner reports the exit. + pub(crate) fn close_after_peer_exit(&self) { + if self.peer_closed_and_drained() { + // A write still in flight on Windows is cancelled: nothing is left to complete it. + #[cfg(windows)] + self.windows_close(true); + #[cfg(not(windows))] + self.close_socket(CloseReason::Normal, CloseFrom::User); + } + self.run_pending(); + } + + /// Whether the channel is open on our side, closed on the other, with no input left to read. + fn peer_closed_and_drained(&self) -> bool { + let SocketUnion::Open(socket) = *self.socket.get() else { + return false; + }; + #[cfg(not(windows))] + { + match bun_sys::recv_peek_non_block(socket.fd(), &mut [0u8]) { + Ok(peeked) => peeked == 0, + // Any error but "nothing to read yet" ends the stream (ECONNRESET: the peer died + // with our data unread). + Err(err) => !err.is_retry(), + } + } + #[cfg(windows)] + { + use bun_sys::windows::kernel32::PeekNamedPipe; + // Fails once the other end is closed and the pipe is empty. + // SAFETY: `socket` is the live pipe (`socket == Open`); each out-pointer may be null. + let peeked = unsafe { + PeekNamedPipe( + (*socket).handle, + core::ptr::null_mut(), + 0, + core::ptr::null_mut(), + core::ptr::null_mut(), + core::ptr::null_mut(), + ) + }; + peeked == 0 + } + } + /// `Taskable::release_unrun`: a scheduled deferred task that will never /// run still owns a ref; drop it (skipping the JS callbacks). /// diff --git a/src/sys/lib.rs b/src/sys/lib.rs index 14ee170f6bb6..bcf6678746d0 100644 --- a/src/sys/lib.rs +++ b/src/sys/lib.rs @@ -3183,6 +3183,10 @@ mod posix_impl { pub fn recv_non_block(fd: Fd, buf: &mut [u8]) -> Maybe { recv(fd, buf, MSG_DONTWAIT) } + /// `recv_non_block` that leaves what it reads in the socket's queue. + pub fn recv_peek_non_block(fd: Fd, buf: &mut [u8]) -> Maybe { + recv(fd, buf, libc::MSG_PEEK | MSG_DONTWAIT) + } /// `MSG_DONTWAIT | MSG_NOSIGNAL` so a broken-pipe write /// returns EPIPE instead of raising SIGPIPE. pub fn send_non_block(fd: Fd, buf: &[u8]) -> Maybe { diff --git a/src/windows_sys/externs.rs b/src/windows_sys/externs.rs index 990071300015..68cc33d8f9c4 100644 --- a/src/windows_sys/externs.rs +++ b/src/windows_sys/externs.rs @@ -955,6 +955,15 @@ pub mod kernel32 { nDefaultTimeOut: DWORD, lpSecurityAttributes: *mut c_void, ) -> HANDLE; + /// `PeekNamedPipe` (`namedpipeapi.h`). Each out-pointer may be null. + pub fn PeekNamedPipe( + hNamedPipe: HANDLE, + lpBuffer: *mut c_void, + nBufferSize: DWORD, + lpBytesRead: *mut DWORD, + lpTotalBytesAvail: *mut DWORD, + lpBytesLeftThisMessage: *mut DWORD, + ) -> BOOL; /// `AddVectoredExceptionHandler` (`errhandlingapi.h`). pub fn AddVectoredExceptionHandler( First: u32, diff --git a/test/js/bun/spawn/spawn.ipc.test.ts b/test/js/bun/spawn/spawn.ipc.test.ts index 1851c4adbe53..4802b398b4c0 100644 --- a/test/js/bun/spawn/spawn.ipc.test.ts +++ b/test/js/bun/spawn/spawn.ipc.test.ts @@ -1,6 +1,7 @@ import { spawn } from "bun"; import { describe, expect, it } from "bun:test"; -import { bunEnv, bunExe, gcTick, isWindows, tempDir } from "harness"; +import { bunEnv, bunExe, gcTick, isLinux, isWindows, shellExe, tempDir } from "harness"; +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; import path from "path"; // The receiver rejects a JSON line that's longer than the UTF-8 encoding of a max-length string can be. @@ -75,6 +76,43 @@ async function runReceiver(serialization: "json" | "advanced", senderSource: str return { stdout: stdout.split("\n").filter(Boolean), stderr, exitCode }; } +function blockUntil(what: string, condition: () => boolean) { + const deadline = Date.now() + 30_000; + while (!condition()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + Bun.sleepSync(1); + } +} + +// Returns once a child that was killed, or is exiting on its own, is dead, without touching the +// event loop, so that its exit is pending at the same time as whatever its death did to the +// channel. On Linux the child is dead once /proc shows it as a zombie with no other threads left +// (the last thread to go is the one that closes its descriptors and signals the exit; a debug build +// takes ~15ms to get there), or once it is gone from /proc (already reaped by the waiter thread). +// Elsewhere such a child is gone within a few milliseconds. +function blockUntilDead(pid: number) { + if (!isLinux) { + Bun.sleepSync(100); + return; + } + blockUntil("the child to die", () => { + try { + const stat = readFileSync(`/proc/${pid}/stat`, "latin1"); + return stat[stat.lastIndexOf(")") + 2] === "Z" && readdirSync(`/proc/${pid}/task`).length === 1; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT" && (error as NodeJS.ErrnoException).code !== "ESRCH") { + throw error; + } + return true; + } + }); +} + +function killAndBlockUntilDead(child: Bun.Subprocess) { + child.kill("SIGKILL"); + blockUntilDead(child.pid); +} + describe.each(["advanced", "json"])("ipc mode %s", mode => { it("the subprocess should be defined and the child should send", done => { gcTick(); @@ -192,8 +230,154 @@ describe.each(["advanced", "json"])("ipc mode %s", mode => { : { name: "DataCloneError", message: "The object can not be cloned." }, }); }); + + // The tests below kill the child and stay off the event loop until it is dead, so the channel + // going away and the exit are both pending when the loop resumes. As in node, the channel's close + // has to be reported before the exit; it used to be left to a later event-loop task, so onExit + // ran first. + async function killAndReportOrder(child: Bun.Subprocess, events: string[], done: Promise) { + killAndBlockUntilDead(child); + await done; + return events; + } + + it.concurrent("onDisconnect runs before onExit when the child dies with the channel drained", async () => { + const events: string[] = []; + const ready = Promise.withResolvers(); + const disconnected = Promise.withResolvers(); + const exited = Promise.withResolvers(); + await using child = spawn({ + cmd: [ + bunExe(), + "-e", + `process.on("message", () => console.log("received")); setInterval(() => {}, 1000); process.send("ready");`, + ], + env: bunEnv, + stdio: ["ignore", "pipe", "inherit"], + serialization: mode, + ipc: () => ready.resolve(), + onDisconnect() { + events.push("disconnect"); + disconnected.resolve(); + }, + onExit() { + events.push("exit"); + exited.resolve(); + }, + }); + await ready.promise; + child.send("read me"); + // Once this is printed the child has read everything we sent, so its end closes cleanly (EOF). + await child.stdout.getReader().read(); + expect(await killAndReportOrder(child, events, Promise.all([disconnected.promise, exited.promise]))).toEqual([ + "disconnect", + "exit", + ]); + }); + + // The child never reads its end of the channel, so what we send stays unread; on Linux our end + // then reports ECONNRESET instead of EOF when the child dies, which closes the channel through + // a different path than the test above. A message larger than the channel's buffers is on top + // of that still being written when the child dies. + it.concurrent.each([ + ["a short message", "never read"], + ["a message larger than the channel's buffers", Buffer.alloc(4 * 1024 * 1024, "x").toString()], + ])("onDisconnect runs before onExit when the child dies with %s unread", async (_label, message) => { + const events: string[] = []; + const disconnected = Promise.withResolvers(); + const exited = Promise.withResolvers(); + await using child = spawn({ + cmd: [bunExe(), "-e", `console.log("ready"); setInterval(() => {}, 1000);`], + env: bunEnv, + stdio: ["ignore", "pipe", "inherit"], + serialization: mode, + ipc() {}, + onDisconnect() { + events.push("disconnect"); + disconnected.resolve(); + }, + onExit() { + events.push("exit"); + exited.resolve(); + }, + }); + await child.stdout.getReader().read(); + child.send(message); + expect(await killAndReportOrder(child, events, Promise.all([disconnected.promise, exited.promise]))).toEqual([ + "disconnect", + "exit", + ]); + }); + + // Closing the channel when the child exits must not discard what the child sent last. On Windows + // the exit reaches the loop ahead of that message when the child wrote it, and exited, while an + // `ipc` handler was running. + it.concurrent("delivers what the child sent right before exiting while an ipc handler was running", async () => { + using dir = tempDir("ipc-last-message", {}); + const parentIsBusy = path.join(String(dir), "parent-is-busy"); + const received: unknown[] = []; + const disconnected = Promise.withResolvers(); + await using child = spawn({ + cmd: [ + bunExe(), + "-e", + `const { existsSync } = require("node:fs"); + process.send("first"); + // The last message goes out only once the parent handles the first, and the exit follows + // once that message has left (Windows writes it from the event loop). + const deadline = Date.now() + 30_000; + const timer = setInterval(() => { + if (Date.now() > deadline) process.exit(1); + if (!existsSync(${JSON.stringify(parentIsBusy)})) return; + clearInterval(timer); + process.send("last", () => process.exit(0)); + }, 1);`, + ], + env: bunEnv, + stdio: ["ignore", "inherit", "inherit"], + serialization: mode, + ipc(message, subprocess) { + received.push(message); + if (message !== "first") return; + try { + writeFileSync(parentIsBusy, ""); + blockUntilDead(subprocess.pid); + } catch (error) { + disconnected.reject(error); + } + }, + onDisconnect: () => disconnected.resolve(), + }); + await disconnected.promise; + expect(received).toEqual(["first", "last"]); + }); }); +// The waiter thread is the Linux fallback for kernels and sandboxes without pidfd. It hands the +// exit to the loop as a task, which runs before the loop so much as polls the channel, so the order +// cannot come from which of the two the loop sees first. Reruns the ordering tests above that way. +it.skipIf(!isLinux || Boolean(process.env.BUN_FEATURE_FLAG_FORCE_WAITER_THREAD))( + "onDisconnect runs before onExit when the exit is reported by the waiter thread", + async () => { + await using proc = spawn({ + cmd: [ + bunExe(), + "test", + import.meta.path, + "-t", + "ipc mode json onDisconnect runs before onExit when the child dies", + ], + // Only honored together with BUN_GARBAGE_COLLECTOR_LEVEL, which bunEnv sets. + env: { ...bunEnv, BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: "1" }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect(stdout + stderr).toContain(" 3 pass"); + expect(exitCode).toBe(0); + }, +); + describe("ipc mode json", () => { it.skipIf(isWindows)("closes the channel on a line that holds only the internal tag byte", async () => { // An internal JSON message is "\\x02" + json + "\\n". A line of just the tag @@ -247,6 +431,52 @@ describe("ipc mode json", () => { exitCode: 0, }); }); + + // A process that inherited the child's end of the channel can still write to it once the child + // is gone. When that input and the exit are pending together, with the exit first, the close that + // the exit brings must wait for the loop to read the input. + it.concurrent.skipIf(isWindows)( + "does not close the channel over input that is unread when the child exits", + async () => { + using dir = tempDir("ipc-unread-at-exit", {}); + const exitNow = path.join(String(dir), "exit-now"); + const writeNow = path.join(String(dir), "write-now"); + const written = path.join(String(dir), "written"); + const received: unknown[] = []; + const disconnected = Promise.withResolvers(); + await using child = spawn({ + // fd 3 is the shell's end of the channel. The background subshell inherits it, outlives the + // shell, and writes one JSON message to it when told to. Both give up after 30 seconds. + cmd: [ + shellExe(), + "-c", + `(i=0; while [ ! -e "$2" ] && [ $i -lt 3000 ]; do sleep 0.01; i=$((i+1)); done + echo '"written after the exit"' >&3; : > "$3") >/dev/null 2>&1 & + echo ready + i=0; while [ ! -e "$1" ] && [ $i -lt 3000 ]; do sleep 0.01; i=$((i+1)); done`, + "sh", + exitNow, + writeNow, + written, + ], + env: bunEnv, + stdio: ["ignore", "pipe", "inherit"], + serialization: "json", + ipc: message => void received.push(message), + onDisconnect: () => disconnected.resolve(), + }); + await child.stdout.getReader().read(); + // A few turns of the loop with the channel idle. Without them the channel is still queued + // from its first writable event, ahead of the exit. + for (let i = 0; i < 3; i++) await new Promise(resolve => setImmediate(resolve)); + writeFileSync(exitNow, ""); + blockUntilDead(child.pid); + writeFileSync(writeNow, ""); + blockUntil("the write to the channel", () => existsSync(written)); + await disconnected.promise; + expect(received).toEqual(["written after the exit"]); + }, + ); }); describe("ipc mode advanced", () => { diff --git a/test/js/node/child_process/child_process_ipc_disconnect_before_exit.test.js b/test/js/node/child_process/child_process_ipc_disconnect_before_exit.test.js new file mode 100644 index 000000000000..976587f7e6b5 --- /dev/null +++ b/test/js/node/child_process/child_process_ipc_disconnect_before_exit.test.js @@ -0,0 +1,129 @@ +"use strict"; +// Written against node:test and node APIs only (no harness), so that the same file also runs under +// node to confirm the behaviour it pins down: `node child_process_ipc_disconnect_before_exit.test.js`. +// +// A forked child's 'disconnect' is emitted before its 'exit' even when the parent gets to look at +// both only after the channel is gone and the child is dead. The parent below stays off its event +// loop until the child is dead, so both are pending at once. Bun used to report the channel's close +// through a later event-loop task, so 'exit' (reported straight from the exit notification) came +// first. + +if (process.argv[2] === "child") { + const fs = require("node:fs"); + process.on("message", () => { + process.disconnect(); + fs.writeFileSync(process.argv[3], ""); + }); + setInterval(() => {}, 1000); // Stay alive until the parent kills us. + console.log("ready"); + return; +} + +if (process.argv[2] === "child-that-exits") { + const fs = require("node:fs"); + // The callback runs once the message has left (Windows writes it from the event loop). Then + // exit on our own, but only when the parent is inside its 'message' handler. + process.send("bye", () => { + blockUntil("the parent to get the message", () => fs.existsSync(process.argv[3])); + process.exit(3); + }); + return; +} + +const assert = require("node:assert"); +const { fork } = require("node:child_process"); +const { once } = require("node:events"); +const fs = require("node:fs"); +const os = require("node:os"); +const path = require("node:path"); +const { after, test } = require("node:test"); + +const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "ipc-disconnect-before-exit-")); +const children = []; +after(() => { + // A test that failed early leaves its child running. + for (const child of children) child.kill("SIGKILL"); + fs.rmSync(tmpdir, { recursive: true, force: true }); +}); + +function sleepSync(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +function blockUntil(what, condition) { + const deadline = Date.now() + 30_000; + while (!condition()) { + if (Date.now() > deadline) throw new Error(`timed out waiting for ${what}`); + sleepSync(1); + } +} + +// On Linux the child is dead once /proc shows it as a zombie with no other threads left (the last +// thread to go is the one that closes its descriptors and signals the exit) or no longer shows it +// at all; elsewhere a child that was killed, or is already exiting, is gone within milliseconds. +function blockUntilDead(pid) { + if (process.platform !== "linux") return sleepSync(100); + blockUntil("the child to die", () => { + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "latin1"); + return stat[stat.lastIndexOf(")") + 2] === "Z" && fs.readdirSync(`/proc/${pid}/task`).length === 1; + } catch (error) { + if (error.code !== "ENOENT" && error.code !== "ESRCH") throw error; + return true; + } + }); +} + +async function forkChild(name) { + const closed = path.join(tmpdir, `${name}-channel-closed`); + const child = fork(__filename, ["child", closed], { stdio: ["ignore", "pipe", "inherit", "ipc"] }); + children.push(child); + const events = []; + child.on("disconnect", () => events.push("disconnect")); + child.on("exit", () => events.push("exit")); + await once(child.stdout, "data"); + return { child, closed, events }; +} + +test("the child closes its end of the channel and is then killed", async () => { + const { child, closed, events } = await forkChild("closed"); + child.send("close your end"); + blockUntil("the child to close the channel", () => fs.existsSync(closed)); + child.kill("SIGKILL"); + blockUntilDead(child.pid); + await once(child, "close"); + assert.deepStrictEqual(events, ["disconnect", "exit"]); +}); + +test("the child is killed with a message from the parent possibly still unread", async () => { + const { child, events } = await forkChild("unread"); + child.send("may never be read"); + child.kill("SIGKILL"); + blockUntilDead(child.pid); + await once(child, "close"); + assert.deepStrictEqual(events, ["disconnect", "exit"]); +}); + +test("the child sends a message and exits on its own", async () => { + const parentIsBusy = path.join(tmpdir, "parent-is-busy"); + const child = fork(__filename, ["child-that-exits", parentIsBusy]); + children.push(child); + const events = []; + const closed = Promise.withResolvers(); + child.on("message", message => { + events.push(`message:${message}`); + try { + // The child exits once it sees this file. Staying in the handler until it is dead leaves + // the channel's end and the exit both pending. + fs.writeFileSync(parentIsBusy, ""); + blockUntilDead(child.pid); + } catch (error) { + closed.reject(error); + } + }); + child.on("disconnect", () => events.push("disconnect")); + child.on("exit", code => events.push(`exit:${code}`)); + child.on("close", closed.resolve); + await closed.promise; + assert.deepStrictEqual(events, ["message:bye", "disconnect", "exit:3"]); +}); diff --git a/test/js/node/cluster.test.ts b/test/js/node/cluster.test.ts index 034a68b99502..97b53ecc79d6 100644 --- a/test/js/node/cluster.test.ts +++ b/test/js/node/cluster.test.ts @@ -557,6 +557,75 @@ if (cluster.isPrimary) { expect(exitCode).toBe(0); }); +test.concurrent("a worker's 'disconnect' is emitted before its 'exit'", async () => { + // The worker exits on its own while the primary is inside a 'message' handler, and the primary + // stays there until the worker is dead, so the channel's end and the exit are both pending when + // its loop resumes. The channel's close used to be reported through a later event-loop task, + // after the exit. + using dir = tempDir("cluster-disconnect-before-exit", { + "main.js": ` +const cluster = require("node:cluster"); +const { existsSync, readdirSync, readFileSync, writeFileSync } = require("node:fs"); + +const deadline = Date.now() + 30_000; +function blockUntil(what, condition) { + while (!condition()) { + if (Date.now() > deadline) throw new Error("timed out waiting for " + what); + Bun.sleepSync(1); + } +} + +// On Linux the worker is dead once /proc shows it as a zombie with no other threads left (the last +// thread to go is the one that closes its descriptors and signals the exit) or no longer shows it +// at all; elsewhere a process that is already exiting is gone within milliseconds. +function blockUntilDead(pid) { + if (process.platform !== "linux") return Bun.sleepSync(100); + blockUntil("the worker to exit", () => { + try { + const stat = readFileSync("/proc/" + pid + "/stat", "latin1"); + return stat[stat.lastIndexOf(")") + 2] === "Z" && readdirSync("/proc/" + pid + "/task").length === 1; + } catch (error) { + if (error.code !== "ENOENT" && error.code !== "ESRCH") throw error; + return true; + } + }); +} + +if (cluster.isPrimary) { + const events = []; + const worker = cluster.fork(); + worker.on("message", () => { + writeFileSync("primary-is-busy", ""); + blockUntilDead(worker.process.pid); + }); + cluster.on("disconnect", () => events.push("disconnect")); + cluster.on("exit", (_worker, code) => events.push("exit:" + code)); + process.on("exit", () => console.log(JSON.stringify(events))); +} else { + // The callback runs once the message has left. Windows writes it from the event loop, so + // blocking right after send() would keep it from ever going out. + process.send("bye", () => { + blockUntil("the primary to get the message", () => existsSync("primary-is-busy")); + process.exit(3); + }); +} +`, + }); + await using proc = Bun.spawn({ + cmd: [bunExe(), "main.js"], + env: bunEnv, + cwd: String(dir), + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]); + expect({ events: stdout.trim(), stderr, exitCode }).toEqual({ + events: JSON.stringify(["disconnect", "exit:3"]), + stderr: "", + exitCode: 0, + }); +}); + test("disconnect() on a cluster.Worker built around a plain object does not abort", async () => { // `kHandle` is a private symbol that only `cluster.fork()` sets, so a // `cluster.Worker({ process })` built around a plain object (how Node's own