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
7 changes: 4 additions & 3 deletions src/runtime/webcore/ResumableSink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,9 +438,10 @@ impl<Js: ResumableSinkJs, Context: ResumableSinkContext> ResumableSink<Js, Conte
/// slots and downgrade `js_this` from a strong to a weak handle so the
/// wrapper (and the `drainReaderIntoSink` closure it caches, which captures
/// the reader/stream graph) becomes collectible. Unlike [`Self::cancel`]
/// this does NOT run any JS callbacks or invoke `on_end`, so it is safe to
/// call from contexts where executing JS is not allowed (e.g. teardown /
/// finalizers).
/// this does NOT run any JS callbacks or invoke `on_end`.
///
/// NOT safe during GC sweep (Weak/cell finalizers): the cached-value
/// setters downcast the wrapper cell and issue a write barrier.
pub fn detach_js(&mut self) {
if let Some(js_this) = self.js_this.try_get() {
let global = self.global_this;
Expand Down
30 changes: 19 additions & 11 deletions src/runtime/webcore/fetch/FetchTasklet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1599,7 +1599,7 @@ impl FetchTasklet {
if this.signal_store.body_receive_mode() == BodyReceiveMode::Ignore {
return;
}
this.ignore_remaining_response_body();
this.ignore_remaining_response_body(false);
}

fn on_stream_drained_callback(ctx: Option<*mut c_void>) {
Expand Down Expand Up @@ -1723,17 +1723,23 @@ impl FetchTasklet {
)
}

fn ignore_remaining_response_body(&mut self) {
fn ignore_remaining_response_body(&mut self, from_finalizer: bool) {
bun_output::scoped_log!(FetchTasklet, "ignoreRemainingResponseBody");
// The response is being abandoned. If the request body is still uploading
// through a ResumableSink, detach its JS wrapper so the cached
// `ondrain` closure (and the reader/stream graph it captures) becomes
// collectible instead of leaking. `detach_js` runs no JS callbacks, so it
// is safe even on the GC-finalizer caller (`on_response_finalize`); the
// sink's own teardown (`Drop`/`finalize`) handles the rest once its refs
// drain.
if let Some(sink) = self.sink_mut() {
sink.detach_js();
// collectible instead of leaking.
//
// When reached from `on_response_finalize` (a JSC Weak finalizer inside
// `WeakBlock::sweep`), `detach_js()` and `clear_stream_handlers()` must be
// skipped: both reach `JSCell::classInfo()` via generated cached-value
// setters / `ReadableStreamTag__tagged`, and touching any cell during
// `MutatorState::Sweeping` is forbidden. `clear_sink()` in `deinit()` (an
// event-loop task, outside sweep) performs the deferred detach.
if !from_finalizer {
if let Some(sink) = self.sink_mut() {
sink.detach_js();
}
}
// enabling streaming will make the http thread to drain into the main thread (aka stop buffering)
// without a stream ref, response body or response instance alive it will just ignore the result
Expand All @@ -1750,7 +1756,9 @@ impl FetchTasklet {
let _ = self.javascript_vm;
self.poll_ref.unref(bun_io::js_vm_ctx());
// clean any remaining references
self.clear_stream_handlers();
if !from_finalizer {
self.clear_stream_handlers();
}
self.readable_stream_ref.deinit();
self.response.clear();

Expand Down Expand Up @@ -2461,11 +2469,11 @@ impl FetchTasklet {
if let Some(promise) = locked.promise {
if promise.is_empty_or_undefined_or_null() {
// Scenario 2b.
this.ignore_remaining_response_body();
this.ignore_remaining_response_body(true);
}
} else {
// Scenario 3.
this.ignore_remaining_response_body();
this.ignore_remaining_response_body(true);
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
}
Expand Down
110 changes: 110 additions & 0 deletions test/js/web/fetch/fetch-response-finalizer-sweep.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
// fetch(): the JSResponse Weak finalizer (WeakBlock::sweep) reaches
// FetchTasklet::ignore_remaining_response_body. That path used to call
// ResumableSink::detach_js(), which writes the wrapper's cached ondrain/
// oncancel/stream slots via generated *SetCachedValue helpers. Those helpers
// uncheckedDowncast<JSResumableFetchSink>(...) -> JSCell::classInfo(), and
// touching any JSCell while MutatorState == Sweeping trips
// validateIsNotSweeping() (assert builds) or silently corrupts the heap
// (release builds).
//
// Scenario: POST with a user-constructed ReadableStream body (so the sink
// takes the JS route and holds a Strong js_this), server replies with headers
// but leaves the body open (response body = Locked with no promise), drop the
// Response unconsumed, force a synchronous sweep.

import { describe, expect, test } from "bun:test";
import { bunEnv, bunExe, isWindows } from "harness";

const fixture = /* js */ `
const net = require("node:net");

let sockets = [];
const server = net.createServer(socket => {
sockets.push(socket);
socket.on("error", () => {});
// Reply once request headers (and the first body chunk) have arrived so
// the client has already entered start_request_stream() and created the
// ResumableSink. Then send response headers + one partial chunk so
// fetch() resolves with is_waiting_body = true (BodyValue::Locked).
let replied = false;
socket.on("data", () => {
if (replied) return;
replied = true;
socket.write(
"HTTP/1.1 200 OK\\r\\n" +
"Transfer-Encoding: chunked\\r\\n" +
"Connection: close\\r\\n" +
"\\r\\n" +
"5\\r\\nhello\\r\\n",
);
// Do NOT send the terminating 0-chunk; keep the body pending.
});
});
await new Promise(r => server.listen(0, r));
const port = server.address().port;

async function once() {
let pullAgain;
const body = new ReadableStream({
start(c) {
c.enqueue(new TextEncoder().encode("abc"));
},
pull() {
// Never resolve: keep the upload sink alive with a Strong js_this
// so detach_js() has a live wrapper to downcast.
return new Promise(r => { pullAgain = r; });
},
});
const res = await fetch("http://127.0.0.1:" + port + "/", {
method: "POST",
body,
duplex: "half",
});
if (res.status !== 200) throw new Error("status " + res.status);
// Drop the Response without touching .body / .text() etc.
return pullAgain;
}

// A few iterations so at least one Response lands in a block that the
// allocation slow-path sweeps while the collector thread is running.
const keep = [];
for (let i = 0; i < 12; i++) {
keep.push(await once());
// Allocation between Bun.gc calls gives LocalAllocator::allocateSlowCase
// a reason to sweep the block the dead Response sits in.
new Error("alloc");
Bun.gc(true);
new Error("alloc");
Bun.gc(true);
}

for (const s of sockets) s.destroy();
server.close();
console.log("ok");
`;

// collectContinuously is slow under Windows CI and the code path is identical
// across platforms; the assertion this guards is platform-independent.
describe.skipIf(isWindows)("fetch Response Weak finalizer during GC sweep", () => {
test("dropping an unconsumed streaming-upload Response does not touch JSCells in the finalizer", async () => {
await using proc = Bun.spawn({
cmd: [bunExe(), "-e", fixture],
env: {
...bunEnv,
BUN_JSC_collectContinuously: "1",
},
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
// On failure the process aborts inside WeakBlock::sweep before reaching
// the print; asserting the combined shape gives a readable diff. stderr
// is included for diagnostics only (debug/ASAN builds emit benign
// warnings there, so it is not required to be empty).
expect({ stdout: stdout.trim(), exitCode, stderr }).toEqual({
stdout: "ok",
exitCode: 0,
stderr: expect.any(String),
});
}, 120_000);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
});
Loading