Skip to content
Closed
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
f0031ab
ipc: deliver a peer-initiated channel close from the read dispatch, b…
robobun Aug 18, 2026
115e9dc
ipc: pass the libuv read-error context as a raw pointer; block the fo…
robobun Aug 18, 2026
820de1d
ipc: shorten the comments on the peer-close path
robobun Aug 18, 2026
b80014d
ipc: on Windows, report a peer close that lands while a write is in f…
robobun Aug 18, 2026
6313483
ipc: let an in-flight Windows write complete before a peer close is r…
robobun Aug 18, 2026
22d2255
ipc: report the channel close from the exit path, before the exit itself
robobun Aug 18, 2026
519958f
ipc: pin the disconnect-before-exit order with a node:test file that …
robobun Aug 18, 2026
904dac0
ipc: at exit, close the channel on Windows without waiting for a writ…
robobun Aug 18, 2026
63d7b8d
Merge branch 'main' into farm/f99e6bad/ipc-peer-close-before-exit
robobun Oct 25, 2026
9cc897a
test: a child and a cluster worker that exit on their own while the p…
robobun Oct 25, 2026
289e7b6
ipc: leave a channel with unread input open when the child exits
robobun Oct 25, 2026
3a2a29d
types: say when onDisconnect follows onExit
robobun Oct 25, 2026
080c4fb
ipc: say what happens to a channel with unread input at exit
robobun Oct 25, 2026
408ae0a
ipc: run the queued close work from the exit path through run_pending
robobun Oct 26, 2026
a089ea7
ipc: at exit, close only a channel whose other end is gone
robobun Oct 26, 2026
93747ea
sys: add recv_peek_non_block and use it for the IPC end-of-channel check
robobun Oct 26, 2026
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: 4 additions & 5 deletions packages/bun-types/bun.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
* - It fires before {@link onExit}: when the process exits, the channel
* is closed (should something else still hold the child's end open)
* and reported first, the order in which `node:child_process` emits
* `'disconnect'` and `'exit'` when the channel closes with the child.
* - 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
Expand Down
15 changes: 6 additions & 9 deletions src/runtime/api/bun/subprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -737,11 +737,6 @@ impl Subprocess<'_> {
)
}

pub(crate) fn disconnect_ipc(&self, next_tick: bool) {
let Some(ipc_data) = self.ipc() else { return };
ipc_data.close_socket_next_tick(next_tick);
}

pub(crate) fn disconnect(&self) {
if let Some(ipc_data) = self.ipc() {
ipc_data.disconnect();
Expand Down Expand Up @@ -863,9 +858,7 @@ impl Subprocess<'_> {
let is_sync = self.flags.get().contains(Flags::IS_SYNC);
self.clear_abort_signal();

// `deref()` and `disconnect_ipc(true)` run at the tail of this body.
// R-2: now that both take `&self`, scopeguard would no longer alias —
// kept explicit at the tail for now (no early returns in this body).
// `deref()` runs at the tail of this body (no early returns).

if self.event_loop_timer.get().state == EventLoopTimerState::ACTIVE {
Self::timer_all().remove(self.event_loop_timer.as_ptr());
Expand Down Expand Up @@ -1014,6 +1007,11 @@ impl Subprocess<'_> {
}
}

// The channel's close is reported before the exit below, as in node.
if let Some(ipc) = self.ipc() {
ipc.close_after_peer_exit();
Comment thread
robobun marked this conversation as resolved.
Resolved
}

let mut did_update_has_pending_activity = false;

// Kept as raw `*mut` so the enter guard and the body can both call
Expand Down Expand Up @@ -1111,7 +1109,6 @@ impl Subprocess<'_> {
if !did_update_has_pending_activity {
self.update_has_pending_activity();
}
self.disconnect_ipc(true);
self.deref();
}

Expand Down
60 changes: 44 additions & 16 deletions src/runtime/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1200,22 +1200,7 @@ impl SendQueue {
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_after_close();
}
// Release the task's ref; the SendQueue may be freed here.
// SAFETY: `this` is live and owns the ref taken at schedule.
Expand All @@ -1232,6 +1217,49 @@ impl SendQueue {
unsafe { <SendQueue as bun_ptr::CellRefCounted>::deref(this) };
}

fn run_after_close(&self) {
if !self.pending_after_close.replace(false) {
return;
}
log!("SendQueue#_onAfterIPCClosed");
if self.close_event_sent.replace(true) {
return;
}
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);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
if let Some(owner) = self.owner.get() {
owner.handle_ipc_close();
}
}

/// The peer process has exited: closes what is left of the channel and reports the close now,
/// for the owner to report before the exit (node's order). The deferred task, which may also
/// have been scheduled for it, runs later and finds nothing to do.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn close_after_peer_exit(&self) {
log!("SendQueue#closeAfterPeerExit");
if self.socket_is_open() {
// A disconnect() still postponed (behind a handle's ack, or on its task) is overtaken.
self.close_after_flush.set(false);
self.pending_close.set(false);
// As is a write still in flight: nothing is left to complete it.
#[cfg(windows)]
self.windows_close(true);
#[cfg(not(windows))]
self.close_socket(CloseReason::Normal, CloseFrom::User);
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if !self.pending_after_close.get() {
return;
}
let _scope = self.get_global_this().bun_vm().enter_event_loop_scope();
self.run_after_close();
}

/// `uv::open_handles` closes the channel's pipe through here at a thread
/// teardown: close now (pending writes finish ECANCELED) and let the owner
/// observe the disconnect, rather than waiting for writes as a user close does.
Expand Down
136 changes: 135 additions & 1 deletion test/js/bun/spawn/spawn.ipc.test.ts
Original file line number Diff line number Diff line change
@@ -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, tempDir } from "harness";
import { readdirSync, readFileSync } 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.
Expand Down Expand Up @@ -75,6 +76,36 @@ async function runReceiver(serialization: "json" | "advanced", senderSource: str
return { stdout: stdout.split("\n").filter(Boolean), stderr, exitCode };
}

// Kills the child and returns once it 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 a SIGKILL'd child is
// gone within a few milliseconds.
function killAndBlockUntilDead(child: Bun.Subprocess) {
child.kill("SIGKILL");
if (!isLinux) {
Bun.sleepSync(100);
Comment thread
robobun marked this conversation as resolved.
Resolved
return;
}
const deadline = Date.now() + 30_000;
for (;;) {
let dead: boolean;
try {
const stat = readFileSync(`/proc/${child.pid}/stat`, "latin1");
dead = stat[stat.lastIndexOf(")") + 2] === "Z" && readdirSync(`/proc/${child.pid}/task`).length === 1;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT" && (error as NodeJS.ErrnoException).code !== "ESRCH") {
throw error;
}
dead = true;
}
if (dead) return;
if (Date.now() > deadline) throw new Error("child did not die");
Bun.sleepSync(1);
}
}

describe.each(["advanced", "json"])("ipc mode %s", mode => {
it("the subprocess should be defined and the child should send", done => {
gcTick();
Expand Down Expand Up @@ -192,8 +223,111 @@ 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<unknown>) {
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<void>();
const disconnected = Promise.withResolvers<void>();
const exited = Promise.withResolvers<void>();
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<void>();
const exited = Promise.withResolvers<void>();
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",
]);
});
});

Comment thread
robobun marked this conversation as resolved.
Resolved
// 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
Expand Down
Loading
Loading