Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions packages/bun-usockets/src/libusockets.h
Original file line number Diff line number Diff line change
Expand Up @@ -738,6 +738,11 @@ int us_socket_set_tos(us_socket_r s, int tos);
int us_socket_get_tos(us_socket_r s);
void us_socket_resume(us_socket_r s);
void us_socket_pause(us_socket_r s);
/* Synchronously dispatch a hangup readable event: delivers data still queued
* in the kernel buffer (on_data / on_fd), then ends and closes the socket as
* the real hangup event would. For when the peer process is known dead but
* its final event has not been dispatched yet. */
void us_socket_drain_hangup(us_socket_r s) nonnull_fn_decl;

#ifdef __cplusplus
}
Expand Down
14 changes: 14 additions & 0 deletions packages/bun-usockets/src/socket.c
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,20 @@ int us_socket_ipc_write_fd(struct us_socket_t *s, const char *data, int length,
}
#endif

/* The owner learned out-of-band (e.g. waitpid) that the peer process is dead,
* but the socket's final readable/hangup event has not been dispatched yet.
* Closing the socket now would discard whatever the peer wrote before dying,
* so run the hangup dispatch synchronously: it drains the kernel receive
* buffer through on_data/on_fd and then ends + closes the socket exactly like
* the real event would. No-op when there is nothing left to deliver (closed /
* EOF already seen) or the owner paused reading. */
void us_socket_drain_hangup(struct us_socket_t *s) {
if (us_socket_is_closed(s) || s->read_eof || s->flags.is_paused) {
return;
}
us_internal_dispatch_ready_poll(&s->p, 0, 1, LIBUS_SOCKET_READABLE);
}

__attribute__((always_inline)) void *us_socket_ext(struct us_socket_t *s) {
return s + 1;
}
Expand Down
7 changes: 7 additions & 0 deletions src/runtime/api/bun/subprocess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1188,6 +1188,13 @@
if !did_update_has_pending_activity {
self.update_has_pending_activity();
}
// The exit can reach the loop before the IPC socket's readable event
// (waiter-thread path): deliver anything the child wrote before it
// exited, or the deferred close below drops it (#37849).
#[cfg(not(windows))]
if let Some(ipc_data) = self.ipc() {
ipc_data.drain_after_peer_exit();
}

Check warning on line 1197 in src/runtime/api/bun/subprocess.rs

View check run for this annotation

Claude / Claude Code Review

IPC drain runs after onExit / .exited resolution

Nit: on the waiter-thread path the drained IPC message is delivered *after* `onExit` fires and `.exited` resolves (the drain sits below the `!is_sync` block). Not a regression — before this PR the message was dropped entirely, and Node doesn't guarantee message-before-exit ordering either — but if you want the message to be observable inside `onExit`, the drain would need to move above the promise/onExit block. That also moves the drain's `on_close` → `onDisconnect` to before `onExit`, so the cu
Comment on lines +1191 to +1197

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Nit: on the waiter-thread path the drained IPC message is delivered after onExit fires and .exited resolves (the drain sits below the !is_sync block). Not a regression — before this PR the message was dropped entirely, and Node doesn't guarantee message-before-exit ordering either — but if you want the message to be observable inside onExit, the drain would need to move above the promise/onExit block. That also moves the drain's on_close → onDisconnect to before onExit, so the current placement may well be the right trade-off; just flagging the ordering.

Extended reasoning...

What this observes

drain_after_peer_exit() is called at the very end of on_process_exit (subprocess.rs:1195), after:

  • the exited promise has been resolved (and its .then continuations drained when _exit_guard drops),
  • the onExit callback has been invoked via run_callback,
  • update_has_pending_activity().

drain_after_peer_exit() synchronously runs the hangup dispatch, which fires on_data → handle_ipc_message → the user's ipc callback (via event_loop.run_callback). So on the waiter-thread path, user code observes: onExit fires (and await child.exited resumes) → then the final IPC message arrives. Semantically the child sent the message before it exited.

Concrete example

const msgs = [];
Bun.spawn({
  cmd: [...],
  ipc: m => msgs.push(m),
  onExit: () => console.log(msgs.length),   // logs 0 on the waiter-thread path
});

On the waiter-thread path (BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1, or when pidfd is unavailable), on_process_exit runs the exit callback first, then drains — so msgs.length is 0 inside onExit and 1 immediately after.

Why this is a nit, not a bug

The refutation's objections are correct and I'm not disputing them:

  1. Not a regression. Before this PR the message was dropped on the waiter-thread path. Delivered-after-onExit is strictly better than lost. The linked issue (IPC message sent right before the child exits is dropped on the waiter-thread exit path (Bun.spawn ipc and child_process.fork) #37849) is about loss, not ordering.
  2. Node.js does not guarantee message-before-exit. libuv delivers SIGCHLD-driven exit and pipe-readable independently; Node's child_process docs explicitly note stdio may still be open when exit fires (see process.send is async and I can't guarantee IPC messages get sent before process.exit nodejs/node#6767, uncatchable segfault when using fetch #7793). Bun.spawn has never documented such a guarantee either.
  3. The pidfd path's ordering is not guaranteed either. When both the pidfd and the IPC socket are ready in the same epoll batch (exactly the scenario the test constructs), dispatch order is unspecified — if the pidfd wins, on_process_exit runs first there too, and with the new drain delivers the message after onExit just like the waiter-thread path.
  4. The PR's stated intent is drain-before-close, not drain-before-exit-event. "Reads the channel to EOF before tearing it down" — the drain sits immediately before disconnect_ipc(true), which is the tear-down it's protecting against. That intent is satisfied.

The trade-off with moving it earlier

Moving the drain above the !is_sync block would deliver the message before onExit on both paths (on pidfd, if the pidfd event is dispatched first, an early drain would still surface the message before onExit). But us_socket_drain_hangup doesn't just fire on_data — it also ends and closes the socket, which synchronously fires handle_ipc_close → the onDisconnect callback + update_has_pending_activity. So moving the drain earlier would fire onDisconnect before onExit, which is its own ordering change to weigh. The current placement (right before disconnect_ipc, the call it functionally replaces) is the minimal-surface change.

Suggestion

If message-before-exit ordering is desired, hoist the drain_after_peer_exit() block to just before the if !is_sync { block (and before the first update_has_pending_activity bookkeeping). If the current ordering is intentional given the onDisconnect trade-off, it might be worth a one-line comment noting that the drain deliberately runs after onExit so onDisconnect stays last. Either way, this doesn't block merging.

self.disconnect_ipc(true);
self.deref();
}
Expand Down
14 changes: 14 additions & 0 deletions src/runtime/ipc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1260,6 +1260,20 @@ impl SendQueue {
let _ = unsafe { bun_core::heap::take(windows) };
}

/// The peer process exited, reported out-of-band (waitpid / the waiter
/// thread) rather than through this socket's own readable event. Bytes
/// the peer wrote right before exiting may still sit unread in the kernel
/// buffer, and the exit path's deferred close would discard them; deliver
/// them now, like node reads the channel to EOF before tearing it down.
/// Dispatches on_data/on_fd and, at EOF, the normal end/close handlers.
#[cfg(not(windows))]
pub fn drain_after_peer_exit(&self) {
if let SocketUnion::Open(socket) = *self.socket.get() {
log!("SendQueue#drainAfterPeerExit");
socket.drain_hangup();
}
}

pub fn close_socket_next_tick(&self, next_tick: bool) {
log!("SendQueue#closeSocketNextTick");
if !self.socket_is_open() {
Expand Down
11 changes: 11 additions & 0 deletions src/uws_sys/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,17 @@ impl<const IS_SSL: bool> NewSocketHandler<IS_SSL> {
)
}

/// The peer process is known dead but the socket's final readable/hangup
/// event has not been dispatched yet: run that dispatch synchronously so
/// data still queued in the kernel buffer is delivered before the socket
/// is ended and closed. May re-enter the socket's handlers and close it.
/// No-op for non-uSockets transports.
pub fn drain_hangup(&self) {
if let InternalSocket::Connected(s) = self.socket {
sock(s).drain_hangup();
}
}

/// The JS wrapper that owns this socket is being finalized: whatever the
/// close below unwinds must not reach back into JS objects.
pub fn prepare_for_finalize(&self) {
Expand Down
15 changes: 15 additions & 0 deletions src/uws_sys/us_socket_t.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,20 @@ impl us_socket_t {
c::us_socket_shutdown(self);
}

/// The peer process is known dead but its final readable/hangup event has
/// not been dispatched yet: run that dispatch synchronously so data still
/// queued in the kernel buffer is delivered (on_data / on_fd) before the
/// socket is ended and closed. May re-enter the socket's handlers and
/// close `self`.
pub fn drain_hangup(&mut self) {
bun_core::scoped_log!(uws, "us_socket_drain_hangup({:p})", self);
unsafe {
// SAFETY: self is a live us_socket_t; a close inside the dispatch
// defers the free to the loop's closed-sockets sweep.
c::us_socket_drain_hangup(self);
}
}

pub(crate) fn shutdown_read(&mut self) {
c::us_socket_shutdown_read(self);
}
Expand Down Expand Up @@ -554,6 +568,7 @@ mod c {
reason: *mut c_void,
) -> *mut us_socket_t;
pub(super) safe fn us_socket_shutdown(s: &mut us_socket_t);
pub(super) fn us_socket_drain_hangup(s: *mut us_socket_t);
pub(super) safe fn us_socket_is_closed(s: &us_socket_t) -> i32;
pub(super) fn us_socket_write_check_error(
s: &us_socket_t,
Expand Down
75 changes: 75 additions & 0 deletions test/js/bun/spawn/spawn-ipc-exit-message.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows, tempDir } from "harness";

// https://github.com/oven-sh/bun/issues/37849
// A child that sends an IPC message and then exits must still get the message
// delivered, even when the parent learns of the exit before it polls the IPC
// socket. That is always the case on the waiter-thread process-exit path
// (BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1, also taken when pidfd is
// unavailable): the exit's deferred socket close used to win against the
// readable event and drop the message.
//
// The fixture makes the race deterministic: the child writes a sentinel file
// after process.send(), and the parent stays off its event loop (blocking in
// spawnSync) until the sentinel exists plus one extra spawnSync, so the child
// has fully exited before the parent processes either event.
const fixture = `
import { existsSync, rmSync } from "node:fs";

const N = 4;
let delivered = 0, lost = 0;
for (let i = 0; i < N; i++) {
const sentinel = "sentinel-" + i;
rmSync(sentinel, { force: true });
const { promise, resolve } = Promise.withResolvers();
const child = Bun.spawn({
cmd: [
process.execPath,
"-e",
'process.send("hello"); require("fs").writeFileSync("' + sentinel + '", "x"); Promise.resolve().then(() => process.exit(0));',
],
ipc: resolve,
stdio: ["inherit", "inherit", "inherit"],
});
while (!existsSync(sentinel)) {
Bun.spawnSync({ cmd: [process.execPath, "-e", "0"] });
}
Bun.spawnSync({ cmd: [process.execPath, "-e", "0"] });
(await Promise.race([promise, Bun.sleep(3000).then(() => "TIMEOUT")])) === "hello" ? delivered++ : lost++;
await child.exited;
rmSync(sentinel, { force: true });
}
console.log(JSON.stringify({ delivered, lost }));
`;

async function run(extraEnv: Record<string, string>) {
using dir = tempDir("ipc-exit-message", { "parent.ts": fixture });
await using proc = Bun.spawn({
cmd: [bunExe(), "parent.ts"],
cwd: String(dir),
env: { ...bunEnv, ...extraEnv },
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
expect(stderr).toBe("");
expect(JSON.parse(stdout)).toEqual({ delivered: 4, lost: 0 });
expect(exitCode).toBe(0);
}

test.concurrent.skipIf(isWindows)(
"ipc message sent right before child exit is delivered (waiter thread)",
async () => {
// The feature flag is only read when BUN_GARBAGE_COLLECTOR_LEVEL is set.
await run({ BUN_GARBAGE_COLLECTOR_LEVEL: "1", BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: "1" });
},
30_000,
);

test.concurrent.skipIf(isWindows)(
"ipc message sent right before child exit is delivered (pidfd)",
async () => {
await run({});
},
30_000,
);

Check warning on line 75 in test/js/bun/spawn/spawn-ipc-exit-message.test.ts

View check run for this annotation

Claude / Claude Code Review

pidfd test does not unset BUN_FEATURE_FLAG_FORCE_WAITER_THREAD

The '(pidfd)' test doesn't unset `BUN_FEATURE_FLAG_FORCE_WAITER_THREAD`, so if it's present in the outer environment it leaks through `bunEnv` (which spreads `process.env` and always sets `BUN_GARBAGE_COLLECTOR_LEVEL`, opening the gate at VirtualMachine.rs:3535) and this test silently exercises the waiter-thread path too — duplicating the first test instead of guarding the pidfd/kqueue path. Pass `BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: undefined` in the second test's extraEnv (and widen the param
Comment on lines +69 to +75

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 The '(pidfd)' test doesn't unset BUN_FEATURE_FLAG_FORCE_WAITER_THREAD, so if it's present in the outer environment it leaks through bunEnv (which spreads process.env and always sets BUN_GARBAGE_COLLECTOR_LEVEL, opening the gate at VirtualMachine.rs:3535) and this test silently exercises the waiter-thread path too — duplicating the first test instead of guarding the pidfd/kqueue path. Pass BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: undefined in the second test's extraEnv (and widen the parameter type to Record<string, string | undefined>).

Extended reasoning...

What the bug is

The second test case is titled "(pidfd)" and is meant to exercise the default pidfd/kqueue process-exit path (as opposed to the first test, which forces the waiter-thread path via BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1). It calls run({}), passing an empty extraEnv on top of bunEnv. However, if the outer test-runner process already has BUN_FEATURE_FLAG_FORCE_WAITER_THREAD set in its environment, the flag leaks into the fixture and both tests end up exercising the waiter-thread path — the pidfd path is never covered.

The specific code path

Step by step, with concrete values:

  1. bunEnv spreads the ambient environment. test/harness.ts:65 does ...process.env, and nothing in bunEnv unsets BUN_FEATURE_FLAG_FORCE_WAITER_THREAD. So if the developer or CI runner has BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1 exported, bunEnv.BUN_FEATURE_FLAG_FORCE_WAITER_THREAD === "1".
  2. bunEnv always sets BUN_GARBAGE_COLLECTOR_LEVEL. test/harness.ts:83 sets it to process.env.BUN_GARBAGE_COLLECTOR_LEVEL || "0" — i.e. it is always present (at minimum "0").
  3. The '(pidfd)' test spreads { ...bunEnv, ...{} }. Lines 69–75 call run({}), which builds env: { ...bunEnv, ...extraEnv } at line 50. With extraEnv = {}, the child receives BUN_GARBAGE_COLLECTOR_LEVEL="0" and (inherited) BUN_FEATURE_FLAG_FORCE_WAITER_THREAD="1".
  4. The runtime gate opens. src/jsc/VirtualMachine.rs:3535 checks map.get(b"BUN_GARBAGE_COLLECTOR_LEVEL").is_some() — presence, not value — and inside that block, line 3539 checks map.get(b"BUN_FEATURE_FLAG_FORCE_WAITER_THREAD").is_some() and calls WaiterThread::set_should_use_waiter_thread(). Both are present, so the fixture parent runs on the waiter-thread path.
  5. Result: the '(pidfd)' test title lies — it exercises the same path as the '(waiter thread)' test, and the pidfd/kqueue path this PR claims still works has no regression guard.

Why this scenario is anticipated

test/js/bun/spawn/spawn.test.ts:611 explicitly guards a test with it.skipIf(Boolean(process.env.BUN_FEATURE_FLAG_FORCE_WAITER_THREAD)), demonstrating that the codebase already treats this env var as something that can be present in the test-runner environment. (That specific guard is recursion protection — the test re-invokes spawn.test.ts on itself with the flag set — rather than proof of a global CI lane, but it establishes that the flag reaching the outer runner is a real state the suite defends against.) REVIEW.md's harness-conventions section also prescribes exactly this pattern: "Spread bunEnv when modifying it ({...bunEnv, KEY: undefined})."

Impact

This never causes a test failure — with the fix in this PR, both the waiter-thread and pidfd paths deliver the message, so both tests pass regardless. The impact is purely lost coverage: in an environment where the flag is inherited, a future regression on the pidfd path (which already worked before this PR and is the no-regression guard here) would go undetected because the '(pidfd)' test would silently be running the waiter-thread code instead. It's a hermeticity gap, not a correctness bug.

How to fix

Explicitly clear the flag in the second test's extraEnv, matching the REVIEW.md convention:

async function run(extraEnv: Record<string, string | undefined>) {
  ...
}

test.concurrent.skipIf(isWindows)(
  "ipc message sent right before child exit is delivered (pidfd)",
  async () => {
    await run({ BUN_FEATURE_FLAG_FORCE_WAITER_THREAD: undefined });
  },
  30_000,
);

(Widening the parameter type to string | undefined is needed so the undefined deletion-via-spread typechecks; Bun.spawn's env already accepts string | undefined values.)

Loading