Skip to content

fetch: settle buffered body promises when an aborted request still has a streaming request body - #32130

Merged
Jarred-Sumner merged 2 commits into
mainfrom
farm/7e5640d9/fetch-abort-streaming-body-zombie
Jun 12, 2026
Merged

Jarred-Sumner merged 2 commits into
mainfrom
farm/7e5640d9/fetch-abort-streaming-body-zombie

Conversation

@robobun

@robobun robobun commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator

Repro

const server = Bun.serve({
  port: 0,
  fetch: () =>
    new Response(new ReadableStream({
      pull(c) { c.enqueue(new Uint8Array(1024)); return new Promise(() => {}); },
    })),
});

const controller = new AbortController();
const res = await fetch(server.url, {
  method: "POST",
  signal: controller.signal,
  body: new ReadableStream({
    pull(c) { c.enqueue(new Uint8Array(64)); return new Promise(() => {}); },
  }),
});

const p = res.arrayBuffer();
controller.abort();
await p; // hangs forever on 1.3.x and current main

await p never settles. The request is leaked permanently: under load (a client that uploads while downloading and aborts, e.g. proxies or streaming API clients), every such abort strands one request, and once enough accumulate all later fetches hang too.

Cause

When the HTTP thread fails an in-flight request (abort, timeout, connection error), FetchTasklet::on_body_received handles the terminal failure result. If the request body was a JS ReadableStream whose sink was still active, the failure path did:

if let Some(sink) = self.sink_mut() {
    sink.cancel(js_err);
    return Ok(());   // <- skips erroring the response body
}

The early return skipped the current_response_mut() branch that rejects a buffered body promise (arrayBuffer/text/json), so that promise stayed pending forever. Failure results are terminal (to_result forces has_more = false once fail is set), so no later update can ever settle it. The bug only triggers when the response arrives while the upload stream is still open; consumers reading res.body directly were unaffected (the readable-stream branch above it errors the stream before the early return).

This was ported faithfully from the Zig implementation, which has the same early return, so 1.3.x releases are affected too.

Fix

Remove the early return: materialize the error for the sink, reject the buffered response body, and cancel the sink last (ResumableSink::cancel invokes the stream's JS cancel callback synchronously via run_callback, so it runs after the tasklet state is settled).

Also restores the HTTP-thread debug+ASAN assertion (present in the Zig implementation, dropped in the port) that every socket pointer in the abort tracker points at live memory, checked around each loop tick. A stale entry there is the likely mechanism behind a family of release-build segfaults in drainQueuedShutdowns -> us_internal_ssl_socket_close -> us_internal_set_loop_ssl_data reported from 1.3.x builds; with the assertion back, any close path that forgets unregister_abort_tracker fails loudly in debug CI at the tick that leaked instead of segfaulting at a later abort.

Verification

New test test/js/web/fetch/fetch-abort-stream-body.test.ts ("abort mid-response rejects buffered body promises while the request body stream is active") runs the repro in a subprocess fixture for both arrayBuffer() and text().

  • Unfixed (USE_SYSTEM_BUN=1, also reproduced on 1.3.14): fixture prints arrayBuffer timed out / text timed out, test fails in ~2.5s.
  • Fixed: both reject with AbortError, test passes.

A stress run (60 concurrent workers doing this shape in a loop) wedged every worker within seconds on the unfixed build and completes cleanly on the fixed one. The wedge reproduces identically on bun 1.3.14, and ~200k aborted-fetch iterations across keepalive/redirect/proxy/TLS/h2 variants ran clean under ASAN with the restored tracker assertion enabled.

…s a streaming body

When a fetch with an in-flight ReadableStream request body was aborted
after response headers arrived, the terminal failure callback returned
right after cancelling the request-body sink and never errored the
response body value. A pending arrayBuffer()/text()/json() promise then
stayed unsettled forever, permanently leaking the request.

Error the buffered body before cancelling the sink (cancel runs the
stream's JS cancel callback synchronously, so it goes last).

Also restore the HTTP-thread debug+ASAN check that every abort-tracker
socket pointer is alive around each loop tick; the Zig implementation
had this and the port dropped it.
@robobun

robobun commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:52 PM PT - Jun 11th, 2026

❌ @robobun, your commit b3da0d7 has 1 failures in Build #61942 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 32130

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

bun-32130 --bun

@coderabbitai

coderabbitai Bot commented Jun 11, 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: 5da85a54-8b7b-4506-b932-16ddea8a60cf

📥 Commits

Reviewing files that changed from the base of the PR and between f8723b1 and cb2632e.

📒 Files selected for processing (4)
  • src/http/HTTPThread.rs
  • src/runtime/webcore/fetch/FetchTasklet.rs
  • test/js/web/fetch/fetch-abort-buffered-body-fixture.ts
  • test/js/web/fetch/fetch-abort-stream-body.test.ts

Walkthrough

This PR fixes a promise-pending hang when aborting a fetch request that has a streaming request body. The core fix reorders error handling in FetchTasklet::on_body_received to settle response promises before cancelling the request-body sink. Runtime invariant checking is added to the HTTP event loop to detect abort-tracker corruption. New tests validate the fix.

Changes

Fetch abort with streaming request body

Layer / File(s) Summary
Fetch tasklet error handling reordering
src/runtime/webcore/fetch/FetchTasklet.rs
In on_body_received failure path, deferred request-body sink cancellation until after response error/promise settlement. Removed early return and guarded sink cancellation so it runs only when error exists, preventing arrayBuffer/text promises from remaining pending after abort.
HTTP thread abort-tracker invariant checker
src/http/HTTPThread.rs
Added debug-only assert_abort_tracker_sockets_alive() helper that uses ASAN to verify socket memory is unpoisoned. Invoked before and after each uws_loop tick to detect use-after-free at the loop iteration where corruption would first manifest.
Abort behavior test fixture and case
test/js/web/fetch/fetch-abort-buffered-body-fixture.ts, test/js/web/fetch/fetch-abort-stream-body.test.ts
New fixture that spawns server keeping response body open while client aborts during streaming request upload. Validates arrayBuffer and text promises are immediately rejected with AbortError instead of pending. New concurrent test spawns fixture subprocess and asserts clean exit with expected rejection messages.
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main fix: settling buffered body promises when an aborted fetch request has a streaming request body.
Description check ✅ Passed The description includes both required sections with substantial detail: a 'Repro' section demonstrating the issue, 'Cause' explaining the root problem, 'Fix' describing the solution, and 'Verification' detailing test coverage.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

@robobun

robobun commented Jun 11, 2026

Copy link
Copy Markdown
Collaborator Author

CI status: the new test passes on every lane in both runs. The remaining red is unrelated to this diff:

  • build 61932: darwin timeouts in terminal.test.ts (PTY spawn) and node-http-backpressure-max.test.ts (4GB transfer, success path only), a SIGTRAP in encode-bad-chunks.test.ts on x64-baseline (no fetch usage, release lane), and an install-migration failure the pipeline itself tagged flaky.
  • build 61942 (retrigger): two pipeline-tagged flakes on Windows (jsc-stress wasm timeout, hot.test.ts), plus init.test.ts failing on the darwin-26 aarch64 runner because bun init scaffolds a CLAUDE.md whenever a claude binary is in PATH, and that runner apparently has one installed now. That failure is runner-environment drift and will hit any PR scheduled onto that machine.

This change only touches the fetch failure path (on_body_received with !success) and a debug-only assertion, so none of these tests can reach it. Not pushing further retriggers; ready for review.

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