Repository navigation
Conversation
…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
|
Warning Review limit reached
Next review available in: 19 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (7)
Comment |
|
CodeRabbit was rate limited and skipped this PR; its review will run on the next push, or it can be requested with |
|
Tip For best results, initiate chat on the files or code changes.
You are interacting with an AI system. |
There was a problem hiding this comment.
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.
| // 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(); | ||
| } |
There was a problem hiding this comment.
🟡 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
exitedpromise has been resolved (and its.thencontinuations drained when_exit_guarddrops), - the
onExitcallback has been invoked viarun_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:
- 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.
- Node.js does not guarantee message-before-exit. libuv delivers SIGCHLD-driven exit and pipe-readable independently; Node's
child_processdocs explicitly note stdio may still be open whenexitfires (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. - 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_exitruns first there too, and with the new drain delivers the message afteronExitjust like the waiter-thread path. - 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.
| test.concurrent.skipIf(isWindows)( | ||
| "ipc message sent right before child exit is delivered (pidfd)", | ||
| async () => { | ||
| await run({}); | ||
| }, | ||
| 30_000, | ||
| ); |
There was a problem hiding this comment.
🟡 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:
bunEnvspreads the ambient environment.test/harness.ts:65does...process.env, and nothing inbunEnvunsetsBUN_FEATURE_FLAG_FORCE_WAITER_THREAD. So if the developer or CI runner hasBUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1exported,bunEnv.BUN_FEATURE_FLAG_FORCE_WAITER_THREAD === "1".bunEnvalways setsBUN_GARBAGE_COLLECTOR_LEVEL.test/harness.ts:83sets it toprocess.env.BUN_GARBAGE_COLLECTOR_LEVEL || "0"— i.e. it is always present (at minimum"0").- The '(pidfd)' test spreads
{ ...bunEnv, ...{} }. Lines 69–75 callrun({}), which buildsenv: { ...bunEnv, ...extraEnv }at line 50. WithextraEnv = {}, the child receivesBUN_GARBAGE_COLLECTOR_LEVEL="0"and (inherited)BUN_FEATURE_FLAG_FORCE_WAITER_THREAD="1". - The runtime gate opens.
src/jsc/VirtualMachine.rs:3535checksmap.get(b"BUN_GARBAGE_COLLECTOR_LEVEL").is_some()— presence, not value — and inside that block, line 3539 checksmap.get(b"BUN_FEATURE_FLAG_FORCE_WAITER_THREAD").is_some()and callsWaiterThread::set_should_use_waiter_thread(). Both are present, so the fixture parent runs on the waiter-thread path. - 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.)
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.
|
Consolidated into #37869, which uses the same synchronous drain but runs it before |
Problem
process.send()and exits right after can have that message silently dropped. AffectsBun.spawn({ ipc })andnode:child_process.fork().BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1, also used when pidfd is unavailable), when the parent sees the exit before it has polled the IPC socket.Fix
spawnSyncuntil it has exited). Fails 4/4 without the fix in waiter-thread mode, passes in both modes with it. Skipped on Windows.Background
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 bothBun.spawn({ ipc })andnode:child_process.fork().Repro (from the issue, parent kept off its event loop with
spawnSync):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.rscallsdisconnect_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_hangupin uSockets: when the owner learns out-of-band that the peer process is dead, synchronously run the hangup readable dispatch (us_internal_dispatch_ready_pollwith the eof hint). That drains the kernel buffer through the normalon_data/on_fdhandlers (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.tsmakes the race deterministic (child touches a sentinel file afterprocess.send(), parent blocks inspawnSyncuntil 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), thechild_processIPC suites (child_process_ipc,ipc_handle,ipc_large_disconnect,send_cb: 15 pass), the upstreamtest-cluster-*exit/disconnect/message tests, andcargo checkfor the Windows target.This unblocks removing the serialization workaround noted in #37834.