Skip to content

spawn: don't panic on Blob/ReadableStream stdio at index >= 3 - #32363

Merged
Jarred-Sumner merged 5 commits into
mainfrom
farm/1c917f9a/fix-spawn-stdio-blob-extra-fd
Jun 16, 2026
Merged

Jarred-Sumner merged 5 commits into
mainfrom
farm/1c917f9a/fix-spawn-stdio-blob-extra-fd

Conversation

@robobun

@robobun robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator

Repro

// /tmp/x.txt contains "hello"
const p = Bun.spawn(["sh", "-c", "cat <&3"], {
  stdio: ["ignore", "pipe", "inherit", Bun.file("/tmp/x.txt")],
});
console.log(await p.stdout.text()); // expected: "hello"
panic: called `Option::unwrap()` on a `None` value

Same panic for new Blob([...]), new Request(...), new Response(...) at any stdio index >= 3, and panic: internal error: entered unreachable code for a user-constructed ReadableStream (or a Request/Response wrapping one) at the same positions.

Cause

Four sites in stdio.rs assumed i < 3:

  • Stdio::extract_blob (line 549) and the Blob arm of Stdio::as_spawn_option (line 230) compute FdStdio::from_int(i).unwrap().fd(); from_int returns None for i > 2.
  • The Locked arm of Stdio::extract_body_value (line 364) and the ReadableStream branch of Stdio::extract (line 494) match i against 0 | 1 | 2 with _ => unreachable!().

All four are reachable from the extra-stdio loop in js_bun_spawn_bindings.rs with i >= 3.

The Zig reference had the equivalent .? / unreachable at the same spots; in a ReleaseFast build those are UB rather than panics, and on the commonly-taken paths (file-path Blob, in-memory Blob) the undefined value is dead, so execution continued. The Rust port turned the latent UB into hard panics.

Fix

  • Bun.file(path) / Bun.file(fd) at i >= 3: keep the standard-fd lookup as an Option<Fd> and compare with Some(store_fd) == fd. For i >= 3 the comparison is always false and control falls through to Stdio::Path / Stdio::Fd, which the spawn machinery already handles (opens the file / dups the fd into the child). This restores the 1.3.x behavior.
  • In-memory Blob / Response / Request / ReadableStream at i >= 3: throw {Blob,ReadableStream} cannot be used for stdio[N] yet, matching the existing stdout/stderr rejections. The parent-side writer that pumps bytes into the child's pipe (Writable::Buffer / memfd) is only wired up for stdin, and for extra slots the Stdio value is a loop-local dropped right after as_spawn_option returns the payload-less Buffer, so letting it through would silently hand the child an empty socketpair end. An empty Blob still becomes Ignore.

Verification

New tests in test/js/bun/spawn/spawn.test.ts under stdio[N>=3] blob-like inputs:

  • Bun.file(path) / Bun.file(fd) at index 3: child reads the file contents via fd 3
  • empty Blob at index 3: treated as ignore, spawn succeeds
  • Blob / Response / Request / ReadableStream / Response(ReadableStream) / Request(ReadableStream) at index 3: throws a clear error instead of panicking
# without fix: panics the test runner
USE_SYSTEM_BUN=1 bun test spawn.test.ts -t "stdio\[N>=3\] blob-like"
# panic: called `Option::unwrap()` on a `None` value

# with fix
bun bd test spawn.test.ts -t "stdio\[N>=3\] blob-like"
# 9 pass, 0 fail

Existing Blob works as stdin / Bun.file() works as stdin / spawn-stdin-readable-stream.test.ts / spawn-empty-arrayBufferOrBlob.test.ts still pass.

Stdio::extract_blob and the Blob arm of Stdio::as_spawn_option computed
FdStdio::from_int(i).unwrap().fd(), which panics for any stdio slot
beyond stdin/stdout/stderr. The fd is only used to short-circuit to
Inherit when the Blob wraps the same standard fd as the slot; for extra
slots there is no standard fd to compare against, so keep it as an
Option and let the comparison fail naturally.
@coderabbitai

coderabbitai Bot commented Jun 15, 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: 522d739b-3125-48db-926f-08c1b1f6237b

📥 Commits

Reviewing files that changed from the base of the PR and between df55ab7 and 6621fa5.

📒 Files selected for processing (2)
  • src/runtime/api/bun/spawn/stdio.rs
  • test/js/bun/spawn/spawn.test.ts

Walkthrough

Blob fd derivation in as_spawn_option and extract_blob switches from unwrap() to fallible Option-based comparison. extract_blob adds an early rejection for any stdio index other than stdin. Two unreachable!() arms for ReadableStream in extract_body_value and extract are replaced with explicit JS invalid-arguments errors. A new test suite covers stdio[3] blob-like input behavior.

Changes

Spawn stdio blob-like handling

Layer / File(s) Summary
Blob fd matching and stdio index restrictions
src/runtime/api/bun/spawn/stdio.rs
as_spawn_option and extract_blob replace unwrap()-based fd conversion with fallible mapping and Some(store_fd) == fd comparison. extract_blob adds an early guard that throws a JS invalid-arguments error for any stdio index other than 0 (stdin).
ReadableStream invalid-index errors and stdio[3] tests
src/runtime/api/bun/spawn/stdio.rs, test/js/bun/spawn/spawn.test.ts
extract_body_value and extract replace unreachable!() default arms with JS invalid-arguments errors for ReadableStream at unsupported stdio indices. New test suite asserts Bun.file path/fd inputs are readable at stdio[3], empty Blob is treated as ignore, and unsupported blob-like types (Blob, Response, Request, ReadableStream) throw rather than panic.

Suggested reviewers

  • Jarred-Sumner
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately summarizes the main change: preventing panics when Blob/ReadableStream objects are used as stdio at indices >= 3.
Description check ✅ Passed The PR description provides a detailed explanation of the issue, root cause, fix strategy, and verification steps, covering all key aspects required by the template.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@robobun

robobun commented Jun 15, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 6:05 PM PT - Jun 15th, 2026

❌ @robobun, your commit c49c59e has some failures in Build #62705 (All Failures)


🧪   To try this PR locally:

bunx bun-pr 32363

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

bun-32363 --bun

Comment thread src/runtime/api/bun/spawn/stdio.rs Resolved
Comment thread src/runtime/api/bun/spawn/stdio.rs Resolved
Two more sibling unreachable!() sites in Stdio::extract and
Stdio::extract_body_value assumed i < 3. A user-constructed
ReadableStream (or a Request/Response wrapping one) at an extra stdio
slot reached them and crashed the process. The parent-side writer that
pumps a ReadableStream into the child's pipe is only wired up for
stdin, so throw the same kind of error the stdout/stderr arms already
produce.
@robobun robobun changed the title spawn: don't panic on Blob-like stdio at index >= 3 spawn: don't panic on Blob/ReadableStream stdio at index >= 3 Jun 15, 2026
Comment thread src/runtime/api/bun/spawn/stdio.rs Resolved
robobun and others added 2 commits June 15, 2026 21:50
…ly dropping bytes

extract_blob previously set Stdio::Blob(blob) for an in-memory Blob at
any index, but for extra stdio slots the Stdio value is a loop-local
that gets dropped right after as_spawn_option returns the payload-less
SpawnOptionsStdio::Buffer. The child would get an empty socketpair end
at that fd with nothing writing to it. Throw the same kind of error the
ReadableStream arms produce. An empty Blob still becomes Ignore.

@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 — all prior feedback addressed; the remaining changes are strictly panic→error conversions with solid test coverage.

Extended reasoning...

Overview

This PR replaces four i < 3 assumptions in src/runtime/api/bun/spawn/stdio.rs that caused hard panics when Blob/ReadableStream/Request/Response values were passed at stdio[3+]. Two .unwrap() calls become Option-based comparisons (so Bun.file(path|fd) now works at extra slots), two unreachable!() arms become throw_invalid_arguments errors, and a new i != 0 guard in extract_blob rejects in-memory Blobs at extra slots rather than silently dropping their bytes. Nine new tests in spawn.test.ts cover the working paths (Bun.file by path/fd, empty Blob → ignore) and the throwing paths (Blob/Response/Request/ReadableStream and stream-wrapped variants).

Security risks

None. The changes only narrow behavior — replacing process-aborting panics with catchable JS TypeErrors, and replacing a silent-data-drop with an explicit throw. No new file/fd handling logic is introduced beyond what the existing Stdio::Path / Stdio::Fd arms already did for i < 3; the Some(store_fd) == fd comparison is semantically identical to the old code for i ∈ {0,1,2} and conservatively false for i ≥ 3.

Level of scrutiny

Low–medium. This is a targeted crash fix in user-input validation, not a design change. Every modification is either (a) equivalent to prior behavior for the previously-valid index range, or (b) a panic→throw conversion for the previously-crashing range. The one behavioral choice — throw vs. silently-accept for in-memory Blob at i ≥ 3 — was discussed in review and resolved to the conservative option, consistent with the ReadableStream arms.

Other factors

I raised three issues on earlier revisions (sibling unreachable!() panics, silent Blob data loss, and a pre-existing integer-0-at-extra-fd quirk). The first two are fixed in the current diff with matching tests; the third is reasonably deferred (pre-existing, not a panic, and the author explained why the one-line fix is insufficient due to posix_spawn action ordering). The current bug-hunt run found nothing new. The CI build failures on 251b007 look like unrelated cross-platform build-infra flakes (identical build-rust failures across 8 targets, linker warning on macOS), not anything tied to these ~30 lines of Rust.

@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 — all prior feedback addressed; the remaining inline note is a pre-existing dead-validation block adjacent to the edit and is optional.

Extended reasoning...

Overview

This PR fixes four i >= 3 panics in src/runtime/api/bun/spawn/stdio.rs when Blob/ReadableStream-like values are passed at extra stdio slots, and adds 9 tests in test/js/bun/spawn/spawn.test.ts. The changes are: (1) two FdStdio::from_int(i).unwrap() → .map(FdStdio::fd) with Some(store_fd) == fd comparison; (2) two unreachable!() arms → throw_invalid_arguments("ReadableStream cannot be used for stdio[i] yet"); (3) an if i != 0 guard in extract_blob so non-empty in-memory Blobs at i >= 3 throw instead of silently dropping bytes.

I reviewed this PR twice previously. The first round flagged the two remaining unreachable!() siblings (fixed in bb167b0) and a pre-existing integer-0-at-extra-fd issue (deferred to follow-up with a clear rationale about posix_spawn action ordering). The second round flagged silent data loss for in-memory Blobs at i >= 3 (fixed in 251b007). All three inline threads are now resolved.

Security risks

None introduced. Every change either preserves existing i < 3 behavior exactly (the Option<Fd> comparison is equivalent to the old Fd == Fd for i ∈ {0,1,2}) or replaces a process-aborting panic with a catchable JS error for i >= 3. No new fd-inheritance paths are opened — Bun.file(path)/Bun.file(fd) at extra slots fall through to the existing Stdio::Path/Stdio::Fd handling that the spawn machinery already supports, restoring 1.3.x behavior per the PR description.

Level of scrutiny

Bun.spawn stdio is a critical user-facing path, but the change shape here is purely defensive: panic → Option, panic → JS error, silent-drop → JS error. There are no new control-flow branches for the standard i < 3 slots, and the i >= 3 slots were unreachable-via-panic before. The diff is small (~30 lines of Rust), mechanically verifiable, and covered by tests that exercise both the working paths (Bun.file(path)/Bun.file(fd) readable at fd 3) and the error paths (Blob/Response/Request/ReadableStream throw with the expected message).

Other factors

The one new inline comment from this run flags a pre-existing dead-validation block in extract_blob's else branch (FdStdio::from_int(i) should be store_fd.stdio_tag()) — it sits adjacent to the line this PR edits but is not introduced or affected by it, and is explicitly marked optional. The robobun CI comment noted failures on 6621fa5 followed by a ci: retrigger commit; CI gating is handled by merge checks. No CODEOWNERS cover this path.

Comment thread src/runtime/api/bun/spawn/stdio.rs Resolved
@robobun

robobun commented Jun 16, 2026

Copy link
Copy Markdown
Collaborator Author

Diff is green on every lane that actually ran tests. The remaining red is infrastructure:

  • darwin-26-aarch64-test-bun (build 62705): guest VM boots without /usr/local/bin/bun and the runner dies with exit 137 before any test starts. A retry of the same job is queued.
  • build 62688 had two darwin test jobs in state Expired (never picked up by an agent).

The only test annotations on either build are warning: flaky (passed on retry), none in code this PR touches. The one spawn.test.ts flake on Windows was in the spawn unref and kill should not hang permutation suite, not the new stdio[N>=3] tests.

Ready for review; needs a maintainer to merge past the darwin infra.

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