Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/runtime/server/RequestContext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2317,15 +2317,17 @@ where

// if we cannot, we have to reject pending promises
// first, we reject the request body promise
// SAFETY: BACKREF
let global_this = self.server().global_this();
let readable = self.request_body_readable_stream_ref.get(global_this);
if let Some(body) = self.request_body_mut() {
// User called .blob(), .json(), text(), or .arrayBuffer() on the Request object
// but we received nothing or the connection was aborted
if matches!(body, Body::Value::Locked(_)) {
// SAFETY: BACKREF
let global_this = self.server().global_this();
body.to_error_instance(
body.to_error_instance_with_readable(
Body::ValueError::AbortReason(jsc::CommonAbortReason::ConnectionClosed),
global_this,
readable,
)?;
return Ok(true);
}
Expand All @@ -2335,7 +2337,6 @@ where
// Locked check above falls through. Error the ByteStream via our own
// strong ref instead so a pending read rejects rather than hanging.
if self.request_body_readable_stream_ref.has() {
let global_this = self.server().global_this();
let strong = core::mem::take(&mut self.request_body_readable_stream_ref);
if let Some(readable) = strong.get(global_this) {
readable.value.ensure_still_alive();
Expand Down
33 changes: 29 additions & 4 deletions src/runtime/webcore/Body.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1330,6 +1330,21 @@ impl Value {
&mut self,
err: ValueError,
global: &JSGlobalObject,
) -> JsTerminated<()> {
self.to_error_instance_with_readable(err, global, None)
}

/// [`to_error_instance`] for callers that own the body's JS wrapper.
///
/// Once `get_body` has migrated `Locked.readable` into the wrapper's
/// traced `m_stream` slot (see [`BodyMixin::check_body_stream_ref`]),
/// `locked.readable` is empty; `owned_readable` supplies the stream for
/// the disturbed check and error delivery in that state.
Comment thread
robobun marked this conversation as resolved.
Resolved
pub(crate) fn to_error_instance_with_readable(
&mut self,
err: ValueError,
global: &JSGlobalObject,
owned_readable: Option<ReadableStream>,
) -> JsTerminated<()> {
if let Value::Locked(_) = self {
// reshaped for borrowck + E0509 (`Value` has `Drop`) — `mem::take`
Expand All @@ -1339,16 +1354,17 @@ impl Value {
Value::Locked(l) => core::mem::take(l),
_ => unreachable!(),
};
let readable = locked.readable.get(global).or(owned_readable);
let was_disturbed = !locked.action.is_none()
|| locked.promise.is_some()
|| locked.readable.is_disturbed(global);
|| readable.as_ref().is_some_and(|r| r.is_disturbed(global));
*self = Value::Error(err);
let Value::Error(err_ref) = self else {
unreachable!()
};

// `deinit` must run on every exit incl. `?` paths.
let strong_readable =
let _strong_readable =
scopeguard::guard(core::mem::take(&mut locked.readable), |mut r| r.deinit());

if let Some(promise_value) = locked.promise.take() {
Expand All @@ -1368,7 +1384,7 @@ impl Value {

// The Promise version goes before the ReadableStream version incase the Promise version is used too.
// Avoid creating unnecessary duplicate JSValue.
if let Some(readable) = strong_readable.get(global) {
if let Some(readable) = readable {
// BACKREF: see `Source::bytes()` — payload live for the
// lifetime of the ReadableStream JS wrapper.
if let Some(bytes) = readable.ptr.bytes() {
Expand Down Expand Up @@ -1799,7 +1815,16 @@ pub(crate) trait BodyMixin: BodyOwnerJs + Sized {
return Ok(readable.value);
}
}
self.get_body_value().to_readable_stream(global_this)
let stream = self.get_body_value().to_readable_stream(global_this)?;
// `to_readable_stream` leaves a `Strong<ReadableStream>` in
// `Locked.readable` when it materializes a Blob/InternalBlob/string
// body or a not-yet-streamed `Locked` body. The wrapper's traced
// `m_stream` slot is the owner once a JS wrapper exists; holding the
// Strong here roots the stream (and its captured async context)
// independently of the wrapper, which becomes an uncollectable cycle
// when that async context references this Response/Request.
Comment thread
robobun marked this conversation as resolved.
Resolved
self.check_body_stream_ref(global_this);
Ok(stream)
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
}

/// <https://fetch.spec.whatwg.org/#dom-body-textstream>
Expand Down
5 changes: 4 additions & 1 deletion src/runtime/webcore/Response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,10 @@ impl BodyAbortListener {
}
let err = BodyValueError::JSValue(bun_jsc::strong::Optional::create(reason, &global));
// R-2: re-derive after `error()` ran JS.
let _ = response.get_body_value().to_error_instance(err, &global);
let readable = response.get_body_readable_stream(&global);
let _ = response
.get_body_value()
.to_error_instance_with_readable(err, &global, readable);
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/webcore/fetch/FetchTasklet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,10 +846,11 @@ impl FetchTasklet {
if let Some(response) = self.current_response_mut() {
// body value now owns the error
let err = scopeguard::ScopeGuard::into_inner(err);
let readable = response.get_body_readable_stream(&global_this);
let body = response.get_body_value();
// Body.rs aliases its `JsTerminated<T>` to `JsResult<T>` for
// now; narrow back to the real `JsTerminated` here.
body.to_error_instance(err, &global_this)
body.to_error_instance_with_readable(err, &global_this, readable)
.map_err(|_| bun_jsc::JsTerminated::JSTerminated)?;
}
// Cancel the request-body sink last: closing the sink signal fires
Expand Down
39 changes: 39 additions & 0 deletions test/regression/issue/29267/29267-fixture.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

49 changes: 49 additions & 0 deletions test/regression/issue/29267/29267.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// https://github.com/oven-sh/bun/issues/29267
//
// Next.js App Router SSR under `bun --bun next start` leaked one
// Strong<ReadableStream> per request. Next's dedupe-fetch stores the fetch
// Response promise in a React.cache()-scoped map that lives inside the
// request's AsyncLocalStorage store, and Next's cloneResponse reads `.body`
// on a Response whose body is a buffered ArrayBuffer. Reading `.body` on a
// Blob/InternalBlob/string-backed Response materializes a ReadableStream and
// cached a Strong handle to it in `Body::PendingValue.readable`; that Strong
// was only migrated into the wrapper's traced `m_stream` slot from
// construct/to_js/clone, not from the `.body` getter. The stream's captured
// async context reached back to the Response, so the Strong formed an
// uncollectable cycle and every request's ALS store (tens to hundreds of KB)
// was retained forever.

import { expect, test } from "bun:test";
import { bunEnv, bunExe, isASAN, isDebug } from "harness";
import path from "node:path";

test("Response.body on a buffered body does not root the stream when the async context references the Response", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), path.join(import.meta.dir, "29267-fixture.ts")],
env: bunEnv,
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);

const jsonLine = stdout.split("\n").find(l => l.startsWith("{"));
expect(jsonLine).toBeDefined();
const result = JSON.parse(jsonLine!);

// Before the fix `protectedRS` equals N (one Strong<ReadableStream> per
// iteration); after the fix it is a small constant. N/2 separates the two
// with wide margin while tolerating a handful of unrelated transients.
expect(result.protectedRS).toBeLessThan(result.N / 2);
// The per-iteration objects should be collected, not accumulate.
expect(result.response).toBeLessThan(result.N / 2);
expect(result.readableStream).toBeLessThan(result.N / 2);

// ~60 KB retained per iteration pre-fix (50 KB ALS payload + 10 KB body).
// ASAN quarantine and debug-heap padding inflate post-GC heapSize, so the
// ceiling here is well under the unfixed ~30 MB but above sanitizer noise.
const heapCeilingMB = isASAN || isDebug ? 14 : 7;
expect(result.heapMB).toBeLessThan(heapCeilingMB);
Comment thread
robobun marked this conversation as resolved.
Resolved

expect(stderr).toBe("");
expect(exitCode).toBe(0);
});
Loading