Skip to content

child_process: set channel to null once the IPC channel disconnects - #43001

Closed
robobun wants to merge 3 commits into
mainfrom
robobun/98183dca/ipc-null-channel-after-close
Closed

robobun wants to merge 3 commits into
mainfrom
robobun/98183dca/ipc-null-channel-after-close

Conversation

@robobun

@robobun robobun commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • subprocess.channel and process.channel stay objects after the IPC channel disconnects. node v26.3.0 sets both to null, its documented test for a closed channel. connected is already correct.
  • Parent: ChildProcess#onDisconnect (src/js/node/child_process.ts:1605) handles a close the peer started. It never clears channel. Child: process.channel is a lazy property (constructProcessChannel in BunProcess.cpp) that nothing writes after the first read.

Fix

  • #onDisconnect sets this.channel = null before it queues 'disconnect', as node does at end of file (child_process.js#L646-L653).
  • process.disconnect() and the native 'disconnect' emit set process.channel to null (#L924-L929). process.disconnect() skips it while the close waits for a sent handle's ack, as node does.
  • node:cluster carried the same two assignments in its 'disconnect' listeners. node's does not, so they are removed.
  • Verified: four new tests in test/js/node/child_process/child_process.test.ts, all failing on main. Other suites: Notes.

Background

  • When the socket closes, the native IPC layer calls #onDisconnect in the parent and Process__emitDisconnectEvent in the child.
  • A lazy property calls its constructor on first read, then becomes a data property. putDirect before that gives the same own property.

Downsides

  • Code that calls channel.ref() or channel.unref() after the disconnect now throws a TypeError, as on node.
  • While a close waits for a handle's ack, node keeps channel. bun's parent clears it right after subprocess.disconnect(). On Windows the child can too (ipc: postpone disconnect() while a handle send is still queued #43081, Notes).
  • Each disconnect adds one property write in the parent, at most two in the child. send() and startup add nothing.
Notes

Repro

// bun 774.cjs ; node 774.cjs
const cp = require("child_process");
if (process.argv[2] === "child-exit") { process.send({ ready: 1 }); setTimeout(() => process.exit(0), 20); return; }
if (process.argv[2] === "child-disc") {
  process.on("disconnect", () => setTimeout(() => {
    process.stdout.write(`childChannelAfterDisconnect=${process.channel === null || process.channel === undefined ? "null" : typeof process.channel} connected=${process.connected}\n`);
    process.exit(0);
  }, 50));
  process.send({ ready: 1 });
  return;
}
const a = cp.fork(__filename, ["child-exit"], { stdio: ["ignore", "ignore", "inherit", "ipc"] });
const b = cp.fork(__filename, ["child-disc"], { stdio: ["ignore", "pipe", "inherit", "ipc"] });
let bLine = "";
b.stdout.on("data", (d) => (bLine += d));
b.on("message", () => setTimeout(() => b.disconnect(), 20));
let done = 0;
const fin = () => {
  if (++done < 2) return;
  setTimeout(() => {
    const parentNull = a.channel === null || a.channel === undefined;
    console.log(`case1 parent subprocess.channel after child exit: ${parentNull ? "null" : typeof a.channel} (connected=${a.connected})`);
    console.log(`case2 ${bLine.trim() || "child produced no report"}`);
    process.exit(parentNull && /childChannelAfterDisconnect=null/.test(bLine) ? 0 : 1);
  }, 150);
};
a.on("exit", fin);
b.on("exit", fin);
case1 (parent) case2 (child) exit
node v26.3.0 null childChannelAfterDisconnect=null 0
bun 1.4.3-canary (c6b7fcb) object childChannelAfterDisconnect=object 1
this branch null childChannelAfterDisconnect=null 0

The four tests cover the child that exits, the parent that disconnects, the child that disconnects, and the child that disconnects while a sent handle waits for its ack. Each reads channel before the close, at 'disconnect', and after. The same scenarios print the same values under node v26.3.0. The test for the parent that disconnects waits for 'exit', because node never emits 'close' after subprocess.disconnect(). The ack test is skipped on Windows: the handle write is asynchronous there, so the handle is not yet waiting for its ack when disconnect() runs.

Windows and #43081. In that state SendQueue::disconnect does not postpone the close, on main and in this PR, so on Windows process.channel is null right after the call. #43081 makes disconnect() wait while any queued item carries a handle, which includes a write in flight. Both PRs edit SendQueue::disconnect. The one that lands second keeps that condition and the bool return of this PR. After that the Windows skip should not be needed. I cannot run Windows here, so CI must confirm it.

Property shape. After the change, Object.getOwnPropertyDescriptor(process, "channel") is { value: null, writable: true, enumerable: true, configurable: true }, and Object.keys(process) lists channel once. node prints the same. This holds when process.channel was read before the disconnect and when it was not.

The ack window. node keeps channel until the close happens. When disconnect() waits for a sent handle to be acknowledged, node still shows the object, connected is already false, and 'message' listeners can still run. A child that sends a server handle and calls process.disconnect() in the same tick prints {"afterDisconnectCall":"object","connectedAfterCall":false,"atDisconnect":null} on node. The child side now does the same: SendQueue::disconnect returns false when it postpones the close, Bun__closeChildIPC passes that on, and process.disconnect() clears the property only when the close was scheduled.

One difference that stays. In that same window the parent still sets subprocess.channel to null at once. ChildProcess#disconnect did that before this PR. To make it exact, JavaScript must learn that the close was postponed, and the only carrier today is the return value of the public Subprocess.disconnect().

The cluster lines came in with #18293. node's lib/internal/cluster/primary.js and child.js at v26.3.0 contain no channel = null.

Suites run on the debug build: child_process.test.ts, cluster.test.ts, child_process_ipc.test.js, child_process_send_cb.test.js, spawn.ipc.test.ts, and 91 files from test/js/node/test/{parallel,sequential} (test-child-process-* and test-cluster-*). Two tests in child_process.test.ts fail in my container with and without this change (should allow us to spawn in the default shell, extra stdio pipes are not double-closed on GC).


no test proof · iteration 7 · platform-specific test(s) that do not run on this machine, deferring to CI, which covers all platforms: test/js/node/child_process/child_process.test.ts

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: oven-sh/bun/.coderabbit.yaml
  • Review profile: ASSERTIVE
  • Plan: Essentials
  • Run ID: 761014e5-0aa6-441d-8556-433a828a7968
📥 Commits

Reviewing files that changed from the base of the PR and between efde780 and f6d6606.

📒 Files selected for processing (1)
  • test/js/node/child_process/child_process.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

Walkthrough

Disconnect handling now clears process.channel at the completed disconnect point. IPC closure reports whether closure is complete, so handle acknowledgment can delay channel clearing. Fork tests cover these states.

Changes

IPC disconnect state

Layer / File(s) Summary
Disconnect event paths
src/js/node/child_process.ts, src/js/internal/cluster/*, src/jsc/bindings/BunProcess.cpp
Child process handling clears the channel before the disconnect event. Cluster handlers no longer clear the channel during their disconnect handling.
Deferred IPC closure
src/runtime/ipc.rs, src/runtime/hw_exports.rs, src/jsc/bindings/BunProcess.cpp
IPC disconnection returns whether closure completed. Native process handling clears the channel only when closure completes.
Disconnect state validation
test/js/node/child_process/child_process.test.ts
Fork tests cover child exit, parent disconnect, child disconnect, and sent-handle acknowledgment delay.

Suggested reviewers: jarred-sumner

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to f6d66

The change aligns parent and child channel state with disconnect behavior, including delayed closure while a sent handle awaits acknowledgment. No concrete merge-blocking risk remains.

Pre-merge checks: Passed 4
Check name Status Explanation
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Title check Passed The title clearly and concisely describes the primary change: setting channel to null after IPC disconnection.
Description check Passed The description explains the problem, implementation, verification steps, test coverage, known failures, platform limitations, and behavioral differences. It does not use the exact template headings, …
Full details: Description check

Explanation

The description explains the problem, implementation, verification steps, test coverage, known failures, platform limitations, and behavioral differences. It does not use the exact template headings, but it provides the required information in equivalent sections.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@robobun

robobun commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:23 AM PT - Oct 10th, 2026

❌ @robobun, your commit f6d6606 has 2 failures in Build #124285 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 43001

That installs a local version of the PR into your bun-43001 executable, so you can run:

bun-43001 --bun

@robobun

robobun commented Sep 17, 2026

Copy link
Copy Markdown
Collaborator Author

Status

  • Reproduced on bun 1.4.3-canary (c6b7fcb) with the script in the PR notes: case1 object, case2 childChannelAfterDisconnect=object, exit 1. node v26.3.0 prints null for both and exits 0.
  • With this branch the same script prints null for both and exits 0.
  • The three new tests fail on main and pass on this branch.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the putDirect against the lazy channel entry in the process static table (PropertyCallback, default attributes) — an own data property shadows the static lookup whether or not the lazy getter has already been reified, and attributes 0 match what reification would produce. I also checked the removed cluster channel = null lines: clearProcessChannel runs before the native 'disconnect' emit and #onDisconnect nulls before the nextTick, so the cluster listeners observe the same state as before.

Extended reasoning...

Two confirmed findings are already posted inline (the un-wired child exit in the new parent-disconnect test, and the window between process.disconnect() and the actual close while a sent handle awaits ack, where node still exposes the Control object). This note records what else was examined and ruled out: the C++ putDirect on the static-table lazy property channel (line 5011 of src/jsc/bindings/BunProcess.cpp) is safe with respect to property shape, and dropping the cluster-side channel = null assignments does not change the ordering cluster listeners observe, since both the C++ Process__emitDisconnectEvent path and the JS #onDisconnect path null the field before the event is dispatched. No exception scope is needed for putDirect on a plain data property with a non-throwing value. A human should still weigh the inline findings, particularly the ack-window divergence from node.

One verified lower-impact observation (a convention, logging or cleanup point) was not posted.

Comment thread src/jsc/bindings/BunProcess.cpp Resolved

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

LGTM — the follow-up commit addresses both earlier threads (the ack-wait window now keeps process.channel until the socket actually closes, and the parent-disconnect test rejects on early child exit), and the change is small and self-contained.

What was reviewed:

  • Bun__closeChildIPC void→bool across hw_exports.rs / BunProcess.cpp: matches the existing bool-returning HOST_EXPORT(..., c) pattern (Bun__isMainThreadVM, Bun__GlobalObject__connectedIPC); no other callers.
  • putDirect(..., jsNull(), 0) attributes match the lazy channel PropertyCallback entry's default, so the descriptor is the same whether or not process.channel was read first.
  • Postponed close (close_after_flush) still reaches close_socket_next_tick → handle_ipc_close → Process__emitDisconnectEvent, which now clears channel before emitting, so the child converges to null on that path too.
  • Cluster channel = null removals are covered by the generic paths (#onDisconnect / #disconnect in the parent, Process__emitDisconnectEvent in the child), so no observable change for cluster workers.
Extended reasoning...

Overview

The PR makes subprocess.channel (parent ChildProcess) and process.channel (forked child) become null once the IPC channel disconnects, matching Node v26.3.0. It touches src/js/node/child_process.ts (one line in #onDisconnect), two one-line removals in the cluster modules, a void→bool return on SendQueue::disconnect / close_child_ipc / Bun__closeChildIPC, a small clearProcessChannel helper in BunProcess.cpp called from Bun__Process__disconnect (only when the close was not postponed) and from Process__emitDisconnectEvent, plus four new concurrent tests. Since my prior review, commit 290435e changed Bun__Process__disconnect to gate the null-out on the return value and rewrote the parent-disconnect test to race readiness against exit, addressing both inline comments I had left.

Security risks

None identified. No untrusted input is parsed; the change only mutates a property on the process object and returns a bool across an existing FFI boundary. putDirect bypasses user-defined setters, which is the correct (tamper-resistant) choice for a builtin mutating its own property.

Level of scrutiny

Moderate. The FFI signature change is the riskiest part, but the bool-returning HOST_EXPORT(..., c) shape is already used elsewhere in the same file and in ipc_host.rs, and there is exactly one C++ caller. I traced the postponed-close path (close_after_flush set → continue_send Next::Nothing → close_socket_next_tick → handle_ipc_close → Process__emitDisconnectEvent) to confirm the child still converges to channel === null after the ack arrives, and confirmed the property attributes of the putDirect match the lazy-property default so the descriptor shape is stable regardless of read order. The cluster removals are safe because both the parent (#onDisconnect / #disconnect) and child (Process__emitDisconnectEvent) generic paths now clear channel before the disconnect event fires.

Other factors

The bug hunt ran to a dry streak with no findings, and no candidate issues were ruled out beyond what I checked directly. No CODEOWNERS entry covers the changed files. The tests cover the variant matrix the review guidance asks for (child exit, parent-initiated disconnect, child-initiated disconnect, and the ack-wait window, with the Windows skip justified by the async handle write). Test cleanup is in finally blocks and every awaited readiness now rejects on early exit. Given the small diff, the established patterns, and that the prior feedback was addressed rather than argued, I have high confidence this does not need a further human look.

`subprocess.channel` stayed an object after the child exited or disconnected, and
`process.channel` stayed an object in the child after `process.disconnect()` or after
the parent disconnected. node sets both to null as soon as the channel is disconnected,
which is the documented way to test whether IPC is still usable. `connected` was already
right on both sides.

- `ChildProcess#onDisconnect` clears `channel`, as `#disconnect` already did.
- `process.disconnect()` and the native 'disconnect' emit clear `process.channel`.
- node:cluster cleared both itself on 'disconnect'. node's cluster does not, and the
  two assignments are now redundant, so they are removed.
…ndle's ack

node keeps `process.channel` until the channel is really disconnected. When
`process.disconnect()` has to wait for a sent handle to be acknowledged, `connected` is
already false and `channel` is still the object, and 'message' listeners can still run
and use it. `Bun__closeChildIPC` now reports whether the close was postponed, and
`process.disconnect()` clears `process.channel` only when it was not. The native
'disconnect' emit clears it when the channel closes.

Also make the readiness wait in the parent-disconnect test reject when the child exits
before it sends "ready".
@robobun
robobun force-pushed the robobun/98183dca/ipc-null-channel-after-close branch from 290435e to efde780 Compare October 10, 2026 01:32

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

The two points from the earlier review (readiness rejecting on early child exit, and nulling process.channel only when the close is actually scheduled) are addressed by the new commits. Beyond the inline nit, I also checked: the Bun__closeChildIPC C++ extern matches the Rust signature (the host-export generator derives the ABI return type from the Rust -> bool); the only other SendQueue::disconnect caller (Subprocess.disconnect in src/runtime/api/bun/subprocess.rs) drops the new bool, which matches the parent-side divergence the description states as intentional; clearProcessChannel runs before the disconnect emit in Process__emitDisconnectEvent and only uses non-throwing putDirect; and after the cluster removals no remaining site in src/ writes channel other than ChildProcess and the two native paths.

Extended reasoning...

The change spans the TS ChildProcess disconnect path, the native process object in BunProcess.cpp, and an FFI return-type change through hw_exports.rs/ipc.rs, plus four new fork() tests; it touches no auth, crypto, or input-parsing surface. The prior-review items are resolved in code, the remaining finding is a test-strength nit, and the cross-language lifecycle change is small but still worth a human glance given it alters observable process-object property shape.

One part of this review's analysis that stopped early was run once more. It finished.

`typeof child.channel` is "object" for null as well, so the read taken before the
disconnect could not fail if `channel` was already null. Use the null-aware form that
the child-side fixtures use.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread src/runtime/ipc.rs Resolved
@robobun

robobun commented Nov 17, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as stale: this PR conflicts with main, and its last commit is from 2026-10-10.

The branch stays, so the work is not lost. To pick it up again, rebase the branch on main and reopen this PR.

@robobun robobun closed this Nov 17, 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.

2 participants