Repository navigation
Conversation
WalkthroughAdds validation and runtime support for redirecting JavaScript ReadableStream values to command stdin, implements cross-platform subprocess stdin wiring using FileSink/assignToStream with captured assignment errors and lifecycle handling, and adds tests for success and failure cases. ChangesReadableStream stdin redirection implementation
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
|
Updated 4:09 PM PT - Jul 2nd, 2026
❌ @robobun, your commit 7d338d6 has 1 failures in
🧪 To try this PR locally: bunx bun-pr 30550That installs a local version of the PR into your bun-30550 --bun |
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/shell/bunshell.test.ts`:
- Around line 424-425: Replace the wall-clock delay Bun.sleep(1) with a
deterministic macrotask barrier by awaiting Bun.sleep(0) instead; locate the
test block that calls Bun.sleep(1) just before controller.enqueue(new
TextEncoder().encode("chunk2")) and change the sleep to Bun.sleep(0) so the
chunking timing uses a macrotask barrier rather than a timed wait.
🪄 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: ad3f17fb-44c9-4321-af30-719444e48c21
📒 Files selected for processing (4)
src/shell/Builtin.zigsrc/shell/states/Cmd.zigsrc/shell/subproc.zigtest/js/bun/shell/bunshell.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/shell/subproc.zig (1)
928-939:⚠️ Potential issue | 🔴 Critical | 🏗️ Heavy liftReturn a shell error instead of panicking on stdin setup failure.
Writable.init()can now fail here for recoverableFileSink.start*()errors, but Line 935 still turns that into a process-wide panic. A broken/closed stdin pipe during setup should unwind like the laterstdin_assign_errorpath, not crash Bun.🤖 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/shell/subproc.zig` around lines 928 - 939, The current call to Subprocess.Writable.init(...) treats any error by panicking on error.UnexpectedCreatingStdin which crashes the process; instead handle recoverable FileSink.start*() failures by returning a shell error and reusing the existing stdin_assign_error flow. Modify the error handler on Subprocess.Writable.init in the spawn code that constructs .stdin (the call using spawn_args.stdio[0], event_loop, subprocess, spawn_result.stdin, &stdin_assign_error) so it does not call std.debug.panic; map the returned error into the same shell-level error path used by stdin_assign_error (or return an appropriate ShellError/result) and propagate it up to the caller rather than panicking, preserving existing behavior for non-recoverable errors.
🤖 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 `@src/shell/subproc.zig`:
- Around line 958-972: The stdin_assign_error branch can leak the
Process/Subprocess and its exit handler on Windows because
subprocess.abortAfterFailedStart() is a no-op there; after calling
subprocess.tryKill(`@intFromEnum`(bun.SignalCode.SIGTERM)) you must explicitly
tear down the subprocess resources and unregister its exit handler before
returning the error. Modify the code around stdin_assign_error to call a
deterministic cleanup routine (e.g.,
subprocess.teardown()/subprocess.close()/subprocess.freeProcess—create one if it
doesn't exist) that stops the exit handler and releases the Process/Subprocess
resources, then continue with abortAfterFailedStart()/return; keep references to
subprocess.tryKill and subprocess.abortAfterFailedStart so the change is local
to this error-handling branch.
---
Outside diff comments:
In `@src/shell/subproc.zig`:
- Around line 928-939: The current call to Subprocess.Writable.init(...) treats
any error by panicking on error.UnexpectedCreatingStdin which crashes the
process; instead handle recoverable FileSink.start*() failures by returning a
shell error and reusing the existing stdin_assign_error flow. Modify the error
handler on Subprocess.Writable.init in the spawn code that constructs .stdin
(the call using spawn_args.stdio[0], event_loop, subprocess, spawn_result.stdin,
&stdin_assign_error) so it does not call std.debug.panic; map the returned error
into the same shell-level error path used by stdin_assign_error (or return an
appropriate ShellError/result) and propagate it up to the caller rather than
panicking, preserving existing behavior for non-recoverable errors.
🪄 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: e752bb64-ca53-4f7b-aa57-6b66bff4bdf9
📒 Files selected for processing (1)
src/shell/subproc.zig
There was a problem hiding this comment.
Additional findings (outside current diff — PR may have been updated during review):
-
🟡
src/shell/subproc.zig:1073-1082— Nit: thiselse if (... cmd.hasFinished())re-check is nested insideif (exit_code) |code|, so whenstatus == .err(nullexit_code) it's skipped — even thoughbufferedInputClose()above may have just madehasFinished()true. Since the branch usescmd.exit_code.?rather thancode, it doesn't actually need the outer unwrap; hoisting it out (or adding it right afterbufferedInputClose()) closes the gap for free. Very narrow trigger (overlaps the pre-existing// TODO: handle errorfor.errstatus), so not blocking.Extended reasoning...
What the gap is
Commit 795dd0e added an
else if (this.stdin == .pipe and cmd.exec == .subproc and cmd.hasFinished())branch to drive completion whencmd.exit_codewas already set beforeonProcessExitfired (the fix for inline-comment 3225887379). However, that branch is nested insideif (exit_code) |code| { ... }, so it only runs when the localexit_codederived fromstatusis non-null — i.e. for.exitedor.signaled. Whenstatus == .err(waitpid/rewatch failure on POSIX, per process.zig:368/636),exit_codeis null and the entire tail block — including the new re-check — is skipped.With
.readable_streamstdin, thebufferedInputClose()call earlier inonProcessExitis the only thing that ever flipsbuffered_closed.stdin(aFileSinkhas no completion callback into the Cmd, andSignal.initis intentionally skipped for.readable_streamat line ~954). So ifcmd.exit_codewas pre-set bybufferedOutputCloseStdout/Stderrand thenonProcessExitarrives withstatus == .err, we end up withhasFinished() == truebut nothing drivingparent.childDone()→ theawait Bun.$hangs.Step-by-step
- ``Bun.$
cmd < ${stream}``` with a JS ReadableStream →spawn_args.stdio[0] = .readable_stream` → `buffered_closed.stdin = false`. - Child writes to stdout; the CapturedWriter hits EPIPE (e.g. parent's own stdout is a broken pipe).
bufferedOutputCloseStdoutsetscmd.exit_code = errno;hasFinished()is false (stdin still open) →.suspended. - The kernel-side process tracking fails:
rewatchPosix()orwaitpid()returns an error →Process.onExitis called withstatus = .{ .err = ... }.hasExited()returns true for.err(process.zig:279), so the Process detaches and no further callback will arrive. onProcessExitruns:this.stdin == .pipe→bufferedInputClose()flipsbuffered_closed.stdin = true. NowallClosed() == trueandhasFinished() == true.exit_codeis computed:.errfalls through the// TODO: handle errorno-op and reachesbreak :brk null.if (exit_code) |code|is false → the whole tail (including the 795dd0e re-check) is skipped.onProcessExitreturns. Nothing else is scheduled → hang.
(One sub-claim from the original report doesn't hold:
.signaledwith an out-of-range signal would panic on the.toExitCode().?unwrap rather than yield null, so.erris the only realistic null-exit_codepath.)Addressing the refutation / why this is only a nit
One reviewer correctly notes that
status == .erris already an explicitly-acknowledged unhandled case (the// TODO: handle errorat line ~1060), and that pre-PR it already hung for all stdin types in the more common case wherecmd.exit_codestays null. That's accurate —.errstatus handling is a known gap, and the trigger here is a triple conjunction (ReadableStream stdin + stdout/stderr error before process-exit + waitpid/rewatch syscall failure) that is essentially theoretical in practice. This is not a regression in any realistic user scenario.The reason it's still worth a one-line nit: the 795dd0e re-check uses
cmd.exit_code.?, not the capturedcode, so it has no actual dependency on the outerif (exit_code) |code|unwrap. Nesting it there is purely incidental, and hoisting it out makes the 795dd0e fix structurally complete (it then covers everyonProcessExitinvocation, not just the ones wherestatusmaps to a numeric exit code) at zero cost. Since the author is already touching exactly this block, it's a free hardening.Suggested fix
Move the re-check outside the
if (exit_code) |code|block (or duplicate it right afterbufferedInputClose()):if (exit_code) |code| { if (cmd.exit_code == null) { cmd.onExit(code); return; } } if (this.stdin == .pipe and cmd.exec == .subproc and cmd.hasFinished()) { cmd.onExit(cmd.exit_code.?); }
This also folds naturally into any future fix for the
// TODO: handle errorcase. - ``Bun.$
|
CI status for b178a03 (build #53725): The diff is green. All 7 new The only failing test is
Passing test lanes include This needs a maintainer to merge — a retrigger won't help since the flake is consistent on Windows 2019. |
b178a03 to
a982e12
Compare
Bun.$`cmd < ${readableStream}` previously panicked with
'TODO SHELL READABLE STREAM'. Wire it up the same way Bun.spawn does:
wrap the child's stdin fd in a FileSink and call assignToStream() so the
ReadableStream pumps into the subprocess. On process exit, call
onAttachedProcessExit() on the sink and mark buffered stdin closed so
the Cmd state machine can finish.
ReadableStream redirected to stdout/stderr now throws a clear error
instead of panicking, and builtins (which read stdin synchronously)
reject ReadableStream with a descriptive error instead of 'Unknown JS
value'.
Fixes #18262
When a ReadableStream's assignToStream call fails (e.g. a direct stream whose pull() throws synchronously), return a shell error with the exception message instead of hitting the 'unexpected error while creating stdin' panic. The subprocess is killed via the same abortAfterFailedStart() path used for other post-spawn start failures.
Appeases ban-words.test.ts which tracks '// autofix' instance count.
…iledStart On Windows, abortAfterFailedStart() leaked the Subprocess with its exit_handler still set. When libuv later delivered the killed child's exit, onProcessExit would dereference cmd_parent whose .exec had already been reset to .none by the caller. Clearing exit_handler first is safe on Windows (just nulls a tagged pointer) and makes the deferred exit callback a no-op. Also guard bufferedInputClose() on exec == .subproc as defense in depth.
'Use an external command or buffer the stream first' only makes sense for stdin redirects; for > / 2> reuse the 'can only be redirected to stdin' message.
…xit_code - Move the stdin_assign_error check after process.watch() so tryKill() can actually signal the child on POSIX (Process.kill is a no-op while poller is still .detached). - In onProcessExit, when exit_code was already set by a stdout/stderr write error before the process exited, re-check hasFinished() after bufferedInputClose() and drive the Cmd forward so the await doesn't hang. - Clear any pending JS exception if toBunString() throws while formatting the assignToStream error (hostile Symbol.toPrimitive).
When abortAfterFailedStart() runs before stdout/stderr pipe.start(), reader.handle is still .closed so PipeReader.deinit() won't close the spawn-created fd. Explicitly close stdio_result in that case. This covers both the new stdin_assign_error path and the pre-existing stdin.buffer.start() failure path.
Main was rewritten in Rust (#30412); the .zig shell files are kept alongside but no longer compiled. Port the fix to Cmd.rs, subproc.rs, and Builtin.rs: - Cmd::setup_redirect: replace the TODO panic with stdin-only validation, to_any_blob fast-path, is_disturbed check, and Stdio::ReadableStream assignment. - Writable::init: add out_assign_error param; POSIX and Windows .readable_stream cases create a FileSink, start its writer, and call assign_to_stream, surfacing errors via the out-param. - spawn_maybe_sync_impl: skip the signal overwrite for readable_stream stdin; after watch(), if assign_to_stream failed, format the error, kill the child, forget the FileSinkPtr (the JS controller owns the remaining ref and will free it on GC — dropping it here would UAF when the controller's dtor later calls FileSink::finalize), and abort_after_failed_start. - on_process_exit: notify the FileSink via on_attached_process_exit and mark buffered stdin closed; re-check has_finished() if exit_code was pre-set. - abort_after_failed_start: clear exit_handler before the Windows early-return; close pending stdout/stderr stdio_result fds when start() never ran. - Builtin::init_redirections: reject ReadableStream with a clear error (builtins read stdin synchronously).
The readable_stream stdin path now adopts a FileSink on POSIX too, so drop the #[cfg(windows)] gate main added while it was Windows-only.
efea2a1 to
86a6b53
Compare
matches!(.., Ok(Some(_))) silently discarded the Err arm, leaving a pending JS exception (e.g. from a hostile Symbol.asyncIterator getter) while later JSC calls run. Return Yield::failed() on Err, matching the Zig spec's catch and the Cmd.rs port's use of ?.
- assign_to_stream returns the thrown value already unwrapped from its JSC::Exception, so a caller-side .to_error() misses non-Error throws (throw "string"). Treat any non-empty, non-promise result as the error signal instead, on both the POSIX and Windows arms. Add a test with a plain-string throw. - Replace mem::forget with ManuallyDrop (clippy: mem_forget on type with Drop fields). - Drop a needless borrow now that on_process_exit takes &Status.
… failure assign_to_stream used to return the thrown value already unwrapped from its JSC::Exception, which callers cannot reliably classify: for a direct stream, pull() throwing null/undefined/a string is indistinguishable from the undefined the success path returns. Return the original JSC::Exception instead so a single .to_error() at call sites detects any throw; switch the shell arms back to .to_error(). Also stop releasing the FileSink ref on Bun.spawn's assign_to_stream error path: the JSReadableFileSinkController created by assignToStream still holds a raw m_sinkPtr (nothing detaches it on the synchronous error path), so its GC finalizer derefs the sink — releasing here too freed it early and the finalizer then read freed memory. Tests: shell throw-null case, and a spawn edge-case test covering synchronous direct-stream throws (Error and null) followed by GC.
alii
left a comment
There was a problem hiding this comment.
Thanks for taking this on — the sync-error refcount analysis here is careful, and dropping the two pipe_release calls is correct (that path was an over-release before: create +1, release -1, controller GC finalize -1).
Requesting changes for two bugs, one UB/leak on the new error arm, and one structural suggestion that I think deletes most of the new complexity. Details and repros are in the line comments; short version:
- Double-free on a success path (
subproc.rs:1324):readDirectStreamreturns success for a direct stream with nopullwithout ever starting/ending/detaching the controller, so the controller's GC destructor derefs the same single ref the shell'sFileSinkPtrowns and later drops. One+1, twoderefs. - Async assign failures are treated as success (
Cmd.rs:792): a rejection out ofreadStreamIntoSink(e.g. a locked but undisturbed stream —getReader()doesn't setm_disturbed, so it passes theisDisturbedguard) never reaches theCmd. The child runs with empty stdin and exits 0; the redirected data is silently dropped. w.end()inassign_to_stream's error arm can synchronously run user JS (FileSink.rs:1412) — the source'scancel()— under the live&mut IOWriterfromwith_mut, and acontroller.end()from in there detaches the controller, which inverts the leak/UAF assumption all three call sites now depend on.- Structural (
FileSink.rs:1406): detach the controller insideassign_to_stream's error branch instead of making every caller deliberately leak its ref.RequestContext.rsalready does exactly this forResponseStreamJSSinkon the sameto_error()path, and the FileSinkdetachalready exists. With that one call (placed before theend()), the two "Do NOT release / would UAF" comments, theManuallyDropforget, and (3) all go away.
Also flagged inline: cat < ${stream} is platform-divergent (builtin on Windows → rejected; external on POSIX → works) and deserves a deliberate decision rather than the test working around it; and the async-error / direct-stream / child-exits-early regimes have no tests, which is where 1 and 2 were hiding.
Happy to re-review quickly once these are addressed — the core approach (reusing the Bun.spawn FileSink path) is right, and this is close.
| } | ||
| }); | ||
|
|
||
| let assign_result = pipe.assign_to_stream(rs, global); |
There was a problem hiding this comment.
There's a refcount hole on a success path. assign_to_stream deliberately takes no per-controller ref (see its comment: "No per-wrapper +1 for the controller"), on the assumption that the JS side always calls controller.end()/.close() (which detach()es) before the controller is GC'd. That doesn't hold for every success path: in readDirectStream (ReadableStreamInternals.ts), a direct stream with no pull hits
if (!underlyingSource.pull) { close(); return; }which returns success without ever calling sink.start()/end() — close() there only closes the stream, never the sink. Nothing roots that controller (m_onPull/m_onClose/readableStreamController are never set on this path), so GC destroys it and its destructor runs FileSink__finalize(m_sinkPtr) → deref(). But that create-time +1 is owned by the Writable::Pipe(FileSinkPtr) we return here, which also derefs it at teardown. One ref, two derefs — whichever runs second is a use-after-free.
// pull-less direct streams are constructible (the ctor never validates `pull` for type:"direct")
await Bun.$`cat < ${new ReadableStream({ type: "direct" })}`.quiet().nothrow();
Bun.gc(true);(That same path also never closes the child's stdin, so the command hangs too — but the double-deref is the dangerous part.) Bun.spawn shares the latent hole; this PR is what makes it reachable from the shell. The minimal fix is probably in readDirectStream: a source with no pull should still sink.end() (which detaches and gives the child EOF). The class fix is to make the controller's lifetime correct by construction (its own ref, or detach-on-every-exit) rather than by the "JS always detaches" convention, which is already false today.
There was a problem hiding this comment.
Fixed in ac682b4 on both sides:
readDirectStreamnow callssink.end()in the no-pullbranch, so the destination gets EOF (no hang) and the controller detaches.- Defense in depth on the native side:
on_attached_process_exit,handle_resolve_streamandhandle_reject_streamalso detach, so even a stream that never reaches a JScontroller.end()leaves the create-time ref solely owned by theWritable.
Regression tests: direct ReadableStream with no pull gives the child EOF (shell) and direct ReadableStream with no pull closes stdin (Bun.spawn), both followed by Bun.gc(true); on the previous head the shell one hangs and the GC double-derefs under ASAN.
| // async pipe path. | ||
| stdio[STDIN_NO].extract_blob(global, blob, STDIN_NO as i32)?; | ||
| } else { | ||
| if rstream.is_disturbed(global) { |
There was a problem hiding this comment.
isDisturbed isn't sufficient here, and the failure behind it is silent. Two parts:
- A locked but undisturbed stream passes this guard —
getReader()doesn't setm_disturbed(onlyread/readMany/canceldo). - It then fails asynchronously: for a default stream,
assignToStream→readStreamIntoSinkis anasync function, so its ownstream.getReader()throw (or any laterpull()rejection) becomes a promise rejection, not a synchronous throw.assign_to_streamonly reports synchronous throws (promise_result.to_error()), sostdin_assign_errorstaysZERO; the rejection lands inhandle_reject_stream, which closes the write end and returnsOk(undefined). Nothing reaches theCmd.
Net observable behavior: the child sees EOF on an empty stdin, runs, and exits 0 — the user gets a successful result with their redirected data silently dropped:
const s = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode("data")); c.close(); } });
s.getReader(); // locked, NOT disturbed
const r = await Bun.$`bun -e ${"process.stdout.write(await Bun.stdin.text())"} < ${s}`.quiet();
// r.exitCode === 0, r.stdout === "" — no error surfaced anywhereSame shape for a pull() that rejects after the first chunk: truncated stdin, exit 0. An async assign/pump failure needs to surface (fail the command like the sync path now does, or at least reject the promise), and this guard should probably be locked || disturbed. None of the added tests cover an async failure — they're all type:"direct" synchronous throws — which is why this didn't show up.
There was a problem hiding this comment.
Both parts addressed in ac682b4:
- The validation moved into a shared
Stdio::extract_readable_stream(used byBun.spawn'sextractand the shell) and now rejectsis_lockedas well asis_disturbed, so the locked-but-undisturbed case throws synchronously before anything is spawned (both APIs). Tests:rejects locked ReadableStream(shell) andlocked ReadableStream is rejected synchronously(spawn). - A pump failure after assignment is no longer silent in the shell:
handle_reject_streamrecords the rejection on theFileSink, and when the child exits the command is marked failed (exit code 1 unless the child already failed) withbun: ReadableStream redirected to stdin erroredon the captured stderr — the same shape as how output IO errors surface (buffered_output_close_*with an err sets the exit code). Test:stream that errors mid-pump fails the command(asserts stdout == the pre-failure chunk, the stderr note, and exit code 1).
One honest caveat on (2): the failure is reported at child-exit time. If the child ignores stdin entirely, exits 0, and the source only errors afterwards, the rejection can land after the command already resolved. Reporting that case too needs an owner-notification channel from FileSink back to the shell that neither the shell nor Bun.spawn has today (the sink's signal slot is occupied by the JS controller); I kept that out of this PR, but happy to add a then-based hook as a follow-up if you want it.
| // immediately (what handle_reject_stream does for async failures); | ||
| // without this a spawned child reading from the pipe would block on | ||
| // the open write-end until GC finalizes the JS controller. | ||
| self.writer.with_mut(|w| w.end()); |
There was a problem hiding this comment.
This end() can synchronously run user JS while the exclusive &mut IOWriter from this very with_mut is still live. The chain is fully synchronous: end() → close() → the on-close callback runs inline → FileSink::on_close → signal.close(None). And the signal is not empty here — the generated assignToStream stores the controller into *controllerValue before invoking the JS, so a synchronous pull() throw leaves it set. That dispatches to the controller's onClose, which readDirectStream installs via $startDirectStream before calling pull() — i.e. the source's cancel() runs, synchronously, inside this with_mut.
From there, a controller.end() (the user holds the controller — it was the argument to their pull()):
- re-enters this same writer through a second
&mut(end_from_js→writer.with_mut(|w| w.flush())) — exactly the re-entrancyJsCell::with_mut's own docs call out as the one forbidden thing; and detach()es first, so the controller's destructor no longer derefs — silently breaking the "the controller's GC finalize will release it" contract that the two call sites inapi/bun/subprocess/Writable.rsand the shell now rely on. That ref is then never released.
If the error branch detaches the controller before this end() (see my other comment on this hunk), the signal is already cleared, on_close has nothing to call into, and both problems disappear.
There was a problem hiding this comment.
Fixed in ac682b4: the error branch detaches the controller first (detach_js_controller takes the Signal out of the JsCell before re-entering JS), so by the time writer.end() runs the signal is empty and on_close has nothing to call into; the end() can no longer re-enter user JS under the with_mut. A controller.end() from inside the source's cancel is a no-op after the detach (null m_sinkPtr), so the ownership assumption no longer depends on what user JS does.
| let promise_result = JSSink::assign_to_stream(global_this, stream.value, self, signal_ptr); | ||
|
|
||
| if let Some(err) = promise_result.to_error() { | ||
| if promise_result.to_error().is_some() { |
There was a problem hiding this comment.
Structural suggestion, and I think it removes most of this PR's difficulty: detach the controller here, in the error branch, instead of making every caller compensate.
As written, on a synchronous assignToStream failure the JSReadableFileSinkController created a few lines up stays attached with a raw m_sinkPtr, so its GC destructor will deref() the sink. That single fact is why (a) the two pipe_release calls in api/bun/subprocess/Writable.rs had to be deleted and replaced with 6-line "Do NOT release … would UAF" comments, and (b) subproc.rs needs a ManuallyDrop(mem::replace(..)) forget plus a 14-line explanation. Three call sites now each hand their ref to a GC finalizer we hope runs exactly once.
We already solve this correctly on the same code path elsewhere: RequestContext.rs does assign_to_stream(...) → on to_error(), ResponseStreamJSSink::detach(&mut sink.signal, global) → then ordinary teardown. The FileSink equivalent already exists and needs no new plumbing — the controller is sitting in self.signal:
if promise_result.to_error().is_some() {
self.readable_stream.set(readable_stream::Strong::default());
JSSink::detach(unsafe { self.signal.get_mut() }, global_this); // <- add this
self.writer.with_mut(|w| w.end());
return promise_result;
}detach() nulls m_sinkPtr (making the controller's destructor a no-op), is idempotent, and doesn't touch the async-promise path. After it: the deleted pipe_release calls can come back as ordinary, balanced releases; both long comments and the ManuallyDrop block become unnecessary; and the end() on the next line can no longer re-enter user JS through the signal (see my other comment). One line here deletes ~40 elsewhere and turns a convention into an invariant.
There was a problem hiding this comment.
Done in ac682b4 — assign_to_stream's error branch now detaches the controller (new FileSink::detach_js_controller, same shape as the ResponseStreamJSSink::detach call in RequestContext.rs) before ending the writer. That let me restore both pipe_release calls in api/bun/subprocess/Writable.rs as ordinary balanced releases and delete the ManuallyDrop forget plus the long ownership comments in the shell. I also went one step further toward "correct by construction": handle_resolve_stream, handle_reject_stream and on_attached_process_exit detach too, so every native terminal of an assigned stream leaves the controller inert; the only remaining path where the controller's destructor runs attached is a stream abandoned mid-pump to GC, which is the pre-existing design issue and out of scope here.
| stdin_assign_error.ensure_still_alive(); | ||
| let global = | ||
| JSGlobalObject::opaque_ref(event_loop.global_object().cast::<JSGlobalObject>()); | ||
| let msg = match stdin_assign_error.to_bun_string(global) { |
There was a problem hiding this comment.
Two issues in this block, both consequences of the controller still being attached (see my comments on FileSink.rs):
to_bun_stringon an arbitrary thrown value runs user JS (toString/Symbol.toPrimitive) — the comment below already concedes that — and it runs beforetry_killand theManuallyDropbelow, while the user still holds the live controller (it was the argument to theirpull()).- The user doesn't even need a hostile
toString: they can callcontroller.end()at any later point.end()detaches (m_sinkPtr = null) without dereffing, so the controller's destructor will no longer release the ref — and this block justManuallyDrop-forgot the only other handle to it. Net: thatFileSinkis never freed. The forget is a bet on the future behavior of a JS-visible object that JS is allowed to change.
Both go away if assign_to_stream detaches on its error branch — then this block keeps subproc.stdin's ordinary drop and needs neither the forget nor the long comment.
There was a problem hiding this comment.
Both are gone in ac682b4. With the detach moved into assign_to_stream's error branch, this block is back to ordinary teardown: kill the child first, then stringify the thrown value (so no user JS runs against a live, unkilled child), then abort_after_failed_start(), which simply drops subproc.stdin's FileSinkPtr as the only ref. No ManuallyDrop, and a later controller.end() from user JS is a no-op on a detached controller instead of a bet we have to win.
| // Builtins read stdin synchronously from a buffer/blob; piping an | ||
| // async ReadableStream into a builtin would require buffering the | ||
| // whole stream first. Reject with a clear error instead of crashing. | ||
| let _ = global.throw_invalid_arguments(format_args!( |
There was a problem hiding this comment.
This makes the original issue's headline example platform-divergent. cat is a shell builtin only on Windows (from_argv0 returns builtins unconditionally under cfg!(windows), and Cat/Cp are in the POSIX-disabled set), so:
await Bun.$`cat < ${stream}`
// POSIX: external /bin/cat → works (the new Cmd.rs path)
// Windows: builtin → throws "ReadableStream cannot be redirected to a builtin command ('cat')"The added test's own comment works around exactly this ("Use a spawned bun process (not the cat builtin, which is only a builtin on Windows) so the redirect always goes through the subprocess path") rather than pinning it. Since Cmd.rs already buffers a stream via to_any_blob for its fast path, builtins could buffer the same way and reuse the existing ArrayBuf redirect instead of hard-rejecting — or, if rejecting is the intended behavior, that's a deliberate cross-platform divergence on Bun.$ and needs a test asserting it on Windows. Either is fine; the current state (silently OS-dependent, untested) isn't.
There was a problem hiding this comment.
Went with the "deliberate divergence, tested" option (45e007b): a new cat < stream (builtin on Windows, external elsewhere) test asserts the builtin rejection message on Windows and the piped output elsewhere, and the PR description now documents the decision. Rationale for not buffering: the to_any_blob fast path in Cmd.rs only covers streams that are already complete in memory; a general builtin redirect would have to asynchronously drain an unbounded user stream before the builtin can start, which is a new async state in Builtin::init and feels like its own change (happy to do it as a follow-up if you'd rather Bun.$ builtins accept streams).
| stdout: "ignore", | ||
| env: bunEnv, | ||
| }), | ||
| ).toThrow(); |
There was a problem hiding this comment.
Bare .toThrow() — this passes if spawn throws for any reason (bad option, unrelated type error), so it doesn't pin that the new "Failed to pipe ReadableStream to stdin" path is what fired. Please assert the message.
Bigger test gap, and it's where both of the real bugs in this review were hiding — none of the added tests cover:
- an async stream failure (a rejection out of
readStreamIntoSink: a locked stream, or apull()that rejects on its second call) — every error test added here is atype:"direct"synchronous throw; - a direct stream with no
pull(the double-deref + hang path); - the child exiting while the stream is still producing — the exact ordering the new
on_process_exitblock exists to handle; in every passing test the child drains stdin fully, so that block is never exercised in the interesting order.
There was a problem hiding this comment.
Done in ac682b4/45e007b:
- The bare
.toThrow()now asserts the thrown value (message for theErrorcase,toBeNull()via try/catch forthrow null). - Async failure:
stream that errors mid-pump fails the command(default stream,pull()rejects on its second call) plus the synchronously-rejected locked case in both APIs. - No-
pulldirect stream: shell + spawn tests (EOF, exit 0, GC). - Child exits early:
child exiting before the stream completes does not hang(the child never reads stdin and exits while the source is still producing), which exercises theon_process_exit→on_attached_process_exit→ cancel ordering.
No test timeouts were raised.
|
|
||
| let stdin = match Writable::init(stdio0, event_loop, subprocess, spawn_stdin) { | ||
| let stdin_is_readable_stream = matches!(stdio0, Stdio::ReadableStream(_)); | ||
| let mut stdin_assign_error = JSValue::ZERO; |
There was a problem hiding this comment.
Two smaller things:
out_assign_error: &mut JSValueplus the!= JSValue::ZEROsentinel is a second, unchecked error channel alongside the function's existingResult<_, WritableInitError>— a caller that passes a slot and never reads it compiles fine. AWritableInitError::StreamAssignFailed(JSValue)variant (or returning the pending error in theOk) expresses "this must be handled, afterwatch()" through the type system and deletes the sentinel and the out-param.- The new ReadableStream arm in
Cmd.rsre-implements the ReadableStream arm ofStdio::extract(from_js→to_any_blobfast path → disturbed check →Stdio::ReadableStream), which the neighbouring branches already delegate to viaextract_blob. Sharing it keeps the two validations and messages from drifting.
There was a problem hiding this comment.
Both done in ac682b4: Writable::init returns WritableInit { writable, assign_error: Option<JSValue> } (the deferred-until-after-watch() handling is now part of the documented type instead of an out-pointer sentinel), and the Cmd.rs arm delegates to the new shared Stdio::extract_readable_stream instead of re-implementing the from_js → to_any_blob → disturbed/locked sequence.
|
@robobun please address the review feedback above (#30550 (review)). Suggested order: start with the structural comment on |
|
Thanks for the thorough review — working through it now in exactly that order. Status:
No test timeouts were raised. Running the wider stream/spawn suites under ASAN now; will push once they're green and re-request review. |
…n assigned stream
Review follow-up: the previous approach left the JSReadable*SinkController
attached after a synchronous assignToStream failure and made every caller
compensate (deleted pipe_release calls in Bun.spawn, a ManuallyDrop forget
in the shell). Fix it at the source instead:
- FileSink::assign_to_stream's error branch now detaches the controller
(new detach_js_controller, the same shape RequestContext.rs already
uses for ResponseStreamJSSink) before ending the writer. The detach
clears the signal, so the writer close cannot re-enter user JS, and
the controller's GC destructor no longer releases a ref it never
owned. handle_resolve_stream, handle_reject_stream and
on_attached_process_exit detach too, so no native terminal path
depends on JS having called controller.end().
- Bun.spawn's two assign-error arms go back to a plain pipe_release;
the shell error arm drops its FileSinkPtr normally (the ManuallyDrop
forget and the long ownership comments are gone).
- readDirectStream: a direct stream with no pull() now ends the sink,
so the child gets EOF and the controller detaches; previously the
controller was never started/ended/detached (its GC destructor
double-released the sink) and the child hung.
- ReadableStream stdio validation is shared between Bun.spawn and the
shell (Stdio::extract_readable_stream) and now also rejects locked
streams: getReader() alone does not disturb a stream, and a locked
stream always fails to pump, asynchronously, after the child started.
- A stream that errors after pumping started is no longer a silent
empty-stdin success in the shell: FileSink records the rejection and
the shell reports it when the child exits (exit code 1 plus a note on
stderr), mirroring how output IO errors surface.
- Writable::init returns WritableInit { writable, assign_error } instead
of writing through an out-pointer sentinel.
On Windows cat is a shell builtin and rejects a ReadableStream stdin redirect; on POSIX it is an external command and the stream is piped to it. Assert both sides instead of only avoiding the builtin in tests.
The no-ref justification cited the JS builtins always detaching the controller before GC. That convention no longer holds on its own: every native terminal of an assigned stream now detaches explicitly via detach_js_controller. State the actual invariant.
…pump on_process_exit read stream_rejected and forced exit code 1 before the child's exit status was extracted, so a child that exited non-zero after its stdin was truncated was reported as 1 and its own code was lost. Extract the status first and only escalate to 1 when the child exited 0 (or its status is unknown). Document that the stderr note goes to the captured buffer.
…eadable-stream-stdin
| // the controller detaches from the native sink (otherwise the controller | ||
| // is never started/ended/detached, the destination never gets EOF, and | ||
| // the controller's GC destructor releases a ref it does not own). | ||
| sink.end(); |
There was a problem hiding this comment.
Is this change, correct or not, strictly required for landing this PR? If not, can we throw it into another PR? We would want to derisk changes like this if it's only tangential.
There was a problem hiding this comment.
Fair. The behavior is required for the PR (without it cat < ${new ReadableStream({ type: "direct" })} never gives the child EOF, so the command hangs, and the never-started controller's GC destructor releases a ref it does not own), but it does not have to live in the generic builtin. Done in d46737c: readDirectStream is back to exactly what main has, and FileSink::assign_to_stream now runs the same terminal as a fulfilled pump (handle_resolve_stream: detach plus close the writer, both idempotent) when assignToStream returns synchronously with no promise, which is precisely the no-pull / pull-ended-inline case. That scopes the change to the sinks this PR is about (spawn stdin, the shell redirect, Bun.write(file, stream)). Both no-pull regression tests still pass, plus a new one for a direct stream whose pull writes and ends inline. Other sink types given a pull-less direct stream still have the underlying issue on main; happy to send the readDirectStream one-liner with its own tests as a follow-up PR.
| 2 => b"stderr", | ||
| _ => { | ||
| return Err(global.throw_invalid_arguments(format_args!( | ||
| "ReadableStream cannot be used for stdio[{i}] yet" |
There was a problem hiding this comment.
Two reasons:
- The shell redirect needs the same validation
Bun.spawn({ stdin })already does for a ReadableStream: the Blob fast path (a file-backed or already-buffered stream is passed as an fd/blob instead of being pumped) and the disturbed check, plus the locked check from your review, sincegetReader()locks without disturbing andassignToStreamcan never pump a locked stream. - Doing that inline in
Cmd.rswould have duplicatedStdio::extract's ReadableStream arm and the two would drift, so that arm became this named method and both call it. The body isBun.spawn's existing code apart from the addedis_lockedcheck.
The one behavior change for Bun.spawn itself: a locked stream now throws synchronously ("'stdin' ReadableStream is locked") instead of spawning the child and having the pump fail asynchronously with an empty stdin and exit 0, the same silent-failure shape you flagged on the shell side. If you'd rather this PR not change Bun.spawn at all, I can do the locked check only in the shell and leave spawn's behavior exactly as on main; say the word.
There was a problem hiding this comment.
Can we unify the implementation then?
There was a problem hiding this comment.
Done in 7d338d6. Stdio::extract_body_value had the second copy (the Request/Response-body-as-stdin path, with its own index/sync/disturbed checks and no locked guard); it now calls the same extract_readable_stream, so there is exactly one implementation behind every entry point that can hand a stream to a child: the stdin/stdio options, a Request/Response body, and the shell redirect. The index and sync checks moved into validate_readable_stream_target, which the body path calls before to_readable_stream (converting can start draining the body, so an unsupported destination must be rejected first).
Two behavior changes fall out of the unification, both visible in the error messages:
- A bare
ReadableStreampassed asstdout/stderrused to be accepted and silently turned into a pipe nobody reads (Readable::initmapsStdio::ReadableStreamtoIgnore), so the child blocked once the pipe filled. It now throwsReadableStream cannot be used for stdout yet. For now, do .stdout, which is what the body path already threw. Covered by atest.eachover bare stream / Response body / Request body. - The body path's disturbed and sync-mode messages gain the
'stdin'prefix the option path already had.
One thing I did not touch: spawn({ stdin: new Response(stream) }) hangs, because Body::to_readable_stream hands back a freshly-created stream rather than the one the Response holds. That reproduces on main (released bun too), so it is a separate bug from this PR and I left it alone rather than widen the diff.
…ssign_to_stream assignToStream returns synchronously with no promise for a direct stream whose pull() ended the sink inline or that has no pull() at all. Run the fulfilled-pump terminal (handle_resolve_stream) on that return so the destination sees EOF and the controller detaches, instead of ending the sink inside the generic readDirectStream builtin.
…dable_stream extract_body_value had a second copy of the ReadableStream stdio checks, with no locked-stream guard. Both entry points now share one implementation: index/sync validation runs before the body is converted into a stream, then the disturbed and locked guards. A bare ReadableStream passed as stdout or stderr was silently turned into a pipe nobody reads; it is now rejected with the same message the body path already used.
|
This PR has been closed because it was flagged as AI slop. Many AI-generated PRs are fine, but this one was identified as having one or more of the following issues:
If you believe this was done in error, please leave a comment explaining why. |
|
Understood, leaving this closed. For anyone landing here from #18262: the panic still reproduces on current main ( |
This PR has been marked as AI slop and the description has been updated to avoid confusion or misleading reviewers.
Many AI PRs are fine, but sometimes they submit a PR too early, fail to test if the problem is real, fail to reproduce the problem, or fail to test that the problem is fixed. If you think this PR is not AI slop, please leave a comment.