Repository navigation
fix(serve): leak when Promise<Response> never settles after abort - #28613
Conversation
|
Updated 12:13 AM PT - Mar 28th, 2026
❌ @autofix-ci[bot], your commit 63afbdf has 3 failures in
🧪 To try this PR locally: bunx bun-pr 28613That installs a local version of the PR into your bun-28613 --bun |
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughAdds a NativePromiseContext GC cell and runtime integration for storing native context pointers across Promise Changes
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/bun.js/bindings/NativePromiseContext.cpp`:
- Around line 30-34: The finalizer (~NativePromiseContext) is performing heavy
RequestContext cleanup (calling RequestContext::deref which can reach
finalizeWithoutDeinit()/deinit), so change the destructor in
NativePromiseContext to do only a minimal, non-blocking ref-release (e.g., an
atomic decrement or call a lightweight release method) and remove any direct
calls that can trigger finalizeWithoutDeinit()/deinit from the GC path; move the
full cleanup logic (the code that currently runs when ref_count hits zero) into
the promise-completion path (e.g., onResolveStream or the explicit request
lifecycle) or schedule it onto the main/event loop (post a task) so that when
RequestContext::deref observes ref_count→0 it enqueues/executes
finalizeWithoutDeinit()/deinit on the safe thread instead of running it inside
NativePromiseContext::~NativePromiseContext/Bun__NativePromiseContext__destroy.
Ensure pointer()/tag() usage remains for locating the context but do not perform
unprotecting/terminating/aborting work in the destructor.
In `@test/js/bun/http/serve-pending-promise-abort-leak-fixture.ts`:
- Around line 10-19: The test races because the client aborts before the
server's fetch installs the abort listener; change the test to synchronize on
the server observing the request rather than using a fixed 5ms sleep: add a
promise/flag that is resolved from inside the server's fetch(req) (where
req.signal.addEventListener increments abortCount) to signal "requestSeen", then
in the client loop await that promise (or await a per-request signal) before
destroying the socket; update uses of server, fetch(req), abortCount and
ITERATIONS to rely on that signal so abortCount reliably equals ITERATIONS on
slow CI.
In `@test/js/bun/http/serve-pending-promise-abort-leak.test.ts`:
- Around line 5-11: The helper waitForPendingRequests currently silently falls
through when the retry loop times out; update waitForPendingRequests(server,
expected) to throw an Error if server.pendingRequests !== expected after the
retries, including the observed server.pendingRequests value in the error
message so callers (tests at the previously mentioned lines) fail immediately
with the actual observed count instead of continuing with unmet preconditions.
- Around line 86-98: The test's late resolve uses setTimeout inside the
fetch(req) promise which makes the UAF race non-deterministic; instead capture
the resolver when constructing the Promise in fetch(req) (e.g., store it in a
outer-scope variable like lateResolve) and replace the setTimeout path with a
direct call to that captured resolver, then in the test body await
waitForPendingRequests(server, 0) and call lateResolve(new Response("very
late")) (and set resolved = true there) to deterministically exercise the
post-abort resolve path; update both places where setTimeout is used in
fetch(req) to this pattern.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 19e8f3b2-8791-463d-af80-e98d1c3dd0ca
📒 Files selected for processing (14)
src/bun.js/api.zigsrc/bun.js/api/NativePromiseContext.zigsrc/bun.js/api/server/RequestContext.zigsrc/bun.js/bindings/BunClientData.cppsrc/bun.js/bindings/BunClientData.hsrc/bun.js/bindings/JSValue.zigsrc/bun.js/bindings/NativePromiseContext.cppsrc/bun.js/bindings/NativePromiseContext.hsrc/bun.js/bindings/ZigGlobalObject.cppsrc/bun.js/bindings/ZigGlobalObject.hsrc/bun.js/bindings/webcore/DOMClientIsoSubspaces.hsrc/bun.js/bindings/webcore/DOMIsoSubspaces.htest/js/bun/http/serve-pending-promise-abort-leak-fixture.tstest/js/bun/http/serve-pending-promise-abort-leak.test.ts
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@bench/snippets/http-hello.node.mjs`:
- Around line 3-20: The handler currently uses a chained deferred pattern
(variable defer, awaiting defer.promise after replacing it and resolving the
previous one) which makes request N complete only when N+1 arrives and leaves
the final request unresolved at exit; revert the handler to immediate-response
semantics used by the other snippets by removing the defer chaining: stop
creating/awaiting Promise.withResolvers(), and simply writeHead/end the response
directly in the createServer request handler (retain the i counter and the
200_000 exit trigger but ensure any pending promise is resolved before calling
process.exit if you keep defer logic), or move the deferred pattern into a
separate leak-repro test instead of http-hello to preserve cross-runtime
benchmark behavior.
In `@src/bun.js/webcore/Body.zig`:
- Around line 1650-1656: The call to assignment_result.thenWithValue currently
swallows any error (catch {}), making control flow unclear; change the catch to
capture the error and handle it explicitly: when thenWithValue on
assignment_result (and the created NativePromiseContext cell) fails, invoke the
rejection path (call onRejectStream with the globalThis, cell and the captured
error) and then return error.PipeFailed (or otherwise return/propagate the
captured error) so the early-return behavior is explicit rather than silently
ignored.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 16d0425d-213c-48ba-9314-a7627063de82
📥 Commits
Reviewing files that changed from the base of the PR and between 676b529 and dae9e3a78ac69d87468468a1eb3b76040882a8db.
📒 Files selected for processing (4)
bench/snippets/http-hello.node.mjssrc/bun.js/api/NativePromiseContext.zigsrc/bun.js/bindings/NativePromiseContext.hsrc/bun.js/webcore/Body.zig
| var defer; | ||
|
|
||
| const server = createServer((req, res) => { | ||
| res.writeHead(200); | ||
| res.end("Hello, World!" + i); | ||
| const server = createServer(async (req, res) => { | ||
| if (i++ === 200_000 - 1) | ||
| setTimeout(() => { | ||
| console.log("RSS", (process.memoryUsage().rss / 1024 / 1024) | 0, "MB"); | ||
| process.exit(0); | ||
| }, 0); | ||
| if (defer) { | ||
| const prev = defer; | ||
| defer = Promise.withResolvers(); | ||
| prev.resolve(); | ||
| } else { | ||
| defer = Promise.withResolvers(); | ||
| } | ||
| await defer.promise; | ||
| res.writeHead(200); | ||
| res.end("Hello, World!" + i); |
There was a problem hiding this comment.
This changes the benchmark semantics and leaves the tail request unresolved.
At Lines 11-18, the handler resolves the previous deferred, replaces it, and then awaits the new promise. That means request N only completes when request N+1 arrives; with low concurrency the first request can stall indefinitely, and at the 200,000th request the process exits with the last response still pending. This no longer measures the same immediate hello-world path as bench/snippets/http-hello.js:1-7 and bench/snippets/http-hello.deno.js:1-7, so the cross-runtime benchmark becomes invalid. If this pending-promise pattern is needed for leak reproduction, please move it to a dedicated snippet/test instead of http-hello.
↩️ Suggested revert for the shared benchmark snippet
-var defer;
-
-const server = createServer(async (req, res) => {
+const server = createServer((req, res) => {
if (i++ === 200_000 - 1)
setTimeout(() => {
console.log("RSS", (process.memoryUsage().rss / 1024 / 1024) | 0, "MB");
process.exit(0);
}, 0);
- if (defer) {
- const prev = defer;
- defer = Promise.withResolvers();
- prev.resolve();
- } else {
- defer = Promise.withResolvers();
- }
- await defer.promise;
res.writeHead(200);
res.end("Hello, World!" + i);
}).listen(parseInt(process.env.PORT || "3000", 10));🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@bench/snippets/http-hello.node.mjs` around lines 3 - 20, The handler
currently uses a chained deferred pattern (variable defer, awaiting
defer.promise after replacing it and resolving the previous one) which makes
request N complete only when N+1 arrives and leaves the final request unresolved
at exit; revert the handler to immediate-response semantics used by the other
snippets by removing the defer chaining: stop creating/awaiting
Promise.withResolvers(), and simply writeHead/end the response directly in the
createServer request handler (retain the i counter and the 200_000 exit trigger
but ensure any pending promise is resolved before calling process.exit if you
keep defer logic), or move the deferred pattern into a separate leak-repro test
instead of http-hello to preserve cross-runtime benchmark behavior.
| const cell = bun.api.NativePromiseContext.create(globalThis, sink); | ||
| assignment_result.thenWithValue( | ||
| globalThis, | ||
| sink, | ||
| cell, | ||
| onResolveStream, | ||
| onRejectStream, | ||
| ); | ||
| ) catch {}; |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Swallowed error on thenWithValue may cause unexpected control flow.
If thenWithValue fails, execution falls through past the early return at line 1669 and hits return error.PipeFailed at line 1673. While this is safe (the NativePromiseContext cell will be GC'd and release its ref), the control flow is non-obvious.
Consider making the error handling explicit:
♻️ Suggested clarification
.Pending => {
const cell = bun.api.NativePromiseContext.create(globalThis, sink);
assignment_result.thenWithValue(
globalThis,
cell,
onResolveStream,
onRejectStream,
- ) catch {};
+ ) catch {
+ // Cell will be GC'd, releasing the ref; fall through to PipeFailed
+ return error.PipeFailed;
+ };
+ return;
},🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bun.js/webcore/Body.zig` around lines 1650 - 1656, The call to
assignment_result.thenWithValue currently swallows any error (catch {}), making
control flow unclear; change the catch to capture the error and handle it
explicitly: when thenWithValue on assignment_result (and the created
NativePromiseContext cell) fails, invoke the rejection path (call onRejectStream
with the globalThis, cell and the captured error) and then return
error.PipeFailed (or otherwise return/propagate the captured error) so the
early-return behavior is explicit rather than silently ignored.
When the fetch handler returns a pending Promise<Response> and the client disconnects before it settles, the RequestContext leaked forever. The ctx.ref() before .then() was only balanced by onResolve/onReject, which never fire for unsettled promises. Introduces NativePromiseContext: a minimal JSCell (CellType + custom IsoHeapCellType) that owns the ref. The cell is passed to .then() instead of a raw pointer. If the Promise settles, onResolve/onReject call take() to transfer ownership and deref deterministically. If the Promise is GC'd without settling, the cell is collected with its reaction and the destructor releases the ref. The cell packs the pointer and type tag into a single CompactPointerTuple (8 bytes of storage beyond the JSCell header). The tag dispatches to the right deref() via a hardcoded switch in Zig — no function pointers, no Weak<> overhead. Applied to all three .then() callsites in RequestContext: the main response promise, the error handler promise, and the response body stream promise.
6a91672 to
664fffd
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/bun.js/api/NativePromiseContext.zig`:
- Around line 22-43: Add a compile-time check to keep the Zig Tag enum in sync
with the C++ Bun::NativePromiseContext::Tag: expose the C++ enum count (or a
sentinel LAST_TAG/NUM_TAGS) from NativePromiseContext.h via `@cImport` and assert
Tag.len (or `@enumToInt` equivalent) equals that C value in
NativePromiseContext.zig; update the file around the Tag declaration and the
fromType function to include this comptime assertion so any drift between the
Zig enum and the C++ enum fails at compile time.
In `@src/bun.js/api/server/RequestContext.zig`:
- Around line 1241-1247: The code calls NativePromiseContext.create(...) and
then assignment_result.thenWithValue(...) but swallows exceptions with catch {},
leaving the extra RequestContext ref and elevated pendingRequests on synchronous
failure; change the pattern so that if thenWithValue throws you immediately
release/drop the RequestContext reference (the cell created by
NativePromiseContext.create), decrement/clear pendingRequests accordingly, and
rethrow or propagate the error instead of silently ignoring it; apply the same
fix at the other occurrences that call assignment_result.thenWithValue with
onResolveStream/onRejectStream (the blocks around the noted lines 1608-1610 and
2180-2186) so failures do proper cleanup and don’t rely on GC to free the cell.
In `@test/js/bun/http/serve-pending-promise-abort-leak.test.ts`:
- Around line 15-17: The test is spawning Bun with an external single-file
fixture (serve-pending-promise-abort-leak-fixture.ts) instead of inlining the
script; replace the spawn that uses Bun.spawn with cmd referencing bunExe() and
the "-e" flag and inline the contents of
serve-pending-promise-abort-leak-fixture.ts as the argument to "-e" so this
becomes a single-file spawn (keep existing bunEnv and the using proc variable),
and remove the separate *-fixture.ts file so the test follows the repo fixture
convention for single-file cases.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: 5e8b9936-cd23-4785-9f03-818bf32cd8af
📥 Commits
Reviewing files that changed from the base of the PR and between dae9e3a78ac69d87468468a1eb3b76040882a8db and 664fffd.
📒 Files selected for processing (15)
src/bun.js/api.zigsrc/bun.js/api/NativePromiseContext.zigsrc/bun.js/api/server/RequestContext.zigsrc/bun.js/bindings/BunClientData.cppsrc/bun.js/bindings/BunClientData.hsrc/bun.js/bindings/JSValue.zigsrc/bun.js/bindings/NativePromiseContext.cppsrc/bun.js/bindings/NativePromiseContext.hsrc/bun.js/bindings/ZigGlobalObject.cppsrc/bun.js/bindings/ZigGlobalObject.hsrc/bun.js/bindings/webcore/DOMClientIsoSubspaces.hsrc/bun.js/bindings/webcore/DOMIsoSubspaces.hsrc/bun.js/webcore/Body.zigtest/js/bun/http/serve-pending-promise-abort-leak-fixture.tstest/js/bun/http/serve-pending-promise-abort-leak.test.ts
| const cell = NativePromiseContext.create(globalThis, this); | ||
| assignment_result.thenWithValue( | ||
| globalThis, | ||
| this, | ||
| cell, | ||
| onResolveStream, | ||
| onRejectStream, | ||
| ) catch {}; // TODO: properly propagate exception upwards |
There was a problem hiding this comment.
Don't treat failed thenWithValue() registration as success.
Each of these branches has already taken an extra RequestContext ref, but the catch {} path still returns as if the continuation was installed. If thenWithValue() throws, nothing drives the request/error cleanup until a later GC happens to collect the cell, so pendingRequests can remain elevated on this synchronous failure path.
Also applies to: 1608-1610, 2180-2186
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bun.js/api/server/RequestContext.zig` around lines 1241 - 1247, The code
calls NativePromiseContext.create(...) and then
assignment_result.thenWithValue(...) but swallows exceptions with catch {},
leaving the extra RequestContext ref and elevated pendingRequests on synchronous
failure; change the pattern so that if thenWithValue throws you immediately
release/drop the RequestContext reference (the cell created by
NativePromiseContext.create), decrement/clear pendingRequests accordingly, and
rethrow or propagate the error instead of silently ignoring it; apply the same
fix at the other occurrences that call assignment_result.thenWithValue with
onResolveStream/onRejectStream (the blocks around the noted lines 1608-1610 and
2180-2186) so failures do proper cleanup and don’t rely on GC to free the cell.
| await using proc = Bun.spawn({ | ||
| cmd: [bunExe(), join(import.meta.dir, "serve-pending-promise-abort-leak-fixture.ts")], | ||
| env: bunEnv, |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major
Inline this fixture with -e instead of spawning a standalone file.
This is a single-file spawn case, so the extra serve-pending-promise-abort-leak-fixture.ts indirection doesn't follow the repo's fixture convention. Please inline the script in the spawned command and reserve *-fixture.ts for multi-file setups.
As per coding guidelines, "Use -e flag for single-file Bun process spawning tests. For multi-file tests, use tempDir from harness and name the test file with *-fixture.ts convention."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@test/js/bun/http/serve-pending-promise-abort-leak.test.ts` around lines 15 -
17, The test is spawning Bun with an external single-file fixture
(serve-pending-promise-abort-leak-fixture.ts) instead of inlining the script;
replace the spawn that uses Bun.spawn with cmd referencing bunExe() and the "-e"
flag and inline the contents of serve-pending-promise-abort-leak-fixture.ts as
the argument to "-e" so this becomes a single-file spawn (keep existing bunEnv
and the using proc variable), and remove the separate *-fixture.ts file so the
test follows the repo fixture convention for single-file cases.
The JSCell destructor runs during GC sweep where touching the JSC heap is unsafe. RequestContext.deref() can cascade into deinit() which detaches responses, unrefs bodies, and calls server.onRequestComplete() — all of which may unprotect JS values. This tripped "Fatal: collector does not believe that the world is stopped" on Linux CI. Enqueue a DeferredDerefTask instead and run the deref on the next event-loop tick. Zero-allocation: the ctx pointer and Tag pack into the task's u49 _ptr slot (pointer in bits 3..48, tag in bits 0..2 — target types are all >= 8-byte aligned), leaving the u15 Task discriminant intact. Same trick PosixSignalTask uses for signal numbers.
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@src/bun.js/api/NativePromiseContext.zig`:
- Around line 22-40: The BodyValueBufferer tag is currently too permissive:
change Tag.fromType to match the concrete ValueBufferer instantiation owned by
HTMLRewriter (e.g., use a pattern like
bun.webcore.Body.ValueBufferer(HTMLRewriter.BufferOutputSink) =>
.BodyValueBufferer) instead of matching any bun.webcore.Body.ValueBufferer type;
update the corresponding tag enum entry if needed and make the same
narrow-matching change in the other occurrence (lines ~141-148) so
create()/deref() call sites that expect HTMLRewriter.BufferOutputSink will fail
at compile time for other owner types.
- Around line 71-73: The GC finalizer path in Bun__NativePromiseContext__destroy
calls DeferredDerefTask.schedule while vm.isShuttingDown() (an unsynchronized
read of is_shutting_down) is checked elsewhere, creating a cross-thread race;
change the teardown gating so the GC thread does not perform an unsynchronized
VM read: add or use an atomic/locked shutdown flag (e.g., make is_shutting_down
atomic) or provide a DeferredDerefTask.enqueue_teardown/queue_without_vm_check
path that accepts a teardown indicator from the caller and does not call
vm.isShuttingDown() from the GC thread; update DeferredDerefTask.schedule
callers to use the new enqueue variant or the atomic flag and ensure all checks
reference the new atomic/locked API instead of the raw is_shutting_down.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro
Run ID: dc309b34-3364-4c83-9223-ee87a491abbe
📒 Files selected for processing (2)
src/bun.js/api/NativePromiseContext.zigsrc/bun.js/event_loop/Task.zig
| /// Must match Bun::NativePromiseContext::Tag in NativePromiseContext.h. | ||
| /// One entry per concrete native type — the tag is packed into the pointer's | ||
| /// upper bits via CompactPointerTuple so the cell stays at one pointer of | ||
| /// storage beyond the JSCell header. | ||
| pub const Tag = enum(u8) { | ||
| HTTPServerRequestContext, | ||
| HTTPSServerRequestContext, | ||
| DebugHTTPServerRequestContext, | ||
| DebugHTTPSServerRequestContext, | ||
| BodyValueBufferer, | ||
|
|
||
| pub fn fromType(comptime T: type) Tag { | ||
| return switch (T) { | ||
| server.HTTPServer.RequestContext => .HTTPServerRequestContext, | ||
| server.HTTPSServer.RequestContext => .HTTPSServerRequestContext, | ||
| server.DebugHTTPServer.RequestContext => .DebugHTTPServerRequestContext, | ||
| server.DebugHTTPSServer.RequestContext => .DebugHTTPSServerRequestContext, | ||
| bun.webcore.Body.ValueBufferer => .BodyValueBufferer, | ||
| else => @compileError("NativePromiseContext.Tag: unsupported type " ++ @typeName(T)), |
There was a problem hiding this comment.
🧹 Nitpick | 🔵 Trivial
Make the BodyValueBufferer tag owner-specific.
Tag.fromType() accepts any bun.webcore.Body.ValueBufferer, but the deferred-deref branch unconditionally casts bufferer.ctx to *HTMLRewriter.BufferOutputSink. A future NativePromiseContext.create(global, some_other_value_bufferer) would compile and then call deref() on the wrong type at runtime. Narrow this tag/constructor to the actual owner type so invalid call sites fail at compile time.
Also applies to: 141-148
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bun.js/api/NativePromiseContext.zig` around lines 22 - 40, The
BodyValueBufferer tag is currently too permissive: change Tag.fromType to match
the concrete ValueBufferer instantiation owned by HTMLRewriter (e.g., use a
pattern like bun.webcore.Body.ValueBufferer(HTMLRewriter.BufferOutputSink) =>
.BodyValueBufferer) instead of matching any bun.webcore.Body.ValueBufferer type;
update the corresponding tag enum entry if needed and make the same
narrow-matching change in the other occurrence (lines ~141-148) so
create()/deref() call sites that expect HTMLRewriter.BufferOutputSink will fail
at compile time for other owner types.
| pub export fn Bun__NativePromiseContext__destroy(ctx: *anyopaque, tag: u8) callconv(.c) void { | ||
| DeferredDerefTask.schedule(ctx, @enumFromInt(tag)); | ||
| } |
There was a problem hiding this comment.
GC-thread shutdown check is racy.
Line 72 is entered from the GC finalizer path, but Line 122 calls vm.isShuttingDown() even though that accessor is just an unsynchronized read of is_shutting_down. That reintroduces a cross-thread data race in the cleanup path and can mis-handle whether the deferred deref gets queued during teardown. Please gate this with an atomic/locked shutdown flag, or use an enqueue path that reports teardown without reading VM state from the GC thread.
Also applies to: 118-123
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/bun.js/api/NativePromiseContext.zig` around lines 71 - 73, The GC
finalizer path in Bun__NativePromiseContext__destroy calls
DeferredDerefTask.schedule while vm.isShuttingDown() (an unsynchronized read of
is_shutting_down) is checked elsewhere, creating a cross-thread race; change the
teardown gating so the GC thread does not perform an unsynchronized VM read: add
or use an atomic/locked shutdown flag (e.g., make is_shutting_down atomic) or
provide a DeferredDerefTask.enqueue_teardown/queue_without_vm_check path that
accepts a teardown indicator from the caller and does not call
vm.isShuttingDown() from the GC thread; update DeferredDerefTask.schedule
callers to use the new enqueue variant or the atomic flag and ensure all checks
reference the new atomic/locked API instead of the raw is_shutting_down.
| //! Zig bindings for the NativePromiseContext JSCell. | ||
| //! | ||
| //! See src/bun.js/bindings/NativePromiseContext.h for the rationale. Short | ||
| //! version: when native code `.then()`s a user Promise and needs a context | ||
| //! pointer, wrap the pointer in this GC-managed cell instead of passing it | ||
| //! raw. If the Promise never settles, GC collects the cell and the destructor | ||
| //! releases the ref — no leak, no use-after-free. | ||
| //! | ||
| //! Usage pattern: | ||
| //! | ||
| //! ctx.ref(); | ||
| //! const cell = NativePromiseContext.create(global, ctx); | ||
| //! try promise.thenWithValue(global, cell, onResolve, onReject); | ||
| //! | ||
| //! // In onResolve/onReject: | ||
| //! const ctx = NativePromiseContext.take(RequestContext, arguments.ptr[1]) orelse return; | ||
| //! defer ctx.deref(); | ||
| //! // ... process ... |
There was a problem hiding this comment.
🟣 The PR fixes the never-settling-Promise ref leak for RequestContext and Body.ValueBufferer, but three other call sites in the codebase still use the old raw-pointer .then() pattern with asPromisePtr() and will leak native contexts if their Promises never settle: FileSink.zig ~line 766 (this.ref() + raw .then()), Blob.zig ~line 2597 (heap-allocated FileStreamWrapper passed via .then()), and server.zig ~line 400 (ServePlugins using asPromisePtr). These are pre-existing issues not introduced by this PR, but they represent the same leak class the PR is explicitly fixing — consider applying NativePromiseContext to these sites as well or tracking them in a follow-up issue.
Extended reasoning...
What the bug is and how it manifests
This PR introduces NativePromiseContext to fix the never-settling-Promise memory leak for Bun.serve() RequestContext (3 call sites) and Body.ValueBufferer (1 call site). However, the NativePromiseContext.Tag enum has only 5 entries covering those two types. At least three other call sites in the codebase follow the exact same vulnerable pattern — raw ref() + raw pointer passed to .then() — and will continue to leak native heap objects whenever the corresponding JavaScript Promise is garbage-collected without ever settling.
The specific code paths that trigger the leaks
-
src/bun.js/webcore/FileSink.zig ~line 766-767: this.ref() is called, then promise_result.then(globalThis, this, onResolveStream, onRejectStream) passes raw this as the context pointer. The callbacks onResolveStream (line 726) and onRejectStream (line 734) call defer this.deref() via asPromisePtr(@this()). If the stream assignment Promise never settles (e.g., the write side is dropped), the ref taken at line 766 is never balanced and the FileSink leaks forever.
-
src/bun.js/webcore/Blob.zig ~line 2597-2602: A heap-allocated FileStreamWrapper is constructed and passed to assignment_result.then(globalThis, wrapper, onFileStreamResolveRequestStream, onFileStreamRejectRequestStream). The callbacks (lines 2386, 2400) use asPromisePtr(FileStreamWrapper) and call defer this.deinit() which calls this.sink.deref() and bun.destroy(this). If the assignment Promise never settles, deinit() never runs — both the FileStreamWrapper allocation and whatever resources it holds (the file_sink ref) leak permanently.
-
src/bun.js/api/server.zig ~line 400-403: ServePlugins calls this.ref() and then promise_value.then(global, this, onResolveImpl, onRejectImpl). The callbacks (lines 433, 467) use asPromisePtr(ServePlugins). If the plugins-loading Promise never settles, the ref taken at line 400 is never balanced.
Why existing code does not prevent it
The PR's NativePromiseContext mechanism works by creating a GC-managed JSCell that owns the ref. When the Promise (and its reaction) is garbage-collected without settling, the JSCell destructor fires and releases the ref through a tag-dispatched call to Bun__NativePromiseContext__destroy. This mechanism is only wired up for the 5 Tag entries in the Zig/C++ enum (4 RequestContext variants + BodyValueBufferer). FileSink, FileStreamWrapper, and ServePlugins have no Tag entries; they still call the old JSValue._then() which passes the raw pointer directly. There is no GC hook to release those refs.
What the impact is
Any Bun user who performs streaming writes via FileSink (e.g., using a WritableStream sink with Bun.serve()) or reads a Blob via a streaming path where the underlying stream is abandoned, or loads server plugins that fail to fully initialize — under these conditions the associated native objects leak permanently. The size of the leak scales with the number of such abandoned operations. The leaks are not new in this PR, but the PR description explicitly frames its goal as fixing this entire class of leak; leaving these sites unaddressed makes the fix partial.
How to fix it
Add Tag enum entries for FileSink, FileStreamWrapper (or its owner type), and ServePlugins to both the Zig NativePromiseContext.Tag enum and the C++ Bun::NativePromiseContext::Tag enum. Add deref dispatch cases in DeferredDerefTask.runFromJSThread for each new tag. Migrate the three call sites from .then() with a raw pointer to .thenWithValue() with a NativePromiseContext.create() cell, and update their callback functions to use NativePromiseContext.take() instead of asPromisePtr().
Step-by-step proof for FileSink
- A Bun.serve() handler returns a Response backed by a WritableStream.
- FileSink.zig calls this.ref() and then promise_result.then(globalThis, this, onResolveStream, onRejectStream) with the raw FileSink pointer.
- The client disconnects mid-stream; the readable side is abandoned.
- The Promise that assignment_result returned is never settled — neither resolve() nor reject() is called.
- JSC marks the Promise reaction chain as unreachable and garbage-collects the Promise and its reactions.
- Because the context pointer is raw (not a JSCell), GC has no destructor to call. The ref() from step 2 is never matched by a deref().
- The FileSink and all its resources (file descriptor, output buffer) remain allocated forever.
…en-sh#28613) ## Summary When `Bun.serve()`'s fetch handler returns a pending `Promise<Response>` and the client disconnects before it settles, the `RequestContext` leaked forever. The `ctx.ref()` before `.then()` was only balanced by `onResolve`/`onReject`, which never fire for unsettled promises. This introduces `NativePromiseContext` — a minimal GC-managed JSCell that owns the ref: - **`JSC::JSCell`** + `CellType` + custom `IsoHeapCellType` for destructor support - **`CompactPointerTuple<Pointee*, Tag>`** packs pointer + tag in 8 bytes (cell = JSCell header + 1 word) - **Tag enum class** with one entry per concrete type (4 RequestContext variants), kept in sync C++↔Zig - **`take()`** transfers ownership for deterministic cleanup in the normal path - **Destructor** calls one extern C function that Zig implements with a tag switch — no function pointers, no `Weak<>` overhead If the Promise settles: `onResolve` calls `take()` → processes → `deref()`. Cell destructor later sees null, no-ops. If the Promise is GC'd without settling: cell collected with its reaction → destructor → `deref()`. No leak, no UAF. Applied to all three `.then()` callsites in `RequestContext`: main response promise, error handler promise, and response body stream promise. ## Test plan - [x] New test: `test/js/bun/http/serve-pending-promise-abort-leak.test.ts` — 4 tests covering the leak fix, normal resolution, resolve-in-abort-handler, and resolve-after-abort-via-setTimeout (UAF safety) - [x] Test fails on system Bun: `LEAK: 100 RequestContexts were never freed` - [x] Test passes with fix: `pendingRequests: 0` - [x] `heapStats().objectTypeCounts.NativePromiseContext` shows 50 for 50 concurrent pending, 0 after resolve+GC - [x] `serve.test.ts`: 189 pass - [x] `bun-serve-routes.test.ts` + `bun-serve-headers.test.ts`: 41 pass - [x] `BUN_JSC_validateExceptionChecks=1`: clean --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…en-sh#28613) ## Summary When `Bun.serve()`'s fetch handler returns a pending `Promise<Response>` and the client disconnects before it settles, the `RequestContext` leaked forever. The `ctx.ref()` before `.then()` was only balanced by `onResolve`/`onReject`, which never fire for unsettled promises. This introduces `NativePromiseContext` — a minimal GC-managed JSCell that owns the ref: - **`JSC::JSCell`** + `CellType` + custom `IsoHeapCellType` for destructor support - **`CompactPointerTuple<Pointee*, Tag>`** packs pointer + tag in 8 bytes (cell = JSCell header + 1 word) - **Tag enum class** with one entry per concrete type (4 RequestContext variants), kept in sync C++↔Zig - **`take()`** transfers ownership for deterministic cleanup in the normal path - **Destructor** calls one extern C function that Zig implements with a tag switch — no function pointers, no `Weak<>` overhead If the Promise settles: `onResolve` calls `take()` → processes → `deref()`. Cell destructor later sees null, no-ops. If the Promise is GC'd without settling: cell collected with its reaction → destructor → `deref()`. No leak, no UAF. Applied to all three `.then()` callsites in `RequestContext`: main response promise, error handler promise, and response body stream promise. ## Test plan - [x] New test: `test/js/bun/http/serve-pending-promise-abort-leak.test.ts` — 4 tests covering the leak fix, normal resolution, resolve-in-abort-handler, and resolve-after-abort-via-setTimeout (UAF safety) - [x] Test fails on system Bun: `LEAK: 100 RequestContexts were never freed` - [x] Test passes with fix: `pendingRequests: 0` - [x] `heapStats().objectTypeCounts.NativePromiseContext` shows 50 for 50 concurrent pending, 0 after resolve+GC - [x] `serve.test.ts`: 189 pass - [x] `bun-serve-routes.test.ts` + `bun-serve-headers.test.ts`: 41 pass - [x] `BUN_JSC_validateExceptionChecks=1`: clean --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…tions (#42464) ### Problem - `CallSite.getFunction()` (the `Error.prepareStackTrace` API) returned the frame's callee unchecked. JSC has callees user code could never have called: a host function, a builtin, an async or generator body function, or no function at all (wasm and program frames). - Five shapes crash 1.4.2, canary and main. After one `await`, calling what `getFunction()` returns gives `panic(main thread): Segmentation fault at address 0x32`. A wasm frame faults at `0x5` on the read. - Cause: `CallSite::finishCreation` (`src/jsc/bindings/CallSite.cpp:34`) only checks the strictness of the frame's code block. `JSCStackFrame` leaves that null for host and hidden builtin frames. ### Fix - `getFunction()` reports `undefined` unless the callee is a function user code could have called. A user function gets itself, including the CommonJS wrapper. - Caller frames keep their function: hiding a callee does not set `Flags::IsStrict`. `isToplevel()` reads a new flag computed from the real callee, so its answers do not change. - Deleted: the function-inspecting block in `callSiteProtoFuncIsToplevel`, and its `JSBoundFunction.h` include. - Verified: four new blocks in `test/js/node/v8/capture-stack-trace.test.js`, all failing on 1.4.2 and with `src/` reverted. 627 pass across the stack-trace suites. ### Background - JSC compiles an async function or a generator into a wrapper (what the user named) and a body that takes five internal arguments. The synchronous prefix runs in the body too, so the wrapper is never a frame's callee. - `createCallSitesFromFrames` (`FormatStackTraceForJS.cpp:844`) copies `isStrict()` down the frame list. JSC shows host frames V8 omits (`Reflect.construct` under a transpiled `super()`), so a cascade from a hidden callee would blank callers node reports. - JSC frames carry no receiver, so `isToplevel()` judges by the callee. <details><summary>Notes</summary> #### The five crashes A fuzz ledger reported the async body and three native promise reactions. A review of the first draft of this patch found the wasm frame. Each crashes release 1.4.2 (exit 139), and each exits cleanly with this change. | shape | 1.4.2 | with this change | | --- | --- | --- | | async function body after `await` | SEGV `0x32` | `undefined` | | generator body after `next()` | SEGV `0x32` | `undefined` | | wasm frame, on read alone | SEGV `0x5` | `undefined` | | HTMLRewriter suspension reaction | SEGV `0x12` | `undefined` | | `Bun.serve` `error()` reaction, and the `Bun.plugin` onLoad reaction | SEGV `0x12` / `0x1A` | `undefined` | The first fixture, as CommonJS so that the top frame is sloppy: ```js async function f() { await 1; Error.prepareStackTrace = (e, sites) => sites; return new Error().stack[0].getFunction(); } f().then(g => { console.log(g === f, g.length); g(); }); ``` 1.4.2 prints `false 5` and then segfaults. `0x32` is an encoded `undefined` (`0xa`) plus `0x28`, the offset of a generator internal field. Under ASAN the frames are `llint_op_put_internal_field <- llint_op_call_ignore_result <- llint_call_javascript <- JSC::MicrotaskCall::tryCallWithArguments`, so the body function wrote a generator field into a plain `undefined`. The wasm crash has three more entry shapes. Each is the same null callee, each segfaults 1.4.2 at `0x5`, and each exits cleanly with this change, also under ASAN: the wasm frame as the first call site of a trap (`WebAssembly.RuntimeError`, which is what an error reporter walks), a wasm stack overflow whose `RangeError` carries only wasm frames, and a wasm frame that JSPI resumed. The test covers the import-callback shape. The reaction crashes all reach the same place. A handler from `Zig::GlobalObject::thenable()` runs user JS synchronously: a later HTMLRewriter element handler, `Bun.serve`'s `error()`, or a getter on a plugin's onLoad result. That user JS keeps the nameless native function `getFunction()` reported, and calls it. The handler then reads its trailing argument as a native context. 12 of the 54 `PromiseFunctions` handlers decode a raw pointer from a JS number, so the class is worse than a bad cast. The host-function arm closes all of them, because `getFunction()` is the only way user code could name one. #### How old each route is The unchecked hand-out itself is old. Release 1.3.14 has the same logic in `CallSite.cpp`, `thenable()` is already `ImplementationVisibility::Public` there, and `Bun__NativePromiseContext__take` already uses `uncheckedDowncast` (#28613). The fuzz ledger reports that the wasm shape crashes 1.3.14 too. The HTMLRewriter route is new in 1.4.0, and the ledger measured it: 1.3.14 is clean, 1.4.0 to 1.4.2 crash at `0x12`. The cause is #36733, not an engine upgrade. Before it, the rewriter handled an async handler with `vm.wait_for_promise()`, which spins the event loop in place, so no native reaction existed. #36733 suspends the rewrite and resumes it through `Bun__HTMLRewriter__onHandlerResolve`, which put a reaction frame on the stack for the first time. The `Bun.serve` `error()` route and the `Bun.plugin` onLoad route use machinery that predates 1.3.14 (the onLoad reaction is from 2022), so they are probably older than that window. I read that from history and did not run it: I have no 1.3.14 binary here. #### What node returns Measured on node v26.3.0 with the same fixtures. | frame | node | 1.4.2 | with this change | | --- | --- | --- | --- | | sloppy user function | itself | itself | itself | | CommonJS module wrapper | itself | itself | itself | | `Array.prototype.map` | undefined | the `map` function | undefined | | program frame under `eval` | undefined | a non-function `JSCallee` object | undefined | | async or generator body | the wrapper | the body (length 5) | undefined | | wasm frame | a `Number` | crash | undefined | | any caller below the above | see 2. below | itself | itself | Two divergences remain, both deliberate: 1. Node returns the wrapper for an async or generator frame. JSC keeps no back pointer from a body function to its wrapper, so the wrapper cannot be recovered. `getFunctionName()` still reports the user's name. JSC applies the same policy in `callerGetter` (`FunctionPrototype.cpp`). 2. Node blanks the caller frames below a builtin frame, because V8 compiles its builtins strict. Bun does not, and this change does not start. I measured that trigger: it moves a 22-shape host and builtin probe from 4/22 to 22/22 against node. It also blanks callers that node reports wherever JSC shows a host frame V8 hides, and `Reflect.construct` under Babel's `_callSuper` is one of those. It is a separable hunk. Say so if you want it. #### isToplevel() `m_function` has two readers, `getFunction()` and `isToplevel()`. The first push of this PR narrowed what `m_function` holds and did not account for the second reader. A review comment about dead branches in `callSiteProtoFuncIsToplevel` made me measure it: on a 16-row probe, `isToplevel()` flipped from `false` to `true` on 5 rows, the `Array.prototype.map` frame and every async or generator frame. `isToplevel()` now reads `Flags::IsSloppyFunctionCall`, which `finishCreation` computes from the real callee: the frame is sloppy and its callee is a `JSFunction` that is not a host function. All 16 rows match 1.4.2 again, and four new `...IsToplevel=false` test rows pin it. Those rows fail on the first push of this PR. The replaced block had a `JSBoundFunction` arm, a host-function arm, a `jsExecutable()` arm and an `InternalFunction` arm. With `m_function` narrowed, only the `jsExecutable()` arm could still run. The `JSBoundFunction` arm never could: a bound-function thunk is `ImplementationVisibility::Private` and never gets a `CallSite`, which I checked on both the `prepareStackTrace` and the `captureStackTrace` path. #### Dropped from the first draft The first draft cascaded from every hidden callee and carried three hardening hunks. A review plus my own measurements cut all four: - The cascade blanked `getFunction()` for a plain sloppy caller that both node and 1.4.2 return. - `ImplementationVisibility::Private` on the `thenable()` handlers hides a useless `at unknown` frame. With `BUN_JSC_showPrivateScriptsInStackTraces=0` it also flips `typeof err.stack` from `"string"` to `"undefined"` for three `Bun.plugin` onLoad validation errors, whose only frame was the reaction. It needs the empty-frame-vector case to produce a header-only stack first, the way `FormatStackTraceForJS.cpp:234` already does for the `captureStackTrace` path. Worth doing, but not here. - A `dynamicDowncast` in `Bun__NativePromiseContext__take`. #40203 is open and already touches that function. - Two `dynamicDowncast` guards in the module loader onLoad reactions. With this change nothing can reach them, and an unreachable, untested guard is not worth the lines. #### Suites run, on the debug ASAN build `capture-stack-trace.test.js` 50/50. The stack-trace set is 627 pass, 0 fail: `test/js/node/v8`, `vm.test.ts`, `vm-sourceUrl.test.ts`, `util.test.js`, `test/js/bun/sourcemap`, `reportError.test.ts`, `console-log.test.ts`, `23022-stack-trace-iterator`, `circular-error-stack`, `circular-error-stack-edge-cases`, `fix-bindings-stack-trace`, `prepare-stack-trace-crash`. `stack.test.ts` and `013880.test.ts` pass on their own. `node:test` `test-error-prepare-stack-trace.js`, `test-util-getcallsites-preparestacktrace.js` and `test-shadow-realm-prepare-stack-trace.js` exit 0. Earlier drafts, whose reach was wider, also cleared the html-rewriter (207), plugin and resolve (506), streams (549), serve (295) and `node:http` (372) suites. Two failures in that area are not from this change, and each now has its own session. `test/regression/issue/013880.test.ts` leaks a global `Error.prepareStackTrace` into the shared test process and breaks 21 tests in `capture-stack-trace.test.js`. It reproduces on release 1.4.2: that file alone passes, and the two files together fail 21. `test/js/node/vm/script-leak.test.ts` sets an `isASAN` RSS threshold but no `isASAN` timeout, so it needs 25s against a 5s default on any `bun bd` build. #### Flake check The four new blocks passed 5 runs in a row, and 3 more with 24 CPU burners running, to stand in for a slow ASAN lane. Each reaction fixture needs a genuinely pending promise to make the native reaction exist. An already-resolved promise and a `queueMicrotask`-resolved promise both fail to install the suspension, which I checked, so the fixtures use `setTimeout(resolve, 1)` inside the fixture process. The test itself only awaits the process exit. Each reaction fixture also asserts `reactionFrameSeen=true`, so `leaked=undefined` cannot pass because the frame stopped appearing. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 4 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/js/node/v8/capture-stack-trace.test.js" bun test v1.4.3 (6a92015) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [24.55ms] (pass) throw inside Error.prepareStackTrace doesnt crash [40.55ms] (pass) capture stack trace [12.79ms] (pass) capture stack trace with message [14.33ms] (pass) capture stack trace with constructor [11.08ms] (pass) capture stack trace limit [43.64ms] (pass) prepare stack trace [22.91ms] (pass) capture stack trace second argument [35.13ms] (pass) capture stack trace edge cases [23.74ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [39.79ms] (pass) prepare stack trace call sites [24.06ms] (pass) sanity check [26.96ms] (pass) CallFrame isEval works as expected [16.18ms] (pass) CallFrame isTopLevel returns false for Function constructor [17.42ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [17.16ms] (pass) CallFrame.p.isConstructor [6.29ms] (pass) CallFrame.p.isNative [7.07ms] 726 | stderr: "pipe", 727 | }); 728 | 729 | const [stdout, st ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (8a7f62b) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [0.14ms] (pass) throw inside Error.prepareStackTrace doesnt crash [0.09ms] (pass) capture stack trace [0.09ms] (pass) capture stack trace with message [0.06ms] (pass) capture stack trace with constructor [0.06ms] (pass) capture stack trace limit [0.19ms] (pass) prepare stack trace [0.11ms] (pass) capture stack trace second argument [0.17ms] (pass) capture stack trace edge cases [0.10ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [0.22ms] (pass) prepare stack trace call sites [0.14ms] (pass) sanity check [0.11ms] (pass) CallFrame isEval works as expected [0.09ms] (pass) CallFrame isTopLevel returns false for Function constructor [0.09ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [0.10ms] (pass) CallFrame.p.isConstructor [0.03ms] (pass) CallFrame.p.isNative [0.03ms] (pass) CallFrame.p.getFunction does not expose the module loader reaction [9.47ms] (pass) CallFrame.p.getFunction does not expose the HTMLRewriter reaction [11.12ms] (pass) CallFrame.p.getFunction does not expose the serve reject reaction [11.29ms] (pass ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/js/node/v8/capture-stack-trace.test.js" bun test v1.4.3 (6a92015) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [22.42ms] (pass) throw inside Error.prepareStackTrace doesnt crash [33.22ms] (pass) capture stack trace [9.60ms] (pass) capture stack trace with message [10.80ms] (pass) capture stack trace with constructor [8.87ms] (pass) capture stack trace limit [32.05ms] (pass) prepare stack trace [17.69ms] (pass) capture stack trace second argument [24.93ms] (pass) capture stack trace edge cases [18.24ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [30.12ms] (pass) prepare stack trace call sites [19.79ms] (pass) sanity check [21.41ms] (pass) CallFrame isEval works as expected [11.96ms] (pass) CallFrame isTopLevel returns false for Function constructor [12.53ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [13.89ms] (pass) CallFrame.p.isConstructor [5.20ms] (pass) CallFrame.p.isNative [5.26ms] (pass) CallFrame.p.getFunction does not expose the serve reject reaction ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 710ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/9] cxx obj/src/jsc/bindings/ZigGlobalObject.cpp.o [2/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-1.cpp.o [3/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o [4/9] gen cpp.rs (cppbind) [4/9] cargo bun_runtime → libbun_runtime.a ^[[1m^[[92m Compiling^[[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) ^[[1m^[[92m Compiling^[[0m bun_errno v0.0.0 (/workspace/bun/src/errno) ^[[1m^[[92m Compiling^[[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) ^[[1m^[[92m Compiling^[[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) ^[[1m^[[92m Compiling^[[0m bun_safety v0.0.0 (/workspace/bun/src/safety) ^[[1m^[[92m Compiling^[[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) ^[[1m^[[92m Compiling^[[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) ^[[1m^[[92m Compiling^[[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) ^[[1m^[[92m Compiling^[[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) ^[[1m^[[92m Compiling^[[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) ^[[1m^[[92m Compiling^[[0m bun_brotli v ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/jsc/bindings/CallSite.cpp | 31 +++- src/jsc/bindings/CallSite.h | 2 + src/jsc/bindings/CallSitePrototype.cpp | 21 +-- test/js/node/v8/capture-stack-trace.test.js | 264 ++++++++++++++++++++++++++++ 4 files changed, 297 insertions(+), 21 deletions(-) ``` </details> **gate history** · 3 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/jsc/bindings/CallSite.cpp 5 11 34 src/jsc/bindings/CallSite.h 2 3 33 src/jsc/bindings/CallSitePrototype.cpp 2 2 33 test/js/node/v8/capture-stack-trace.test.js 6 10 33 ``` </details> **root cause** · written by the author bot `CallSite` treated a frame as non-strict whenever it lacked a CodeBlock with a strict executable, so native frames, builtin JS frames, and the internal async/generator body functions that JSC runs after the first suspension all had their callee stored and handed back through `getFunction()`; calling one of those internal callees with caller-chosen arguments let plain JavaScript write generator internal fields into arbitrary objects, which segfaulted the interpreter. The fix narrows the callee exposure in one place: the function is only stored when it is a `JSFunction` whose `FunctionExecuta… <!-- robobun:evidence:end -->
…tions (oven-sh#42464) ### Problem - `CallSite.getFunction()` (the `Error.prepareStackTrace` API) returned the frame's callee unchecked. JSC has callees user code could never have called: a host function, a builtin, an async or generator body function, or no function at all (wasm and program frames). - Five shapes crash 1.4.2, canary and main. After one `await`, calling what `getFunction()` returns gives `panic(main thread): Segmentation fault at address 0x32`. A wasm frame faults at `0x5` on the read. - Cause: `CallSite::finishCreation` (`src/jsc/bindings/CallSite.cpp:34`) only checks the strictness of the frame's code block. `JSCStackFrame` leaves that null for host and hidden builtin frames. ### Fix - `getFunction()` reports `undefined` unless the callee is a function user code could have called. A user function gets itself, including the CommonJS wrapper. - Caller frames keep their function: hiding a callee does not set `Flags::IsStrict`. `isToplevel()` reads a new flag computed from the real callee, so its answers do not change. - Deleted: the function-inspecting block in `callSiteProtoFuncIsToplevel`, and its `JSBoundFunction.h` include. - Verified: four new blocks in `test/js/node/v8/capture-stack-trace.test.js`, all failing on 1.4.2 and with `src/` reverted. 627 pass across the stack-trace suites. ### Background - JSC compiles an async function or a generator into a wrapper (what the user named) and a body that takes five internal arguments. The synchronous prefix runs in the body too, so the wrapper is never a frame's callee. - `createCallSitesFromFrames` (`FormatStackTraceForJS.cpp:844`) copies `isStrict()` down the frame list. JSC shows host frames V8 omits (`Reflect.construct` under a transpiled `super()`), so a cascade from a hidden callee would blank callers node reports. - JSC frames carry no receiver, so `isToplevel()` judges by the callee. <details><summary>Notes</summary> #### The five crashes A fuzz ledger reported the async body and three native promise reactions. A review of the first draft of this patch found the wasm frame. Each crashes release 1.4.2 (exit 139), and each exits cleanly with this change. | shape | 1.4.2 | with this change | | --- | --- | --- | | async function body after `await` | SEGV `0x32` | `undefined` | | generator body after `next()` | SEGV `0x32` | `undefined` | | wasm frame, on read alone | SEGV `0x5` | `undefined` | | HTMLRewriter suspension reaction | SEGV `0x12` | `undefined` | | `Bun.serve` `error()` reaction, and the `Bun.plugin` onLoad reaction | SEGV `0x12` / `0x1A` | `undefined` | The first fixture, as CommonJS so that the top frame is sloppy: ```js async function f() { await 1; Error.prepareStackTrace = (e, sites) => sites; return new Error().stack[0].getFunction(); } f().then(g => { console.log(g === f, g.length); g(); }); ``` 1.4.2 prints `false 5` and then segfaults. `0x32` is an encoded `undefined` (`0xa`) plus `0x28`, the offset of a generator internal field. Under ASAN the frames are `llint_op_put_internal_field <- llint_op_call_ignore_result <- llint_call_javascript <- JSC::MicrotaskCall::tryCallWithArguments`, so the body function wrote a generator field into a plain `undefined`. The wasm crash has three more entry shapes. Each is the same null callee, each segfaults 1.4.2 at `0x5`, and each exits cleanly with this change, also under ASAN: the wasm frame as the first call site of a trap (`WebAssembly.RuntimeError`, which is what an error reporter walks), a wasm stack overflow whose `RangeError` carries only wasm frames, and a wasm frame that JSPI resumed. The test covers the import-callback shape. The reaction crashes all reach the same place. A handler from `Zig::GlobalObject::thenable()` runs user JS synchronously: a later HTMLRewriter element handler, `Bun.serve`'s `error()`, or a getter on a plugin's onLoad result. That user JS keeps the nameless native function `getFunction()` reported, and calls it. The handler then reads its trailing argument as a native context. 12 of the 54 `PromiseFunctions` handlers decode a raw pointer from a JS number, so the class is worse than a bad cast. The host-function arm closes all of them, because `getFunction()` is the only way user code could name one. #### How old each route is The unchecked hand-out itself is old. Release 1.3.14 has the same logic in `CallSite.cpp`, `thenable()` is already `ImplementationVisibility::Public` there, and `Bun__NativePromiseContext__take` already uses `uncheckedDowncast` (oven-sh#28613). The fuzz ledger reports that the wasm shape crashes 1.3.14 too. The HTMLRewriter route is new in 1.4.0, and the ledger measured it: 1.3.14 is clean, 1.4.0 to 1.4.2 crash at `0x12`. The cause is oven-sh#36733, not an engine upgrade. Before it, the rewriter handled an async handler with `vm.wait_for_promise()`, which spins the event loop in place, so no native reaction existed. oven-sh#36733 suspends the rewrite and resumes it through `Bun__HTMLRewriter__onHandlerResolve`, which put a reaction frame on the stack for the first time. The `Bun.serve` `error()` route and the `Bun.plugin` onLoad route use machinery that predates 1.3.14 (the onLoad reaction is from 2022), so they are probably older than that window. I read that from history and did not run it: I have no 1.3.14 binary here. #### What node returns Measured on node v26.3.0 with the same fixtures. | frame | node | 1.4.2 | with this change | | --- | --- | --- | --- | | sloppy user function | itself | itself | itself | | CommonJS module wrapper | itself | itself | itself | | `Array.prototype.map` | undefined | the `map` function | undefined | | program frame under `eval` | undefined | a non-function `JSCallee` object | undefined | | async or generator body | the wrapper | the body (length 5) | undefined | | wasm frame | a `Number` | crash | undefined | | any caller below the above | see 2. below | itself | itself | Two divergences remain, both deliberate: 1. Node returns the wrapper for an async or generator frame. JSC keeps no back pointer from a body function to its wrapper, so the wrapper cannot be recovered. `getFunctionName()` still reports the user's name. JSC applies the same policy in `callerGetter` (`FunctionPrototype.cpp`). 2. Node blanks the caller frames below a builtin frame, because V8 compiles its builtins strict. Bun does not, and this change does not start. I measured that trigger: it moves a 22-shape host and builtin probe from 4/22 to 22/22 against node. It also blanks callers that node reports wherever JSC shows a host frame V8 hides, and `Reflect.construct` under Babel's `_callSuper` is one of those. It is a separable hunk. Say so if you want it. #### isToplevel() `m_function` has two readers, `getFunction()` and `isToplevel()`. The first push of this PR narrowed what `m_function` holds and did not account for the second reader. A review comment about dead branches in `callSiteProtoFuncIsToplevel` made me measure it: on a 16-row probe, `isToplevel()` flipped from `false` to `true` on 5 rows, the `Array.prototype.map` frame and every async or generator frame. `isToplevel()` now reads `Flags::IsSloppyFunctionCall`, which `finishCreation` computes from the real callee: the frame is sloppy and its callee is a `JSFunction` that is not a host function. All 16 rows match 1.4.2 again, and four new `...IsToplevel=false` test rows pin it. Those rows fail on the first push of this PR. The replaced block had a `JSBoundFunction` arm, a host-function arm, a `jsExecutable()` arm and an `InternalFunction` arm. With `m_function` narrowed, only the `jsExecutable()` arm could still run. The `JSBoundFunction` arm never could: a bound-function thunk is `ImplementationVisibility::Private` and never gets a `CallSite`, which I checked on both the `prepareStackTrace` and the `captureStackTrace` path. #### Dropped from the first draft The first draft cascaded from every hidden callee and carried three hardening hunks. A review plus my own measurements cut all four: - The cascade blanked `getFunction()` for a plain sloppy caller that both node and 1.4.2 return. - `ImplementationVisibility::Private` on the `thenable()` handlers hides a useless `at unknown` frame. With `BUN_JSC_showPrivateScriptsInStackTraces=0` it also flips `typeof err.stack` from `"string"` to `"undefined"` for three `Bun.plugin` onLoad validation errors, whose only frame was the reaction. It needs the empty-frame-vector case to produce a header-only stack first, the way `FormatStackTraceForJS.cpp:234` already does for the `captureStackTrace` path. Worth doing, but not here. - A `dynamicDowncast` in `Bun__NativePromiseContext__take`. oven-sh#40203 is open and already touches that function. - Two `dynamicDowncast` guards in the module loader onLoad reactions. With this change nothing can reach them, and an unreachable, untested guard is not worth the lines. #### Suites run, on the debug ASAN build `capture-stack-trace.test.js` 50/50. The stack-trace set is 627 pass, 0 fail: `test/js/node/v8`, `vm.test.ts`, `vm-sourceUrl.test.ts`, `util.test.js`, `test/js/bun/sourcemap`, `reportError.test.ts`, `console-log.test.ts`, `23022-stack-trace-iterator`, `circular-error-stack`, `circular-error-stack-edge-cases`, `fix-bindings-stack-trace`, `prepare-stack-trace-crash`. `stack.test.ts` and `013880.test.ts` pass on their own. `node:test` `test-error-prepare-stack-trace.js`, `test-util-getcallsites-preparestacktrace.js` and `test-shadow-realm-prepare-stack-trace.js` exit 0. Earlier drafts, whose reach was wider, also cleared the html-rewriter (207), plugin and resolve (506), streams (549), serve (295) and `node:http` (372) suites. Two failures in that area are not from this change, and each now has its own session. `test/regression/issue/013880.test.ts` leaks a global `Error.prepareStackTrace` into the shared test process and breaks 21 tests in `capture-stack-trace.test.js`. It reproduces on release 1.4.2: that file alone passes, and the two files together fail 21. `test/js/node/vm/script-leak.test.ts` sets an `isASAN` RSS threshold but no `isASAN` timeout, so it needs 25s against a 5s default on any `bun bd` build. #### Flake check The four new blocks passed 5 runs in a row, and 3 more with 24 CPU burners running, to stand in for a slow ASAN lane. Each reaction fixture needs a genuinely pending promise to make the native reaction exist. An already-resolved promise and a `queueMicrotask`-resolved promise both fail to install the suspension, which I checked, so the fixtures use `setTimeout(resolve, 1)` inside the fixture process. The test itself only awaits the process exit. Each reaction fixture also asserts `reactionFrameSeen=true`, so `leaked=undefined` cannot pass because the frame stopped appearing. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 1 · 4 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 4 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/js/node/v8/capture-stack-trace.test.js" bun test v1.4.3 (6a92015) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [24.55ms] (pass) throw inside Error.prepareStackTrace doesnt crash [40.55ms] (pass) capture stack trace [12.79ms] (pass) capture stack trace with message [14.33ms] (pass) capture stack trace with constructor [11.08ms] (pass) capture stack trace limit [43.64ms] (pass) prepare stack trace [22.91ms] (pass) capture stack trace second argument [35.13ms] (pass) capture stack trace edge cases [23.74ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [39.79ms] (pass) prepare stack trace call sites [24.06ms] (pass) sanity check [26.96ms] (pass) CallFrame isEval works as expected [16.18ms] (pass) CallFrame isTopLevel returns false for Function constructor [17.42ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [17.16ms] (pass) CallFrame.p.isConstructor [6.29ms] (pass) CallFrame.p.isNative [7.07ms] 726 | stderr: "pipe", 727 | }); 728 | 729 | const [stdout, st ... (truncated) release without fix: all passed bun test v1.4.3-canary.1 (8a7f62b) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [0.14ms] (pass) throw inside Error.prepareStackTrace doesnt crash [0.09ms] (pass) capture stack trace [0.09ms] (pass) capture stack trace with message [0.06ms] (pass) capture stack trace with constructor [0.06ms] (pass) capture stack trace limit [0.19ms] (pass) prepare stack trace [0.11ms] (pass) capture stack trace second argument [0.17ms] (pass) capture stack trace edge cases [0.10ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [0.22ms] (pass) prepare stack trace call sites [0.14ms] (pass) sanity check [0.11ms] (pass) CallFrame isEval works as expected [0.09ms] (pass) CallFrame isTopLevel returns false for Function constructor [0.09ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [0.10ms] (pass) CallFrame.p.isConstructor [0.03ms] (pass) CallFrame.p.isNative [0.03ms] (pass) CallFrame.p.getFunction does not expose the module loader reaction [9.47ms] (pass) CallFrame.p.getFunction does not expose the HTMLRewriter reaction [11.12ms] (pass) CallFrame.p.getFunction does not expose the serve reject reaction [11.29ms] (pass ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" "test/js/node/v8/capture-stack-trace.test.js" bun test v1.4.3 (6a92015) test/js/node/v8/capture-stack-trace.test.js: (pass) Regular .stack [22.42ms] (pass) throw inside Error.prepareStackTrace doesnt crash [33.22ms] (pass) capture stack trace [9.60ms] (pass) capture stack trace with message [10.80ms] (pass) capture stack trace with constructor [8.87ms] (pass) capture stack trace limit [32.05ms] (pass) prepare stack trace [17.69ms] (pass) capture stack trace second argument [24.93ms] (pass) capture stack trace edge cases [18.24ms] (pass) Error.captureStackTrace installs .stack as non-enumerable [30.12ms] (pass) prepare stack trace call sites [19.79ms] (pass) sanity check [21.41ms] (pass) CallFrame isEval works as expected [11.96ms] (pass) CallFrame isTopLevel returns false for Function constructor [12.53ms] (pass) CallFrame.p.getThisgetFunction: strict/sloppy mode interaction [13.89ms] (pass) CallFrame.p.isConstructor [5.20ms] (pass) CallFrame.p.isNative [5.26ms] (pass) CallFrame.p.getFunction does not expose the serve reject reaction ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 710ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/9] cxx obj/src/jsc/bindings/ZigGlobalObject.cpp.o [2/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-1.cpp.o [3/9] cxx obj/unified/UnifiedSource-src_jsc_bindings-0.cpp.o [4/9] gen cpp.rs (cppbind) [4/9] cargo bun_runtime → libbun_runtime.a ^[[1m^[[92m Compiling^[[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) ^[[1m^[[92m Compiling^[[0m bun_errno v0.0.0 (/workspace/bun/src/errno) ^[[1m^[[92m Compiling^[[0m bun_ptr v0.0.0 (/workspace/bun/src/ptr) ^[[1m^[[92m Compiling^[[0m bun_boringssl_sys v0.0.0 (/workspace/bun/src/boringssl_sys) ^[[1m^[[92m Compiling^[[0m bun_safety v0.0.0 (/workspace/bun/src/safety) ^[[1m^[[92m Compiling^[[0m bun_base64 v0.0.0 (/workspace/bun/src/base64) ^[[1m^[[92m Compiling^[[0m bun_cares_sys v0.0.0 (/workspace/bun/src/cares_sys) ^[[1m^[[92m Compiling^[[0m bun_zlib_sys v0.0.0 (/workspace/bun/src/zlib_sys) ^[[1m^[[92m Compiling^[[0m bun_zstd v0.0.0 (/workspace/bun/src/zstd) ^[[1m^[[92m Compiling^[[0m bun_picohttp v0.0.0 (/workspace/bun/src/picohttp) ^[[1m^[[92m Compiling^[[0m bun_brotli v ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/jsc/bindings/CallSite.cpp | 31 +++- src/jsc/bindings/CallSite.h | 2 + src/jsc/bindings/CallSitePrototype.cpp | 21 +-- test/js/node/v8/capture-stack-trace.test.js | 264 ++++++++++++++++++++++++++++ 4 files changed, 297 insertions(+), 21 deletions(-) ``` </details> **gate history** · 3 passed · 0 rejected · iteration 1 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/jsc/bindings/CallSite.cpp 5 11 34 src/jsc/bindings/CallSite.h 2 3 33 src/jsc/bindings/CallSitePrototype.cpp 2 2 33 test/js/node/v8/capture-stack-trace.test.js 6 10 33 ``` </details> **root cause** · written by the author bot `CallSite` treated a frame as non-strict whenever it lacked a CodeBlock with a strict executable, so native frames, builtin JS frames, and the internal async/generator body functions that JSC runs after the first suspension all had their callee stored and handed back through `getFunction()`; calling one of those internal callees with caller-chosen arguments let plain JavaScript write generator internal fields into arbitrary objects, which segfaulted the interpreter. The fix narrows the callee exposure in one place: the function is only stored when it is a `JSFunction` whose `FunctionExecuta… <!-- robobun:evidence:end -->
Summary
When
Bun.serve()'s fetch handler returns a pendingPromise<Response>and the client disconnects before it settles, theRequestContextleaked forever. Thectx.ref()before.then()was only balanced byonResolve/onReject, which never fire for unsettled promises.This introduces
NativePromiseContext— a minimal GC-managed JSCell that owns the ref:JSC::JSCell+CellType+ customIsoHeapCellTypefor destructor supportCompactPointerTuple<Pointee*, Tag>packs pointer + tag in 8 bytes (cell = JSCell header + 1 word)take()transfers ownership for deterministic cleanup in the normal pathWeak<>overheadIf the Promise settles:
onResolvecallstake()→ processes →deref(). Cell destructor later sees null, no-ops.If the Promise is GC'd without settling: cell collected with its reaction → destructor →
deref(). No leak, no UAF.Applied to all three
.then()callsites inRequestContext: main response promise, error handler promise, and response body stream promise.Test plan
test/js/bun/http/serve-pending-promise-abort-leak.test.ts— 4 tests covering the leak fix, normal resolution, resolve-in-abort-handler, and resolve-after-abort-via-setTimeout (UAF safety)LEAK: 100 RequestContexts were never freedpendingRequests: 0heapStats().objectTypeCounts.NativePromiseContextshows 50 for 50 concurrent pending, 0 after resolve+GCserve.test.ts: 189 passbun-serve-routes.test.ts+bun-serve-headers.test.ts: 41 passBUN_JSC_validateExceptionChecks=1: clean