Skip to content

ai slop - #30550

Closed
robobun wants to merge 29 commits into
mainfrom
farm/eb0b47ce/shell-readable-stream-stdin
Closed

ai slop#30550
robobun wants to merge 29 commits into
mainfrom
farm/eb0b47ce/shell-readable-stream-stdin

Conversation

@robobun

@robobun robobun commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator

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.

@coderabbitai

coderabbitai Bot commented May 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

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

Changes

ReadableStream stdin redirection implementation

Layer / File(s) Summary
ReadableStream validation entry points
src/shell/Builtin.zig, src/shell/states/Cmd.zig
Builtin commands reject ReadableStream redirection with a user-facing error; command redirection validates streams, permits only stdin redirection, extracts blobs when available, rejects disturbed streams, and stores readable_stream in spawn args.
Subprocess stdin wiring
src/shell/subproc.zig
Writable.init signature updated to accept stdio pointer and out_assign_error; Windows and non-Windows .readable_stream stdin paths use FileSink.create + assignToStream, capturing assignment errors and canceling streams on start failures.
Spawn lifecycle and error handling
src/shell/subproc.zig
spawnMaybeSyncImpl allocates stdin_assign_error and passes it to Writable.init; skips initializing stdin pipe signal for readable_stream sources; converts assignment failures to shell errors, SIGTERMs the child, aborts startup, clears exit handlers and closes unused fds, and onProcessExit notifies stdin pipe and closes buffered stdin safely.
Test coverage for ReadableStream redirection
test/js/bun/shell/bunshell.test.ts
Adds tests covering successful redirection from subprocess stdout and JS ReadableStream (chunked and large-buffer), failure cases (non-stdin redirection, disturbed stream reuse, pull() exceptions), and builtin command rejection message.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main change: adding support for ReadableStream as stdin redirection in Bun shell commands.
Linked Issues check ✅ Passed The PR implementation fully addresses all coding objectives from issue #18262: eliminates the TODO panic, implements ReadableStream-to-stdin piping via FileSink, manages stream lifecycles on process exit, and provides clear errors for unsupported redirect cases.
Out of Scope Changes check ✅ Passed All changes are directly scoped to implementing ReadableStream stdin redirection: Cmd.initRedirections, Writable.init for stdin handling, spawnMaybeSyncImpl signal management, process exit cleanup, and builtin error handling.
Description check ✅ Passed The PR description follows the required template and includes purpose, implementation details, error semantics, and verification steps.

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

@robobun

robobun commented May 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 4:09 PM PT - Jul 2nd, 2026

❌ @robobun, your commit 7d338d6 has 1 failures in Build #68068 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 30550

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

bun-30550 --bun

Comment thread src/runtime/shell/subproc.zig Resolved

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 314ffe3 and 95be871.

📒 Files selected for processing (4)
  • src/shell/Builtin.zig
  • src/shell/states/Cmd.zig
  • src/shell/subproc.zig
  • test/js/bun/shell/bunshell.test.ts

Comment thread test/js/bun/shell/bunshell.test.ts Resolved
Comment thread src/shell/subproc.zig Resolved

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

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 lift

Return a shell error instead of panicking on stdin setup failure.

Writable.init() can now fail here for recoverable FileSink.start*() errors, but Line 935 still turns that into a process-wide panic. A broken/closed stdin pipe during setup should unwind like the later stdin_assign_error path, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 95be871 and dc5b8eb.

📒 Files selected for processing (1)
  • src/shell/subproc.zig

Comment thread src/runtime/shell/subproc.zig Resolved
Comment thread src/runtime/shell/Builtin.zig Resolved
Comment thread src/runtime/shell/subproc.zig Resolved
Comment thread src/runtime/shell/subproc.zig Resolved
Comment thread src/runtime/shell/subproc.zig Resolved
Comment thread src/runtime/shell/subproc.zig 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.

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 src/shell/subproc.zig:1073-1082 — Nit: this else if (... cmd.hasFinished()) re-check is nested inside if (exit_code) |code|, so when status == .err (null exit_code) it's skipped — even though bufferedInputClose() above may have just made hasFinished() true. Since the branch uses cmd.exit_code.? rather than code, it doesn't actually need the outer unwrap; hoisting it out (or adding it right after bufferedInputClose()) closes the gap for free. Very narrow trigger (overlaps the pre-existing // TODO: handle error for .err status), 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 when cmd.exit_code was already set before onProcessExit fired (the fix for inline-comment 3225887379). However, that branch is nested inside if (exit_code) |code| { ... }, so it only runs when the local exit_code derived from status is non-null — i.e. for .exited or .signaled. When status == .err (waitpid/rewatch failure on POSIX, per process.zig:368/636), exit_code is null and the entire tail block — including the new re-check — is skipped.

    With .readable_stream stdin, the bufferedInputClose() call earlier in onProcessExit is the only thing that ever flips buffered_closed.stdin (a FileSink has no completion callback into the Cmd, and Signal.init is intentionally skipped for .readable_stream at line ~954). So if cmd.exit_code was pre-set by bufferedOutputCloseStdout/Stderr and then onProcessExit arrives with status == .err, we end up with hasFinished() == true but nothing driving parent.childDone() → the await Bun.$ hangs.

    Step-by-step

    1. ``Bun.$cmd < ${stream}``` with a JS ReadableStream → spawn_args.stdio[0] = .readable_stream` → `buffered_closed.stdin = false`.
    2. Child writes to stdout; the CapturedWriter hits EPIPE (e.g. parent's own stdout is a broken pipe). bufferedOutputCloseStdout sets cmd.exit_code = errno; hasFinished() is false (stdin still open) → .suspended.
    3. The kernel-side process tracking fails: rewatchPosix() or waitpid() returns an error → Process.onExit is called with status = .{ .err = ... }. hasExited() returns true for .err (process.zig:279), so the Process detaches and no further callback will arrive.
    4. onProcessExit runs: this.stdin == .pipe → bufferedInputClose() flips buffered_closed.stdin = true. Now allClosed() == true and hasFinished() == true.
    5. exit_code is computed: .err falls through the // TODO: handle error no-op and reaches break :brk null.
    6. if (exit_code) |code| is false → the whole tail (including the 795dd0e re-check) is skipped. onProcessExit returns. Nothing else is scheduled → hang.

    (One sub-claim from the original report doesn't hold: .signaled with an out-of-range signal would panic on the .toExitCode().? unwrap rather than yield null, so .err is the only realistic null-exit_code path.)

    Addressing the refutation / why this is only a nit

    One reviewer correctly notes that status == .err is already an explicitly-acknowledged unhandled case (the // TODO: handle error at line ~1060), and that pre-PR it already hung for all stdin types in the more common case where cmd.exit_code stays null. That's accurate — .err status 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 captured code, so it has no actual dependency on the outer if (exit_code) |code| unwrap. Nesting it there is purely incidental, and hoisting it out makes the 795dd0e fix structurally complete (it then covers every onProcessExit invocation, not just the ones where status maps 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 after bufferedInputClose()):

    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 error case.

Comment thread src/runtime/shell/subproc.zig Resolved
@robobun

robobun commented May 12, 2026

Copy link
Copy Markdown
Collaborator Author

CI status for b178a03 (build #53725):

The diff is green. All 7 new redirect stdin from ReadableStream tests in bunshell.test.ts pass on every platform, and ban-words.test.ts passes.

The only failing test is test/js/bun/test/parallel/test-http-should-emit-close-when-connection-is-aborted.ts timing out on windows-2019-x64-test-bun and windows-2019-x64-baseline-test-bun. This HTTP connection-abort test:

  • is unrelated to the shell / ReadableStream changes in this PR
  • has timed out on every build of this PR from the very first commit (builds #53658, #53682, #53696, #53702, #53723, #53725) on Windows 2019 x64, including before any review-driven changes
  • windows-11-aarch64-test-bun passes, so Windows ReadableStream-stdin support itself works

Passing test lanes include debian-13-x64-asan-test-bun (ASAN), windows-11-aarch64-test-bun, and all Linux/macOS test lanes that have completed.

This needs a maintainer to merge — a retrigger won't help since the flake is consistent on Windows 2019.

@robobun
robobun force-pushed the farm/eb0b47ce/shell-readable-stream-stdin branch from b178a03 to a982e12 Compare May 16, 2026 17:57
robobun and others added 10 commits May 22, 2026 22:03
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.
@robobun
robobun force-pushed the farm/eb0b47ce/shell-readable-stream-stdin branch from efea2a1 to 86a6b53 Compare May 22, 2026 23:24
Comment thread src/runtime/shell/Builtin.rs Resolved
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 ?.
Comment thread src/runtime/shell/subproc.rs Resolved
- 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.
Comment thread src/runtime/shell/subproc.rs Resolved
… 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 alii left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Double-free on a success path (subproc.rs:1324): readDirectStream returns success for a direct stream with no pull without ever starting/ending/detaching the controller, so the controller's GC destructor derefs the same single ref the shell's FileSinkPtr owns and later drops. One +1, two derefs.
  2. Async assign failures are treated as success (Cmd.rs:792): a rejection out of readStreamIntoSink (e.g. a locked but undisturbed stream — getReader() doesn't set m_disturbed, so it passes the isDisturbed guard) never reaches the Cmd. The child runs with empty stdin and exits 0; the redirected data is silently dropped.
  3. w.end() in assign_to_stream's error arm can synchronously run user JS (FileSink.rs:1412) — the source's cancel() — under the live &mut IOWriter from with_mut, and a controller.end() from in there detaches the controller, which inverts the leak/UAF assumption all three call sites now depend on.
  4. Structural (FileSink.rs:1406): detach the controller inside assign_to_stream's error branch instead of making every caller deliberately leak its ref. RequestContext.rs already does exactly this for ResponseStreamJSSink on the same to_error() path, and the FileSink detach already exists. With that one call (placed before the end()), the two "Do NOT release / would UAF" comments, the ManuallyDrop forget, 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);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ac682b4 on both sides:

  • readDirectStream now calls sink.end() in the no-pull branch, so the destination gets EOF (no hang) and the controller detaches.
  • Defense in depth on the native side: on_attached_process_exit, handle_resolve_stream and handle_reject_stream also detach, so even a stream that never reaches a JS controller.end() leaves the create-time ref solely owned by the Writable.

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.

Comment thread src/runtime/shell/states/Cmd.rs Outdated
// async pipe path.
stdio[STDIN_NO].extract_blob(global, blob, STDIN_NO as i32)?;
} else {
if rstream.is_disturbed(global) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

isDisturbed isn't sufficient here, and the failure behind it is silent. Two parts:

  1. A locked but undisturbed stream passes this guard — getReader() doesn't set m_disturbed (only read/readMany/cancel do).
  2. It then fails asynchronously: for a default stream, assignToStream → readStreamIntoSink is an async function, so its own stream.getReader() throw (or any later pull() rejection) becomes a promise rejection, not a synchronous throw. assign_to_stream only reports synchronous throws (promise_result.to_error()), so stdin_assign_error stays ZERO; the rejection lands in handle_reject_stream, which closes the write end and returns Ok(undefined). Nothing reaches the Cmd.

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 anywhere

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both parts addressed in ac682b4:

  1. The validation moved into a shared Stdio::extract_readable_stream (used by Bun.spawn's extract and the shell) and now rejects is_locked as well as is_disturbed, so the locked-but-undisturbed case throws synchronously before anything is spawned (both APIs). Tests: rejects locked ReadableStream (shell) and locked ReadableStream is rejected synchronously (spawn).
  2. A pump failure after assignment is no longer silent in the shell: handle_reject_stream records the rejection on the FileSink, and when the child exits the command is marked failed (exit code 1 unless the child already failed) with bun: ReadableStream redirected to stdin errored on 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());

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-entrancy JsCell::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 in api/bun/subprocess/Writable.rs and 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two issues in this block, both consequences of the controller still being attached (see my comments on FileSink.rs):

  1. to_bun_string on an arbitrary thrown value runs user JS (toString/Symbol.toPrimitive) — the comment below already concedes that — and it runs before try_kill and the ManuallyDrop below, while the user still holds the live controller (it was the argument to their pull()).
  2. The user doesn't even need a hostile toString: they can call controller.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 just ManuallyDrop-forgot the only other handle to it. Net: that FileSink is 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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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!(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 a pull() that rejects on its second call) — every error test added here is a type:"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_exit block exists to handle; in every passing test the child drains stdin fully, so that block is never exercised in the interesting order.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in ac682b4/45e007b:

  • The bare .toThrow() now asserts the thrown value (message for the Error case, toBeNull() via try/catch for throw 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-pull direct 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 the on_process_exit → on_attached_process_exit → cancel ordering.

No test timeouts were raised.

Comment thread src/runtime/shell/subproc.rs Outdated

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;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two smaller things:

  • out_assign_error: &mut JSValue plus the != JSValue::ZERO sentinel is a second, unchecked error channel alongside the function's existing Result<_, WritableInitError> — a caller that passes a slot and never reads it compiles fine. A WritableInitError::StreamAssignFailed(JSValue) variant (or returning the pending error in the Ok) expresses "this must be handled, after watch()" through the type system and deletes the sentinel and the out-param.
  • The new ReadableStream arm in Cmd.rs re-implements the ReadableStream arm of Stdio::extract (from_js → to_any_blob fast path → disturbed check → Stdio::ReadableStream), which the neighbouring branches already delegate to via extract_blob. Sharing it keeps the two validations and messages from drifting.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/runtime/shell/states/Cmd.rs Resolved
@alii

alii commented Jul 2, 2026

Copy link
Copy Markdown
Member

@robobun please address the review feedback above (#30550 (review)).

Suggested order: start with the structural comment on FileSink.rs (detach the controller in assign_to_stream's error branch, like RequestContext.rs does) — it resolves the w.end() re-entrancy and the leak findings and lets you delete the ManuallyDrop forget plus the three long ownership comments. Then the two independent bugs: the readDirectStream no-pull double-deref (success path) and the silently-swallowed async assign rejection (locked-but-undisturbed stream ⇒ empty stdin, exit 0). Each of those needs a regression test that fails on the current head. Please don't raise any test timeouts, and keep the cat < ${stream} platform question as an explicit decision in the PR description rather than a test that avoids it.

@robobun

robobun commented Jul 2, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the thorough review — working through it now in exactly that order. Status:

  1. Structural (FileSink.rs): done. assign_to_stream's error branch now detaches the controller (new detach_js_controller, same shape as RequestContext.rs) before ending the writer, so the w.end() re-entrancy is gone (the signal is already cleared when the writer closes), the ManuallyDrop forget and both long ownership comments are deleted, and Bun.spawn's two pipe_release calls are restored as ordinary balanced releases. I also detach at the other native terminals of an assigned stream (handle_resolve_stream, handle_reject_stream, on_attached_process_exit) so the "JS always detaches" convention stops being load-bearing anywhere the shell or Bun.spawn can reach.
  2. No-pull direct stream: fixed in readDirectStream — the no-pull branch now calls sink.end() (EOF for the child + detach) before closing the stream. Regression tests for both the shell and Bun.spawn.
  3. Async assign/pump failures: the locked-but-undisturbed case is now rejected synchronously — the validation moved into a shared Stdio::extract_readable_stream used by both Bun.spawn and the shell (so the message/checks can't drift), with is_locked added alongside is_disturbed. For a rejection after pumping starts, handle_reject_stream records it on the sink and the shell reports it when the child exits: non-zero exit code + a note on stderr instead of a silent empty-stdin success. Regression tests for the locked case, a mid-pump pull() rejection, and the child-exits-early ordering.
  4. The spawn test's bare .toThrow() now asserts the message, and I'll put the cat builtin-vs-external platform divergence in the PR description as an explicit decision (builtins read stdin synchronously from a blob/buffer, so a ReadableStream redirect to a builtin errors with instructions to use an external command; no test papering over it).

No test timeouts were raised. Running the wider stream/spawn suites under ASAN now; will push once they're green and re-request review.

robobun and others added 3 commits July 2, 2026 05:37
…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.
@robobun
robobun requested a review from alii July 2, 2026 05:47
Comment thread src/runtime/webcore/FileSink.rs Resolved
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.
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
robobun added 2 commits July 2, 2026 07:02
…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.
// 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();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread src/runtime/api/bun/spawn/stdio.rs Outdated
2 => b"stderr",
_ => {
return Err(global.throw_invalid_arguments(format_args!(
"ReadableStream cannot be used for stdio[{i}] yet"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two reasons:

  1. 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, since getReader() locks without disturbing and assignToStream can never pump a locked stream.
  2. Doing that inline in Cmd.rs would have duplicated Stdio::extract's ReadableStream arm and the two would drift, so that arm became this named method and both call it. The body is Bun.spawn's existing code apart from the added is_locked check.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we unify the implementation then?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 ReadableStream passed as stdout/stderr used to be accepted and silently turned into a pipe nobody reads (Readable::init maps Stdio::ReadableStream to Ignore), so the child blocked once the pipe filled. It now throws ReadableStream cannot be used for stdout yet. For now, do .stdout, which is what the body path already threw. Covered by a test.each over 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.
@robobun
robobun requested a review from alii July 2, 2026 17:09
robobun added 2 commits July 2, 2026 17:41
…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.
@github-actions

github-actions Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

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:

  • Fails to verify the problem actually exists
  • Fails to test that the fix works
  • Makes incorrect assumptions about the codebase
  • Submits changes that are incomplete or misleading

If you believe this was done in error, please leave a comment explaining why.

@github-actions github-actions Bot changed the title shell: support ReadableStream as stdin redirect in Bun.$ ai slop Aug 4, 2026
@github-actions github-actions Bot closed this Aug 4, 2026
@robobun

robobun commented Aug 4, 2026

Copy link
Copy Markdown
Collaborator Author

Understood, leaving this closed.

For anyone landing here from #18262: the panic still reproduces on current main (panic: TODO SHELL READABLE STREAM on the issue's repro). The narrower fix that turns the panic into a clear error is open at #33996; this PR was the fuller implementation that actually pipes the stream into the child's stdin. @alii had reviewed it through 7d338d6 (structural FileSink controller detach, unified Stdio::extract_readable_stream, error semantics and tests) with CI at 284/286 green, the remaining red being the darwin-aarch64 artifact-download infra and the autobahn WebSocket suite on one agent. The branch (farm/eb0b47ce/shell-readable-stream-stdin) is kept in case any of it is useful to salvage.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants