Skip to content

[JSC] A module that a termination stops records null and rejects its capability with null - #866

Draft
robobun wants to merge 3 commits into
mainfrom
robobun/6243fcc3/module-evaluation-terminated
Draft

robobun wants to merge 3 commits into
mainfrom
robobun/6243fcc3/module-evaluation-terminated

Conversation

@robobun

@robobun robobun commented Oct 21, 2026 •

Copy link
Copy Markdown
Collaborator

Draft. Two questions for maintainers (details and #443 in Notes):

  1. Which value does a stopped module keep: null (V8, Node, this PR) or the run's error (Worker teardown, round 3: node:vm timeout on TerminationDeadline; take-at-landing termination; exit/streams/serve/valkey/Bun.build fixes bun#38660)?
  2. Is the edit in aot/runtime wanted here?

Problem

  • After an embedder withdraws a termination (VM::cancelTermination, node:vm's timeout), a module that it stopped has the termination's value as its error. A later import() rejects with the string "JavaScript execution terminated.".
  • Six places store it: step 9 of CyclicModuleRecord::evaluate() and five in aot/runtime. All end in setEvaluationError.
  • Step 9 leaves the capability (the promise of Evaluate()) pending, so an import() made during the evaluation never settles. Debug builds: ASSERTION FAILED: promise->status() != JSPromise::Status::Pending (AbstractModuleRecord.cpp:1568).

Fix

  • setEvaluationError stores null for the value of a pending termination.
  • For a termination, step 9 and its copy in aot/runtime reject the capability with null, as handled.
  • Correct because V8 stores null (Module::RecordError), and Node v26.3.0 rejects these import() calls with null.
  • Verified: JSTests/stress/module-evaluation-cut-short-by-termination.js and testaot's module-programs/termination-in-module-body. Both fail on main.

Background

  • A termination stops script from another thread. Script cannot catch it.
  • aot/ evaluates the modules of bun build --compile --aot programs.
  • Considered step 9 alone: a compiled program kept the string. Considered a drop of the capability: that import() stayed pending.

Downsides

Notes

All line numbers are for the head of this PR, b7a7dba, which is main f495db1 and this change. Each measurement has its date and its builds. runtime/CyclicModuleRecord.cpp has +16 -1, aot/runtime/AOTModuleEvaluation.cpp has +7 -2, and the rest is tests.

Question 1: the value. This PR stores null, as V8 and Node do. Merged code has two other answers for a module that a termination stops:

Is null right for a module of the program's own loader? If the answer is the error of the run, the guard in the writer is the place to mark the module (one bit) in place of null. The embedder that withdraws the termination then gives the module its error, and rejects the capability with it.

Question 2: the edit in aot/runtime. Modules::evaluateWithOwnStack has a copy of step 9. This PR changes it (AOTModuleEvaluation.cpp:2063, +7 -2): for a termination it rejects the capability with null, where it kept it pending. Without that edit, a plain program and a program from bun build --compile --aot do not end the same way for an import() made while the root evaluated: rejected with null in the plain program, pending in the compiled one. On main both are pending. If this file must not change here, I take the edit out and this description says what stays different.

About #443. #443 (closed, not merged) added a return for a termination in front of step 9.d. Its subject was an assertion in terminated workers (ASSERTION FAILED: exception, in JSPromise::rejectWithCaughtException). It left the state of the modules as it was, and it closed with "this is working around a bun bug". This PR is about that state: the error that a stopped module keeps, and its capability. It is not a workaround of Bun code. main's jsc shows the defect with --watchdog and two files (see "Upstream"), and with $vm.callWithTimeLimit, which #440 added. #440 says what a withdrawal is for: "take the request back so nothing of it reaches whatever the same VM entry runs next". The error of a stopped module is a thing that reaches it.

No report from a user. The defect was found in the work on oven-sh/bun#46004, which lists it under "Not fixed". In Bun it needs a node:vm timeout or breakOnSigint around a synchronous evaluation: a require() of an ES module, the first read of an import defer namespace, or evaluate() of a vm.SourceTextModule. oven-sh/bun#30598 (bun test --timeout) and oven-sh/bun#33411 (Ctrl+C in the REPL) would add two more. --aot is in no stable release: oven-sh/bun#45631 merged on Oct 27, after v1.4.4.

Where the value was stored. m_evaluationError has one write, in setEvaluationError (CyclicModuleRecord.cpp:540). Six places give it the value of an exception with no test for a termination:

  • Step 9.a.iii of evaluate() (CyclicModuleRecord.cpp:652).
  • In aot/runtime/AOTModuleEvaluation.cpp, through Modules::setFailed (AOTModules.cpp:303): Modules::innerModuleEvaluation (:465), Modules::callBodyUnderOwnMark (:541 and :545) and Modules::evaluateCommonJS (:2587).
  • Modules::evaluateWithOwnStack (AOTModuleEvaluation.cpp:2059), which has the same loop as step 9.

A seventh place is JSModuleLoader.cpp:487, after a failed link. Its one caller in Source/JavaScriptCore is JSC::linkAndEvaluateModule (Completion.cpp:307), which neither Bun nor jsc.cpp calls. AOTModuleLinking.cpp:530 already tests for a termination before its store.

The three heads of this PR.

  1. Step 9 only (6316bdb). A program built with bun build --compile --aot still printed the string. So the fix moved to the writer.
  2. The guard in the writer, and step 9 dropped the capability (b39f654). An import() made while the module evaluated holds that promise, and it stayed pending. aot/runtime kept its capability, so the two modes did not end the same way.
  3. This head (b7a7dba). Step 9 and its copy reject the capability with null.

Other places for the fix that I considered. A helper at each store that maps an exception to the error to record: each of the six stores is then an edit, five of them in aot/runtime, and a new store can forget it. A null value for the termination exception of the VM: that changes what every reader of that value gets, not only the module code, and the stores still record a termination. A rejection inside JSPromise::rejectWithCaughtException: it has 33 call sites in the loader. Most of them settle a promise of the load phase, and merged code says that a termination is not a failure of a load (JSModuleLoader.cpp:841).

The guard (CyclicModuleRecord.cpp:537) has two conditions. V8 has the same mapping in its one writer: Module::RecordError stores null for an exception that script cannot catch (deps/v8/src/objects/module.cc:118-123 in Node v26.3.0).

  • A termination is pending on the VM (VM::hasPendingTerminationException). Each store above runs while the termination unwinds.
  • The value is the value of the termination exception. So an error that some code records while a termination is pending stays as it is, and so does the clear with an empty value (Modules::dropErrorOfFile, AOTModuleEvaluation.cpp:1993). A value that script throws is never changed: no script runs while a termination is pending.

One store is outside the reach of this key: operationAOTAbandonModuleEvaluation (AOTModules.cpp:1927) runs inside a DeferTerminationForAWhile scope (:1926), where the termination is not pending. By my reading no termination reaches it: a handler of compiled code calls it, and the unwinder enters no handler for a termination (AOTUnwinding.cpp:197, and the assertion at AOTExceptionOperations.cpp:176). I did not make a test for that.

The capability (CyclicModuleRecord.cpp:658). Step 9.d cannot reject it for a termination: JSPromise::rejectWithCaughtException does nothing then (JSPromise.cpp:262). A module that keeps the pending promise gives it to each later Evaluate(). In a build without assertions, the second read of a deferred namespace then returned 1 for a binding that the body had set, and a ReferenceError for one that it had not.

  • The arm calls rejectAsHandled(vm, jsNull()) and leaves the termination pending. With the handled flag, the rejection tracker of the embedder is not called while the termination is pending. The reactions of the capability are jobs, which run after the withdrawal.
  • The promise of an import() is another promise. The rejection reaches it as usual, so with no handler it is an unhandled rejection.
  • The arm is behind the loop of step 9.a and in front of the assertions of 9.b and 9.c. Step 9.c compares the error of the module with the value of the exception, and for a termination they now differ.
  • V8 drops the capability in this case (v8/v8@d31de88587d2). Node v26.3.0 still rejects an import() made while the module evaluated with null (see "Bun").
  • main lets a record that is EVALUATING be evaluated again (require() of an ES module from inside its own evaluation). InnerModuleEvaluation returns at once for such a record (AbstractModuleRecord.cpp:1929), so its stack is empty and nothing is stored. The walk that owns the record stores the error when the termination reaches its own step 9.

Return value. For a termination, evaluate() returns nullptr with the termination pending. Before this change it returned the capability. I read each caller of the promise-returning Evaluate() outside aot/. Each one tests the exception before it uses the promise:

  • JSMicrotask.cpp:1545, :1664 and :1701.
  • AbstractModuleRecord.cpp:1565 (evaluateSync) and :1720 (evaluateModuleSync).
  • JSModuleLoader.cpp:491.
  • NodeVMModule.cpp:160 in Bun, the only caller in src/jsc/bindings.

AbstractModuleRecord::evaluate's wrap returns nullptr for an empty value (AbstractModuleRecord.cpp:1676). In aot/, Modules::evaluate returns the result of record->evaluate() to its own caller (AOTModuleEvaluation.cpp:2096). I did not follow that caller.

The state is not new. A module body that runs throw null leaves the same state: status EVALUATED, the error null, and a capability that is rejected with null. The readers of the error test for an empty value, and null is not empty.

What a program sees, with the same two files under each runtime:

// wait.mjs
globalThis.waitStarted = true;
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1000);
// main.cjs
const vm = require("node:vm");
const path = require("node:path");
const file = path.join(__dirname, "wait.mjs");
const context = vm.createContext({ load: () => require(file) });
let stopped;
try {
  vm.runInContext("load()", context, { timeout: 500 });
} catch (error) {
  stopped = error.code;
}
const started = globalThis.waitStarted === true;
import(file).then(
  () => console.log(JSON.stringify({ stopped, started, later: "fulfilled" })),
  error => console.log(JSON.stringify({ stopped, started, later: "rejected", typeofError: typeof error, error: String(error) })),
);
output
Bun 1.4.3-canary.1+367d939d9 {"stopped":"ERR_SCRIPT_EXECUTION_TIMEOUT","started":true,"later":"rejected","typeofError":"string","error":"JavaScript execution terminated."}
Bun with this change (see "Bun") {"stopped":"ERR_SCRIPT_EXECUTION_TIMEOUT","started":true,"later":"rejected","typeofError":"object","error":"null"}
Node v26.3.0 the same line as Bun with this change

The module waits and does not spin, so the program ends on each runtime. With a timeout that passes before the module body starts (1 ms), Bun prints "started":false,"later":"fulfilled" with and without this change: the run stopped the load, and Evaluate() did not run.

The stress test. $vm.callWithTimeLimit arms VM::addTerminationDeadline and withdraws the termination, like node:vm. Six scenarios, 34 checks:

  1. an import() that a job evaluates inside the limited call, then import() of the module twice and of a module that imports it.
  2. a graph whose root imports a module that finishes, the module that is stopped, and a module that is not reached.
  3. the first read of an import defer namespace inside the limited call (EvaluateModuleSync).
  4. two walks on the stack: a module body reads a deferred namespace, and that module is stopped.
  5. a module with top-level await that is stopped before its first await.
  6. a module body that calls import() of its own module and lets that job run. The evaluation is the first read of a deferred namespace. The import() must reject with null.

The module body to stop waits in Atomics.wait for 1 s longer than the limit. The termination wakes that wait and is thrown from it (WaiterListManager::waitSyncImpl), so no loop has to be stopped while it spins. The test takes about 80 ms in the lto jsc.

A limit can pass before the body starts, on a slow or a busy machine. A wait can also end by itself, and the body logs that. The test sees both in its log and takes the next turn with a longer limit (10 ms, then 4 times the last one) and new module records (a specifier with one more / is another URL of the same file). Two turns with a wait that ended fail the scenario, so a limit that does not stop the body fails the test in about 2 s for each scenario. On the second head I forced each branch of that loop in its first turn and read a trace of the turns. The loop did not change since.

The import() whose own evaluation job the limit stopped stays pending, before and after this change (see "Not fixed"). Scenario 1 pins that state.

The test of testaot. module-programs/termination-in-module-body (aot/tests/AOTModuleProgramTests.cpp:900) compiles four programs and runs each in the shell. The script stops a module body with requestTerminationAndCall inside callAndCancelTermination, so there is no timer.

  1. The program of termination-during-import-handoff: a later import() of the stopped module rejects with null.
  2. require() of a module, and two modules that import each other: each later import() rejects with null.
  3. A CommonJS file whose error is dropped while the termination is pending: a later require() of the file returns, as on main. This program fails if the guard loses its second condition. I checked that on the second head with a breakpoint in gdb that gives the writer the value of the termination for each store: the two require() lines change from returned to threw null.
  4. Two import() calls of a root while require() evaluates it, one from a module that it requires and one from its own body: both reject with null, and so does a later one.

A trace of the callers of the writer (a breakpoint in the assertions-aot shell of this head, Oct 29) shows these stores in the four programs: innerModuleEvaluation (:465), callBodyUnderOwnMark (:541 and :545), evaluateWithOwnStack (:2059), and the clear in dropErrorOfFile. No program reaches the store of evaluateCommonJS (:2587).

Four lines of the expected output say only not the value of the termination. For those steps a compiled program and plain Bun do not end the same way today, and this test must not pin what only a compiled program does. They are a second require() of a stopped module (two programs) and an import() of a module that imports a stopped CommonJS file (two programs).

Results, on Oct 29, Linux x64, with the builds of this head (autobuild-preview-pr-866-b7a7dba4), of the second head (autobuild-preview-pr-866-b39f654a) and of main (autobuild-f495db1d248886d7de1077d0abe3a604694ebb4c):

main second head this head
stress test, lto jsc exit 3: 13 of 34 checks fail, 10 of them with the string exit 3: 1 check fails, the import() of scenario 6 is pending pass (lto and lto-aot)
stress test, assertions-aot ASSERTION FAILED: promise->status() != JSPromise::Status::Pending, AbstractModuleRecord.cpp(1568) not run with this test pass, also with --validateExceptionChecks=true. ASAN debug: the same
the testaot test of this head, with the jsc of fails: later import of first.js: rejected with string fails: the two import() calls of program 4 are pending passes (lto-aot and assertions-aot). All 9 module-programs tests pass

CI passed on this head: 84 checks, with the six test jobs (Linux x64 and arm64: lto, lto-aot, lto-hardened-aot). They run run-javascriptcore-tests, and testaot on the aot lanes.

Cost. Measured on Oct 29 with the lto jsc of main (f495db1) and of this head.

  • .text of jsc (llvm-size -A): amd64-lto -288 B, amd64-lto-aot -512 B, arm64-lto 0 B, arm64-lto-aot -704 B.
  • The writer is NEVER_INLINE. Each of its callers is on a failure path. Without the attribute the guard is in each inlined copy. With it, evaluate() goes from 1,232 to 971 bytes and asyncExecutionRejected from 743 to 368 (amd64-lto), and the writer is one function of 351 bytes. In amd64-lto-aot, evaluateWithOwnStack goes from 654 to 713 bytes.
  • .data, .bss and .data.rel.ro are equal. .rodata is 12,800 bytes smaller in each of the four lanes, and 12,784 of them are in the ICU data at its start. That data differs from one build of CI to the next. I did not find what the other 16 bytes are.
  • A successful Evaluate() (single steps in gdb, instructions inside evaluate(), amd64-lto): 89 to 86 for an empty module, 77 to 76 for a module with await 0.
  • An ordinary failure, the same way, evaluate() and the writer together: 125 to 149 for a module with throw 1 (one record), 173 to 212 for a root whose third import throws (two records). The call of the writer is out of line now.
  • Calls of the writer (a breakpoint that counts, amd64-lto and amd64-lto-aot): 0 in 2,000 imports that succeed, 2,000 in 2,000 imports that fail.
  • The change adds no field and no header line, so sizeof(JSModuleRecord) and sizeof(VM) stay as they are.

What changes for a user, other than the value.

  • An import() made while the module evaluated, with no handler: it was pending for good, and it now rejects with null. Bun then prints error: null and exits with 1. Node v26.3.0 ends the same program with ERR_UNHANDLED_REJECTION and the reason null.
  • An import() that was in flight when a vm run required the same module and was stopped: the same. This shape is Bun's only: in Node that require() throws ERR_REQUIRE_ESM_RACE_CONDITION.
  • The shell, with two module files: jsc --watchdog=300 --watchdog-exception-ok -m spin.mjs importer.mjs, where the watchdog stops spin.mjs and importer.mjs imports it. It exits with 0 on main and with 3 (Exception: null) now: the shell knows a termination by its value (jsc.cpp:4408). With one file the exit code is 0 as before. The test jobs of CI pass, so no test of JSTests needs that flow.

Not fixed, with what I saw.

  1. A compiled program with no import(). A termination that stops a module that require() evaluates reaches no store there: a breakpoint counts 0 calls of the writer, and a second require() returns (a program of two modules in the lto-aot shells of main and of this head). All four programs of the testaot test hold an import(), so they do not show it.
  2. A termination while a graph loads never reaches Evaluate(). With a root that imports 400 modules and a vm timeout that passes during the load, the later import() of the root stays pending (Bun 1.4.3, and Bun with this change). A debug build of Bun can also stop there, at ASSERTION FAILED: mapEntry->status() != ModuleRegistryEntry::Status::New (JSModuleLoader.cpp:869). The capability is one of five promises that the loader keeps on a record or on a registry entry (m_topLevelCapability, m_asyncCapability, m_fetchPromise, m_modulePromise, m_loadPromise). rejectWithCaughtException leaves each of them pending for a termination. This PR settles the first, at step 9.
  3. The import() whose own evaluation job the termination stopped stays pending (JSMicrotask.cpp:1669 is that call). Scenario 1 of the stress test pins it.
  4. A module with top-level await that is stopped after its first await (JSMicrotask.cpp:1073). Its import(), a later import() and an import() of a module that imports it all stay pending, on main and on this head (lto and assertions-aot shells, Oct 29).
  5. AsyncModuleExecutionFulfilled 12.b and 12.c (the TRY_CLEAR_EXCEPTION at CyclicModuleRecord.cpp:940 and :950): by the text it returns for a termination before asyncExecutionRejected runs. I did not run that case. v8/v8@e7292baec0 is V8's change for this exit.
  6. A termination in the body of a CommonJS module that an ES module imports. In Bun the later import() of the importer stays pending, with and without this change. Node v26.3.0 fulfils it: the importer ran with undefined for the default export.
  7. In plain Bun, a second require() of the stopped module returns an empty object. Node throws ERR_REQUIRE_CYCLE_MODULE, and a compiled program throws null. The object is in Bun's own map of required modules, which the engine does not see.
  8. JSModuleLoader.cpp:485 stores the value in the registry entry, which the writer does not see. No test can reach it (see "Where the value was stored").

There is no issue for these. This account cannot open one.

Upstream. Upstream's main (1b03d89) has the same store and the same rejection with no test for a termination (CyclicModuleRecord.cpp:414 and :421). The shell shows the defect with upstream's own flags:

// spin.mjs
for (const end = Date.now() + 3000; Date.now() < end; );
export const x = 1;
// second.mjs
print("second file starts");
import("./spin.mjs").then(
  () => print("later import fulfilled"),
  error => print("later import rejected with " + (error === null ? "null" : typeof error + " " + String(error))),
);
$ jsc --watchdog=300 -m spin.mjs second.mjs
second file starts
later import rejected with string JavaScript execution terminated.

That is main's jsc. With this change the last line is later import rejected with null. The change is behind USE(BUN_JSC_ADDITIONS) because upstream's shell reads the value of the termination as its marker (see the shell item above). I did not file a bug at bugs.webkit.org.

Other open PRs on these lines. #845 edits the body of setEvaluationError, and draft #871 changes evaluate() around step 9. #934 changes aot/. The one that lands second can have a conflict in the text.

The base is f495db1, and main in this description is that commit. main is now 8c6c963. It has three merges more (#919, #936, #937), and none of them changes a file of this PR. CI built this head on its own base, not on a merge with main. I rebase when the two questions have an answer.

Bun. Bun's main pins 8c6c963 since oven-sh/bun#47129. My debug build of Oct 29 is an earlier commit of the branch of that PR, 6e63b62277, which pins f495db1. It has oven-sh/bun#46319 and the tests branch merged in, and --webkit-version=autobuild-preview-pr-866-b7a7dba4.

  • The plain program above prints "typeofError":"object","error":"null" (3 of 3).
  • The same two files as TypeScript, built with bun build --compile --aot, print the same line (3 of 3). With the first head, that program printed the string.
  • A second program has three graphs: a root that imports the module to stop and a module with top-level await, a root with top-level await, and two modules that import each other. Plain and --aot print the same lines, with null for each later import().
  • A third program has a root that require() evaluates. A module that it requires calls import() of the root, and the root calls import() of itself. Both calls reject with null, plain and --aot. With the second head, the Bun test had the first pending and the second null, and program 4 of the testaot test had both pending. The one line that still differs between the two modes is the second require() of the root (item 7 above).
  • The tests branch has 24 scenarios in child processes, through each node:vm entry point, with timeout and with breakOnSigint. The modules to stop wait in Atomics.wait. Its 3 tests pass (3 runs). With Bun 1.4.3 all 3 fail: the later import() rejects with the string. On a debug build of Bun's main the import defer scenario stops at the assertion above.
  • Three of the scenarios enter a record again while it is evaluating: a module that calls require() of itself, the same module behind an importer, and a require() cycle. One scenario has the two import() calls of the third program. Each import() rejects with null, and no assertion fails.
  • Node v26.3.0 prints the same lines for the scenarios that it can run. The test says where it does not.
  • The two test files of Keep the termination string out of mock.results and Module._extensions handlers bun#46319 pass on that build (124 tests).
  • I did not make a release build.

The tests for Bun are on the branch robobun/6243fcc3/vm-plain-module-stopped of oven-sh/bun (2584cafc76). They go in with the change of WEBKIT_VERSION that has this PR, and a program for test/aot/programs belongs with them.

oven-sh/bun#46319 keeps the same string out of mock.results and Module._extensions handlers and needs no engine change.

Self-review. 3 concerns raised, 2 addressed: the capability is rejected and not dropped, in both evaluators, and program 3 of the testaot test covers the second condition of the guard. The third asks for a tracking issue for the list above, which this account cannot open.

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

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Beyond the inline findings, I also checked the re-entry path after a cut-short module: the next Evaluate() passes step 3's m_evaluationError assert (jsNull is a non-empty value), InnerModuleEvaluation rethrows null, and step 9.c's evaluationError() == exception->value() holds, so the second import() rejects with null without tripping an assert. The nested-walk case (scenario 4) is also fine: the inner Evaluate() only marks its own stack, so the outer walk's per-record Evaluating assert is not violated.

Extended reasoning...

The engine change is a single guarded arm in CyclicModuleRecord::evaluate() step 9 for termination exceptions, plus a new fork-only stress test and fixtures; it touches no security-sensitive surface. Inline findings cover the Link()-time sibling, the forever-pending import() after a withdrawn termination, and test runtime; this note records the re-entry and nested-walk paths that were examined and found consistent.

@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

No actionable comments were generated in the recent review.

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: b0bbb941-d4f4-41be-8e91-393091e9f5e2
📥 Commits

Reviewing files that changed from the base of the PR and between a31a630 and 45e98d6.

📒 Files selected for processing: 12
  • JSTests/stress/module-evaluation-cut-short-by-termination.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/deferred-spin.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/graph-leaf.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/graph-never.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/graph-root.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/graph-spin.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/nested-inner.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/nested-outer.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/spin-importer.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/spin.js
  • JSTests/stress/resources/module-evaluation-cut-short-by-termination/tla-spin.js
  • Source/JavaScriptCore/runtime/CyclicModuleRecord.cpp

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.

Walkthrough

The change adds a termination-specific path to module evaluation when Bun additions are enabled. A new stress test checks interrupted dynamic imports, module graphs, deferred namespace reads, nested evaluations, and top-level await.

Changes

Module termination handling

Layer / File(s) Summary
Handle termination during module evaluation
Source/JavaScriptCore/runtime/CyclicModuleRecord.cpp
When module evaluation ends with a VM termination exception, the code sets null evaluation errors for modules on the evaluation stack, clears the top-level capability, and returns nullptr.
Set up retry and assertion helpers
JSTests/stress/module-evaluation-cut-short-by-termination.js
The test adds shared state, assertion and timeout helpers, microtask draining, synchronous-throw checks, and retries with increasing time limits.
Check interrupted dynamic imports
JSTests/stress/module-evaluation-cut-short-by-termination.js, JSTests/stress/resources/module-evaluation-cut-short-by-termination/spin*.js
The test checks interrupted import outcomes and module execution using spinning modules and an importer.
Check module graph evaluation
JSTests/stress/module-evaluation-cut-short-by-termination.js, JSTests/stress/resources/module-evaluation-cut-short-by-termination/graph-*.js
The test checks rejection and fulfillment outcomes for completed, interrupted, and unreached modules, and verifies their execution log.
Check deferred reads and top-level await
JSTests/stress/module-evaluation-cut-short-by-termination.js, JSTests/stress/resources/module-evaluation-cut-short-by-termination/deferred-spin.js, JSTests/stress/resources/module-evaluation-cut-short-by-termination/nested-*.js, JSTests/stress/resources/module-evaluation-cut-short-by-termination/tla-spin.js
The test checks interrupted deferred namespace reads, nested module evaluation, and top-level await. The supporting modules log evaluation and wait for the test to release them.

Priority: Low

Merge Risk: Minimal · up to 45e98

No actionable merge-blocking issue is established. The uninspected evaluation callers remain a verification limit, not a demonstrated failure.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description follows the WebKit template in spirit. It has a bug-style title, a Problem and Fix explanation, and a Verified section. It includes a detailed Notes section with reproduction steps, te… Add a Bugzilla bug link (https://bugs.webkit.org/show_bug.cgi?id=#####) and a bug title that matches the template. Replace the draft framing with a concise Explanation of why the change fixes the bug. Add the changed-file list in the templa…
Passed Passed checks: 3 passed
Check name Status Explanation
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.
Title check Passed The title names the main behavior change: a module stopped by a termination records null and its capability is rejected with null. It matches the changeset, which changes CyclicModuleRecord::evaluate(…
Full details: Title check

Explanation

The title names the main behavior change: a module stopped by a termination records null and its capability is rejected with null. It matches the changeset, which changes CyclicModuleRecord::evaluate() and the aot/runtime copy so stopped modules store null and reject with null. The title is specific and concise, and it has the [JSC] component prefix. It is 89 characters, which is long, but it stays a single clear sentence.

Full details: Description check

Explanation

The description follows the WebKit template in spirit. It has a bug-style title, a Problem and Fix explanation, and a Verified section. It includes a detailed Notes section with reproduction steps, test results, and measurements. However, it lacks the template's required elements: no Bugzilla bug link (the author says no bug was filed), no 'Reviewed by' line, and no changed-file list with function names (for example, '* runtime/CyclicModuleRecord.cpp: (CyclicModuleRecord::evaluate)'). The description is also a draft with open questions, and it is very long, which makes the key information hard to find.

Resolution

Add a Bugzilla bug link (https://bugs.webkit.org/show_bug.cgi?id=#####) and a bug title that matches the template. Replace the draft framing with a concise Explanation of why the change fixes the bug. Add the changed-file list in the template format, naming the modified files and functions (for example, runtime/CyclicModuleRecord.cpp: (CyclicModuleRecord::evaluate), (CyclicModuleRecord::setEvaluationError), and aot/runtime/AOTModuleEvaluation.cpp: (Modules::evaluateWithOwnStack)). Remove or move the long Notes content out of the commit-message body, and resolve or remove the two open questions before marking the PR ready for review. Include the reviewer line once a reviewer is assigned.

  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Git: CodeRabbit could not clone the repository, so clone-backed analysis was skipped and this review may be incomplete. Verify repository clone access, such as SSH credentials, before requesting another full review. If clone access is intentionally unavailable, use path_filters to narrow the review scope.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@github-actions

github-actions Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

Preview build of b7a7dba: autobuild-preview-pr-866-b7a7dba4

@robobun

robobun commented Oct 22, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status

How to reproduce on main (f495db1, the base of this PR):

  • Run jsc --useDollarVM=1 --useImportDefer=1 JSTests/stress/module-evaluation-cut-short-by-termination.js (the test of this PR) with the lto jsc of autobuild-f495db1d248886d7de1077d0abe3a604694ebb4c. It exits with 3, and 13 of 34 checks fail. The first one: import() of the module that was cut short: expected rejected with null, got rejected with the string "JavaScript execution terminated.".
  • Put the testaot of this PR beside the jsc of that release and run testaot native module-programs/termination-in-module-body. It fails with later import of first.js: rejected with string.
  • Run the two files under "What a program sees" in the PR body with Bun 1.4.3. The output has "typeofError":"string".

With this PR (autobuild-preview-pr-866-b7a7dba4), both tests pass, and CI is green on Linux x64 and arm64. A Bun built with that release prints "typeofError":"object","error":"null" for the two files, as a plain program and as a program built with bun build --compile --aot.

The PR is a draft. It waits for a maintainer's answer to the two questions at the top of the description.

The tests for Bun are on the branch robobun/6243fcc3/vm-plain-module-stopped of oven-sh/bun. oven-sh/bun#46319 has the two places in Bun that need no engine change.

@robobun
robobun force-pushed the robobun/6243fcc3/module-evaluation-terminated branch 3 times, most recently from b2bb0cd to 05b90bb Compare October 26, 2026 17:38
@robobun

robobun commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

I am moving this PR to draft. I do not know that it is wrong, but I cannot vouch for it against main as it is now. Two reasons.

1. The evidence in this PR is older than main. CI ran on 40b30d2. main is 16 commits later, and since then CyclicModuleRecord.cpp, AbstractModuleRecord.cpp, JSMicrotask.cpp, JSModuleLoader.cpp, aot/runtime/AOTModuleEvaluation.cpp and aot/runtime/AOTModules.cpp all changed. The line numbers and the list of callers in the description are from 40b30d2. I have not run the change or its test on the current tip.

2. #927 lets evaluate() run again on a record that is already EVALUATING, and the arm of this PR has two assertions that may not hold then. This is from reading evaluate() at d6e9f85, not from a test.

  • [JSC] AOT: counted loops that can be interrupted, vector loops over typed arrays, number fields past 32 bits, records that passes keep true #927 relaxed the assertions of step 2 and step 10.a, with the comment "A record that is evaluating may be linked and evaluated again where require() of an ES module re-enters it". Step 9 is not changed.
  • Take a dependency D that the walk of another root has set to EVALUATING, and a second evaluate(D) from inside its body. D has no [[TopLevelCapability]], so step 4 does not return. Steps 5 to 7 make a new stack and a new capability on D. If InnerModuleEvaluation returns at once for a record that is EVALUATING (I did not read Bun's version), the stack is empty and D is still EVALUATING.
  • If a termination is pending at step 9 of that second call, the arm of this PR runs ASSERT(module->status() == Status::Evaluated) and ASSERT(module->evaluationError().isNull()) on D. Both are false in that case. The arm then clears the capability that this call made and returns nullptr. I expect that the first walk then reaches its own step 9 with D on its stack, but I did not check that.
  • Steps 9.b and 9.c on main make the same assumption for an ordinary exception, and I copied them. So this is not new with this PR, but the PR adds two more assertions of that kind.
  • I do not know if an exception can be pending there. If InnerModuleEvaluation returns at once, the second call runs no module code before step 9.

The stress test has no case where the same record is entered twice, and jsc has no require(). That case needs a test in Bun.

Questions, for whoever knows #927:

  1. Can step 9 be reached in a second evaluate() of a record that is EVALUATING? If it can, do the two assertions in this arm have to go, as for step 10.a?
  2. The question from the description is still open: does the module evaluation in aot/ need the same change? I have not analyzed that code.

I will rebase and add the test in Bun when I have an answer, or sooner if the answer is clear from the code.

@robobun
robobun marked this pull request as draft October 28, 2026 04:12
@robobun

robobun commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

Two more findings for this draft. I have not pushed anything.

1. The first question above is mostly answered by the code. I read AbstractModuleRecord::innerModuleEvaluation at d6e9f85.

  • Step 3 (AbstractModuleRecord.cpp:1929-1931) returns at once for a record that is EVALUATING. It does not put the record on the stack. So the condition in my last comment holds: a second evaluate(D) has an empty stack, and D stays EVALUATING.
  • The comment at :1982 says the same about a nested evaluation: the module "is Evaluating but lives on the OUTER stack vector, not the local one", and "the outer DFS owns the module's evaluation lifecycle".
  • For a module that runs as bytecode, that second call runs no module code before step 9. So I see no way for an ordinary exception to be pending there, and steps 9.b and 9.c hold. A termination is different: it may be raised in the allocation of step 6 (CyclicModuleRecord.cpp:625), if that allocation ends a DeferTermination scope. I did not verify that path, and I did not make it happen in a test. I did not read the version of aot/ (:1907).
  • So the two assertions that this PR adds after its loop (module->status() == Status::Evaluated and module->evaluationError().isNull()) assume that module is on the local stack, which the code says is not always true. I think they have to go. The loop changes only the records on the local stack, which agrees with that comment.

2. The stress test depends on a loop that spins, and that is not safe. Each module body of the test is while (!globalThis.cutShort.done) { } under $vm.callWithTimeLimit. In oven-sh/bun#46319 a test of mine with a loop of that kind failed once in CI: on Alpine aarch64 the node:vm timeout did not stop the loop for 10 s. I do not know why, and I could not make it happen on Linux x64. Here the loop has no other end, so the same event makes this test hang, not fail.

What I will do, in one push, so that CI runs once: rebase onto main, remove the two assertions, and change the bodies of the test to Atomics.wait. The second question is still open: I have not analyzed the module evaluation in aot/.

… error of the modules it stops

Step 9 of CyclicModuleRecord::evaluate() stored the value of whatever
unwound InnerModuleEvaluation as the error of every module on the stack.
For a termination that value is the string "JavaScript execution
terminated.". An embedder can withdraw a termination
(VM::cancelTermination) and run script again. A later import() of such a
module then rejected with that string.

Step 9 now records null for a termination, as V8 does. The module also
does not keep the capability, which the termination cannot reject, so the
next Evaluate() of that module makes a rejected one. Before, the next
Evaluate() returned the pending capability. A second read of a deferred
namespace then failed
ASSERT(promise->status() != JSPromise::Status::Pending) in
AbstractModuleRecord::evaluateSync, and returned a binding of the module
in a build without assertions.
@robobun
robobun force-pushed the robobun/6243fcc3/module-evaluation-terminated branch from 05b90bb to 6316bdb Compare October 28, 2026 20:42
@robobun

robobun commented Oct 28, 2026

Copy link
Copy Markdown
Collaborator Author

I pushed 6316bdb. It is the one push that my last comment describes. The PR stays a draft until I have run the build of this head.

What changed.

  • The branch is rebased onto main (f495db1). Step 9 is the same on main, so the arm is the same code.
  • The two assertions after the loop of the arm are gone (module->status() == Status::Evaluated and module->evaluationError().isNull()). The loop still changes only the records on the local stack.
  • The five module bodies that the test stops now wait in Atomics.wait, for 1 s longer than the limit. The termination wakes the wait and is thrown from it (WaiterListManager::waitSyncImpl), so no loop has to be stopped while it spins.
  • A body logs when its wait ends by itself. The test takes such a turn again, like a turn where the limit passes before the body starts. Two turns with a wait that ended fail the scenario. So a limit that does not stop the body fails the test in about 2 s for each scenario, and nothing can hang.

What I ran, with the test files of this push, on Linux x64:

jsc result
lto, main (autobuild-f495db1d248886d7de1077d0abe3a604694ebb4c) exit 3: 11 of 29 checks fail, with the string
assertions, main (same release) ASSERTION FAILED: promise->status() != JSPromise::Status::Pending, AbstractModuleRecord.cpp(1568)
lto and assertions, the head before this one (autobuild-preview-pr-866-05b90bba) pass, 3 of 3 each. The assertion jsc also passes with --validateExceptionChecks=true.

That head has the arm with the two assertions, on 40b30d2. No build has the arm of this push yet.

I also forced each branch of the loop of the test in its first turn, with a trace of the turns:

first turn, forced lto with the arm lto of main
the limit passes before the body starts second turn passes second turn: the 11 failures
the wait ends, and the limit passes later in the call second turn passes second turn: the 11 failures
the wait ends, and no limit passes second turn passes second turn: the 11 failures
the wait ends in each turn 5 failures after 2 turns: no limit passed inside the wait of the module body the same 5 failures

A correction. The description and the status comment said "11 of 34 checks". The test has 29 checks, and I counted them in a run this time. The status comment has the right number now.

One answer to my second question, from reading only. Modules::evaluateWithOwnStack (aot/runtime/AOTModuleEvaluation.cpp:2036 at f495db1) has the same store as step 9. Line 2059 does cyclic->setEvaluationError(vm, exception->value()) for each member of its stack. Line 2063 tests for a termination, but only before it rejects the capability. So by the text, a termination that stops a compiled module there leaves its string as the error of those modules. I did not run that path, and this PR does not change it.

Not done yet.

  • Run the test with the build of this head, on the lto, assertion and ASAN shells.
  • The test in Bun where a record is entered twice. It needs a build of Bun with this head. Bun's pin (fcc1ea0) is two commits before f495db1, so I do not know yet if Bun's main builds with it.
  • The description still has line numbers and measurements from 40b30d2.

robobun added a commit to oven-sh/bun that referenced this pull request Oct 28, 2026
The module that a run stops waits in Atomics.wait for longer than the run
has. The run wakes that wait and stops the body in it, so no loop has to be
stopped while it spins. An attempt whose wait ends by itself is made again.

Three scenarios enter a module record again while it is evaluating: a module
that calls require() of itself, the same module behind an importer, and a
require() cycle.

These tests need the engine change of oven-sh/WebKit#866.
…ing termination

A program that is compiled ahead of time has its own module evaluation
(aot/runtime). It stores the value of the exception as the error of a
module in five places that step 9 of CyclicModuleRecord::evaluate() does
not see. So such a program still got the string "JavaScript execution
terminated." as the error of a module that a withdrawn termination had
stopped.

Every store of the error of a module goes through
CyclicModuleRecord::setEvaluationError(). It now stores null when the value
is the value of the termination that is pending. Step 9 keeps what the
writer cannot do: it drops the capability and returns with the termination
pending. The loop of step 9.a is the loop of the specification again.

The new test of testaot stops the body of a compiled module in four of
the five places.
@robobun robobun changed the title [JSC] Evaluate() records null, not the value of a termination, as the error of the modules it stops [JSC] The writer of a module's error never stores the value of a pending termination Oct 29, 2026
@robobun

robobun commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

I pushed b39f654 on top of 6316bdb. It changes where the fix is. The PR stays a draft until the build of this head has run.

Why. The first version fixed step 9 of CyclicModuleRecord::evaluate(). A program built with bun build --compile --aot does not go through step 9 for its compiled modules, and I ran it: with the engine of 6316bdb such a program still gets the string. In one graph the root rejects with null and the stopped module keeps the string. On main the two modes at least agree.

What changed.

  • CyclicModuleRecord::setEvaluationError (CyclicModuleRecord.cpp:532) is the one writer of the error of a module. It now stores null when a termination is pending and the value is the value of that termination. The stores in aot/runtime end in this function, so there is no edit in aot/runtime.
  • Step 9 has the loop of the specification again. Behind the loop, for a termination, it drops the capability and returns nullptr with the termination pending. That part is as before.
  • The writer is NEVER_INLINE. Each of its callers is on a failure path, and a compile of the one file is smaller with it than without it. I will measure the lanes of CI and remove the attribute if a lane is larger.
  • New test of testaot: module-programs/termination-in-module-body (aot/tests/AOTModuleProgramTests.cpp). It stops the body of a compiled module with requestTerminationAndCall and has no timer. It reaches four stores of aot/runtime: AOTModuleEvaluation.cpp:465, :541, :545 and :2059.

What I know, and how.

  • The two files compile: CyclicModuleRecord.cpp as one translation unit with the flags of the lto-aot lane, and the test file with -fsyntax-only. Tools/Scripts/aot/check-unified-sources.py reports 0 problems. No build of the whole engine has this change yet.
  • The script and the programs of the new test ran in the shells of main and of 6316bdb: both print rejected with string, so the test fails there. With the condition of the guard set by a breakpoint in gdb at the writer, they print the expected lines. The termination was pending at each of those stores.
  • Not known yet: the result of the real build, in jsc, in testaot and in Bun.

Next. When CI has built this head: the stress test and the new test on its shells, the sizes of the four lto lanes, and a Bun built with it (the plain program and the --aot program from the description must both print null). Then I bring the description up to date.

For a termination, step 9 of CyclicModuleRecord::evaluate() dropped the
capability of the module. An import() that had joined the evaluation then
waited for a promise that nothing settled. Modules::evaluateWithOwnStack
kept the capability, so a compiled program and a plain program did not end
the same way.

Both places now reject the capability with null, as handled, and leave the
termination pending. The module keeps the rejected capability, as a module
that threw does.

The stress test has a scenario with an import() that joins the evaluation.
The test of testaot has two more programs. One drops the error of a
CommonJS file while the termination is pending, which the second condition
of the guard in setEvaluationError() must leave alone. The other has
import() calls that join the evaluation. Where a compiled program and plain
Bun do not end the same way, the test says only that the value of the
termination did not come out.
@robobun

robobun commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

I pushed b7a7dba after a self-review of the last head. The review had 3 concerns about the code, and this push has a change for each. The PR stays a draft: no build has this head yet, and two questions are for maintainers (below).

What changed.

  • The capability is rejected, not dropped. For a termination, step 9 of CyclicModuleRecord::evaluate() now calls capability->rejectAsHandled(vm, jsNull()) and leaves the termination pending. The last head cleared the capability. An import() that had joined the evaluation then waited for a promise that nothing settled. Node v26.3.0 rejects that import() with null.
  • aot/runtime has the same change, in one place. Modules::evaluateWithOwnStack (AOTModuleEvaluation.cpp:2063) skipped the rejection for a termination and kept the capability. With the last head, a plain program and a program built with --aot therefore did not end the same way for an import() of a stopped root, which main does not have. It now rejects with null too.
  • Stress test: a sixth scenario. The module body calls import() of its own module and lets that job run, then waits. The last head and main leave that import() pending (I ran both).
  • testaot: two more programs in module-programs/termination-in-module-body.
    • One drops the error of a CommonJS file while the termination is pending. It fails if the guard in setEvaluationError loses its second condition. I checked that with a breakpoint in gdb that gives the writer the value of the termination for each store: the two require() lines change from returned to threw null.
    • One has two import() calls that join the evaluation of a root that require() evaluates. Its expected lines for those two are a prediction: no build has the change in aot/runtime yet.
  • The test no longer pins what only a compiled program does. For three steps, a compiled program and plain Bun do not end the same way today (a second require() of a stopped module, and import() of a module that imports a stopped CommonJS file). The test prints not the value of the termination for them, and the string if it comes out.

What I know about this head. CyclicModuleRecord.cpp compiles as one translation unit, and AOTModuleEvaluation.cpp and the test file pass -fsyntax-only. The programs and scripts of the test ran in the shells of the last head and of main. The rest waits for CI.

Not changed, by decision. The review also asked for these, and they are not in the diff:

Questions for maintainers. The description will start with them when I rewrite it for this head.

  1. Which value does a stopped module keep? This PR stores null, as V8 and Node do. Bun's merged code for vm.SourceTextModule keeps the error of the run (ERR_SCRIPT_EXECUTION_TIMEOUT, Worker teardown, round 3: node:vm timeout on TerminationDeadline; take-at-landing termination; exit/streams/serve/valkey/Bun.build fixes bun#38660). If the answer is the error of the run, the guard in the writer is the place for a mark.
  2. Is the change in aot/runtime wanted here? If not, I take it out and the description says that a compiled program keeps a pending capability.

@robobun robobun changed the title [JSC] The writer of a module's error never stores the value of a pending termination [JSC] A module that a termination stops records null and rejects its capability with null Oct 29, 2026
@robobun

robobun commented Oct 29, 2026

Copy link
Copy Markdown
Collaborator Author

This draft needs two decisions from maintainers before it can go further. CI is green on b7a7dba, both new tests pass on the builds of that head, and the description is current for it.

  1. @dylan-conway Which value does a module keep when a termination stops its evaluation? This PR stores null and rejects the capability with null, as V8 and Node do. Merged code has two other answers. A vm.SourceTextModule keeps the error of the run (ERR_SCRIPT_EXECUTION_TIMEOUT, Worker teardown, round 3: node:vm timeout on TerminationDeadline; take-at-landing termination; exit/streams/serve/valkey/Bun.build fixes bun#38660), and AOTModuleLinking.cpp:530 fails nothing for a termination. If the answer is the error of the run, the guard in setEvaluationError is the place for a mark on the module. I then rework the PR.
  2. @Jarred-Sumner Is the edit in aot/runtime wanted in this PR? It is +7 -2 in Modules::evaluateWithOwnStack. Without it, a plain program and a --aot program do not end the same way for an import() made while the root evaluated. If no line of aot/ must change here, I take it out.

About #443, which closed as "this is working around a bun bug": this defect needs no Bun code. The jsc of f495db1 shows it with --watchdog and two module files. The commands are in the description under "Upstream".

The description also lists eight cases that this PR does not fix. This account cannot open an issue for them.

Two corrections to my comment of Oct 29, 14:13 UTC. The testaot test has four lines that say only not the value of the termination, not three. The expected lines of its fourth program were a prediction then, and they hold on the builds of this head.

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