Skip to content

Bun.serve: survive aborted uploads when responding with a req.body.tee() branch - #33778

Merged
Jarred-Sumner merged 4 commits into
mainfrom
claude/farm-9d2eaba5/tee-branch-torn-controller
Jul 8, 2026
Merged

Jarred-Sumner merged 4 commits into
mainfrom
claude/farm-9d2eaba5/tee-branch-torn-controller

Conversation

@robobun

@robobun robobun commented Jul 8, 2026

Copy link
Copy Markdown
Collaborator

What

const [a, b] = req.body.tee(); return new Response(a) followed by the client aborting the upload (closed tab, curl ^C, lost network) SIGABRTs the whole server process.

Repro

const srv = Bun.serve({
  port: 0, idleTimeout: 0,
  async fetch(req) {
    if (!req.body) return new Response("nobody");
    const [a, b] = req.body.tee();
    b.getReader().read().catch(() => {});
    return new Response(a);
  },
});
// POST a few chunks of a content-length body, destroy the socket mid-upload.
// Within a few dozen aborts: SIGABRT.

Assert build:

SHOULD NEVER BE REACHED
src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp(55)
Bun::WebStreams::defaultControllerOf(JSReadableStream *)

Cause

readableStreamDefaultTee creates two branch streams, each with a ControllerKind::Default controller, and registers the onDefaultTeeReaderClosedRejected / onDefaultTeeReadChunkMicrotask reactions on the source reader.

When the server sends branch a as the response body, readStreamIntoSink pumps it into the HTTP response sink. That pump's finally step (rsisFinally, and resumableReleaseReader for the resumable-sink pump) calls clearStreamControllerSlots(branch), which sets branch->m_controllerKind = ControllerKind::None and clears branch->m_controller.

When the client then aborts the upload mid-body, the request-body source stream errors, rejecting the tee reader's closedPromise. The queued defaultTeeReaderClosedRejected reaction runs and calls defaultControllerOf(teeState->m_branch1.get()), which RELEASE_ASSERTs on a non-Default controller kind. The same race exists for the tee's chunk microtask and read-request closeSteps, and for the byte-tee equivalents.

Fix

Add null-safe branch-controller recovery (teeBranchDefaultController / teeBranchByteController) and use it in every tee reaction that operates on teeState->m_branch{1,2}. A branch whose controller has been torn down by a Bun consumer is terminal; the spec AOs (ReadableStreamDefaultControllerError/Close/Enqueue and byte equivalents) would no-op on it anyway, so the reaction simply skips that branch.

Verification

  • New test in test/js/bun/http/serve.test.ts spawns a server that returns a req.body.tee() branch and hits it with 40 aborted uploads. Without the fix: SIGABRT (exit 134) 5/5 on the debug build within the first few iterations. With the fix: exits 0 with empty stderr, 3/3.
  • test/js/third_party/wpt-streams/wpt-streams.test.ts: 1175 pass / 0 fail.
  • test/js/web/streams/streams.test.js: no new failures (2 pre-existing timeouts also present on main).
  • test/js/bun/spawn/spawn-stdin-readable-stream.test.ts (uses tee): 25 pass / 0 fail.

…e() branch

When a tee() branch is returned as a Response body, readStreamIntoSink
consumes it and clears the branch's controller slot in its finally step.
If the client aborts the upload, the tee's queued reader-closed / chunk
reactions run afterwards and call defaultControllerOf(branch) on a
stream whose controller kind is now None, hitting a
RELEASE_ASSERT_NOT_REACHED and aborting the server process.

Add null-safe branch-controller recovery in every tee reaction (default
and byte, chunk/close/error paths) so a torn-down branch is simply
skipped; the spec AOs would no-op on a terminal stream anyway.
@robobun

robobun commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status: diff is green; CI red is unrelated flake. Ready for maintainer review/merge.

Reproduced: 5/5 on the debug build; defaultControllerOf() asserts at ReadableStreamOperations.cpp:55 within the first few aborted uploads.

Gate proof (against origin/main's src/):

  • without fix → subprocess SIGABRT (exit 134, SHOULD NEVER BE REACHED)
  • with fix → SURVIVED 40 true, exit 0, empty stderr (3/3)

CI status:

  • build 70597: only error was test/regression/issue/26030.test.ts (MySQL docker container health-check timeout on 3.23 x64-baseline).
  • build 70611: only error was test/napi/napi.test.ts napi_wrap > has the right lifetime on Windows 2019 x64 ("Condition was not met after 100 GC attempts"); same test is also in the flaky list at 3 retries on x64-baseline.
  • My new tests (serve.test.ts "survives aborted uploads..." and the spawn-stdin byte-tee test) passed on every lane in both builds.
  • wpt-streams (1175 tests) passes locally.

Neither failure touches streams, tee, or Bun.serve; both are known-flaky infra/GC-timing tests on lanes this diff doesn't affect.

@github-actions github-actions Bot added the claude label Jul 8, 2026
@robobun

robobun commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:08 PM PT - Jul 8th, 2026

⏳ @robobun, your commit 16b7685 is still building in Build #70611, but has 1 failures so far (All Failures):

@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 9941b4b1-5055-45b6-adf2-ed7d0683e24c

📥 Commits

Reviewing files that changed from the base of the PR and between 969164a and 16b7685.

📒 Files selected for processing (1)
  • test/js/bun/spawn/spawn-stdin-readable-stream.test.ts

Walkthrough

This PR makes tee-branch controller recovery and downstream stream operations null-safe when a branch controller has already been cleared, and adds regression tests for aborted uploads and tee() behavior after stdin subprocess exit.

Changes

Tee branch controller null-safety

Layer / File(s) Summary
Controller recovery helpers
src/jsc/bindings/webcore/streams/JSReadRequest.cpp, src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp
defaultControllerOf/byteControllerOf and the tee-branch recovery helpers return nullptr when the controller kind does not match.
Close-step guards for tee branches
src/jsc/bindings/webcore/streams/JSReadRequest.cpp
closeSteps for JSReadRequest and JSReadIntoRequest caches tee-branch controllers and conditionally closes or responds only when the controller exists and the branch is not canceled.
Default tee microtask guards
src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp
defaultTeeChunkStepsMicrotask and defaultTeeReaderClosedRejected guard default-stream error and enqueue calls with null checks on recovered controllers.
Byte tee microtask guards
src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp
byteTeeChunkStepsMicrotask and byteTeeReaderClosedRejected guard byte-stream error and enqueue calls with null checks on recovered controllers.
BYOB read-into guards and regression tests
src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp, test/js/bun/http/serve.test.ts, test/js/bun/spawn/spawn-stdin-readable-stream.test.ts
byteTeeReadIntoChunkStepsMicrotask guards BYOB and other-branch error/respond/enqueue calls, and the new tests exercise aborted uploads and tee() behavior when upstream completion happens after stdin subprocess exit.

Suggested reviewers: alii

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main fix: surviving aborted uploads with a req.body.tee() branch.
Description check ✅ Passed The description covers the bug, cause, fix, and verification, though its headings do not exactly match the repository template.
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.

@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/jsc/bindings/webcore/streams/JSReadRequest.cpp`:
- Around line 34-46: The tee-branch helper names in JSReadRequest.cpp are
misleading because they reuse defaultControllerOf/byteControllerOf for a
null-safe contract that differs from the assert-on-mismatch helpers in
ReadableStreamOperations.cpp. Rename these helpers to teeBranchDefaultController
and teeBranchByteController, and update the two call sites to match, so the name
reflects the actual behavior and avoids semantic collisions with the sibling
file. Keep the contract consistent with the tee-branch helpers already used
elsewhere.

In `@test/js/bun/http/serve.test.ts`:
- Around line 3211-3227: The test in serve.test.ts uses a fixed 20ms sleep after
the abort loop, which is flaky and violates the “await the condition, not time”
rule. Replace the hardcoded timeout with waiting on a real completion signal
from the request/abort path, such as a counter or promise tied to the fetch
handler’s teardown/finally work, so the test only proceeds once the async
teardown from the last iteration has actually finished. Use the existing loop
around net.connect and the “SURVIVED” assertion to locate the spot to make the
condition-based wait.
- Around line 3190-3194: The inline comment in the serve test is too long and
includes bug history that should be moved out of the code; shorten the note near
the `req.body.tee()` / `new Response(a)` case to at most 3 lines and keep only
the durable, non-obvious behavior being documented. Remove the detailed crash
narrative about `RELEASE_ASSERT`, `defaultControllerOf()`, and SIGABRT, and keep
a concise comment that identifies the abort/tee interaction the test is
covering.
🪄 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: 409ae6f7-5058-416d-b4fa-354b489957f9

📥 Commits

Reviewing files that changed from the base of the PR and between 332f744 and 601eb80.

📒 Files selected for processing (3)
  • src/jsc/bindings/webcore/streams/JSReadRequest.cpp
  • src/jsc/bindings/webcore/streams/ReadableStreamOperations.cpp
  • test/js/bun/http/serve.test.ts

Comment thread test/js/bun/http/serve.test.ts Resolved
Comment thread test/js/bun/http/serve.test.ts 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 `@src/jsc/bindings/webcore/streams/JSReadRequest.cpp`:
- Around line 31-46: The tee branch controller helpers are duplicated in this
translation unit and in ReadableStreamOperations.cpp, which risks the recovery
logic drifting between files. Move teeBranchDefaultController and
teeBranchByteController, along with their shared comment, into a common
streams-internal header or shared helper location, then have both
JSReadRequest.cpp and ReadableStreamOperations.cpp include and use that single
implementation instead of keeping separate static copies.
🪄 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: 7d22e2d6-18ee-4dfa-b1ca-088c8b489ea0

📥 Commits

Reviewing files that changed from the base of the PR and between 601eb80 and 969164a.

📒 Files selected for processing (2)
  • src/jsc/bindings/webcore/streams/JSReadRequest.cpp
  • test/js/bun/http/serve.test.ts

The existing serve.test.ts case exercises the default-tee
reader-closed-rejected path (ReadableStreamOperations.cpp:55). This adds
a deterministic, no-network test.each over {bytes,default} x {error,close}
using Bun.spawn stdin as the native sink, covering the byte-tee assert
at ReadableStreamOperations.cpp:70 and the read-request closeSteps at
JSReadRequest.cpp:40.
@Jarred-Sumner
Jarred-Sumner merged commit c03fea0 into main Jul 8, 2026
71 of 75 checks passed
@Jarred-Sumner
Jarred-Sumner deleted the claude/farm-9d2eaba5/tee-branch-torn-controller branch July 8, 2026 20:21
Jarred-Sumner pushed a commit that referenced this pull request Jul 8, 2026
…rs down the readable (#33781)

### What

`Bun.serve` responding with `req.body.pipeThrough(transform)` where the
transformer's async `transform()` calls `controller.error()` (a
streaming validator rejecting a payload) segfaults the whole server
process when the client aborts the upload mid-body. The same applies to
`controller.enqueue()`, `controller.terminate()` and
`controller.desiredSize`.

### Repro

```js
const srv = Bun.serve({
  port: 0, idleTimeout: 0,
  async fetch(req) {
    if (!req.body) return new Response("nobody");
    return new Response(req.body.pipeThrough(new TransformStream({
      async transform(_ch, c) { await new Promise(r => setTimeout(r, 2)); c.error(new Error("bad payload")); },
    })));
  },
});
// POST a few chunks of a content-length body, destroy the socket mid-upload. Within a few
// dozen aborts: SIGSEGV (release) / SIGABRT (asserts on).
```

Assert build:

```
ASSERTION FAILED: readable && readable->m_controllerKind == ControllerKind::Default
src/jsc/bindings/webcore/streams/TransformStreamOperations.cpp(34)
JSReadableStreamDefaultController *Bun::WebStreams::transformReadableController(JSTransformStream *)
```

Release build: `Segmentation fault at address 0x88`.

### Cause

When a Bun native sink (`Bun.serve` response body, `Bun.spawn` stdin)
consumes a `TransformStream`'s readable side and the consumer aborts,
the sink pump's finally step (`rsisFinally` / `resumableReleaseReader` /
`readDirectStreamCloseImpl` in `BunStreamSource.cpp`) runs
`clearStreamControllerSlots()` on the readable, setting
`m_controllerKind = None` and clearing `m_controller`. The
`TransformStream` still holds that readable via `m_readable`, so a later
controller method call (from an async `transform()`/`flush()` that
resumed after the abort, or from a queued sink reaction) walks
`transformReadableController()`, which asserts `ControllerKind::Default`
and then `uncheckedDowncast`s a null slot. Every caller immediately
dereferences the result.

This is the TransformStream sibling of the tee-branch crash addressed in
#33778.

### Fix

Make both `transformReadableController()` copies null-safe (return
`nullptr` when the readable's controller slot has been cleared) and make
every call site skip the readable-side abstract operation on null:
`transformStreamError`,
`transformStreamDefaultControllerEnqueue`/`Terminate`, the `desiredSize`
getter, and the four sink abort/close reaction handlers. The spec AOs
(`ReadableStreamDefaultControllerError`/`Close`/`Enqueue`) would no-op
on a non-`Readable` stream anyway; the writable-side error/unblock still
runs. This mirrors the `teeBranch*Controller` approach from #33778.

### Verification

New test in `test/js/web/streams/streams.test.js` passes `ts.readable`
as stdin to a child process, kills the child, awaits the sink teardown
(`ts.readable.locked === false`), then exercises all four controller
members.

Without the fix: SIGABRT on the first action, 3/3 on the debug build.
With the fix: `desiredSize` returns `null`, `enqueue()` throws
`TypeError`, `terminate()` and `error()` return normally; exit 0, 3/3.

- `test/js/third_party/wpt-streams/wpt-streams.test.ts`: 1175 pass / 0
fail.
- `test/js/web/streams/streams.test.js`: no new failures (2 pre-existing
timeouts also present on main).
- `test/js/bun/spawn/spawn-stdin-readable-stream.test.ts`: 25 pass / 0
fail.
- `test/js/web/streams/transform-stream-leak.test.ts`: 3 pass / 0 fail.
- Original Bun.serve + `node:net` client-abort loop (400 iterations):
survives.
robobun added a commit that referenced this pull request Jul 18, 2026
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