Skip to content
Closed

ai slop #30550

Show file tree
Hide file tree
Changes from 24 commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
96fb9b5
shell: support ReadableStream as stdin redirect in Bun.$
robobun May 12, 2026
163086c
shell: surface assignToStream errors instead of panicking
robobun May 12, 2026
9c4d47a
shell: drop unused err capture in readable_stream stdin path
robobun May 12, 2026
65204af
shell: clear exit_handler before Windows early-return in abortAfterFa…
robobun May 12, 2026
83bfe97
shell: split ReadableStream-to-builtin error message by direction
robobun May 12, 2026
c5dbf87
shell: fix stdin_assign_error teardown ordering and hang on pre-set e…
robobun May 12, 2026
ac6a48f
shell: close pending stdout/stderr fds in abortAfterFailedStart
robobun May 12, 2026
02d29d4
shell: port ReadableStream stdin redirect to Rust
robobun May 16, 2026
74e6c01
[autofix.ci] apply automated fixes
autofix-ci[bot] May 16, 2026
86a6b53
shell: allow FileSinkPtr::adopt on POSIX
robobun May 22, 2026
3d1d4fb
shell: propagate from_js errors in builtin ReadableStream check
robobun May 22, 2026
a9eaadd
shell: detect non-Error throws from assign_to_stream, fix clippy
robobun May 23, 2026
697f3ce
streams: return original exception from FileSink::assign_to_stream on…
robobun May 23, 2026
00d9af4
shell: drop two no-op let _ suppressions
robobun May 23, 2026
c77625d
shell: drop stale .zig reference edits and outdated comment
robobun May 23, 2026
bf80823
shell: drop now-redundant let _ = this in abort_after_failed_start
robobun May 23, 2026
869011f
shell: update stale comment about Writable::Pipe on POSIX
robobun May 23, 2026
df4722b
streams: close FileSink writer on assign_to_stream failure
robobun May 23, 2026
089836a
Merge branch 'main' into farm/eb0b47ce/shell-readable-stream-stdin
alii Jul 2, 2026
ac682b4
shell,streams: detach the JS controller at every native terminal of a…
robobun Jul 2, 2026
c73ed66
[autofix.ci] apply automated fixes
autofix-ci[bot] Jul 2, 2026
45e007b
shell: pin the cat-builtin platform divergence with a test
robobun Jul 2, 2026
d450552
ci: retrigger
robobun Jul 2, 2026
c760dc4
streams: update stale controller ownership comment in assign_to_stream
robobun Jul 2, 2026
d2c591c
shell: keep the child's own exit code when a stdin stream errors mid-…
robobun Jul 2, 2026
90eeeda
Merge remote-tracking branch 'origin/main' into farm/eb0b47ce/shell-r…
robobun Jul 2, 2026
d46737c
streams: handle synchronously-completed direct streams in FileSink::a…
robobun Jul 2, 2026
0e0554f
streams: remove stale TODO comment in FileSink::assign_to_stream
robobun Jul 2, 2026
7d338d6
spawn: route the Request/Response body stdio path through extract_rea…
robobun Jul 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/js/builtins/ReadableStreamInternals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -763,6 +763,11 @@ export function readDirectStream(stream, sink, underlyingSource) {
var close = $readDirectStreamOnClose.bind(state);

if (!underlyingSource.pull) {
// Nothing will ever write. End the sink so its destination sees EOF and
// 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.

close();
return;
}
Expand Down
101 changes: 65 additions & 36 deletions src/runtime/api/bun/spawn/stdio.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,42 +513,7 @@ impl Stdio {
}

if let Some(stream_) = webcore::ReadableStream::from_js(value, global)? {
let mut stream = stream_;
if let Some(blob) = stream.to_any_blob(global) {
return out_stdio.extract_blob(global, blob, i);
}

let name: &'static [u8] = match i {
0 => b"stdin",
1 => b"stdout",
2 => b"stderr",
_ => {
return Err(global.throw_invalid_arguments(format_args!(
"ReadableStream cannot be used for stdio[{i}] yet"
)));
}
};

if is_sync {
return Err(global.throw_invalid_arguments(format_args!(
"'{}' ReadableStream cannot be used in sync mode",
bstr::BStr::new(name),
)));
}

if stream.is_disturbed(global) {
return Err(global
.err(
jsc::ErrorCode::INVALID_STATE,
format_args!(
"'{}' ReadableStream has already been used",
bstr::BStr::new(name),
),
)
.throw());
}
*out_stdio = Stdio::ReadableStream(stream);
return Ok(());
return out_stdio.extract_readable_stream(global, stream_, i, is_sync);
}

if let Some(array_buffer) = value.as_array_buffer(global) {
Expand All @@ -575,6 +540,70 @@ impl Stdio {
)))
}

/// Validate a `ReadableStream` destined for a spawned process's stdio and
/// store it. Shared by `Bun.spawn`'s option extraction and the shell's
/// `cmd < ${stream}` redirect so the two cannot drift.
///
/// Streams that are really an already-complete Blob/File take the blob
/// fast-path. Disturbed (already read from) and locked (a reader is held)
/// streams are rejected up front: `assignToStream` could not pump either,
/// and that failure would otherwise surface only asynchronously, after the
/// child is already running with an empty stdin.
pub fn extract_readable_stream(
&mut self,
global: &JSGlobalObject,
stream: webcore::ReadableStream,
i: i32,
is_sync: bool,
) -> JsResult<()> {
let mut stream = stream;
if let Some(blob) = stream.to_any_blob(global) {
return self.extract_blob(global, blob, i);
}

let name: &'static [u8] = match i {
0 => b"stdin",
1 => b"stdout",
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.

)));
}
};

if is_sync {
return Err(global.throw_invalid_arguments(format_args!(
"'{}' ReadableStream cannot be used in sync mode",
bstr::BStr::new(name),
)));
}

if stream.is_disturbed(global) {
return Err(global
.err(
jsc::ErrorCode::INVALID_STATE,
format_args!(
"'{}' ReadableStream has already been used",
bstr::BStr::new(name),
),
)
.throw());
}

if stream.is_locked(global) {
return Err(global
.err(
jsc::ErrorCode::INVALID_STATE,
format_args!("'{}' ReadableStream is locked", bstr::BStr::new(name)),
)
.throw());
}

*self = Stdio::ReadableStream(stream);
Ok(())
}

pub fn extract_blob(
&mut self,
global: &JSGlobalObject,
Expand Down
4 changes: 4 additions & 0 deletions src/runtime/api/bun/subprocess/Writable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,8 @@ impl<'a> Writable<'a> {
subprocess.update_flags(|f| {
f.set(Flags::DEREF_ON_STDIN_DESTROYED, false)
});
// `assign_to_stream` detached the JS controller on its
// error path, so this create-time ref is the only one.
Self::pipe_release(pipe_nn);
subprocess.deref();
let _ = global.throw_value(err_val);
Expand Down Expand Up @@ -340,6 +342,8 @@ impl<'a> Writable<'a> {
if let Some(err_val) = assign_result.to_error() {
subprocess.weak_file_sink_stdin_ptr.set(None);
subprocess.update_flags(|f| f.set(Flags::DEREF_ON_STDIN_DESTROYED, false));
// `assign_to_stream` detached the JS controller on its error
// path, so this create-time ref is the only one.
Self::pipe_release(pipe_nn);
subprocess.deref();
let _ = global.throw_value(err_val);
Expand Down
22 changes: 22 additions & 0 deletions src/runtime/shell/Builtin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,28 @@ impl Builtin {
if redirect.stderr() {
me.stderr = BuiltinIO::ArrayBuf { buf: mk(), i: 0 };
}
} else if match crate::webcore::ReadableStream::from_js(jsval, global) {
Ok(Some(_)) => true,
Ok(None) => false,
// from_js threw (e.g. a hostile Symbol.asyncIterator getter);
// propagate instead of continuing with a pending exception.
Err(_) => return Some(Yield::failed()),
} {
if redirect.stdin() {
// 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).

"ReadableStream cannot be redirected to a builtin command ('{}'). \
Use an external command or buffer the stream first",
kind.as_str()
));
} else {
let _ = global.throw_invalid_arguments(format_args!(
"ReadableStream can only be redirected to stdin"
));
}
return Some(Yield::failed());
} else if let Some(body) =
crate::webcore::body::Value::from_request_or_response(jsval)
{
Expand Down
50 changes: 48 additions & 2 deletions src/runtime/shell/states/Cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -776,8 +776,22 @@ impl Cmd {
STDERR_NO as i32,
)?;
}
} else if crate::webcore::ReadableStream::from_js(jsval, global)?.is_some() {
panic!("TODO SHELL READABLE STREAM");
} else if let Some(rstream) =
crate::webcore::ReadableStream::from_js(jsval, global)?
{
if !flags.stdin() {
return Err(global.throw_invalid_arguments(format_args!(
"ReadableStream can only be redirected to stdin"
)));
}
// Shared with `Bun.spawn`: blob fast-path + the
// disturbed/locked validation live in one place.
stdio[STDIN_NO].extract_readable_stream(
global,
rstream,
STDIN_NO as i32,
false,
)?;
} else if let Some(req) = jsval.as_::<crate::webcore::Response>() {
// SAFETY: `as_` returns a live JSC-owned `*mut Response`.
let req = unsafe { &mut *req };
Expand Down Expand Up @@ -939,6 +953,38 @@ impl Cmd {
}
}

/// The ReadableStream redirected to this command's stdin failed after the
/// pump started (its `pull()` rejected / the stream errored), so the child
/// only saw a truncated stdin. Mirror how output IO errors surface: note
/// it on the captured stderr and make the command fail unless the child
/// already produced a failing exit code of its own.
pub fn on_stdin_stream_rejected(&mut self) {
log!("cmd stdin stream rejected");
const MSG: &[u8] = b"bun: ReadableStream redirected to stdin errored\n";
match &self.io.stderr {
IoOutKind::Fd(fd) => {
// SAFETY: single-threaded; the captured `Vec<u8>` lives in the
// owning `ShellExecEnv` and no other borrow of it is live here.
if let Some(captured) = unsafe { fd.captured_mut() } {
captured.append_slice(MSG);
}
}
Comment thread
robobun marked this conversation as resolved.
Resolved
IoOutKind::Pipe => {
// Same destination `close_out` uses for piped/captured stderr.
let shell_buf = self.base.shell_mut().buffered_stderr();
if !shell_buf.is_null() {
// SAFETY: `shell_buf` points into `ShellExecEnv::_buffered_*`,
// which `base.shell` keeps live for the command's duration.
unsafe { (*shell_buf).append_slice(MSG) };
}
}
IoOutKind::Ignore => {}
}
if self.exit_code.is_none() {
self.exit_code = Some(1);
}
Comment thread
robobun marked this conversation as resolved.
Resolved
}

/// Mark the subprocess's buffered stdout/stderr as closed (flushing the
/// captured bytes into the shell buffers); if that makes the command
/// finished, transition to `Done` and yield back to the trampoline.
Expand Down
Loading
Loading