Repository navigation
Conversation
WalkthroughChangesEmpty stdin Empty stdin pipe handling
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts`:
- Around line 40-51: Run the synchronous spawn tests sequentially by replacing
test.concurrent with test in both the Bun.spawnSync case at
test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts lines 40-51 and the
child_process.spawnSync case at lines 69-74; make no other changes.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: b89cbaac-f9f4-4854-a6a6-d79d69cafce8
📒 Files selected for processing (3)
src/runtime/api/bun/spawn/stdio.rssrc/spawn/static_pipe_writer.rstest/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts
on_write on Windows does not release start()'s +1 (the cfg(not(windows)) release_start_ref block), and on_close_io replaces stdin with Ignore so take_pending_start_writer never matches afterwards. Inline the release (started=false; writer.close; deref) so the empty path is balanced. Also drop test.concurrent on the spawnSync cases (sync body).
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime/api/bun/spawn/stdio.rs (1)
555-560: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winUse platform-neutral wording for ArrayBuffer stdin.
Line 558 says the child “gets a pipe,” but
Stdio::ArrayBufferis explicitly eligible foruse_memfd()on Linux, so this path can produce a memfd rather than a pipe. Describe this as pipe-like/data-backed stdin or document the platform-specific behavior.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/api/bun/spawn/stdio.rs` around lines 555 - 560, Update the comment near Stdio::ArrayBuffer to avoid claiming stdin always uses a pipe; describe it as pipe-like or data-backed stdin, or explicitly note that Linux may use a memfd via use_memfd(), while preserving the existing behavior and explanation for other slots.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/runtime/api/bun/spawn/stdio.rs`:
- Around line 555-560: Update the comment near Stdio::ArrayBuffer to avoid
claiming stdin always uses a pipe; describe it as pipe-like or data-backed
stdin, or explicitly note that Linux may use a memfd via use_memfd(), while
preserving the existing behavior and explanation for other slots.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: a8bd7e1e-0f94-4429-b645-693677242c6c
📒 Files selected for processing (4)
src/runtime/api/bun/spawn/stdio.rssrc/runtime/shell/states/Cmd.rssrc/spawn/static_pipe_writer.rstest/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.ts
|
Updated 11:09 AM PT - Jul 23rd, 2026
✅ @robobun, your commit 97ee042cfd1822c4b2ef15c82ec96af5bb0e94cc passed in 🧪 To try this PR locally: bunx bun-pr 35286That installs a local version of the PR into your bun-35286 --bun |
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/runtime/api/bun/spawn/stdio.rs (1)
645-650: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick winCorrect the empty-Blob scope in the comment.
The preceding guard rejects Blob values at indices 1 and 2, so this branch cannot treat empty Blobs as
Ignorefor all fds 0–2. Limit the wording to stdin and extra slots.Proposed wording
- // (/dev/null at fds 0-2, left closed at extra slots). This diverges + // (stdin maps to /dev/null; extra slots remain closed). This diverges🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@src/runtime/api/bun/spawn/stdio.rs` around lines 645 - 650, Update the comment above the empty-Blob handling in extract_blob to state that empty Blobs are treated as “ignore” for stdin and extra slots only, excluding fds 1 and 2 because the preceding guard rejects them.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Outside diff comments:
In `@src/runtime/api/bun/spawn/stdio.rs`:
- Around line 645-650: Update the comment above the empty-Blob handling in
extract_blob to state that empty Blobs are treated as “ignore” for stdin and
extra slots only, excluding fds 1 and 2 because the preceding guard rejects
them.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 3856b1af-eade-4f06-aa3f-e6b7c3d0e02b
📒 Files selected for processing (1)
src/runtime/api/bun/spawn/stdio.rs
There was a problem hiding this comment.
The Windows refcount fix in 0698638 looks correct — I re-traced BaseWindowsPipeWriter::close() and the async on_pipe_close callback only frees the standalone Box<uv::Pipe>, so the trailing deref freeing StaticPipeWriter inside start() doesn't race it. All my prior findings are addressed. Deferring to a human for a final look since this adds a new "start() may synchronously free self" path on both platforms in intrusive-refcount code.
What was reviewed:
- Windows empty branch:
started=false→writer.close()(source taken, uv_close scheduled on the detached Pipe box,on_close_ioswaps stdin→Ignore and derefs 2→1) → trailingderef1→0;take_pending_start_writercan't re-release since stdin isIgnore. - POSIX empty branch:
on_write(0, Drained)hitsrelease_start_ref, same 2→1→0 sequence; poll is unregistered bywriter.close()beforeselfis freed. - Caller at
js_bun_spawn_bindings.rs:1754doesn't touchbufferafterstart()returns Ok; the laterwatch()at :1927 no longer matches (Writable::Ignore). - Shell (
Cmd.rs) can't reach the new empty-writer path — its ArrayBuffer stdin arm still usesStdio::Ignoreandextract_blobis unchanged.
Extended reasoning...
Overview
Changes Stdio::extract so an empty ArrayBuffer at stdin falls through to Stdio::ArrayBuffer (pipe/memfd) instead of Stdio::Ignore (null device), matching Node's spawnSync({input: Buffer.alloc(0)}). To make that not deadlock, StaticPipeWriter::start() gains an if empty branch on both Windows and POSIX that closes the write end immediately so the child reads EOF. Comment-only updates in Cmd.rs and extract_blob document the intentional divergence for Blob/shell paths. New tests cover Bun.spawn/spawnSync/child_process.spawnSync × three empty-buffer types.
Security risks
None. No parsing of untrusted input, no auth/crypto/permissions.
Level of scrutiny
High — this is native intrusive-refcount code with platform-gated branches, the exact class REVIEW.md flags as most-blocked. My first pass found a Windows refcount leak; the fix (0698638) mirrors the POSIX release_start_ref sequence and I've re-verified the balance by reading through BaseWindowsPipeWriter::close() in PipeWriter.rs: the async on_pipe_close callback frees only the detached Box<uv::Pipe> (via heap::take(handle)), never the StaticPipeWriter, so freeing the writer at refcount 0 inside start() is safe. Drop for StaticPipeWriter runs writer.end() with source = None (no-op).
Other factors
- Tests fail on main / pass with fix; ASan clean per PR evidence. robobun reports Windows x64 100-iteration RSS-flat verification.
- All three prior review threads (Windows leak, stale Cmd.rs comment,
test.concurrenton sync tests) are resolved in the current head. - The new contract that
start()can synchronously freeselfand swapsubprocess.stdintoIgnoreis a lifetime change worth a human sanity check, even though I couldn't find a path where the caller touches the writer afterward. - Linux takes the memfd path (
can_use_memfdmatchesStdio::ArrayBuffer), so the newStaticPipeWriterempty branch is exercised only on macOS (POSIX arm) and Windows.
|
CI status: the new test (
None of the flaky tests touch the |
…n write completes (#35297) On Windows, `Bun.spawn`/`Bun.spawnSync` with a non-empty `ArrayBuffer`/`Blob` `stdin` leaked one `StaticPipeWriter` allocation per spawn. ## Cause `StaticPipeWriter::start()` takes a `+1` and sets `started = true`. #30875 added a `release_start_ref` block to `on_write()` that clears `started` and derefs once the buffer drains, but gated it behind `#[cfg(not(windows))]`: https://github.com/oven-sh/bun/blob/892b1dabc6/src/spawn/static_pipe_writer.rs#L228-L241 On Windows, when the `uv_write` completes before the child exits (the common ordering for a small buffer): ``` on_write_complete(status=0) -> Parent::on_write(Pending) (release_start_ref gated out) -> writer.close() -> BaseWindowsPipeWriter::close -> on_close_source -> StaticPipeWriter::on_close -> Subprocess::on_close_io(Stdin) stdin <- Writable::Ignore; buffer.deref() (create()'s +1) scopeguard deref (write()'s +1) ``` Net: `started` is still `true` but `stdin` is `Writable::Ignore`, so the other release site, `take_pending_start_writer` (called from `on_process_exit` / `close_io`), matches nothing and start()'s `+1` is stranded. The error arm of `on_write_complete` (e.g. `ERROR_BROKEN_PIPE` when the child closes stdin without reading) reaches `on_close` via `close()` without ever calling `Parent::on_write`, so start()'s `+1` is stranded there the same way. `ShellSubprocess` has the same leak for `cmd < ${buf}` stdin since its `on_process_exit`/`close_io` never look at `started` at all and depend entirely on `on_write`'s release. ## Fix - `StaticPipeWriter::on_write`: drop the `cfg(not(windows))` gates so `release_start_ref` runs on every platform. `WindowsBufferedWriter` never passes `EndOfFile`, so the existing `status != EndOfFile` guard is a no-op there and is left for the POSIX path (`PosixBufferedWriter::_on_write` still touches `self` after the callback on `EndOfFile`). - `StaticPipeWriter::on_close` (Windows only): claim `started` and deref after `on_close_io` for paths that reach `close()` without going through `on_write` (the `on_write_complete` error arm). `write()`'s +1, held by that callback's scopeguard, keeps `self` live past the release. This is gated to Windows because on POSIX `drain_buffered_data` may call `on_error()` -> `close()` -> `on_close` and then `on_write()` on the same object with no extra ref held; #34697 changes that ordering and the gate can go once it lands. - `Subprocess::take_pending_start_writer`: clear `started` when it claims the pointer. The three release sites are then mutually exclusive via `started`, covering the ordering where `on_process_exit` closes the pipe while a `uv_write` whose I/O already completed is still queued (libuv delivers that callback with its real status after `uv_close`, not `ECANCELED`). - `WindowsBufferedWriter::on_write_complete`: `saturating_sub` for `has_pending_data` so the late-success-after-close ordering does not underflow in debug builds. `SecurityScanSubprocess` already derefs and writes `started = false` immediately after `start()`, so both new release sites see `started = false`; no change in its refcount balance. ## Verification Verified on Windows x64 by instrumenting `Drop` with a live counter and spawning 400 children per mode: unfixed leaves 400 live writers after each of the drain (64 B into `sort`) and reject (256 KB into `cmd /c exit`) workloads; fixed returns to 0 on both, in release and debug builds. Also verified on Windows x64: `spawn.test.ts -t 'stdin|Uint8Array|Blob'` (45/45), `spawnSync.test.ts` (6/6), `file-io.test.ts` (26/26), `child_process.test.ts` (41/41), and on Linux: `bunshell.test.ts` (414/414), `bun-security-scanner-workspaces.test.ts` (3/3). `rust:check-all` is green across all 10 targets. Found while working on #35286, which scopes its change to the empty-buffer path and does not overlap.
|
Closing this PR because it has been inactive for more than 90 days. |
Bun.spawn/Bun.spawnSyncwith an emptystdinbuffer (andchild_process.spawnSyncwithinput: Buffer.alloc(0)) hand the child the null device (/dev/nullon POSIX,NULon Windows) instead of a pipe. A non-empty buffer uses a pipe; Node uses a pipe for both.Repro
Same on POSIX via
fstat(0).isCharacterDevice(). The child's stdin fd type flips on whether the buffer happened to be empty, which trips tools that branch onS_ISFIFO/S_ISSOCK, and in a Windows AppContainer openingNULfails withEPERM.Cause
Stdio::extractshort-circuits an emptyArrayBufferat any slot toStdio::Ignore:This was #9557's "don't throw for empty ArrayBuffer", but Ignore gives a character device; the non-empty path gives a pipe.
Letting the empty buffer fall through to
Stdio::ArrayBufferalone would deadlock on macOS/Windows:StaticPipeWriterwith a zero-byte source registers for write readiness (POSIX) or returns fromwrite()(Windows) and never closes the pipe, so the child'sread(0)blocks forever.Fix
Stdio::extract: only downgrade an emptyArrayBuffertoIgnoreati != 0; at stdin let it becomeStdio::ArrayBufferlike a non-empty one. stdout/stderr/extras are unchanged (no reader is wired forStdio::ArrayBufferat those slots).StaticPipeWriter::start: after a successful start, if the source is empty, drive theon_write(0, Drained)path immediately so the write end closes and the child reads EOF. This is the same tail-call contractPosixPipeWriter::on_pollalready documents ("don't touchselfafter the callback").What the child sees on fd 0 for
stdin: Buffer.alloc(0)after this change matches the non-empty case on each platform: a pipe on macOS/Windows, a memfd on Linux (can_use_memfdstill converts theArrayBufferslot).subprocess.stdinstaysundefinedfor buffer stdin (it isWritable::Bufferregardless of size).Blob stdin (
stdin: new Blob([])) still becomesIgnore; changingextract_blobwould pull in the shell'sCmd::extract_blobcallers. Only the ArrayBuffer path changes, which is whatchild_process.spawnSyncinput:uses.Relation to #34477
#34477 removes the
Stdio::Pipe->Ignoreremap for a barestdin: "pipe"underspawnSync. That is the other half of the same symptom (the handoff that prompted this PR reported both); this PR addresses the empty-buffer path, which #34477 does not touch. The two changes are independent and compose.Verification
New tests in
test/js/bun/spawn/spawn-empty-arrayBufferOrBlob.test.tscoverBun.spawnSync,Bun.spawn, andchild_process.spawnSyncwithArrayBuffer(0)/Uint8Array(0)/Buffer.alloc(0), asserting!isCharacterDevice()and 0 bytes to EOF.Same result on Windows x64.
spawnSync.test.ts, the stdin subset ofspawn.test.ts, and thechild_process.spawnSync*node parallel tests pass on both platforms;rust:check-allis green across the target matrix.[review] gate passed · iteration 1 · 4 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 2 passed · 0 rejected · iteration 1
evidence per changed file