Skip to content

JSC: route promise jobs to the handler/then realm's microtask queue - #277

Open
robobun wants to merge 1 commit into
mainfrom
farm/536434af/promise-job-handler-realm-routing
Open

robobun wants to merge 1 commit into
mainfrom
farm/536434af/promise-job-handler-realm-routing

Conversation

@robobun

@robobun robobun commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

HTML's HostEnqueuePromiseJob places a PromiseReactionJob on the handler's realm's microtask queue and a PromiseResolveThenableJob on then's realm's queue. JSC instead enqueues on the caller's global (typically the promise's realm). While every global shares the VM's default queue the two are equivalent, but Bun's node:vm gives a context its own MicrotaskQueue for microtaskMode: "afterEvaluate", and there the difference is observable.

Repro (under bun)

const vm = require('node:vm');
const c = vm.createContext({}, { microtaskMode: 'afterEvaluate' });
const p = vm.runInContext("Promise.resolve('v')", c);
p.then(v => console.log('then:', v));
setImmediate(() => console.log('done'));
// node v26.3.0:  then: v  /  done
// bun (before):  done          <- host handler never runs

Cause

performPromiseThen / settleInlineHandler / triggerPromiseReactions call globalObject->queueMicrotask(...) where globalObject is the then function's realm (the context). Under afterEvaluate that is the context's private queue, which only drains inside the next evaluation of that context, so a reaction attached from the host is stranded forever. The same mismatch in the other direction (host promise, context handler) runs on the host queue instead of waiting for the context to be drained.

Fix

Add globalObjectForPromiseJob(vm, globalObject, callable) which returns callable's realm when its microtask queue differs from globalObject's, and apply it at the PromiseReactionJob and PromiseResolveThenableJob* enqueue sites. The redirect is gated on a new VM::mayHaveMultipleMicrotaskQueues() flag that is set the first time JSGlobalObject::setMicrotaskQueue installs a non-default queue, so programs that never create an afterEvaluate context pay one predicted-not-taken branch.

The thenable-job routing is needed so await contextPromise keeps matching Node: the thenable job goes on then's realm's queue (the context), and only runs when that context is next drained. Without it the reaction-job redirect alone would let the await resume immediately.

Verification

Against a bun built with this change:

  • test/js/node/test/parallel/test-vm-script-after-evaluate.js exits 0
  • test/js/node/test/parallel/test-vm-module-after-evaluate.js exits 0
  • test/js/node/test/parallel/test-vm-timeout-escape-promise*.{js,mjs} exit 0
  • test/js/node/vm/vm.test.ts passes (210 tests)
  • test/js/node/async_hooks/ passes (111 tests)
  • the four new routing cases in bun's companion PR (host .then/.catch on a settled context promise, host .then on a pending context promise, context .then on a host promise) match Node

Companion bun PR with the tests: oven-sh/bun#33765

@coderabbitai

coderabbitai Bot commented Jul 8, 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: 27 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: a812242f-0f32-43f3-9a44-5efb5b22368e

📥 Commits

Reviewing files that changed from the base of the PR and between a8d15c1 and 0a3688d.

📒 Files selected for processing (3)
  • Source/JavaScriptCore/runtime/JSGlobalObject.cpp
  • Source/JavaScriptCore/runtime/JSPromise.cpp
  • Source/JavaScriptCore/runtime/VM.h

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

@github-actions

github-actions Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Preview Builds

Commit Release Date
0a3688dd autobuild-preview-pr-277-0a3688dd 2026-07-18 03:09:54 UTC
d6999dc9 autobuild-preview-pr-277-d6999dc9 2026-07-08 16:05:34 UTC

@robobun
robobun force-pushed the farm/536434af/promise-job-handler-realm-routing branch from d6999dc to f0cf430 Compare July 18, 2026 02:26
HTML's HostEnqueuePromiseJob places a PromiseReactionJob on the
handler's realm's microtask queue, and a PromiseResolveThenableJob on
then's realm's queue. JSC enqueues both on the caller's global
(typically the promise's realm), which is fine while every global
shares the VM's default queue.

Bun's node:vm gives a context its own MicrotaskQueue for
microtaskMode: "afterEvaluate". With the old routing, a host
.then(handler) on a context promise landed on the context's isolated
queue and was never drained, and a context handler on a host promise
ran immediately on the host queue instead of waiting for the next
evaluation. V8 already keys the enqueue on the handler's context.

Gate the redirect on a VM flag set the first time any global installs
a non-default microtask queue, so the common single-queue case is one
predicted-not-taken branch.
@robobun
robobun force-pushed the farm/536434af/promise-job-handler-realm-routing branch from f0cf430 to 0a3688d Compare July 18, 2026 02:31

@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.

Additional findings (outside current diff — PR may have been updated during review):

  • 🟡 Source/JavaScriptCore/runtime/JSPromise.cpp:1075-1077 — Redirecting PromiseResolveThenableJobWithInternalMicrotask to then's realm also drags the follow-up AsyncFunctionResume onto that realm's queue: the job now runs with globalObject == contextGlobal, so createResolvingFunctionsWithInternalMicrotask mints context-realm resolve/reject, and when they fire fulfillWithInternalMicrotask enqueues the resume on the context queue instead of the awaiter's (host) queue. Per spec the elided intermediate promise's onFulfilled is host-realm, so the resume belongs on the host queue — observable as a host await contextThenable resuming inside runInContext's drain rather than after it. Still a strict improvement over pre-PR and the fix (threading the awaiter's realm through the ResolvingWithInternalMicrotask context cell) is a nontrivial refactor, so fine as a follow-up alongside the GetFunctionRealm note.

    Extended reasoning...

    What happens

    The PR correctly routes PromiseResolveThenableJobWithInternalMicrotask to then's realm at line 1076. But because JSC's internal-microtask fast path elides the spec's intermediate promise, the next hop — the AsyncFunctionResume (or other internal-microtask continuation) that resumes the awaiting code — now also lands on then's realm's queue instead of the awaiter's realm's queue.

    Step-by-step trace

    Take a host async function doing await p where p is a context-realm promise (or any thenable whose .then lives in an afterEvaluate context) and the fast paths in resolveWithInternalMicrotaskForAsyncAwait miss (e.g. p->realm() != hostGlobal and constructor != hostGlobal->promiseConstructor()):

    1. resolveWithInternalMicrotask(hostGlobal, vm, p, AsyncFunctionResume, ctx) reaches line 1076. globalObjectForPromiseJob(vm, hostGlobal, then) returns contextGlobal (its queue differs from the host's), and PromiseResolveThenableJobWithInternalMicrotask is enqueued there. JSGlobalObject::queueMicrotask stores this (contextGlobal) as the QueuedTask dispatcher.
    2. When the context's private queue drains, MicrotaskQueue::drainImpl reads the task's stored dispatcher and invokes runInternalMicrotask with globalObject == contextGlobal.
    3. JSMicrotask.cpp:1666 calls createResolvingFunctionsWithInternalMicrotask(vm, contextGlobal, task, context). The resolve/reject JSFunctionWithFields are allocated in contextGlobal — their realm() is the context.
    4. The context-realm then schedules and eventually calls resolve(v). promiseResolvingFunctionResolveWithInternalMicrotask receives globalObject == contextGlobal (callee's realm) and forwards to resolveWithInternalMicrotask(contextGlobal, vm, v, AsyncFunctionResume, ctx).
    5. For a non-thenable v that lands in fulfillWithInternalMicrotask(vm, contextGlobal, v, AsyncFunctionResume, ctx), which unconditionally does globalObject->queueMicrotask(...). AsyncFunctionResume is enqueued on the context's private queue.

    Why the spec says host queue

    Per ECMA-262 Await, the intermediate promise and its onFulfilled continuation are created in the awaiting async function's realm (host). The thenable job runs on then's realm's queue and fulfills that intermediate host-realm promise; TriggerPromiseReactions then routes the resume reaction to onFulfilled's realm — the host queue — via HTML's HostEnqueuePromiseJob. JSC's internal-microtask fast path elides the intermediate promise, and after this PR the elided path no longer carries the awaiter's realm through: the resume follows the resolve function's realm instead.

    The non-elided PromiseResolveThenableJob path (JSMicrotask.cpp:1640–1651) is unaffected because it keeps a real promiseToResolve; createResolvingFunctions stores that promise, and promiseResolvingFunctionResolve → resolvePromise → fulfillPromise uses this->realm() (host) plus triggerPromiseReactions' per-handler redirect.

    Observable divergence from Node

    const vm = require('node:vm');
    const c = vm.createContext({}, { microtaskMode: 'afterEvaluate' });
    const p = vm.runInContext("Promise.resolve(1)", c);
    let resumed = false;
    (async () => { await p; resumed = true; })();
    queueMicrotask(() => {});   // drain host once — thenable job is on the context queue, still pending
    vm.runInContext('0', c);    // drains the context queue
    console.log(resumed);
    // Node:            false — resume is on the host queue, runs after this line
    // Bun (this PR):   true  — resume ran on the context queue inside runInContext

    Before this PR the resume also mis-landed (differently — the whole chain sat on the host queue and could strand); after this PR the thenable job correctly moves to the context queue but the resume follows it there instead of returning to the host. It's a timing/ordering divergence, not a hang or crash — the await always resumes once the context queue drains.

    Why nothing prevents it / how to fix

    createResolvingFunctionsWithInternalMicrotask stores only task + context in the resolve/reject fields (via a JSSlimPromiseReaction context cell); the original awaiter's globalObject is not threaded through, and fulfillWithInternalMicrotask / rejectWithInternalMicrotask enqueue on whatever globalObject they're handed. A fix would carry the awaiter's realm alongside task/context (e.g. in the context cell's currently-unused promise slot) so promiseResolvingFunction{Resolve,Reject}WithInternalMicrotask can pass it to fulfillWithInternalMicrotask. That's a nontrivial refactor and reasonable as a follow-up — the PR remains a strict improvement for its stated cases and its listed tests are unaffected.

@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.

The getFunctionRealm change in 0a3688d looks right — the revoked-Proxy TypeError is caught and falls back to the caller's global, and termination isn't swallowed. No issues found this pass, but this reworks which microtask queue every PromiseReactionJob / PromiseResolveThenableJob lands on, so it's worth a human look.

Checked: all globalObjectForPromiseJob call sites pass a value already confirmed .isCallable() (satisfying getFunctionRealm's assert); the nullptr return on revoked Proxy is guarded by the scope.exception() check before callableRealm is dereferenced; the triggerPromiseReactions fallthrough only routes when task == PromiseReactionJob so PromiseResolveWithoutHandlerJob (whose handler slot holds argument, not a callable) stays on the caller's global; and the fast path is a single VM-flag branch, so no overhead until a non-default queue is installed.

Extended reasoning...

Overview

The PR adds globalObjectForPromiseJob() in JSPromise.cpp and threads it through eight enqueue sites (performPromiseThen, performPromiseThenWithContext, settleInlineHandler, resolvePromise, triggerPromiseReactions ×2, resolveWithInternalMicrotask) so that promise reaction and thenable jobs are enqueued on the handler's / then's realm's microtask queue rather than the caller's, per HTML's HostEnqueuePromiseJob. It adds a sticky VM::m_mayHaveMultipleMicrotaskQueues flag set from JSGlobalObject::setMicrotaskQueue to keep the common case (every global on the default queue) at one predicted branch. Since my prior comment, the slow path was moved to a NEVER_INLINE helper that calls getFunctionRealm under a TopExceptionScope and clears the revoked-Proxy TypeError via clearExceptionExceptTermination().

Security risks

None identified. The change is entirely about which MicrotaskQueue a job is appended to; it doesn't touch parsing, JIT, memory layout, or trust boundaries. All new code is under USE(BUN_JSC_ADDITIONS).

Level of scrutiny

High. JSPromise::performPromiseThen / triggerPromiseReactions / resolvePromise are on the hot path of every await and .then in the runtime, and cross-realm microtask ordering is subtle spec territory. The fast-path gate keeps perf risk low, but the semantic change — jobs from a promise in realm A with a handler from realm B now land on B's queue — deserves human sign-off, especially the interaction with Bun's afterEvaluate drain model and the PromiseResolveThenableJobFast path (which already uses promise->realm() and was left untouched).

Other factors

My earlier nit (use getFunctionRealm to unwrap bound/Proxy handlers) was addressed in 0a3688d and the thread is resolved. I re-checked the new slow path: getFunctionRealm returns nullptr only after throwing, and the scope.exception() guard returns globalObject before the null is used; clearExceptionExceptTermination() preserves a pending termination so it isn't masked. Every call site that reaches the slow path has already established the value is callable (via isCallable() checks or the handler.isUndefined() normalization in triggerPromiseReactions), so the ASSERT(object->isCallable()) inside getFunctionRealm holds. The companion Bun PR carries the tests. Deferring because this is a behavioral change to core promise scheduling, not because of any concrete concern.

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.

1 participant