Skip to content

child_process: keep subprocess.stdin null after exit for non-pipe stdio - #33707

Merged
dylan-conway merged 4 commits into
mainfrom
farm/a3448236/child-process-stdin-null-after-exit
Jul 9, 2026
Merged

dylan-conway merged 4 commits into
mainfrom
farm/a3448236/child-process-stdin-null-after-exit

Conversation

@robobun

@robobun robobun commented Jul 7, 2026

Copy link
Copy Markdown
Collaborator

What does this PR do?

Node documents that for any non-pipe stdio[0] configuration ('ignore', 'inherit', an fd, fork()'s default), subprocess.stdin is null. The if (child.stdin) child.stdin.end(data) guard is the documented idiom for distinguishing piped from non-piped children.

In Bun, the value of subprocess.stdin depended on when it was first read: null while the child was alive, but a destroyed Writable if first accessed after the child exited. Cleanup code that runs on 'exit'/'close' and branches on child.stdin would take the wrong path.

Repro

const cp = require("node:child_process");
const a = cp.spawn(process.execPath, ["-e", "0"], { stdio: ["ignore", "pipe", "ignore"] });
a.once("close", () => console.log(a.stdin));
// node: null
// bun (before): Writable { ..., destroyed: true }

Cause

ChildProcess.#handleOnExit marked #stdioOptions[0] = "destroyed" whenever the lazy #stdin had not yet been materialized, clobbering the real slot-0 kind. The subsequent getter then took the case "destroyed" branch of #getBunSpawnIo(0) and fabricated a dummy destroyed Writable instead of the null the 'ignore'/'inherit'/default branches would have returned.

Fix

Only overwrite #stdioOptions[0] with "destroyed" when the original value was "pipe", since that is the only configuration where stdin is a stream that needs a destroyed placeholder.

How did you verify your code works?

New tests in test/js/node/child_process/child_process.test.ts cover 'ignore', 'inherit', fd 0, and fork()'s default stdio, all first-read after 'close', plus a consistency check (before vs after) and a regression guard that 'pipe' still yields a destroyed writable.

Fail-before with released bun:

(fail) spawn stdio[0]=ignore
(fail) spawn stdio[0]=inherit
(fail) spawn stdio[0]=fd 0
(fail) fork() default stdio

Pass-after with this change: 6 pass, 0 fail.

When stdio[0] is 'ignore', 'inherit', or an fd, subprocess.stdin must be
null for the lifetime of the ChildProcess. #handleOnExit was overwriting
the stored stdio kind with 'destroyed' whenever the lazy #stdin had not
yet been materialized, so the first read of .stdin after 'exit'/'close'
would fabricate a destroyed Writable instead of returning null. Only
overwrite when the original slot was 'pipe'.
@github-actions github-actions Bot added the claude label Jul 7, 2026
@robobun

robobun commented Jul 7, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 10:06 PM PT - Jul 7th, 2026

❌ @robobun, your commit bd81846 has 3 failures in Build #70171 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 33707

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

bun-33707 --bun

@coderabbitai

coderabbitai Bot commented Jul 7, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: f690e372-9503-4e7f-af59-5e2fb1570648

📥 Commits

Reviewing files that changed from the base of the PR and between 4bb11e5 and bd81846.

📒 Files selected for processing (2)
  • src/js/node/child_process.ts
  • test/js/node/child_process/child_process.test.ts
💤 Files with no reviewable changes (1)
  • test/js/node/child_process/child_process.test.ts

Walkthrough

Child process exit handling now only destroys stdio streams that were configured as pipes. Tests were added to verify stdin, stdout, and stderr state after exit for non-pipe spawn modes, fork defaults, and pipe-mode stdin.

Changes

Stdin Exit Handling Fix

Layer / File(s) Summary
Restrict stdio drain fallback to pipe mode
src/js/node/child_process.ts
Exit handling now destroys stdin only when stdioOptions[0] is "pipe", and only destroys stdout/stderr in the error path when those streams were configured as pipes.
Tests for stdin state across stdio modes
test/js/node/child_process/child_process.test.ts
Imports fork and adds exit-state tests for non-pipe spawn stdio, fork defaults, and pipe-mode stdin destruction.

Sequence Diagram(s)

sequenceDiagram
  participant Process
  participant ChildProcess
  participant StdioStreams

  Process->>ChildProcess: exit event
  ChildProcess->>ChildProcess: `#handleOnExit`()
  alt stdioOptions[0] == "pipe"
    ChildProcess->>StdioStreams: destroy stdin
  else non-pipe stdin
    ChildProcess->>ChildProcess: leave stdin unset
  end
  alt err is present
    ChildProcess->>StdioStreams: destroy stdout/stderr only when pipe
  end
Loading

Compact metadata

  • Related issues: None referenced.
  • Related PRs: None referenced.
  • Suggested labels: bug, node.js, tests
  • Suggested reviewers: None specified.

Poem
A pipe was drained, but only there,
Non-pipe streams got gentler care,
Tests now watch the exit-time flow,
Null or destroyed, as configs show.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main behavior change for non-pipe stdin after exit.
Description check ✅ Passed The description matches the required template and includes both the PR purpose and verification details.
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.

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

@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 — targeted one-line fix with good test coverage; the inline nit about the stdout/stderr err-path is optional.

Extended reasoning...

Overview

One-line change to src/js/node/child_process.ts (#handleOnExit): only overwrite #stdioOptions[0] with "destroyed" when it was originally "pipe", so non-pipe stdin configurations (ignore, inherit, fd, fork default) correctly return null from child.stdin after exit instead of a fabricated destroyed Writable. Six new tests in the existing child_process.test.ts cover the variant matrix (ignore/inherit/fd/fork), a before-vs-after consistency check, and a regression guard that 'pipe' still yields a destroyed writable.

Security risks

None. This is a Node.js compat fix to a getter's return value; no auth, crypto, path handling, or untrusted-input parsing is involved.

Level of scrutiny

Low. The change narrows an unconditional assignment to a conditional one, and I traced every possible #stdioOptions[0] value ("pipe", null, "inherit", "ipc", number) through #getBunSpawnIo(0) — all non-pipe values correctly reach null via the default: or "inherit" branches, and "pipe" still gets the destroyed placeholder. The PR description shows fail-before/pass-after verification.

Other factors

The bug-hunter nit about the analogous unconditional overwrite for stdout/stderr on the err path (6 lines below) is valid but pre-existing and only reachable via the rare waitpid Status::Err path — it doesn't block this fix. Tests follow harness conventions (bunEnv, bunExe, once(child, 'close'), it.each) and are placed in the correct existing file.

Comment thread src/js/node/child_process.ts 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 — tiny, well-scoped narrowing of the "destroyed" sentinel to pipe-only slots; the earlier stdout/stderr err-path feedback has been applied.

Extended reasoning...

Overview

Three-line change in src/js/node/child_process.ts (#handleOnExit): the unconditional #stdioOptions[0] = "destroyed" becomes else if (#stdioOptions[0] === "pipe"), and the err-path stdout/stderr overwrite gets the same per-slot guard (added after my previous review). Six new tests added to the existing child_process.test.ts.

Security risks

None. Pure Node-compat behavioral fix in the JS shim layer — no native code, no untrusted-input parsing, no auth/crypto/permissions surface.

Level of scrutiny

Low. The change strictly narrows an existing overwrite: where before every falsy-#stdin exit clobbered slot 0 to "destroyed", now only "pipe" slots are. For non-pipe slots (null/"inherit"/fd number), #getBunSpawnIo(0) already had a default: return null branch — the fix just lets it be reached. There is no way for this to regress the pipe case (either #stdin is already materialized and destroyed via the if arm, or slot 0 is still "pipe" and the sentinel is written exactly as before). The err-path stdout/stderr change is symmetric.

Other factors

  • My previous review comment (apply the same guard to the err-path stdout/stderr overwrite) was addressed in d83f51e and the thread is resolved.
  • Four of the six new tests are verified fail-before/pass-after per the PR description; the inline nit about the other two being non-load-bearing is a test-quality observation, not a correctness concern, and doesn't change the fact that the fix itself has real coverage.
  • The change matches Node's documented contract (subprocess.stdin === null for non-pipe stdio[0]) and is placed in the correct file alongside existing stdio tests.

@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 — both review comments addressed, minimal and correct Node compat fix.

Extended reasoning...

Overview

3-line change to src/js/node/child_process.ts narrowing an unconditional else { #stdioOptions[0] = "destroyed" } in #handleOnExit to else if (#stdioOptions[0] === "pipe"), plus the same per-slot guard applied to slots 1/2 on the err path (my earlier feedback, applied in d83f51e). ~30 lines of new tests in test/js/node/child_process/child_process.test.ts covering ignore/inherit/fd/fork() default stdio configurations.

Security risks

None. This only affects whether subprocess.stdin/stdout/stderr return null vs a destroyed placeholder stream for non-pipe stdio slots — no auth, crypto, permissions, or untrusted-input parsing involved.

Level of scrutiny

Low. The production change is a strict narrowing of existing behavior: the "destroyed" sentinel now only overwrites "pipe" (the one case where a destroyed placeholder is needed), leaving non-pipe slot kinds intact so #getBunSpawnIo falls through to its default: branch and returns null, matching Node's documented contract. No new code paths, no allocation/lifetime changes.

Other factors

Both of my prior inline comments were addressed: the sibling stdout/stderr err-path pattern got the same guard (d83f51e), and the non-load-bearing "is consistent" test was dropped (8782288) with a reasonable justification for keeping the pipe behavioral guard. The four it.each/fork tests are fail-before/pass-after per the PR description. Tests use tmpdirSync rather than the newer tempDir helper, but that matches the existing conventions in this file (already imported and used throughout).

@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 — both earlier comments addressed, and the remaining change is a minimal, well-tested Node-compat fix.

Extended reasoning...

Overview

Three-line change to src/js/node/child_process.ts in #handleOnExit: the unconditional else { #stdioOptions[0] = "destroyed" } becomes else if (#stdioOptions[0] === "pipe"), and the same per-slot guard is applied to the err-path stdout/stderr overwrite. Five new tests in the existing child_process.test.ts cover ignore/inherit/fd-0/fork()-default (all assert stdin === null after close) plus a behavioral guard that pipe still yields a destroyed writable.

Security risks

None. This only narrows when an internal sentinel string is written into a private array; no user input parsing, no fd handling changes, no privilege or network surface.

Level of scrutiny

Low-to-moderate. The change is a strict narrowing of an existing branch — every case that previously took the else and should have (i.e., "pipe") still does, and every other case now falls through to no-op, which restores the documented Node contract (subprocess.stdin === null for non-pipe stdio). Traced each new test config through nodeToBun → #stdioOptions → #handleOnExit → #getBunSpawnIo and confirmed they reach the default:/"inherit" branches that return null. No CODEOWNERS entry for this path.

Other factors

I left two prior review comments on this PR; both were addressed:

  • The identical stdout/stderr clobbering on the err path now has the same per-slot === "pipe" guard (d83f51e).
  • The redundant "is consistent" test that passed both ways was dropped (8782288); the author gave a sound rationale for keeping the pipe behavioral guard as-is.

The four it.each/fork tests are load-bearing (fail-before/pass-after per the PR description), tests live in the correct existing file, and follow local conventions (tmpdirSync, bunEnv, once(child, "close")). Change is small, self-contained, and matches Node semantics.

@robobun

robobun commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator Author

The diff is ready. CI red across the last three runs is unrelated infra flake on lanes this change doesn't touch:

  • 70136: postgres-invalid-message-length.test.ts on Windows 2019 x64 with ERR_POSTGRES_CONNECTION_REFUSED
  • 70158: postgres-binary-array-bounds.test.ts on Windows 2019 x64-baseline with ERR_POSTGRES_CONNECTION_REFUSED
  • 70171: test/regression/issue/26030.test.ts (MySQL) on Alpine 3.23 x64 with Docker container health timeout ("application not healthy after 1m0s")

None of these run child_process code. The new tests in test/js/node/child_process/child_process.test.ts pass on all lanes. Needs a maintainer to merge past the flake.

@dylan-conway
dylan-conway merged commit 02c5c04 into main Jul 9, 2026
73 of 77 checks passed
@dylan-conway
dylan-conway deleted the farm/a3448236/child-process-stdin-null-after-exit branch July 9, 2026 22:26
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