Skip to content

shell: buffer a fetch() Response body before redirecting it to stdin - #35551

Closed
robobun wants to merge 12 commits into
mainfrom
farm/bef41b95/shell-buffer-response-stdin
Closed

robobun wants to merge 12 commits into
mainfrom
farm/bef41b95/shell-buffer-response-stdin

Conversation

@robobun

@robobun robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

$`cmd < ${await fetch(url)}` delivered zero bytes whenever the response body had not finished arriving by the time the shell resolved the redirect: any body larger than the first ~128 KB socket read, or any chunked/slow origin. The command runs on nothing and reports exit 0, so e.g. $`gzip < ${resp} > out.gz` produces a valid empty archive.

import { $ } from "bun";
const srv = Bun.serve({ port: 0, fetch: () => new Response(Buffer.alloc(500_000, "x")) });
const r = await fetch(`http://127.0.0.1:${srv.port}/`);
console.log((await $`wc -c < ${r}`.text()).trim());
// 1.3.14: 500000
// main:   0
srv.stop(true);

Regression since the fetch receive-backpressure coupling (81dfd59): the client socket is now paused after the first read until a consumer asks for more, so the body is still Locked when the shell reaches it. 1.3.14 buffered the whole body eagerly, so the same code delivered all 500000 bytes.

Cause

Cmd::init_subproc_redirections and Builtin::init_redirections call Body::use_as_any_blob() on the Response body. For Value::Locked with no synchronously-readable source, that falls through to .unwrap_or(AnyBlob::Blob(Blob::default())) (src/runtime/webcore/Body.rs), and Stdio::extract_blob maps the empty blob to Stdio::Ignore. Value::Used and Value::Error take the same empty-blob fallback.

Fix

A new CmdState::BufferingRedirectBody runs between redirect expansion and argv expansion. When the stdin redirect is a Request/Response whose body is still Locked with a native producer (the fetch tasklet or a server request context) attached:

  • PendingValue::hook_native_receiver fires on_start_buffering with the producer's own task pointer (so the paused fetch socket switches to BufferAll and resumes), then installs on_receive_value with the shell's resume context. The remaining producer-facing hooks (on_start_streaming, on_stream_cancelled, ...) are cleared because task now names the consumer.
  • The command parks in BufferingRedirectBody under its own KeepAlive.
  • When the producer finishes it replaces the body with InternalBlob / Error and calls resolve / to_error_instance, which fires the hook; the command resumes and use_as_any_blob() now returns the buffered bytes.

Bodies that cannot be buffered natively (a JS-driven ReadableStream, an already-consumed body, a stored body error, or a body whose .body stream is already in use) now throw instead of being substituted with an empty blob, via Cmd::reject_unbufferable_body on both the subproc and builtin paths. handle_template_value and the subproc redirect path now use Body::from_request_or_response, so Request is accepted alongside Response (previously cat < ${request} threw Invalid JS object used in shell: [object Request]).

Body::use_as_any_blob() itself is unchanged.

Related

How did you verify your code works?

test/js/bun/shell/bunshell.test.ts under redirects > stdin from Request/Response:

  • a 100-byte body (fits the first read), a 500 000-byte body (paused by backpressure), and a chunked/slow 500 000-byte body each deliver their full byte count to a spawned bun -e counter
  • the 500 000-byte body through the cat builtin
  • the 500 000-byte body through a cat | bun -e pipeline
  • the body is marked used after the redirect and a second redirect throws Body already used
  • a Request body delivers its full byte count
  • a ReadableStream body, an async-generator body, and an already-consumed body each reject instead of delivering zero bytes
  • echo hi > ${new Response(stream)} rejects with the stream-body message and without the stdin hint
USE_SYSTEM_BUN=1 bun test bunshell.test.ts -t "stdin from Request/Response"   # 10 fail, 1 pass (small-body control)
bun bd test bunshell.test.ts -t "stdin from Request/Response"                 # 11 pass
bun bd test bunshell.test.ts                                                  # 425 pass, 0 fail
bun bd test test/js/web/fetch/body.test.ts                                    # 348 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

$`cmd < ${await fetch(url)}` delivered zero bytes whenever the response
body had not finished arriving by the time the shell resolved the redirect
(any body larger than the first ~128 KB socket read, or any chunked/slow
origin). The Response body is a Locked PendingValue, and
Body::use_as_any_blob() falls through to an empty Blob for that case, so
the command ran on nothing and reported exit 0. This is a regression since
the fetch receive-backpressure coupling landed: before it, the body would
have buffered on its own.

Add CmdState::BufferingRedirectBody: before spawning, if the stdin
redirect is a Request/Response whose body is still Locked with a native
producer attached, fire on_start_buffering (so the paused fetch socket
resumes in BufferAll mode) and park on its on_receive_value hook; the
producer replaces the body with the buffered InternalBlob and resumes the
command. Bodies that cannot be buffered natively (a JS-driven
ReadableStream, an already-consumed body, a stored body error) now throw
instead of being substituted with an empty blob.

The builtin path and the subproc path share the same state-machine step,
and Request is now accepted alongside Response.

PendingValue::hook_native_receiver encapsulates the on_start_buffering +
on_receive_value sequencing so the shared task field is handed from the
producer to the consumer exactly once.
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

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

Next review available in: 2 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: 802a90a7-f3f0-4d30-b26e-80cf034102a0

📥 Commits

Reviewing files that changed from the base of the PR and between d68fd88 and 8069dd1.

📒 Files selected for processing (6)
  • src/runtime/server/RequestContext.rs
  • src/runtime/shell/states/Cmd.rs
  • src/runtime/webcore/Blob.rs
  • src/runtime/webcore/Body.rs
  • src/runtime/webcore/blob/write_file.rs
  • test/js/bun/shell/bunshell.test.ts

Walkthrough

Changes

Request/Response bodies used as shell redirects now use native raw-pointer receiver callbacks, asynchronous stdin buffering, shared body validation, and blob extraction for subprocess stdio. Tests cover buffering, pipelines, body usage, failures, and invalid stream or consumed-body cases.

Request/Response redirect buffering

Layer / File(s) Summary
Native body receiver contract
src/runtime/webcore/Body.rs, src/runtime/webcore/blob/write_file.rs, src/runtime/server/RequestContext.rs
Native body callbacks and locked-value wrappers now pass raw pointers and reconstruct mutable references at callback boundaries.
Shell redirect buffering and validation
src/runtime/shell/states/Cmd.rs, src/runtime/shell/Builtin.rs, src/runtime/shell/shell_body.rs
Shell redirect expansion buffers eligible stdin bodies, rejects unbufferable bodies, accepts Request/Response template values, and extracts blobs for subprocess stdio.
Redirect behavior validation
test/js/bun/shell/bunshell.test.ts
Tests cover buffered Request/Response bodies, pipelines, body usage, buffering failures, and invalid redirect targets.

Possibly related PRs

  • oven-sh/bun#35314: Updates shell Request/Response redirect handling with body validation and unbuffering logic.

Suggested reviewers: jarred-sumner

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main shell stdin buffering change, though it omits Request bodies.
Description check ✅ Passed The description includes the required purpose and verification sections and provides enough implementation detail.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

Found 1 issue this PR may fix:

  1. TODO SHELL READABLE STREAM #18262 - PR converts the "TODO SHELL READABLE STREAM" panic/crash into a proper error when a ReadableStream is used as a stdin redirect in Bun Shell

If this is helpful, copy the block below into the PR description to auto-close this issue on merge.

Fixes #18262

🤖 Generated with Claude Code

@robobun

robobun commented Jul 25, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:24 PM PT - Jul 25th, 2026

⏳ @robobun, your commit 8069dd1 is still building in Build #81234, but has 1 failures so far (All Failures):

@github-actions

Copy link
Copy Markdown
Contributor

This PR may be a duplicate of:

  1. shell: throw on Response/Request stream body used as redirect instead of delivering zero bytes #35314 - Also fixes the zero-bytes regression when a fetch() Response body is used as a shell redirect, but throws an error instead of buffering

🤖 Generated with Claude Code

@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/runtime/shell/states/Cmd.rs:417-431 — If the fetch body errors mid-buffer (connection reset, abort, server closes early), on_redirect_body_received resumes the trampoline, reject_unbufferable_body matches Value::Error and throws, and the trampoline treats Yield::Failed as Suspended and returns — nothing on this path calls child_done/finish(), so the shell promise never settles, has_pending_activity stays >0, and the interpreter's keep_alive holds the event loop open forever. Before this PR the same input ran on zero bytes; now it hangs. on_redirect_body_received needs to check global_this.has_exception() after run(interp) and route the failure through child_done (or reject the shell promise directly).

    Extended reasoning...

    What the bug is

    CmdState::BufferingRedirectBody is the first shell state that suspends before redirect resolution and later resumes on an async producer callback. When that resume path throws a JS exception, the Yield::failed() it returns is dropped on the floor by the trampoline, and the interpreter is left permanently pending: the awaited $...`` promise never settles and the process's event loop never drains.

    The code path

    Step-by-step, for await $cat < ${await fetch(url)}.text() where the origin resets the connection after headers + a partial body:

    1. try_buffer_redirect_body sees a Locked body with a native producer, calls hook_native_receiver (which fires on_start_buffering on the fetch tasklet and installs on_redirect_body_received as on_receive_value with the shell's ctx as task), and parks the Cmd in BufferingRedirectBody. The initial synchronous Interpreter::run() returns with no exception; the shell promise is pending; has_pending_activity was incremented at interpreter.rs:1260.
    2. The socket errors → FetchTasklet::on_body_received (!success branch) calls body.to_error_instance(err, global) on the response body.
    3. Body::Value::to_error_instance (Body.rs:1331–1375) does *self = Value::Error(err), then — because hook_native_receiver was only accepted with !readable.has() and promise.is_none(), so the earlier readable/promise branches are skipped — fires on_receive_value(locked.task.unwrap(), self) → Cmd::on_redirect_body_received.
    4. on_redirect_body_received unrefs the ctx keep-alive, sets state = ExpandingArgs { idx: 0 }, and drives Yield::Next(this).run(interp) — a fresh trampoline with an empty pipeline_stack.
    5. For a simple argv like cat, expansion is synchronous, so the trampoline reaches transition_to_exec → init_subproc_redirections (or Builtin::init_redirections on Windows). There, body.to_blob_if_possible() is a no-op on Value::Error, so reject_unbufferable_body matches the Value::Error(err) arm → global.throw_value(err.dupe(...).to_js(...)) → Err(_). transition_to_exec maps that to return Yield::failed().
    6. Yield::run (Yield.rs:138–143) handles Failed identically to Suspended: drain_pipelines on the empty stack returns None → the trampoline returns.
    7. Control returns to on_redirect_body_received, which does nothing after run(interp), then to to_error_instance → Ok(()), then to FetchTasklet, which continues with a pending VM exception it doesn't know about (surfaces later via the event-loop's unhandled-exception path, not as a rejection of the awaited shell promise).

    Why nothing recovers

    The only place the shell promise is settled and has_pending_activity is decremented is Interpreter::finish() (interpreter.rs:1170–1228, via DecrOnDrop at 1190), reached only via child_done bubbling up to the root Script. Nothing on this path calls interp.child_done(parent, this, ...): the Cmd is stuck in state Exec with exec = None and no pending callback. So:

    • has_pending_activity stays > 0 → hasPendingActivity() keeps the JSShellInterpreter wrapper (and its rooted jsobjs) alive; the finalizer never runs.
    • The interpreter's own keep_alive (ref'd at construction, .disable()d only in finish() or the finalizer) keeps the event loop alive indefinitely.
    • The awaited $....text() promise never settles.

    The pre-existing Yield::failed() sites in Cmd/Builtin redirect setup all ran during the initial synchronous run(), where run_from_js checks global_this.has_exception() afterward and propagates the throw. BufferingRedirectBody is the first async suspend before redirect resolution, so its resume is the first async Yield::failed() from a JS throw with no exception check afterward. (The general pattern does pre-exist in Cmd::on_io_writer_chunk, but that requires a stderr-fd write to fail, which is essentially unreachable; a mid-body fetch error is common.) The same applies to the Bun.serve request-abort path, which also calls to_error_instance on a hooked body.

    Impact

    Before this PR the same scenario silently ran the command on zero bytes and exited 0. After, it hangs forever and pins the interpreter. That's a regression on a realistic error path (connection reset / abort / server closes early mid-body after await fetch() returned), and directly matches REVIEW.md → Error handling: "Every error/abort/timeout path actively completes the operation. Settle every pending promise slot (an unsettled promise pins objects and hangs callers forever)." None of the added tests exercise a fetch that errors mid-body while buffering.

    Fix

    After Yield::Next(this).run(interp) in on_redirect_body_received, check interp.global_this_ref().is_some_and(|g| g.has_exception()) (or check the body variant before resuming) and, on failure, route through interp.child_done(parent, this, 1) / Interpreter::finish so the shell promise is rejected with the body error and the keep-alive is released. Alternatively, handle Value::Error in on_redirect_body_received itself (before entering the trampoline) by driving the Cmd to Done with a nonzero exit and rejecting the interpreter's promise with the stored error.

  • 🟡 src/runtime/shell/states/Cmd.rs:417-431 — on_redirect_body_received receives _value: &mut Value (a protected mutable borrow of response.body.value) and, while that borrow is live, synchronously drives Yield::Next(this).run(interp) into init_subproc_redirections / Builtin::init_redirections, which does unsafe { &mut *body } on the same location and writes through it (use_as_any_blob() → *self = Value::Used). Two live &mut to one object with one under a function-argument protector is UB under Stacked Borrows / Tree Borrows (Miri would flag it). No miscompile today since _value is never read and resolve returns immediately after the callback, but the trivial fix is to change the on_receive_value fn-pointer signature to take *mut Value (matching the borrow = ptr mode in src/CLAUDE.md), or to enqueue an event-loop task instead of running the trampoline inline.

    Extended reasoning...

    What the bug is

    Cmd::on_redirect_body_received is installed as a PendingValue::on_receive_value hook, whose signature is fn(ctx: *mut c_void, value: &mut Value). When the fetch producer completes, BodyValue::resolve is called with new = unsafe { &mut *body } where body points at response.body.value (FetchTasklet.rs:797), and resolve reborrows new into the callback parameter (Body.rs:1065). Under Stacked Borrows and Tree Borrows, that &mut function argument receives an FnEntry protector that lasts for the entire duration of on_redirect_body_received — the _ prefix and the fact that _value is never dereferenced do not release the protector.

    Inside the callback, Yield::Next(this).run(interp) is a synchronous trampoline (Yield.rs:101–147). It drives Cmd::next from ExpandingArgs { idx: 0 } through argv expansion into transition_to_exec, which calls either init_subproc_redirections (Cmd.rs) or Builtin::init_redirections (Builtin.rs). Both re-look-up the same Response via Value::from_request_or_response(jsval), do let body = unsafe { &mut *body } on the same memory location, and then write through it: body.to_blob_if_possible() and body.use_as_any_blob() / body.use_() (which does *self = Value::Used). The to_error_instance path (Body.rs:1374) has the identical shape — it passes self (the response body) to the callback, and the callback then re-derives &mut to that same self in reject_unbufferable_body.

    Step-by-step trace

    1. Fetch finishes → FetchTasklet.rs:797: BodyValue::resolve(&mut old, unsafe { &mut *body }, ...). body: *mut Value points at response.body.value; a Unique tag U1 is pushed for the new: &mut Value argument.
    2. Body.rs:1064–1066: callback(locked.task.unwrap(), new). new is reborrowed into _value: &mut Value; on function entry _value gets tag U2 (child of U1) with a strong protector for the whole call frame.
    3. on_redirect_body_received sets state = ExpandingArgs { 0 } and calls Yield::Next(this).run(interp).
    4. The trampoline synchronously reaches init_subproc_redirections → from_request_or_response(jsval) returns a fresh *mut Value derived from the JSC cell (interior mutability), i.e. not derived from U2. unsafe { &mut *body } pushes a new Unique U3 on the same location.
    5. body.use_as_any_blob() writes *self = Value::Used through U3. Under Stacked Borrows this pops every tag above the parent of U3 — including protected U2 → UB (protector violation). Under Tree Borrows the foreign write disables the protected Active U2 → same UB.
    6. Control returns to on_redirect_body_received, then to resolve (which returns immediately at line 1066), then to FetchTasklet (block ends at 799). Neither touches new/body again.

    Why existing code does not prevent it

    The comment on on_redirect_body_received says "this only has to resume", but it resumes synchronously into code that mutably re-borrows the exact object _value aliases. hook_native_receiver clears the producer-facing hooks so nothing else races, but it does not (and cannot) release the caller's &mut protector. The pre-existing on_receive_value consumer (ValueBufferer::on_receive_value, Body.rs:2559) mutates through the passed value directly, so this PR is the first callback to re-derive a &mut to the same location independently.

    Impact

    No observable miscompile today: _value is never accessed, so LLVM noalias on that parameter has nothing to reorder against, and neither resolve nor its FetchTasklet caller reads new/body after the callback returns. This is a memory-model violation that Miri would report, in a codebase whose own src/CLAUDE.md documents the borrow = ptr mode precisely for "when the callback may free self" and whose REVIEW.md flags "Anything that can run user JS can synchronously free your state" as the most-blocked category. It is worth fixing but does not produce a concrete runtime failure to block on.

    How to fix

    Either of:

    • Change the hook signature to fn(ctx: *mut c_void, value: *mut Value) so no protected &mut is held across the callback. ValueBufferer::on_receive_value would form its &mut *value locally; on_redirect_body_received would ignore the pointer as it does today. This matches the borrow = ptr idiom in src/CLAUDE.md and the FFI callback pattern used elsewhere (e.g. impl_streaming_writer_parent!).
    • Defer the resume: instead of Yield::Next(this).run(interp) inline, enqueue an event-loop task (the shell already has KeepAlive here) so the _value protector is released before init_subproc_redirections re-borrows the body.

Comment thread test/js/bun/shell/bunshell.test.ts Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
robobun and others added 2 commits July 25, 2026 06:17
…ake *mut Value in on_receive_value

A mid-body fetch error while parked in BufferingRedirectBody reached
reject_unbufferable_body on resume, which throws; Yield::Failed drops on the
floor from an async re-entry, so the shell promise never settled. Route
Value::Error through cmd_write_failing_error instead so the command finishes
with exit 1 and the fetch error on stderr, matching how file-redirect failures
are reported.

Change PendingValue::on_receive_value to take *mut Value (borrow=ptr) so the
shell callback does not hold a protected &mut over the same body it re-borrows
via from_request_or_response while driving the trampoline. Existing consumers
(ValueBufferer, WriteFileWaitFromLockedValueTask, RequestContext) form their
&mut locally.

@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: 3

🤖 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/runtime/shell/states/Cmd.rs`:
- Around line 893-912: Align the subprocess redirection path in the
Request/Response body branch with Builtin::init_redirections: reject non-file
stdout/stderr targets via the existing immutable-blob validation before calling
use_as_any_blob(). For combined stdout/stderr redirection, ensure the body is
validated and consumed once while preserving the expected rejection behavior.
- Around line 404-438: Clear the redirect body’s native receive hook during
Cmd::deinit(), including both on_receive_value and task, before the command or
interpreter can be released. Reuse the body/hook state associated with
hook_native_receiver() so pending resolution cannot invoke
on_redirect_body_received() with stale pointers or retain RedirectBodyBufferCtx.

In `@src/runtime/webcore/Body.rs`:
- Around line 332-342: Prevent synchronous completion from accessing invalid
state: in src/runtime/webcore/Body.rs lines 332-342, assign task and
on_receive_value and clear producer hooks before invoking on_start_buffering,
then revalidate that the body remains Locked after the callback returns; in
src/runtime/shell/states/Cmd.rs lines 356-370, acquire keep_alive.ref_ before
publishing ctx and release it on the false path, and make Cmd::next’s
BufferingRedirectBody assignment conditional so it cannot overwrite state
advanced by the callback.
🪄 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: 14cf2b92-842e-4e5a-85e8-676e2b8392b2

📥 Commits

Reviewing files that changed from the base of the PR and between 85f22bb and d68fd88.

📒 Files selected for processing (7)
  • src/runtime/server/RequestContext.rs
  • src/runtime/shell/Builtin.rs
  • src/runtime/shell/shell_body.rs
  • src/runtime/shell/states/Cmd.rs
  • src/runtime/webcore/Body.rs
  • src/runtime/webcore/blob/write_file.rs
  • test/js/bun/shell/bunshell.test.ts

Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
robobun and others added 2 commits July 25, 2026 08:21
…ering

A native receiver installed via hook_native_receiver now counts as the body
being consumed: is_disturbed/is_disturbed2, to_readable_stream and tee all
return used when on_receive_value is set, so a later .body/.clone()/.text()
on the same Response while the shell is parked cannot attach a readable and
divert delivery away from resolve(), and cannot create+protect() a promise
that the on_receive_value early-return would then never settle.

hook_native_receiver now installs the hook first and hands back a
DeferredStartBuffering token the caller fires after its own state/keep-alive
are in place. try_buffer_redirect_body re-reads the body after firing it and
falls back to the synchronous path when a producer's on_start_buffering
resolved the body in place without invoking the hook (server empty-body).
Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/shell/Builtin.rs Resolved
Comment thread src/runtime/webcore/Body.rs Resolved
ValueBufferer::buffer_locked_body_value and RequestContext::do_render_with_body
both materialised a stream and recursed when either on_receive_value or task
was set; with to_readable_stream now returning used() for a pending native
receiver that recursion never terminates. Split the check: a pending receiver
is StreamAlreadyUsed / render_missing; only a bare producer task materialises
and recurses.

Bun.write's body_dispatch Locked arm wrote task/on_receive_value
unconditionally, so Bun.write(path, res) after the shell had claimed the body
silently replaced the hook and left the shell parked forever. Reject via
is_disturbed2 before installing the write task.

@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 issues found after c48deb8 — the earlier rounds (hook displacement via Bun.write, .text() promise leak, to_readable_stream recursion in ValueBufferer/RequestContext, mid-buffer error hang) are all addressed. Deferring to a human reviewer given the scope: this introduces hook_native_receiver (which repurposes PendingValue::task from producer to consumer and clears the producer hooks), a new BufferingRedirectBody parking state with a heap-allocated ctx + KeepAlive, and new disturbed-body guards threaded through Body.rs / Blob.rs / RequestContext.rs.

What was reviewed:

  • RedirectBodyBufferCtx lifetime — freed on all three paths (hook-not-installed, sync-resolve-without-fire, on_redirect_body_received); keep_alive unref'd on each.
  • Competing consumers while parked (.body/.text()/tee/Bun.write/serve return) now reject via the on_receive_value.is_some() guards; the two recursive callers bail before to_readable_stream.
  • on_receive_value signature change to *mut Value applied at all four impls; the remaining resolve(&mut new) protector overlap is acknowledged and new is dead after the callback.
  • reject_unbufferable_body covers Locked/Used/Error on both subproc and builtin paths; stdout redirect omits the stdin hint.
Extended reasoning...

Overview

Fixes a regression where $cmd < ${await fetch(url)}`` delivered zero bytes for any body still Locked when the shell resolved the redirect. Adds a `CmdState::BufferingRedirectBody` phase: when the stdin redirect is a Request/Response with a native producer attached, `PendingValue::hook_native_receiver` installs a consumer callback, returns a `DeferredStartBuffering` token, and the Cmd parks under its own `KeepAlive` until `resolve`/`to_error_instance` fires the hook. Bodies with no native producer (JS `ReadableStream`, already-consumed, stored error) now throw instead of silently substituting an empty blob. Touches 8 files across `src/runtime/shell/`, `src/runtime/webcore/`, and `src/runtime/server/`, plus 11 new tests in `bunshell.test.ts`.

Security risks

None identified. No new untrusted-input parsing; the new error paths surface existing body errors. The task pointer repurposing is type-erased *mut c_void but the producer-facing hooks that would misinterpret it are explicitly cleared in hook_native_receiver.

Level of scrutiny

High. Body.rs is the shared substrate for fetch, Bun.serve, Bun.write, HTMLRewriter, and the shell; changing what counts as "disturbed" and adding a new consumer-side owner of task has broad reach. The PR went through five fix commits in review addressing real bugs: a mid-buffer-error hang, a .text() promise that never settled and stayed protect()'d, a Bun.write hook displacement that leaked the ctx and hung the shell, and a stack-overflow recursion in ValueBufferer/RequestContext. That iteration count alone argues for human sign-off on the final shape.

Other factors

  • One nit was acknowledged and left as-is: resolve() still holds a protected &mut Value across the callback while the trampoline re-derives a fresh &mut from the JSC cell. new is dead after the callback returns so there is nothing for noalias to reorder, and the codebase already documents this class on JsCell::get_mut; a maintainer should confirm they're comfortable leaving it.
  • A pre-existing inverted is_file_blob guard in Builtin::init_redirections is being left for #35318 to avoid a merge conflict.
  • hook_native_receiver sets on_start_streaming/on_readable_stream_available/on_stream_cancelled/on_stream_drained to None because task now names the consumer — a maintainer familiar with the server request-context path should confirm dropping those hooks on a server-side incoming-request body (the other producer besides FetchTasklet) is correct.
  • Test coverage is good (small/large/chunked bodies, builtin + subproc + pipeline, body-used-after, Request, mid-buffer error, three rejection cases, stdout-redirect message); the PR description shows the suite passing under bun bd and failing under USE_SYSTEM_BUN=1.

Comment thread src/runtime/webcore/Body.rs Resolved
Comment thread src/runtime/webcore/Blob.rs Resolved
Comment thread src/runtime/shell/states/Cmd.rs Resolved
…fer error wording; test the Bun.write guard

A body can reach action != None with readable/promise/on_receive_value all
clear (res.body then res.text() deinits locked.readable, sets action=GetText,
returns without setting promise); the fetch tasklet then delivers via its own
readable_stream_ref and never reaches resolve(), so a hook installed on that
state would never fire. Match the to_readable_stream/tee guards and refuse.

The mid-buffer error message now says 'body' rather than 'Response body' since
a server-side Request can reach the same path.

Add a test that parks the shell via .run() and asserts Bun.write(path, res)
throws ERR_BODY_ALREADY_USED while the shell still settles with the full body.
Comment thread src/runtime/webcore/Body.rs Resolved
res.bodyUsed and the .clone() pre-check go through body_stream_check, the one
Locked-body used-guard the on_receive_value sweep missed. Fold the receiver
into the action guard so bodyUsed/clone agree with is_disturbed/to_readable_stream/tee
while the shell is parked.
Comment thread src/runtime/webcore/Blob.rs Resolved
@robobun

robobun commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator Author

Diff is green locally: the 13 stdin from Request/Response tests pass under bun bd and 12 fail under USE_SYSTEM_BUN=1 (the small-body control passes both); full bunshell.test.ts, body.test.ts and html-rewriter.test.js pass with no regressions.

The last four Buildkite builds (80394, 80880, 81094, 81234) have only failed on build-bun/build-cpp lane timeouts and unrelated flakes (node-dns, napi, fastutf8stream-reopen, inspect EADDRINUSE). None of the failing lanes ran bunshell.test.ts or touched the changed code paths. Ready for a maintainer to merge.

@robobun

robobun commented Sep 13, 2026

Copy link
Copy Markdown
Collaborator Author

Closing as part of a cleanup of stale pull requests. This PR has had no new commits since 2026-07-25, it conflicts with main, and its last CI run failed. This is not a judgment on the fix itself. If the problem still reproduces on a current build, reopen this PR after a rebase or open a new one against main.

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.

2 participants