From c23cd3af0af12c1e6322b3b95efbb2310390be8a Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 26 Jun 2026 02:57:57 +0000 Subject: [PATCH 1/3] fetch: do not touch JSCells in the Response Weak finalizer during GC sweep FetchTasklet::on_response_finalize runs from WeakRefOwner::finalize inside WeakBlock::sweep (MutatorState::Sweeping). It called ignore_remaining_response_body, which in turn called ResumableSink::detach_js() to clear the sink wrapper's cached ondrain/oncancel/stream slots. Those generated *SetCachedValue helpers uncheckedDowncast(...) -> JSCell::classInfo(), and any classInfo() call while the mutator is sweeping trips the validateIsNotSweeping assertion in assert builds (and is latent heap corruption otherwise, since the cell's structure may already have been swept). Gate detach_js() and clear_stream_handlers() on a from_finalizer flag. When called from the Weak finalizer only native state is touched; the JS-side detach still happens later from clear_sink() in deinit(), which runs as an event-loop task outside the sweep. Also correct the detach_js() doc comment that claimed it was safe from finalizers. --- src/runtime/webcore/ResumableSink.rs | 7 +- src/runtime/webcore/fetch/FetchTasklet.rs | 30 +++-- .../fetch-response-finalizer-sweep.test.ts | 114 ++++++++++++++++++ 3 files changed, 137 insertions(+), 14 deletions(-) create mode 100644 test/js/web/fetch/fetch-response-finalizer-sweep.test.ts diff --git a/src/runtime/webcore/ResumableSink.rs b/src/runtime/webcore/ResumableSink.rs index fba1e99d8b6e..69ccefce571a 100644 --- a/src/runtime/webcore/ResumableSink.rs +++ b/src/runtime/webcore/ResumableSink.rs @@ -438,9 +438,10 @@ impl ResumableSink) { @@ -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 @@ -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(); @@ -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); } } } diff --git a/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts b/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts new file mode 100644 index 000000000000..e5095680a20d --- /dev/null +++ b/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts @@ -0,0 +1,114 @@ +// 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(...) -> 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); +}); From 458ebda116f1e64bce139b5dae5645e144bb3f65 Mon Sep 17 00:00:00 2001 From: "autofix-ci[bot]" <114827586+autofix-ci[bot]@users.noreply.github.com> Date: Fri, 26 Jun 2026 03:00:42 +0000 Subject: [PATCH 2/3] [autofix.ci] apply automated fixes --- test/js/web/fetch/fetch-response-finalizer-sweep.test.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts b/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts index e5095680a20d..9df2a9b32fd9 100644 --- a/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts +++ b/test/js/web/fetch/fetch-response-finalizer-sweep.test.ts @@ -96,11 +96,7 @@ describe.skipIf(isWindows)("fetch Response Weak finalizer during GC sweep", () = stdout: "pipe", stderr: "pipe", }); - const [stdout, stderr, exitCode] = await Promise.all([ - proc.stdout.text(), - proc.stderr.text(), - proc.exited, - ]); + 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 From 0889b05fc151b45eefde829b875a847e65fc9625 Mon Sep 17 00:00:00 2001 From: robobun <117481402+robobun@users.noreply.github.com> Date: Fri, 26 Jun 2026 03:17:31 +0000 Subject: [PATCH 3/3] ci: retrigger