Skip to content

Keep async context active while settling the async function promise - #295

Merged
Jarred-Sumner merged 1 commit into
mainfrom
robobun/async-function-resume-thenable-context
Jul 15, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
robobun/async-function-resume-thenable-context

Conversation

@robobun

@robobun robobun commented Jul 15, 2026

Copy link
Copy Markdown
Collaborator

Problem

oven-sh/bun#34266: a thenable returned from an async function that has suspended at least once runs its then() (and, for a getter-defined then, the Get(thenable, "then") lookup) with an empty AsyncLocalStorage context:

import { AsyncLocalStorage } from "node:async_hooks";
const als = new AsyncLocalStorage();

async function f() {
  await null; // any await before the return triggers the bug
  return {
    then(resolve) {
      console.log(als.getStore()); // undefined in Bun, "CTX" in Node
      resolve(42);
    },
  };
}

await als.run("CTX", () => f());

This breaks ORMs that expose queries as thenables and read the ambient transaction from AsyncLocalStorage inside then() (Knex, Objection.js, Orchid ORM).

Cause

InternalMicrotask::AsyncFunctionResume restores Bun's async context before calling promise->resolve() / promise->reject() on the body-completed paths. JSPromise::resolvePromise performs Get(resolution, "then") synchronously and captures the current async context into the queued PromiseResolveThenableJob, so by that point the context has already been swapped back to the outer (empty) one.

Fix

Settle the promise first, then restore the outer context, matching the ordering PromiseReactionJob already uses ("Keep async context active during resolvePromise/rejectPromise so that any thenables returned from the handler can capture the correct async context") and the await-suspension path in the same handler.

Verification

Built Bun against this change locally: the repro above prints "CTX", and test/js/node/async_hooks/ passes (112 pass, 0 fail). Bun-side test: oven-sh/bun PR adding "Returning a thenable in an async function after an await" to test/js/node/async_hooks/async-local-storage-thenable.test.ts.

…ion promise

InternalMicrotask::AsyncFunctionResume restored Bun's async context before
calling promise->resolve()/reject() when the async function body completed.
JSPromise::resolvePromise captures the current async context when it queues
PromiseResolveThenableJob (and performs Get(resolution, "then")
synchronously), so a thenable returned from an async function that had
suspended at least once ran its then() with an empty AsyncLocalStorage
context.

Settle the promise before restoring the outer context, matching the ordering
PromiseReactionJob and the await-suspension path already use.

Fixes oven-sh/bun#34266
@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@robobun, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b96832e2-d102-4baf-b5c9-4879626df7cb

📥 Commits

Reviewing files that changed from the base of the PR and between 4895f45 and ff8154f.

📒 Files selected for processing (1)
  • Source/JavaScriptCore/runtime/JSMicrotask.cpp

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM — targeted reorder that mirrors the existing PromiseReactionJob pattern.

What was reviewed:

  • Confirmed the new ordering matches PromiseReactionJob (JSMicrotask.cpp:1855-1866) and the await-suspension path in the same handler (2012-2018).
  • Checked that putInternalField still runs after resolve/reject even if a JS exception is pending — it's a plain field write, no early return.
  • Verified scope.release() placement is unchanged relative to the settle call; only the Bun context-restore moved.
Extended reasoning...

Overview

The PR reorders two statements on the error and State::Executing branches of InternalMicrotask::AsyncFunctionResume in JSMicrotask.cpp: it now calls promise->reject() / promise->resolve() before restoring Bun's outer async context via asyncContextData->putInternalField(vm, 0, restoreAsyncContext), rather than after. A comment is added explaining why.

Security risks

None. This is Bun-specific (USE(BUN_JSC_ADDITIONS)) AsyncLocalStorage context propagation. No new inputs, no allocation changes, no type-confusion surface — just statement ordering.

Level of scrutiny

This is core JSC runtime code on the async function completion path, so it warrants a careful look. However, the change is a pure reordering of existing statements with no new logic. Crucially, it makes these two branches consistent with:

  • The PromiseReactionJob case ~130 lines earlier in the same function, which already carries the exact comment and ordering this PR introduces ("Keep async context active during resolvePromise/rejectPromise so that any thenables returned from the handler can capture the correct async context").
  • The third branch of AsyncFunctionResume itself (the await-again path calling resolveWithInternalMicrotaskForAsyncAwait), which already restores context after the settle call.

So this is bringing two outlier branches in line with the established pattern, not introducing a new one.

Other factors

  • scope.release() remains immediately before the settle call, as before — only the #if USE(BUN_JSC_ADDITIONS) restore block moved.
  • If resolve/reject leave a pending JS exception, C++ control flow continues and putInternalField (a plain internal-field write) still executes, so the outer context is always restored before return. This matches how PromiseReactionJob already behaves.
  • The PR description reports the fix was verified against a local Bun build (repro now prints "CTX") and test/js/node/async_hooks/ passes (112/112), with a companion Bun-side regression test.
  • The bug hunting system found no issues.

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
ff8154f3 autobuild-preview-pr-295-ff8154f3 2026-07-15 20:45:02 UTC

@Jarred-Sumner
Jarred-Sumner merged commit e5f7fc2 into main Jul 15, 2026
49 checks passed
robobun added a commit to oven-sh/bun that referenced this pull request Jul 16, 2026
The AsyncFunctionResume settle-ordering fix landed independently as
oven-sh/WebKit#295, so #268 was rebased onto it and now carries only the
PromiseFinallyAwaitJob fix. Pin to the new preview (on top of e5f7fc2b).
robobun added a commit to oven-sh/bun that referenced this pull request Jul 18, 2026
The AsyncFunctionResume settle-ordering fix landed independently as
oven-sh/WebKit#295, so #268 was rebased onto it and now carries only the
PromiseFinallyAwaitJob fix. Pin to the new preview (on top of e5f7fc2b).
robobun added a commit to oven-sh/bun that referenced this pull request Jul 18, 2026
The AsyncFunctionResume settle-ordering fix landed independently as
oven-sh/WebKit#295, so #268 was rebased onto it and now carries only the
PromiseFinallyAwaitJob fix. Pin to the new preview (on top of e5f7fc2b).
robobun added a commit to oven-sh/bun that referenced this pull request Jul 18, 2026
The AsyncFunctionResume settle-ordering fix landed independently as
oven-sh/WebKit#295, so #268 was rebased onto it and now carries only the
PromiseFinallyAwaitJob fix. Pin to the new preview (on top of e5f7fc2b).
robobun added a commit to oven-sh/bun that referenced this pull request Jul 18, 2026
The AsyncFunctionResume settle-ordering fix landed independently as
oven-sh/WebKit#295, so #268 was rebased onto it and now carries only the
PromiseFinallyAwaitJob fix. Pin to the new preview (on top of e5f7fc2b).
robobun added a commit to oven-sh/bun that referenced this pull request Jul 18, 2026
The previous preview was based on WebKit main, which pulled in the
JSMicrotask/JSPromise refactors (oven-sh/WebKit#295/#301) and nudged the
node-net mimalloc-page-count leak test past its threshold on aarch64.
The minimal branch carries only the termination fixes the new stress
test needs (plus Jarred's oven-sh/WebKit#286 for the property-lookup
assertions the same sweep surfaces).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants