Skip to content

ipc: deliver messages sent right before child exit on the waiter-thread path - #37882

Closed
robobun wants to merge 1 commit into
mainfrom
farm/785627c4/ipc-drain-on-exit
Closed

robobun wants to merge 1 commit into
mainfrom
farm/785627c4/ipc-drain-on-exit

Conversation

@robobun

@robobun robobun commented Aug 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

Fix

  • uSockets gains a call that runs the socket's hangup dispatch synchronously; the exit handler calls it (POSIX only) before scheduling the close.
  • Correct because it is the same dispatch the real hangup event runs: queued bytes reach the normal handlers, then the socket ends and closes. No-op if already closed, at EOF, or paused. Node likewise reads the channel to EOF.
  • Verification: a new test makes the race deterministic (child writes a sentinel after sending, parent blocks in spawnSync until it has exited). Fails 4/4 without the fix in waiter-thread mode, passes in both modes with it. Skipped on Windows.

Background

  • IPC channel: parent and child share a socket pair; a sent message waits in the parent's kernel buffer until its event loop reads the socket, so the child can exit with it unread.
  • Exit notification: the parent learns of an exit via a pidfd in the same epoll as its sockets, or via a waiter thread that posts a task to the loop. They differ only in ordering against socket events.
  • Hangup dispatch: in uSockets the peer closing shows up as a readable event with an EOF hint; handling it reads remaining data (including passed fds), then runs end and close. The fix invokes that handler directly.

no test proof · iteration 3 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/spawn/spawn-ipc-exit-message.test.ts

Original description

What does this PR do?

Fixes #37849. An IPC message sent by a child right before it exits was dropped when Bun uses the waiter-thread process-exit fallback (BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1, which is also the production path when pidfd is unavailable) and the parent only reaches its event loop after the child has already exited. Affects both Bun.spawn({ ipc }) and node:child_process.fork().

Repro (from the issue, parent kept off its event loop with spawnSync):

const { promise, resolve } = Promise.withResolvers();
const a = Bun.spawn({
  cmd: [process.execPath, "-e", `process.send("hello"); Promise.resolve().then(() => process.exit(0));`],
  ipc: resolve,
});
Bun.spawnSync({ cmd: [process.execPath, "-e", "0"] });
await promise; // lost with BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1

Before: { delivered: 5, lost: 5 } (varies). After: { delivered: 10, lost: 0 } in both modes, matching Node, which reads the IPC channel to EOF regardless of when it notices the exit.

Cause

On the waiter-thread path the exit arrives as a task posted to the event loop, which runs before the loop polls the IPC socket. The exit handler in subprocess.rs calls disconnect_ipc(true) -> SendQueue::close_socket_next_tick, and the deferred close runs before the socket's readable event is ever dispatched, discarding the child's final bytes still queued in the kernel buffer. On the pidfd path both events come through epoll and the read wins, so nothing was lost there.

Fix

New us_socket_drain_hangup in uSockets: when the owner learns out-of-band that the peer process is dead, synchronously run the hangup readable dispatch (us_internal_dispatch_ready_poll with the eof hint). That drains the kernel buffer through the normal on_data/on_fd handlers (including SCM_RIGHTS handle passing) and then ends and closes the socket exactly like the real event would. The subprocess exit path calls it (POSIX only) before scheduling the IPC close.

Verification

New test test/js/bun/spawn/spawn-ipc-exit-message.test.ts makes the race deterministic (child touches a sentinel file after process.send(), parent blocks in spawnSync until the child has fully exited): fails 4/4 iterations on the unfixed build in waiter-thread mode, passes with the fix in both waiter-thread and pidfd modes.

Also ran: test/js/bun/spawn/spawn.test.ts (140 pass), the child_process IPC suites (child_process_ipc, ipc_handle, ipc_large_disconnect, send_cb: 15 pass), the upstream test-cluster-* exit/disconnect/message tests, and cargo check for the Windows target.

This unblocks removing the serialization workaround noted in #37834.

…ad path

On the waiter-thread process-exit path (BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1,
also the fallback when pidfd is unavailable) the exit notification reaches the
event loop as a posted task, which runs before the IPC socket's readable event
is polled. The exit handler's deferred socket close then discarded IPC data
the child wrote right before exiting.

Add us_socket_drain_hangup, which synchronously dispatches the hangup readable
event (draining the kernel buffer through on_data/on_fd, then end+close like
the real event), and call it from the subprocess exit path before scheduling
the IPC close, matching how node reads the channel to EOF before tearing it
down.

Fixes #37849
@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 19 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: d1361e49-0405-4efe-adb7-81ffcbaee8e2

📥 Commits

Reviewing files that changed from the base of the PR and between 9a543cc and 8943787.

📒 Files selected for processing (7)
  • packages/bun-usockets/src/libusockets.h
  • packages/bun-usockets/src/socket.c
  • src/runtime/api/bun/subprocess.rs
  • src/runtime/ipc.rs
  • src/uws_sys/socket.rs
  • src/uws_sys/us_socket_t.rs
  • test/js/bun/spawn/spawn-ipc-exit-message.test.ts

Comment @coderabbitai help to get the list of available commands.

@robobun

robobun commented Aug 12, 2026

Copy link
Copy Markdown
Collaborator Author

CodeRabbit was rate limited and skipped this PR; its review will run on the next push, or it can be requested with @coderabbitai review once the limit resets.

@coderabbitai

coderabbitai Bot commented Aug 12, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@robobun Acknowledged. The review is pending until the next push or an explicit @coderabbitai review request.

You are interacting with an AI system.

@claude claude Bot left a comment

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.

Beyond the inline nits, I also checked two things about the new synchronous us_socket_drain_hangup re-entry into us_internal_dispatch_ready_poll: (1) recv-buffer clobbering — the drain runs from either the waiter-thread task or the pidfd POLL_TYPE_CALLBACK, neither of which is holding loop->data.recv_buf, so the shared buffer isn't live; (2) double-dispatch on the pidfd path when both the pidfd and the IPC socket are ready in the same epoll/kqueue batch — the drain's close reaches us_poll_stop → us_internal_loop_update_pending_ready_polls, which nulls the IPC socket's pending ready-poll slot, and the outer loop's if (poll) guard skips it.

Extended reasoning...

This PR adds a new uSockets primitive and calls it from inside Subprocess::on_process_exit, synchronously firing the user's ipc callback (and the socket's end/close handlers) from a new call site. The refcounting looks right — the exit handler holds a Subprocess ref until its trailing deref(), the Subprocess holds the SendQueue ref until finalize, and compute_has_pending_activity still sees !close_event_sent so this_value stays Strong across the drain — but this is exactly the class of change (new re-entrant user-JS call site inside a lifecycle handler, new nested us_internal_dispatch_ready_poll) that a maintainer should look at. The two inline findings are nits; the ruled-out items above are the extra things I traced.

Comment on lines +1191 to +1197
// 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();
}

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.

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

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.)

robobun added a commit that referenced this pull request Aug 13, 2026
The existing tests pin the ordering deterministically via /proc and are
Linux-only. This adds the sentinel-file variant from #37882, which also
runs on macOS: the child writes a file once it has sent, and the parent
stays off its event loop until the file exists and the child has had time
to exit. Loses the message without the fix, passes with it.
@robobun

robobun commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator Author

Consolidated into #37869, which uses the same synchronous drain but runs it before exited resolves and onExit runs (so the messages precede the exit, as in node) and leaves a close the user already requested alone. #37869 now also carries the portable sentinel-file test from this PR, so the race is covered on macOS as well as through /proc on Linux. Closing.

@robobun robobun closed this Aug 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IPC message sent right before the child exits is dropped on the waiter-thread exit path (Bun.spawn ipc and child_process.fork)

1 participant