Skip to content

[JSC] A module loader can name the async context its modules' top-level code runs in - #646

Merged
Jarred-Sumner merged 1 commit into
mainfrom
claude/module-loader-async-context
Sep 14, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
claude/module-loader-async-context

Conversation

@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

JSModuleLoader::setAsyncContext(vm, context): when set, JSModuleRecord::execute runs a module of that loader with context installed in JSGlobalObject::m_asyncContextData field 0 (an AsyncContextSwapScope), instead of whatever is current when the loader pipeline reaches the module. Empty (the default) changes nothing.

Why

An embedder-created loader (#522) evaluates its modules from the loader pipeline's microtasks, which carry no async context. A module with top-level await captures the current async context for its first await in asyncModuleResolveEvaluation, after moduleLoader()->evaluate(...) — the embedder's evaluate hook — has returned, so an embedder that enters a context around its hook still gets a module whose code after the first top-level await runs with none: AsyncModuleExecutionResume restores what was captured, and then calls module->evaluate() directly, not through the hook.

With the scope in execute() spanning both the body and that capture, the first await captures the loader's context and every later resume restores what its own await captured, as for any async function.

Bun uses this for Bun.unsafe.ModuleGraph({ isolateIO: true }): the graph's context (which owns the timers, sockets and handles its code opens) travels as an async context frame, and the graph's modules must run in it however their evaluation is reached.

Changes

  • JSModuleLoader: m_asyncContext (WriteBarrier<Unknown>, visited), asyncContext() / setAsyncContext(), under USE(BUN_JSC_ADDITIONS).
  • JSModuleRecord::execute: an AsyncContextSwapScope for the loader's context, when it has one.

Tested from Bun (test/js/bun/module-graph/module-graph-io.test.ts, "code after a top-level await is still in the graph's context": a timer armed after a top-level await, and one armed by a dependency with its own top-level await, stop when the graph is disposed; both fail without this).

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
81aba39b autobuild-preview-pr-646-81aba39b 2026-09-13 12:20:25 UTC

Jarred-Sumner added a commit to oven-sh/bun that referenced this pull request Sep 13, 2026
JSModuleLoader::setAsyncContext. To be replaced by the merged commit before this lands.

No-Verification-Needed: version bump
@Jarred-Sumner
Jarred-Sumner marked this pull request as ready for review September 14, 2026 02:23
@Jarred-Sumner
Jarred-Sumner merged commit cc4a560 into main Sep 14, 2026
48 checks passed

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

I reviewed this PR and didn't find any bugs. It's a small, well-guarded change that follows existing patterns, but since it touches module top-level execution semantics in JSC (a CODEOWNERS-covered path) and the interaction with TLA resume is subtle, a human look would still be worthwhile.

What was reviewed:

  • GC correctness: m_asyncContext is a WriteBarrier<Unknown>, setAsyncContext uses .set(vm, this, ...), and it's appended in visitChildrenImpl alongside m_moduleScope.
  • Null safety: moduleLoader() is already dereferenced unconditionally later in execute(), so the new call adds no new hazard; empty m_asyncContext short-circuits and preserves current behavior.
  • Non-Bun builds: AsyncContextSwapScope.h is included unconditionally but its body is #if USE(BUN_JSC_ADDITIONS)-guarded, so it's a no-op include when the flag is off.
  • Scope placement: the RAII scope spans both the sync body and asyncModuleResolveEvaluation, so the first TLA capture sees the loader's context as described.
Extended reasoning...

Overview

This PR adds an optional per-loader async context to JSModuleLoader and installs it (via the existing AsyncContextSwapScope RAII helper) around JSModuleRecord::execute. Three files change: a new WriteBarrier<Unknown> m_asyncContext field with accessors and GC visitation in JSModuleLoader.{h,cpp}, and a std::optional<AsyncContextSwapScope> emplaced at the top of JSModuleRecord::execute in JSModuleRecord.cpp. Everything new is behind #if USE(BUN_JSC_ADDITIONS), and the default (unset) field leaves behavior unchanged.

Security risks

None identified. The change adds no new attacker-reachable surface: setAsyncContext is a C++-only setter with no JS binding in this diff, so only the embedder can populate it. The stored value is properly write-barriered and visited, so there's no GC hazard, and the swap scope is stack-only (WTF_FORBID_HEAP_ALLOCATION) so the saved previous context is conservatively rooted. The unconditional #include "AsyncContextSwapScope.h" is safe for non-Bun builds because that header's contents are themselves guarded.

Level of scrutiny

Moderate-to-high. The diff is ~30 lines and mechanically mirrors the existing m_moduleScope field pattern, which lowers risk. However, it sits directly in the ES module execution path and alters which async context is observable during top-level evaluation and the first TLA capture — a subtle semantic area where a design-level sanity check by a human familiar with Bun's AsyncLocalStorage and ModuleGraph({ isolateIO: true }) model is appropriate. Source/JavaScriptCore is also covered by CODEOWNERS (@ WebKit/jsc-reviewers), which per policy weighs against auto-approval even in the fork.

Other factors

moduleLoader() is already assumed non-null in execute() (it's called on both the sync and TLA branches), so the new dereference introduces no new precondition. AsyncContextSwapScope's constructor is a no-op when !vm.isAsyncContextTrackingEnabled(), so an embedder that sets a loader context without enabling tracking is harmless. Testing is on the Bun side (test/js/bun/module-graph/module-graph-io.test.ts), not in this repo, so there's no in-tree coverage to run here.

@coderabbitai

coderabbitai Bot commented Sep 14, 2026

Copy link
Copy Markdown

Review Change StackReview Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 4e473ac4-a436-480b-98fb-7734c7ea0179

📥 Commits

Reviewing files that changed from the base of the PR and between 28f58fb and 81aba39.

📒 Files selected for processing (3)
  • Source/JavaScriptCore/runtime/JSModuleLoader.cpp
  • Source/JavaScriptCore/runtime/JSModuleLoader.h
  • Source/JavaScriptCore/runtime/JSModuleRecord.cpp

Disabled knowledge base sources:

  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.


Walkthrough

Under USE(BUN_JSC_ADDITIONS), JSModuleLoader stores and traces an async context. JSModuleRecord::execute applies that context through module execution, including top-level-await handling.

Changes

Module async context

Layer / File(s) Summary
Loader async-context storage and GC
Source/JavaScriptCore/runtime/JSModuleLoader.h, Source/JavaScriptCore/runtime/JSModuleLoader.cpp
JSModuleLoader adds async-context accessors and a garbage-collected write barrier. Garbage collection now visits the stored context.
Module execution context scope
Source/JavaScriptCore/runtime/JSModuleRecord.cpp
JSModuleRecord::execute creates an AsyncContextSwapScope from the loader context before module execution. The scope covers top-level-await continuation handling.

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

Jarred-Sumner added a commit to oven-sh/bun that referenced this pull request Sep 14, 2026
JSModuleLoader::setAsyncContext. To be replaced by the merged commit before this lands.

No-Verification-Needed: version bump
Jarred-Sumner added a commit to oven-sh/bun that referenced this pull request Sep 14, 2026
oven-sh/WebKit#646 (JSModuleLoader::setAsyncContext) is merged; replaces the preview build.

No-Verification-Needed: version bump
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