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
55 changes: 30 additions & 25 deletions src/runtime/webcore/ByteStream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,7 @@ pub(crate) type Source = readable_stream::NewSource<ByteStream>;
/// A network body producer's (fetch, S3) hold on the stream it feeds: a counted ref on the stream's
/// `Source`, so delivery and unhooking go through memory the producer keeps alive rather than the
/// JS wrapper (which the VM's last sweep destroys in no particular order), plus the parked bit of
/// the receive backpressure. The ref roots the wrapper except while parked, so an unread stream
/// can be collected (`SourceHandle::consumer_collected`).
/// the receive backpressure. It roots the wrapper only for a native sink or a whole-body read.
#[derive(Default)]
pub(crate) struct ProducerHold {
source: Cell<Option<core::ptr::NonNull<Source>>>,
Expand All @@ -83,7 +82,7 @@ pub(crate) enum AfterDelivery {
Resume,
/// At the mark with a back-pressured sink: it resumes the producer when it drains.
Pause,
/// At the mark and nothing reads: pause, release the loop, leave the stream collectable.
/// At the mark and nothing reads: pause, release the loop.
Park,
}

Expand All @@ -97,8 +96,28 @@ impl ProducerHold {
// SAFETY: fn contract; the ref keeps the Source alive past this call.
unsafe {
let source = Source::from_context_ptr(bytes);
(*source).increment_count();
self.source.set(core::ptr::NonNull::new(source));
// Before the ref, so `increment_count` only roots a wrapper that stays rooted.
self.sync_wrapper_root();
(*source).increment_count();
}
}

fn sync_wrapper_root(&self) {
let Some(source) = self.source.get() else {
return;
};
let source = source.as_ptr();
// SAFETY: live through our ref. The caller may hold the `&ByteStream` of this very source
// (the chunk it just delivered): shared reads of its cells here, and the root is a
// separate field written through the raw pointer.
unsafe {
let bytes = &(*source).context;
if bytes.sink.get().is_some() || bytes.buffer_action.get().is_some() {
Source::root_wrapper(source);
} else {
Source::unroot_wrapper(source);
Comment on lines +116 to +119

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.

🟡 (optional) High-throughput fetch clients that touch res.body and then drop the Response now lose a keep-alive connection per request whenever a GC lands before the short body finishes. The unroot at ByteStream.rs:119 makes the wrapper collectable as soon as JS drops it; the sweep then reaches on_body_stream_collected (FetchTasklet.rs:1767) and abort_transport closes the HTTP/1.1 socket the pool would have reused after draining. On the base the wrapper stayed rooted under the mark, the body drained, and the connection returned to the pool. Fix: for a collected stream whose remaining body is small (under the high-water mark and content-length known), drain to the mark and return the connection to the pool instead of aborting, as undici does; abort only when the remaining body exceeds the drain budget.

Why this was flagged

Trigger: any code that reads res.body (e.g. checks res.body !== null, calls getReader() and releases it, or passes the body to a helper that never reads it) and then drops every reference before the body completes. Common in status probes, HEAD-like GETs, and libraries that access .body eagerly. Rate: once per such fetch; a GC during a body still arriving over several packets is routine under load. Mechanism: hold() at ByteStream.rs:101 now calls sync_wrapper_root, which takes the unroot branch at ByteStream.rs:119 because no sink or buffer_action exists; ReadableStream.rs:1197-1202 downgrades this_jsvalue to Weak. On sweep NewSource finalize runs consumer_collected (streams.rs:1117) -> on_body_stream_collected (FetchTasklet.rs:1767) -> abandon_response_body (FetchTasklet.rs:1931), which calls abort_transport, closing the socket. On the base branch the wrapper stayed Strong (increment_count at ReadableStream.rs:1169-1171) until buffered_len reached BODY_HIGH_WATER_MARK, so a short body completed and the keep-alive connection was reused. The PR calls this an accepted downside, but at…

Verification: nit — acknowledged in diff: the PR description's "Downsides" paragraph states exactly this ("A touched stream dropped while a short body still arrives is aborted if a collection lands first. On HTTP/1.1 that closes a connection the pool would have reused"), and the bound is accurate. Trigger: JS accesses res.body (or getReader() without reading/cancelling), drops every reference, and a GC…

}
}
}

Expand All @@ -107,7 +126,7 @@ impl ProducerHold {
}

/// The held stream, pinned for the guard's life: a consumer inside `on_data` can cancel the
/// producer (which drops the hold), and while parked the wrapper is not rooted.
/// producer (which drops the hold), and the wrapper is not always rooted.
pub(crate) fn bytes(&self) -> Option<PinnedBytes> {
let source = self.source.get()?;
// SAFETY: live through our ref; no borrow of the source exists yet.
Expand All @@ -133,7 +152,8 @@ impl ProducerHold {
drop(self.take());
}

pub(crate) fn after_delivery(bytes: &ByteStream) -> AfterDelivery {
pub(crate) fn after_delivery(&self, bytes: &ByteStream) -> AfterDelivery {
self.sync_wrapper_root();
if bytes.buffered_len() < bun_http::signals::BODY_HIGH_WATER_MARK
|| bytes.buffer_action.get().is_some()
{
Expand All @@ -147,28 +167,13 @@ impl ProducerHold {

/// Returns whether this call parked (the caller then releases its loop ref).
pub(crate) fn park(&self) -> bool {
if self.parked.replace(true) {
return false;
}
if let Some(source) = self.source.get() {
// SAFETY: live through our ref. The caller may hold the `&ByteStream` of this very
// source (the chunk it just delivered), which is why this is not a method call.
unsafe { Source::unroot_wrapper(source.as_ptr()) };
}
true
!self.parked.replace(true)
}

/// Returns whether this call unparked (the caller then re-takes its loop ref). Reached from a
/// consumer holding the stream.
/// A consumer attached or took bytes; returns whether this unparked (re-take the loop ref).
pub(crate) fn unpark(&self) -> bool {
if !self.parked.replace(false) {
return false;
}
if let Some(source) = self.source.get() {
// SAFETY: as in `park`.
unsafe { Source::root_wrapper(source.as_ptr()) };
}
true
self.sync_wrapper_root();
self.parked.replace(false)
}
}

Expand Down
11 changes: 4 additions & 7 deletions src/runtime/webcore/ReadableStream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -810,7 +810,7 @@ pub trait SourceContext: Sized {
}

/// The JS wrapper was collected while native refs remain. Runs inside a GC
/// sweep: no JS. `ByteStream` tells a parked producer nobody can read it now.
/// sweep: no JS. `ByteStream` tells its producer nobody can read it now.
fn wrapper_finalized(&mut self) {}

/// `setRefUnrefFn` — default no-op.
Expand Down Expand Up @@ -878,9 +878,7 @@ pub struct NewSource<C: SourceContext> {
/// `Finalized` so [`Self::on_close`] reads `None` instead of a
/// dead-but-unswept cell.
pub this_jsvalue: jsc::JsRef,
/// The producer holding a native ref has parked ([`Self::unroot_wrapper`]):
/// its ref keeps this allocation, not the wrapper, so an unread stream can
/// be collected. Cleared by [`Self::root_wrapper`].
/// The producer's native ref does not root the wrapper ([`Self::unroot_wrapper`]).
pub wrapper_unrooted: Cell<bool>,
/// R-2: written by context methods (`ByteStream::to_any_blob`,
/// `ByteBlobLoader::to_any_blob`) through their parent accessor, so
Expand Down Expand Up @@ -1187,8 +1185,7 @@ impl<C: SourceContext> NewSource<C> {
}
}

/// The producer keeps its native ref but stops rooting the wrapper: nothing
/// is reading, so the stream should be collectable. [`SourceContext::wrapper_finalized`]
/// The producer's ref leaves the wrapper collectable. [`SourceContext::wrapper_finalized`]
/// tells the producer if that happens.
///
/// Takes a raw pointer: the producer reaches this while it holds a `&C` into
Expand All @@ -1205,7 +1202,7 @@ impl<C: SourceContext> NewSource<C> {
}
}

/// Undo [`Self::unroot_wrapper`]: a consumer is reading again.
/// Undo [`Self::unroot_wrapper`]: a consumer that does not hold the wrapper takes the bytes.
///
/// # Safety
/// As [`Self::unroot_wrapper`].
Expand Down
6 changes: 3 additions & 3 deletions src/runtime/webcore/fetch/FetchTasklet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1760,7 +1760,7 @@ impl FetchTasklet {
self.abandon_response_body();
}

/// `SourceHandle::consumer_collected`: the parked stream's wrapper was swept, so nothing
/// `SourceHandle::consumer_collected`: the stream's wrapper was swept, so nothing
/// can read the rest of the body. Inside a GC sweep, like `on_response_finalize`.
pub(crate) fn on_body_stream_collected(&self) {
bun_output::scoped_log!(FetchTasklet, "onBodyStreamCollected");
Expand All @@ -1785,13 +1785,13 @@ impl FetchTasklet {

/// The other half of this rule is in `callback` (HTTP thread).
fn after_body_chunk_delivered(&self, bytes: &crate::webcore::ByteStream) {
use crate::webcore::byte_stream::{AfterDelivery, ProducerHold};
use crate::webcore::byte_stream::AfterDelivery;
bun_output::scoped_log!(
FetchTasklet,
"afterBodyChunkDelivered buffered={}",
bytes.buffered_len()
);
match ProducerHold::after_delivery(bytes) {
match self.response_stream.after_delivery(bytes) {
AfterDelivery::Resume => self.resume_receive(),
AfterDelivery::Pause => self.signal_store.pause_receive(),
AfterDelivery::Park => {
Expand Down
8 changes: 4 additions & 4 deletions src/runtime/webcore/s3/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1375,12 +1375,12 @@ impl S3DownloadStreamWrapper {
/// The other half of this rule is in `S3HttpDownloadStreamingTask::process_http_callback`
/// (HTTP thread).
fn after_chunk_delivered(&self, bytes: &ByteStream) {
use crate::webcore::byte_stream::{AfterDelivery, ProducerHold};
use crate::webcore::byte_stream::AfterDelivery;
let task = self.task.get();
if task.is_null() {
return;
}
match ProducerHold::after_delivery(bytes) {
match self.stream.after_delivery(bytes) {
// SAFETY: see `task`.
AfterDelivery::Resume => unsafe { (*task).resume_receive() },
// SAFETY: see `task`.
Expand All @@ -1389,7 +1389,7 @@ impl S3DownloadStreamWrapper {
// SAFETY: see `task`.
unsafe { (*task).signal_store.pause_receive() };
if self.stream.park() {
// SAFETY: see `task`; `park` touched the stream's source, not the task.
// SAFETY: see `task`.
unsafe { (*task).poll_ref.unref(bun_io::js_vm_ctx()) };
}
}
Expand Down Expand Up @@ -1417,7 +1417,7 @@ impl S3DownloadStreamWrapper {
self.unpark();
}

/// The parked stream's wrapper was collected: nothing can read the rest. Inside a GC sweep;
/// The stream's wrapper was collected: nothing can read the rest. Inside a GC sweep;
/// touches no JS cell.
pub(crate) fn on_stream_collected(&self) {
self.on_stream_cancelled();
Expand Down
161 changes: 161 additions & 0 deletions test/js/web/fetch/fetch-backpressure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,56 @@ describe.concurrent("fetch() receive backpressure — a Response whose body noth
}
});

// An origin whose body stays under the mark, as an event stream does between events: a head and
// one small chunk, then nothing until `trickle()` sends every response one more chunk and
// `finish()` ends them. The origin never closes, so every close it sees is the client's.
const PIECE = 1024;
async function quietOrigin() {
const piece = Buffer.from(`${PIECE.toString(16)}\r\n${Buffer.alloc(PIECE, 65)}\r\n`);
let closed = 0;
let responded = 0;
const responses = new Set<import("node:net").Socket>();
const sockets = new Set<import("node:net").Socket>();
const closeWaiters: [number, () => void][] = [];
const responseWaiters: [number, () => void][] = [];
const srv = createTcpServer(socket => {
sockets.add(socket);
socket.on("error", () => {});
socket.on("close", () => {
closed++;
sockets.delete(socket);
responses.delete(socket);
for (const [n, resolve] of closeWaiters) if (closed >= n) resolve();
});
socket.once("data", () => {
socket.write("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nTransfer-Encoding: chunked\r\n\r\n");
socket.write(piece, () => {
responses.add(socket);
responded++;
for (const [n, resolve] of responseWaiters) if (responded >= n) resolve();
});
});
});
srv.listen(0, "127.0.0.1");
await once(srv, "listening");
const { port } = srv.address() as import("node:net").AddressInfo;
const toEach = (data: string | Buffer) =>
Promise.all(Array.from(responses, socket => new Promise(resolve => socket.write(data, resolve))));
return {
url: `http://127.0.0.1:${port}/`,
respondedTo: (n: number) =>
responded >= n ? Promise.resolve() : new Promise<void>(resolve => responseWaiters.push([n, resolve])),
trickle: () => toEach(piece),
finish: () => toEach("0\r\n\r\n"),
closedAtLeast: (n: number) =>
closed >= n ? Promise.resolve() : new Promise<void>(resolve => closeWaiters.push([n, resolve])),
[Symbol.asyncDispose]: () => {
for (const socket of sockets) socket.destroy();
return new Promise<void>(resolve => srv.close(() => resolve()));
},
};
}

// S3 downloads go through the same HTTP client with their own body producer
// (S3DownloadStreamWrapper). The same rule applies: a reader that stalls pauses the transport,
// an unread stream does not hold the process, and a collected one aborts the download.
Expand Down Expand Up @@ -1652,3 +1702,114 @@ describe.serial("fetch() receive backpressure — an unread body hands its conne
});
}
});

// A body stream nothing can read is collected and its fetch aborted, even under the mark.
// Serial: every test here runs full collections, which would stall the concurrent blocks above.
describe.serial("fetch() receive backpressure — an abandoned body stream under the mark", () => {
const N = 4;
const shapes: [string, (res: Response) => Promise<unknown>, "quiet" | "trickle"][] = [
["res.body touched", async res => res.body, "quiet"],
["getReader(), never read", async res => void res.body!.getReader(), "quiet"],
// A pull that is in flight when the stream is dropped waits for bytes, and holds the
// stream until some arrive for it.
[
"one read(), then releaseLock()",
async res => {
const reader = res.body!.getReader();
await reader.read();
reader.releaseLock();
},
"trickle",
],
["dropped while a reader holds the lock", async res => void (await res.body!.getReader().read()), "trickle"],
];

for (const [name, shape, peer] of shapes) {
test(`${name}, ${peer} peer: the stream is collected and its fetch is aborted`, async () => {
await using origin = await quietOrigin();
// Its own frame, so that nothing on this one still refers to a response afterwards.
async function abandonOne() {
await shape(await fetch(origin.url));
}
for (let i = 0; i < N; i++) await abandonOne();
await origin.respondedTo(N);
if (peer === "trickle") await origin.trickle();
await collectUntil(origin.closedAtLeast(N));
});
}

test("an S3 stream, trickle peer: the stream is collected and its download is aborted", async () => {
await using origin = await quietOrigin();
const s3 = new S3Client({ accessKeyId: "test", secretAccessKey: "test", endpoint: origin.url, bucket: "b" });
// Its own frame: after it returns nothing refers to the stream.
await (async () => {
const reader = s3.file("k").stream().getReader();
await reader.read();
reader.releaseLock();
})();
await origin.respondedTo(1);
await origin.trickle();
await collectUntil(origin.closedAtLeast(1));
});

// The other side of that rule: a consumer is often held by nothing but its own promise, and
// its body must still arrive, through full collections between the pieces of a body that is
// never anywhere near the mark.
const PIECES = 4;
const count = async (chunks: AsyncIterable<{ length: number }>) => {
let total = 0;
for await (const chunk of chunks) total += chunk.length;
return total;
};
const consumers: [string, (res: Response, dir: string) => Promise<number>][] = [
[
"a reader loop",
async res => {
let total = 0;
for (let r, reader = res.body!.getReader(); !(r = await reader.read()).done; ) total += r.value.byteLength;
return total;
},
],
[
"pipeTo()",
async res => {
let total = 0;
await res.body!.pipeTo(new WritableStream({ write: chunk => void (total += chunk.byteLength) }));
return total;
},
],
["tee()", async res => Math.min(...(await Promise.all(res.body!.tee().map(count))))],
["Readable.fromWeb()", res => count(Readable.fromWeb(res.body as any))],
["textStream()", res => count(res.textStream())],
["res.body.text()", async res => (await res.body!.text()).length],
["res.text() after res.body", async res => (void res.body, (await res.text()).length)],
["HTMLRewriter.transform()", async res => (await new HTMLRewriter().on("x", {}).transform(res).text()).length],
["Bun.write() after res.body", (res, dir) => (void res.body, Bun.write(join(dir, "body"), res))],
[
"a Bun.serve response",
async res => {
using proxy = Bun.serve({ port: 0, fetch: () => new Response(res.body) });
return (await (await fetch(proxy.url)).bytes()).byteLength;
},
],
];

for (const [name, consume] of consumers) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
test(`${name} gets a whole body that trickles in while the collector runs`, async () => {
using dir = tempDir("fetch-trickle-consumer", {});
await using origin = await quietOrigin();
// Its own frame: once it returns, the consumer's promise is all that is held.
const received = (async () => consume(await fetch(origin.url), String(dir)))();
await origin.respondedTo(1);
for (let i = 1; i < PIECES; i++) {
await stat(import.meta.path);
Bun.gc(true);
await origin.trickle();
}
await stat(import.meta.path);
Bun.gc(true);
await origin.finish();
expect(await received).toBe(PIECES * PIECE);
});
}
});
Loading