Repository navigation
Bun.serve: survive aborted uploads when responding with a req.body.tee() branch - #33778
Conversation
…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.
|
Status: diff is green; CI red is unrelated flake. Ready for maintainer review/merge. Reproduced: 5/5 on the debug build; Gate proof (against origin/main's
CI status:
Neither failure touches streams, tee, or |
|
Updated 1:08 PM PT - Jul 8th, 2026
⏳ @robobun, your commit 16b7685 is still building in
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: 📒 Files selected for processing (1)
WalkthroughThis 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. ChangesTee branch controller null-safety
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
src/jsc/bindings/webcore/streams/JSReadRequest.cppsrc/jsc/bindings/webcore/streams/ReadableStreamOperations.cpptest/js/bun/http/serve.test.ts
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
src/jsc/bindings/webcore/streams/JSReadRequest.cpptest/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.
…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.
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
Assert build:
Cause
readableStreamDefaultTeecreates two branch streams, each with aControllerKind::Defaultcontroller, and registers theonDefaultTeeReaderClosedRejected/onDefaultTeeReadChunkMicrotaskreactions on the source reader.When the server sends branch
aas the response body,readStreamIntoSinkpumps it into the HTTP response sink. That pump's finally step (rsisFinally, andresumableReleaseReaderfor the resumable-sink pump) callsclearStreamControllerSlots(branch), which setsbranch->m_controllerKind = ControllerKind::Noneand clearsbranch->m_controller.When the client then aborts the upload mid-body, the request-body source stream errors, rejecting the tee reader's
closedPromise. The queueddefaultTeeReaderClosedRejectedreaction runs and callsdefaultControllerOf(teeState->m_branch1.get()), whichRELEASE_ASSERTs on a non-Defaultcontroller kind. The same race exists for the tee's chunk microtask and read-requestcloseSteps, and for the byte-tee equivalents.Fix
Add null-safe branch-controller recovery (
teeBranchDefaultController/teeBranchByteController) and use it in every tee reaction that operates onteeState->m_branch{1,2}. A branch whose controller has been torn down by a Bun consumer is terminal; the spec AOs (ReadableStreamDefaultControllerError/Close/Enqueueand byte equivalents) would no-op on it anyway, so the reaction simply skips that branch.Verification
test/js/bun/http/serve.test.tsspawns a server that returns areq.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.