Skip to content

shell: fix inverted file-blob check for builtin > ${Response(...)} redirect - #35318

Closed
robobun wants to merge 5 commits into
mainfrom
farm/6b88bbd2/shell-builtin-blob-redirect-polarity
Closed

robobun wants to merge 5 commits into
mainfrom
farm/6b88bbd2/shell-builtin-blob-redirect-polarity

Conversation

@robobun

@robobun robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Builtin::init_redirections guards a > ${jsvalue} stdout/stderr redirect against in-memory Blob bodies with:

let is_file_blob = matches!(body, Value::Blob(b) if !b.needs_to_read_file());
if (redirect.stdout() || redirect.stderr()) && !is_file_blob { /* throw */ }

needs_to_read_file() is true for file-backed blobs, so is_file_blob was true for in-memory bodies and false for file-backed ones, the opposite of the sibling direct-Blob branch. Since echo always runs as a builtin:

import { $ } from "bun";
// throws "Cannot redirect stdout/stderr to an immutable blob", should write
await $`echo hi > ${new Response(Bun.file("/tmp/out"))}`;
// succeeds with exit 0 and output discarded, should throw
await $`echo hi > ${new Response(new Blob(["x"]))}`;

Fixing the predicate alone isn't sufficient: a file-backed body that passes the guard was stored as BuiltinIO::Blob(..), and write_no_io_to treated that variant as Ok(buf.len()) (a no-op), so output would still be silently dropped. The same silent drop also affected echo hi > ${Bun.file(fd)} (fd-backed blobs reach the JsBuf arm because only path-backed Bun.file is inlined as a path string by handle_template_value).

Fix

The Request/Response and bare-Blob JsBuf branches now share one setup_blob_redirect helper:

  • a file-backed blob has its store.data.File.pathlike extracted and is opened through the same IOReader/IOWriter path that an Atom (> filename) redirect already uses (hoisted into open_file_redirect); an fd-backed blob is shell_dup'd so the writer owns a private fd, and the dup'd fd is probed with is_pollable() so a pipe/socket/tty takes the async writer path
  • an in-memory blob as stdout/stderr throws "Cannot redirect stdout/stderr to an immutable blob"; as stdin it stays BuiltinInput::Blob

This mirrors what Stdio::extract_blob already does for the spawned-subprocess path in Cmd::init_subproc_redirections.

The BuiltinIO::Blob output variant is no longer constructed anywhere and has been removed so the silent-drop arm cannot reappear; BuiltinInput::Blob stays for in-memory stdin.

Related

  • shell: throw on Response/Request stream body used as redirect instead of delivering zero bytes #35314 adds a Locked/Used/Error body check just before this branch; that PR does not touch the polarity and its added check_body_for_redirect call sits cleanly above the new body.use_() line.
  • shell: throw instead of panic on ReadableStream redirect #33996 fixes the interpreter keepalive left pinned after a Yield::failed() throw; the new tests spawn a subprocess per case so they do not depend on that fix.
  • setup_blob_redirect also routes < ${Response(Bun.file(p))} stdin through IOReader (previously it delivered empty bytes via shared_view() on a file store). This is only observable via builtin cat (Windows, or POSIX with BUN_ENABLE_EXPERIMENTAL_SHELL_BUILTINS=1), where builtin cat < file has a separate pre-existing issue on POSIX; left out of this PR's test coverage.

How did you verify your code works?

Added to test/js/bun/shell/bunshell.test.ts under redirect builtin stdout to Blob / Response body:

  • echo > ${new Response(Bun.file(path))} writes hello\n to the file
  • echo > ${new Response(new Blob([..]))}, ${new Response("..")}, ${new Blob([..])} each reject with the exact "immutable blob" message
  • echo > ${Bun.file(fd)} writes to the fd (and the user's fd stays open)
USE_SYSTEM_BUN=1 bun test bunshell.test.ts -t "redirect builtin stdout"   # 3 fail, 2 pass
bun bd test bunshell.test.ts -t "redirect builtin stdout"                 # 5 pass
bun bd test bunshell.test.ts                                              # 419 pass, 0 fail

no test proof · iteration 0 · Platform-specific test(s) that do not run on this machine. Deferring to CI, which covers all platforms: test/js/bun/shell/bunshell.test.ts

…direct

The Request/Response branch in Builtin::init_redirections computed
is_file_blob as !needs_to_read_file(), the opposite of its sibling
direct-Blob branch. As a result, for a builtin command like echo:

  echo hi > ${new Response(Bun.file(path))}  threw 'immutable blob'
  echo hi > ${new Response(new Blob([..]))}  succeeded with exit 0
                                             and discarded the output

Fixing the guard alone is not enough: a file-backed body that passes
the guard was stored as BuiltinIO::Blob, and write_no_io_to treats
that variant as a no-op, so output would still be silently dropped.
The same silent discard also affected echo > ${Bun.file(fd)}.

Both the Response/Request and bare-Blob JsBuf branches now go through
a shared setup_blob_redirect helper. A file-backed blob has its
path/fd extracted and is opened via the same IOReader/IOWriter path as
a > filename redirect (factored into open_file_redirect); an in-memory
blob is rejected for stdout/stderr and kept for stdin.
@coderabbitai

coderabbitai Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: b6c6ef5f-6326-426c-88bc-c79de2b3343e

📥 Commits

Reviewing files that changed from the base of the PR and between b39a270 and 9d0d364.

📒 Files selected for processing (3)
  • src/runtime/shell/Builtin.rs
  • src/runtime/shell/interpreter.rs
  • test/js/bun/shell/bunshell.test.ts

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

@robobun

robobun commented Jul 23, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 7:15 PM PT - Jul 23rd, 2026

❌ @robobun, your commit 9d0d364 has 1 failures in Build #79017 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 35318

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

bun-35318 --bun

@github-actions

Copy link
Copy Markdown
Contributor

No open issues found that this PR would fix.

🤖 Generated with Claude Code

Comment thread src/runtime/shell/Builtin.rs Resolved
Match open_file_redirect and the interpreter root stdout/stderr: a
pipe/FIFO/socket fd now takes the pollable IOWriter path instead of the
synchronous do_file_write loop.
Comment thread test/js/bun/shell/bunshell.test.ts Resolved
robobun added 2 commits July 23, 2026 23:25
setup_blob_redirect routes file-backed blobs to BuiltinIO::Fd and
rejects in-memory blobs for stdout/stderr, so the Blob output variant
is never constructed. Its write_no_io_to arm returned Ok(buf.len())
without writing, which is exactly the silent-drop this change removes;
deleting the variant turns that into a compile-time guarantee.
BuiltinInput::Blob stays for in-memory stdin.
@robobun

robobun commented Jul 23, 2026

Copy link
Copy Markdown
Collaborator Author

Diff is green: bunshell.test.ts passes on every lane across builds 78964/78988/79017. The remaining red is test/js/bun/spawn/spawn.test.ts (gcTick > spawn > pipe > hello > should allow reading stdout > before exit) on ubuntu 25.04 x64 / debian 13 x64, which also fails on main (e.g. build 78377) and is unrelated to this shell-builtin change. Ready for review.

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

No new findings — both earlier nits (fd-arm is_pollable probe, toBe on the exact error string) are confirmed addressed. Deferring to a human because this reworks native fd ownership / IOWriter lifecycle in the builtin redirect path rather than being a mechanical fix.

What was reviewed:

  • open_file_redirect is a pure hoist of the Atom-arm body; behavior for > path is unchanged.
  • setup_blob_redirect path/fd extraction: path bytes are cloned and the fd is shell_dup'd before drop(blob), so no borrow into freed store; the dup'd fd is owned by IOWriter/IOReader and closed on Drop.
  • BuiltinIO::Blob has no remaining references after removal (grepped src/).
  • body.use_() now runs before the immutable-blob guard, so a rejected Response body is consumed before the throw — benign since the operation fails either way.
Extended reasoning...

Overview

The PR fixes an inverted needs_to_read_file() predicate in Builtin::init_redirections's Request/Response body branch, then goes further: it hoists the Atom-redirect open logic into open_file_redirect, adds setup_blob_redirect to unify the bare-Blob and Request/Response arms, routes file-backed blobs through real IOReader/IOWriter (path via open_file_redirect, fd via shell_dup + is_pollable probe), and deletes the now-unreachable BuiltinIO::Blob output variant whose write_no_io_to arm silently discarded writes. interpreter.rs only promotes is_pollable to pub. Five subprocess-spawning tests are added under bunshell.test.ts.

Security risks

None identified. Inputs are user-owned JS Blob/Response objects; paths come from Bun.file(path) and go through the same shell_openat/open_for_writing_impl machinery the > filename atom redirect already uses; fds are dup'd so the writer owns a private handle it can close.

Level of scrutiny

Medium-high. This is native Rust touching fd ownership, IOWriter lifecycle, and Blob Drop ordering — exactly the class REVIEW.md's memory-safety section flags ("who frees this, when, on which paths"). The hoist looks byte-identical, the new helper's Drop ordering checks out, and Stdio::extract_blob (the subprocess-spawn analogue the PR cites) does the same pathlike unpacking. But it is not a one-line polarity flip: it removes an enum variant, changes when body.use_() fires relative to the guard, and introduces a new IOWriter construction site. That's enough moving parts in native I/O code to warrant a human pass rather than bot approval.

Other factors

Two prior review rounds from me raised nits (hardcoded pollable on the fd arm; toContain vs toBe); both were fixed in follow-up commits and are visible in the current diff. The bug hunt on the latest revision found nothing. Tests use tempDir, bunEnv, test.concurrent, drain both pipes, and the PR description reports the USE_SYSTEM_BUN=1 fail / bun bd pass split. I grepped src/ for BuiltinIO::Blob — no remaining references, so the variant removal is complete.

@github-actions

Copy link
Copy Markdown
Contributor

Closing this PR because it has been inactive for more than 90 days.

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

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant