Repository navigation
ipc: deliver messages sent right before child exit on the waiter-thread path #37882
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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
|
||
|
Comment on lines
+69
to
+75
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 The '(pidfd)' test doesn't unset Extended reasoning...What the bug isThe 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 The specific code pathStep by step, with concrete values:
Why this scenario is anticipated
ImpactThis 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 fixExplicitly 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 |
||
There was a problem hiding this comment.
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
onExitfires and.exitedresolves (the drain sits below the!is_syncblock). 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 insideonExit, the drain would need to move above the promise/onExit block. That also moves the drain'son_close→onDisconnectto beforeonExit, 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 ofon_process_exit(subprocess.rs:1195), after:exitedpromise has been resolved (and its.thencontinuations drained when_exit_guarddrops),onExitcallback has been invoked viarun_callback,update_has_pending_activity().drain_after_peer_exit()synchronously runs the hangup dispatch, which fireson_data→handle_ipc_message→ the user'sipccallback (viaevent_loop.run_callback). So on the waiter-thread path, user code observes:onExitfires (andawait child.exitedresumes) → then the final IPC message arrives. Semantically the child sent the message before it exited.Concrete example
On the waiter-thread path (BUN_FEATURE_FLAG_FORCE_WAITER_THREAD=1, or when pidfd is unavailable),
on_process_exitruns the exit callback first, then drains — somsgs.lengthis 0 insideonExitand 1 immediately after.Why this is a nit, not a bug
The refutation's objections are correct and I'm not disputing them:
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.on_process_exitruns first there too, and with the new drain delivers the message afteronExitjust like the waiter-thread path.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_syncblock would deliver the message beforeonExiton both paths (on pidfd, if the pidfd event is dispatched first, an early drain would still surface the message beforeonExit). Butus_socket_drain_hangupdoesn't just fireon_data— it also ends and closes the socket, which synchronously fireshandle_ipc_close→ theonDisconnectcallback +update_has_pending_activity. So moving the drain earlier would fireonDisconnectbeforeonExit, which is its own ordering change to weigh. The current placement (right beforedisconnect_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 theif !is_sync {block (and before the firstupdate_has_pending_activitybookkeeping). If the current ordering is intentional given theonDisconnecttrade-off, it might be worth a one-line comment noting that the drain deliberately runs afteronExitsoonDisconnectstays last. Either way, this doesn't block merging.