Repository navigation
[JSC] A suspended generator or async function keeps its scopes' SymbolTables when its code is generated again - #657
Conversation
…lTables when its code is generated again
A closure made in the body of a loop can go on reading the binding of an earlier iteration:
```js
async function main() {
for (let iter = 0; iter < 3; iter++) {
const box = { iter };
if (!iter)
await somethingLong(); // all code is thrown away meanwhile, or just this function's gets old
for (let k = 0; k < 20000; k++) {
if ([0].reduce(acc => acc + box.iter, 0) !== iter)
throw new Error("read iteration " + box.iter + "'s box in iteration " + iter); // thrown in iteration 1
}
}
}
```
It needs the function to resume in code that was generated again while it was suspended: after `VM::deleteAllCode`, or
after its CodeBlock was jettisoned for old age and its unlinked code was dropped too (`Heap::deleteAllUnlinkedCodeBlocks`,
`UnlinkedFunctionExecutable::clearCode`, or the collector clearing the weak edge to it). Correct with the DFG off.
### Cause
- `DFG::ByteCodeParser` folds `resolve_scope` of a closure variable to a constant scope when the scope's SymbolTable has
only ever had one environment (`SymbolTable::singleton()`), under a watchpoint that `SymbolTable::notifyCreation` fires
when a second environment is made. `get_from_scope` then folds the variable under its own watchpoint set in the same
table.
- The table in question is the clone that `CodeBlock::setConstantRegisters` makes of the SymbolTable constant in the
enclosing function's unlinked code. `JSGlobalObject::symbolTableCache` finds the clone again for a later CodeBlock linked
from the same unlinked code, keyed by the unlinked SymbolTable, so re-linking is fine.
- When the unlinked code is generated (or decoded) again its SymbolTable constants are new objects, the cache misses, and
the new CodeBlock gets new clones. An activation that was suspended across this still holds the environment it made from
the old clone. Closures made over that environment after the resume are compiled against the old clone's inference,
which still says "one environment". The next iteration's environment comes from the new clone and notifies the new
clone. Nothing ever tells the compiled closure code, which all closures from that site share.
- Only an activation that is not on the stack can span a regeneration, so only generators, async functions, async arrow
functions, async generators and module bodies (top-level await) are affected. Only the first activation since the code
was generated: a second one has invalidated the inference already.
### Fix
For the body of a generator, an async function or a module, `CodeBlock::setConstantRegisters` finds the clone of a
SymbolTable constant by whose code it is and which constant (`JSGlobalObject::resumableCodeSymbolTableClones()`, per
realm, weak in the clone: the `UnlinkedFunctionExecutable`, which is what code is dropped from and what clones are shared
by today, or the `ModuleProgramExecutable`, and the constant's index) instead of by the constant itself
(`symbolTableCache`, which everything else keeps using). When the clone that is found was made of another constant, the
code has been generated or decoded again since:
- if it describes the scope part of the new constant exactly (`SymbolTable::isCloneOfScopePartOf`: kind of scope,
offsets, arguments, every entry's offset and attributes, private names, type profiling), it becomes the new constant's
clone (`SymbolTable::adoptOriginal`), so the environments the new code makes reach the inference that older code holds;
- otherwise everything inferred through it is given up (`SymbolTable::invalidateInferencesOfAbandonedClone`: the
singleton and every variable's watchpoint set, including ones nobody watches yet), and the new clone starts with its
singleton invalidated, because the scope has environments it did not see being made. This is rare: the code of such a
body is generated the way it was when it first ran (below), so the shape only differs when two executables that share
the unlinked function are pinned to different modes, when only one of the two constants was prepared for the type
profiler, or when the owner in the key has died and its address is another owner's by now. Every outcome is
conservative (the older environments' inferences are gone and the new clone never claims to be a singleton, or an
unrelated scope of the same shape shares a clone); a debugger would show the older scope's name for a shared one.
Acting where code is linked covers every way unlinked code goes away with one check.
The per-variable watchpoint sets of such bodies have been pre-invalidated at link time since 323583 (`put_to_scope` in
`CodeBlock::finishCreation`), which covered the assignment half of this for function bodies; that is left as it is.
### Also: a module with a top-level await
- `ModuleProgramExecutable::getUnlinkedCodeBlock` took the realm's current `CodeGenerationMode` every time. A module that
is suspended at a top-level await has its registers in a generator frame; when its code was generated again for the
debugger (or without it) in the meantime, every variable moved between register and scope and the resumed code read
whatever was in the slots: `slow_path_inc` on an empty value, a crash. From the moment its body is about to run
(`ScriptExecutable::newCodeBlockFor`), such a module now keeps the mode that code was generated with, as the body of a
generator does; the two share `ScriptExecutable::codeGenerationModeForResumableBody`.
- `ScriptExecutable::clearCode` dropped the clone of the module environment's SymbolTable and `getUnlinkedCodeBlock`
cloned the new constant again, while the module's one `JSModuleEnvironment` keeps the clone it was made from: after the
resume, the body's assignments to top-level bindings notified watchpoint sets that nothing compiled against the
environment was watching (`let x = 1; function f() { return x }` ... `await` ... `x = 2`: a compiled `f` went on returning
1). The clone now stays with the executable and is adopted by, or invalidated against, the new constant like the clones
above.
### Tests
- `stress/suspended-activation-keeps-scope-inference-when-code-is-generated-again.js`: generator, async function, async
arrow function, async generator, a `for (let ...)` binding, a nested closure over a binding that is assigned again, a
body whose code is generated again twice, and the function scope of later activations; `$vm.deleteAllCodeWhenIdle()`
while suspended. Default tiers, DFG and FTL forced with the concurrent JIT off, and the bytecode cache. Seven of the
eight shapes read every value wrong in the iterations after the resume without the change (the last is there to stay
right).
- `stress/suspended-module-resumes-in-code-that-is-generated-again.js`: a module suspended at a top-level await in a loop
while `$vm.enableDebuggerModeWhenIdle()` and then `$vm.disableDebuggerModeWhenIdle()` generate all code again; closures
over the loop's bindings and a function over a top-level binding that is assigned again after each resume. Crashes
without the pin; with the pin and without the rest, both read wrong values.
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes DFG scope-inference and watchpoint-invalidation semantics on a code path that is only reachable across code regeneration, and adds a WeakGCMap keyed by an owner cell address whose reuse is handled conservatively by design, a JSC reviewer should still look this over.
What was reviewed:
CodeBlock::setConstantRegistersresumable-body branch: owner selection, adopt-vs-invalidate fallback, and that the non-resumable path is byte-for-byte the old behavior.- New
SymbolTablehelpers:isCloneOfScopePartOfcompares only whatcloneScopePartcopies; twoConcurrentJSLockers are taken in a single-caller order. ScriptExecutable::clearCode/hasClearableCodeand the module code-generation-mode pin — checked that droppingm_moduleEnvironmentSymbolTablefromhasClearableCodedoesn't leave the executable in the clearable set forever.- New stress tests: use
testLoopCount, throw on failure, and cover the shapes described.
Extended reasoning...
Overview
This PR fixes a DFG correctness bug where a suspended generator/async function/async module resumes in a freshly regenerated CodeBlock whose SymbolTable constants are new clones, so environments created after the resume no longer notify the singleton/per-variable watchpoints that already-compiled closures folded against. The fix threads prior clones through regeneration: JSGlobalObject gains m_resumableCodeSymbolTableClones (a WeakGCMap<(JSCell*, unsigned), SymbolTable>); CodeBlock::setConstantRegisters and ModuleProgramExecutable::getUnlinkedCodeBlock re-adopt the prior clone via new SymbolTable::isCloneOfScopePartOf / adoptOriginal, or fall back to invalidateInferencesOfAbandonedClone plus a pre-invalidated fresh clone. ScriptExecutable factors out and extends the generator-body CodeGenerationMode pin to async modules, and clearCode stops dropping m_moduleEnvironmentSymbolTable. Two stress tests exercise generators, async (arrow) functions, async generators, nested/reassigned bindings, and a top-level-await module across deleteAllCodeWhenIdle and debugger-mode toggles.
Security risks
No direct attack surface is added — no new API, parsing, or untrusted-input handling. The risk profile is JIT-correctness: an incorrect isCloneOfScopePartOf true result would let two differently-shaped scopes share a clone, and the DFG could fold to a wrong offset. The comparison mirrors cloneScopePart (scope flags, m_maxScopeOffset, arguments, per-entry offset+attributes, private names, type-profiling readiness) and the fallback path is strictly conservative (invalidate everything). The WeakGCMap key includes a raw JSCell* that can be reused after the owner dies; the PR explicitly relies on the shape check to keep that case conservative, and a false positive would only over-share a watchpoint set (deopt, not miscompile). isCloneOfScopePartOf takes two ConcurrentJSLockers; only this main-thread caller does so, so there is no opposing lock order today, but it is worth a reviewer's eye. I did not find a concrete flaw in any of these.
Level of scrutiny
High. This is not a mechanical change: it alters when watchpoints are invalidated on a rarely exercised path (code regeneration under a live suspended activation), introduces a new per-realm weak map with an ABA-tolerant key, changes what clearCode leaves alive, and adds a code-generation-mode pin for async modules. All changed paths are under /Source/JavaScriptCore and /JSTests, which are covered by CODEOWNERS (WebKit/jsc-reviewers). Under the approval guidelines, complexity plus CODEOWNERS coverage means a human review is appropriate even with zero findings.
Other factors
The two new stress tests follow JSTests/README.md conventions (throw on failure, testLoopCount, //@ directives) and directly target the fixed behavior, which gives good regression coverage for the happy path. The non-resumable branch of setConstantRegisters is unchanged in effect, so the blast radius for ordinary functions should be nil. The module-side change to stop clearing m_moduleEnvironmentSymbolTable is paired with removing it from hasClearableCode, so the executable won't be perpetually re-enqueued as clearable; the retained SymbolTable is per-module and small. Given the subtlety of the invariants involved, deferring to a JSC reviewer is the right call.
Preview Builds
|
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (10)
Included review availability: 4 reviews are currently available. Your included PR review attempts over the past 7 days set your current allowance at 5 reviews per hour. WalkthroughThe change preserves scope inference across regenerated suspended generator, async, and module code. It adds symbol-table clone lifecycle handling, pins resumable code-generation modes, preserves module environments, updates watchpoints, and adds stress tests for resumed bindings and closures. ChangesResumable scope inference
Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to No actionable merge-blocking risk is supported by the available evidence. 🚥 Pre-merge checks | ✅ 3 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description provides a detailed cause, fix, scope, and test explanation, but it does not follow the required WebKit template. It omits the bug title, Bugzilla URL, reviewer line, and changed-file/function list. Resolution Add the required template sections: a bug title, the associated Bugzilla URL, “Reviewed by NOBODY (OOPS!).” or the actual reviewer, and a changed-file/function list. Keep the existing technical explanation and test coverage details because they provide useful context for the fix.
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 Comment |
…e try range runs into the next (oven-sh/WebKit#629) (#42787) ### What this fixes In DFG-compiled code, a local that is live only at the head of a `catch` handler came back as `undefined` after an exception whenever that handler's try range was followed *directly* by another one. Two ways to get that bytecode layout: **`bun build --bytecode` (regression from #42002).** The bytecode optimizer deletes the `jmp` that closes a try body once an empty `catch {}` has been threaded to the loop header, so the catch's range falls through into the next one. This then breaks after tier-up: ```js function f(kind) { for (let name of ["a", "b"]) { try { return JSON.parse(kind === "k" && name === "b" ? "1" : "{bad"), true; } catch {} } return false; } // TypeError: undefined is not a function (near '...name of ["a", "b"]...') ``` It is not specific to for-of or to `JSON.parse`: a `while (true)` inside `try … finally`, or a labelled `break` into code that starts with a `try`, loses whatever only the loop uses, and when that is a number nothing throws — a loop-only `doubled` silently became `NaN`. Building with `--no-optimize-bytecode` / `optimize: { bytecode: false }` avoided it. **`using` (not a regression, all bytecode).** The dispose call's synthesized catch range ends right at the call, inside the enclosing handler's range. A dispose method that threw after the body also threw reported its own `Error` instead of a `SuppressedError` carrying both, once the function was optimized. ### Cause and fix (oven-sh/WebKit#629) `DFG::LiveCatchVariablePreservationPhase` flushes, when the covering exception handler changes, every local live at the catch head of the handler being left. The lookup of the *new* handler overwrote that live set before the flush ran, so a direct A → B transition flushed B's set for A. Locals live only at A's catch were then dead in the block, and the exception OSR exit to A's `op_catch` recovered them as `undefined`. Stock `try`/`catch` always ends a range with an explicit `jmp`, so only the two layouts above reach it. The phase now looks the handler up, flushes with the old set, and only then computes the new one, keyed on (handler, inline call frame) so recursive inlining keeps following the frame. The fixing line is the reordering in `handleBlockForTryCatch`; everything else in that diff is the lookup returning the pair. ### Also in this WebKit range `9b02218df662..65513e295c73`: oven-sh/WebKit#657 (suspended generators keep their scopes' SymbolTables), #658 (MicrotaskCallCache over zeroed storage), #583 (no weak `Bun__thisThreadHasVM` fallback — bun defines it in `VirtualMachine.rs`), #627 (`JSModuleLoader::clearAll()` in one pass), #624 (DFG constant-folding a module variable across an import cycle). ### Tests - `test/bundler/bun-build-compile.test.ts` → `locals live only at a catch inside a loop`: builds a fixture with `bun build --bytecode` and runs it; covers for-of (result discarded and used), `while` inside a user `finally`, labelled `break` into a `try`, the loop-only number that turns into `NaN`, the for-of inlined into a caller, and a recursively inlined try/catch on source (that last one is a no-regression check for the inline-frame keying, it passes before too). JIT thresholds are lowered in the child's environment so DFG is reached after ~100 calls; every case goes wrong within 70 iterations on the unfixed engine and the test runs 300. - `test/js/web/explicit-resource-management.test.ts` → `a dispose that throws after the body threw reports a SuppressedError from optimized code`. On `1.4.3-canary.1+7e56b402b` (unfixed): the two `--bytecode` cases fail (`loopOnlyNumber: got false:4:NaN`, `TypeError: undefined is not a function`) and the `using` test prints `Error | undefined | undefined`. With this PR (`bun bd test`, debug build on the published prebuilt) all of them pass. They pass on 1.4.2 as well for the `--bytecode` part, since that predates the optimizer. Supersedes #37941, which pinned a preview build of an earlier, now closed, version of the same engine fix (oven-sh/WebKit#417).
#42822) ### What does this PR do? Moves `WEBKIT_VERSION` from `65513e295c73` to `c775a5dc527da387fd84cc444096af38f6810b44` (oven-sh/WebKit main). No Bun source change is needed to build: main builds against it as it is. One workaround the new engine makes redundant is removed (`BunDebugger.cpp`, below); the other two files are tests. What comes with it, on the JavaScriptCore side: - oven-sh/WebKit#628, "less memory per function that never runs, and code that can be dropped and decoded again": - a module's function declarations are instantiated when their binding is first read, and stay in the embedded bytecode until then; - call sites in the interpreter and in Baseline code get their link record (and array profile) on their second execution, in either tier, and the collector is told about those records; - an unlinked code block's value and array profiles are allocated when it first reaches the Baseline JIT, and a metadata table's value-profile predictions are kept out of line and only for code that has warmed up; - module and program code that has run is released right away; a module record that is not going to run its body is done with its executable's code; - code decoded from an embedded bytecode cache (`bun build --compile --bytecode`) can be dropped and decoded again (`VM::shrinkFootprintNow` with flags; nothing in Bun calls it yet), not under a suspended generator or async activation; a released RegExp keeps its atom; - the thunks of the call slow paths clear the stack their C++ function's frame is going to occupy, so that what the last callee left there is not kept alive by a later conservative scan; - `Heap::totalBytesAllocated()`, `sizeAfterLastCollection()` and `allocationBudgetThisCycle()` for embedders; `$vm.codeBlockCensus()`. - Consequence for Bun: `Bun.shrink()`, a debugger attaching (`recompileAllJSFunctions`) and a Worker going away (`VM::deleteAllCode`) now also drop executables that were decoded from a persistent payload (`--compile --bytecode`, `NODE_COMPILE_CACHE`) and decode them again on their next call; before, such code was never touched. There is a test for it now (below). `Bun.shrink()` also returns early, without collecting or returning allocator memory, when a concurrent collection is in progress, and it clears `vm.lastException()`; both are benign. - oven-sh/WebKit#630: `for`-`of` and array destructuring over arrays without an Array Iterator object, and one RegExpObject per `/x/.test(s)` literal site. - oven-sh/WebKit#635: `Heap::evacuateSparseAuxiliaryBlocks` (a prototype; nothing calls it by default). - oven-sh/WebKit#657: a suspended generator or async function keeps its scopes' SymbolTables when its code is generated again. - The bytecode cache format revision goes from 5 to 9 (#630 took 6-8, #628 takes 9), so caches written by an older Bun are rejected and rebuilt, and `--compile --bytecode` executables must be rebuilt with the new Bun (as with every revision bump). The release `autobuild-c775a5dc527da387fd84cc444096af38f6810b44` is published with the same 42 assets, name for name, as the release of the current pin (`autobuild-65513e295c73...`), so every flavour `scripts/build/deps/webkit.ts` downloads today exists for this one: linux glibc, musl and android, macos, windows and freebsd, amd64 and arm64, each as release, `-lto` (not windows-arm64, as today) and `-debug`, plus `-asan` and `-debug-asan` for linux amd64/arm64 and macos-arm64 and `-asan` for windows-amd64. `src/jsc/bindings/BunDebugger.cpp`: `protectModuleExecutablesFromClearCode()` removed every module executable from the VM's clearable-code set before the debugger's `recompileAllJSFunctions`, because `ModuleProgramExecutable::clearCode` used to drop the module environment's symbol table, and code regenerated in debugger mode then no longer matched the live environment. At this WebKit a module executable keeps one environment symbol table and its function declarations for its whole life, its code-generation mode is pinned, and module code that has run is released by the engine itself, so the invariant the comment described no longer exists. The function and its call are deleted. ### What it gives A large bundled CLI application built as a standalone executable with embedded bytecode (`--compile --bytecode`), a scripted 20-request session against a local fake API, release builds (`--lto=off`) of main (782c402) and of this branch, same application commit. RSS in MB (anonymous + file-backed). | | main | this PR | |---|---|---| | parked at its first prompt, 10 s after it appears | 229 (133 + 95) | 207-213 (116 + 90-97) | | ... 30 s | 228-229 (133-134 + 95) | 206-213 (114-116 + 92-96) | | ... 2.5 min (after main's second idle collection and the page-out of the module graph) | 140-145 (108 + 32-36) | 136-140 (95-99 + 41) | | ... 10 min | 142-145 (108 + 33-37) | 135-141 (93-98 + 42-43) | | **peak of the 20-request session** (10 runs each, interleaved; the larger of the kernel's `VmHWM` and the highest `VmRSS` seen) | **median 474, range 452-490** | **median 453, range 434-472** | | what the highest sample of those runs is made of (medians) | 368 anonymous + 103 file | 342 anonymous + 105 file | | 30 s after the session | 385-391 (282-288 + 102-103) | 353-359 (259-260 + 94-98) | | ... 2.5 min | 215-216 (178 + 37-38) | 210-213 (167-171 + 42-43) | | ... 10 min | 225-231 (179-183 + 45-47) | 217-224 (168-171 + 49-52) | | `--help`, user-mode instructions (7 runs each, interleaved) | 548.5 M (543.0-548.8) | 507.9 M (506.6-528.8): -7.4% | Two runs per row unless said otherwise; the idle timer is main's on both sides (its defaults: collections after 10 s, 75 s and 140 s without heap growth). What it is: about 17 MB less anonymous memory from the moment the prompt is up (functions that are declared and never called no longer exist as objects, call sites that have run once or never carry no link record, code that never reached the Baseline JIT has no profiles), about 10 MB of that left once the idle collections have run on both sides, and 5-9 MB more file-backed memory at rest (the declarations that are not instantiated stay in the embedded bytecode, which is part of the executable's mapping). The peak is lower too, by about the same amount as the fresh prompt and a little more: 22 MB at the median, all of it anonymous; the spread between runs is 40 MB on both sides, and this PR is the lower one in 9 of the 10 interleaved pairs. So the lazily allocated metadata lowers the peak as well as the idle footprint, by roughly what it saves at the prompt; nothing here changes what a request allocates while it runs. ### Binary size Against main's canary (BuildKite's binary-size annotation on this PR's first build): | target | main | this PR | delta | |---|---|---|---| | bun-darwin-aarch64 | 59.95 MB | 60.07 MB | +129.2 KB | | bun-darwin-x64 | 65.83 MB | 65.97 MB | +144.3 KB | | bun-linux-aarch64 | 76.43 MB | 76.55 MB | +128.0 KB | | bun-linux-x64 | 76.38 MB | 76.51 MB | +128.0 KB | | bun-linux-aarch64-musl | 69.63 MB | 69.70 MB | +64.0 KB | | bun-linux-x64-musl | 70.51 MB | 70.59 MB | +80.0 KB | | bun-linux-aarch64-android | 83.40 MB | 83.47 MB | +64.0 KB | | bun-linux-x64-android | 85.84 MB | 85.95 MB | +112.0 KB | | bun-freebsd-x64 | 87.94 MB | 88.06 MB | +124.0 KB | | bun-freebsd-aarch64 | 91.29 MB | 91.41 MB | +128.0 KB | | **bun-windows-x64** | 82.58 MB | 83.14 MB | **+575.5 KB** | | bun-windows-aarch64 | 72.27 MB | 72.37 MB | +101.5 KB | `bun-windows-x64` is over the 0.5 MB gate, so the commit carries `[skip size check]`. Where that target's growth comes from, by the size of the published WebKit prebuilt (`.tar.gz` bytes, which are not linked bytes, but the shape is clear) at each commit of the range: | oven-sh/WebKit main at | windows-amd64-lto | step | linux-amd64-lto step | |---|---|---|---| | 65513e29 (current pin) | 646,774,059 | | | | a76e6b08 (#316: `BCRASH` is `__builtin_trap` on clang-cl) | 648,250,706 | +1.48 MB | +1.4 KB (windows-arm64: +19 KB) | | 03897bd1 (#630) | 649,000,141 | +0.75 MB | +0.31 MB | | 16a8ab73 (#635, #485) | 649,449,191 | +0.45 MB | +0.15 MB | | c775a5dc (#628) | 651,166,232 | +1.72 MB | +0.63 MB | About a third of the Windows x64 growth is #316, a crash-instruction fix that only shows on Windows x64 with LTO and that any upgrade past it brings; the rest is the new engine code (#628, #630, #635), which costs 64-144 KB on every other target. There is no Bun code in this PR to make smaller. #42383's earlier builds, on a preview of #628 alone, passed the gate. ### How did you verify your code works? Release build (`bun scripts/build.ts --profile=release --lto=off`) with the downloaded prebuilt; the same build of main next to it. - `test/bundler/bundler_bytecode_portable.test.ts`: the pinned encoder output changes on a WebKit upgrade that changes the cache format, and the file says to regenerate it then. Regenerated with this build and checked entry by entry: only the `bytes` and `sha256` of the serialized caches move (every one of them: the revision is in every header, and seven commits in the range change `runtime/CachedTypes.cpp`); the `sha256` of the printed JavaScript next to each and the string corpus are unchanged. Bundles are 0.1-0.2% smaller (`libraries.js` 22,009,472 -> 21,977,536 bytes), `vm.Script` / `vm.SourceTextModule` caches 0-1.6% larger (`typescript.js` 11,684,048 -> 11,769,312; `acorn.mjs` 257,168 -> 261,216: its function declarations are in the payload now). The cases that decode every corpus from its cache and compare the program's output, and the one that encodes in a second process and compares the bytes, pass: 22 of 22. CI runs the same snapshot on every platform, which is the point of the test. - `test/cli/inspect/compile-bytecode-tooling.test.ts`: the heap-snapshot case expected `hotWork`, a module function nobody had read, to be in the snapshot. A module's function declaration is now created when its binding is first read, so that cannot hold; the case now takes one snapshot before anything reads `hotWork` (it is absent) and one after (it is present). - New case in `compile-bytecode-tooling.test.ts`, "code dropped by Bun.shrink() is decoded again and runs the same": three rounds of `Bun.shrink()`, a tick and `Bun.gc(true)`, then a function that had run, one that had not, a class method, a generator suspended across the shrinks (its captured locals are the shape #657 fixes) and a pending async function. It asserts exact values, and that the output is identical from source, from the `--compile --bytecode` executable and from `NODE_COMPILE_CACHE` on its second run (the cache directory is checked to have been written). 5 of 5. - Without the `BunDebugger.cpp` workaround: `test/cli/inspect` 48 pass (one run had the port-collision flake of `websocket > bun --inspect=<port>`, which passed on the next), `test/js/node/inspector/inspector.test.ts` 24 of 24 (it has the script that turns breakpoints on between two top-level awaits, which is the case the workaround was for), `test/regression/issue/21654` 1 of 1; the same counts with it. - `test/cli/run/require-cache.test.ts` 18/18, `test/js/workerd/html-rewriter-leak.test.ts` 13 pass / 1 skip, `test/js/bun/jsc/heapStats-mimalloc.test.ts` 7 pass / 1 skip. - `test/js/bun/resolve` (41 files): 360 pass, 3 fail; `test/js/web/fetch/fetch.test.ts`: 361 pass, 4 fail; `test/js/bun/http/serve.test.ts`: 303 pass, 1 fail. The failures are the same ones, test for test, with the build of main on the same machine (they need a user that is not root: unreadable directories and files, a port below 1024). - No Rust changes, so there is nothing for clippy or the cross-target `cargo check` to look at; the C++ change is a deletion.
A closure made in the body of a loop can go on reading the binding of an earlier iteration:
It needs the function to resume in code that was generated again while it was suspended: after
VM::deleteAllCode, orafter its CodeBlock was jettisoned for old age and its unlinked code was dropped too (
Heap::deleteAllUnlinkedCodeBlocks,UnlinkedFunctionExecutable::clearCode, or the collector clearing the weak edge to it). Correct with the DFG off.Cause
DFG::ByteCodeParserfoldsresolve_scopeof a closure variable to a constant scope when the scope's SymbolTable hasonly ever had one environment (
SymbolTable::singleton()), under a watchpoint thatSymbolTable::notifyCreationfireswhen a second environment is made.
get_from_scopethen folds the variable under its own watchpoint set in the sametable.
CodeBlock::setConstantRegistersmakes of the SymbolTable constant in theenclosing function's unlinked code.
JSGlobalObject::symbolTableCachefinds the clone again for a later CodeBlock linkedfrom the same unlinked code, keyed by the unlinked SymbolTable, so re-linking is fine.
the new CodeBlock gets new clones. An activation that was suspended across this still holds the environment it made from
the old clone. Closures made over that environment after the resume are compiled against the old clone's inference,
which still says "one environment". The next iteration's environment comes from the new clone and notifies the new
clone. Nothing ever tells the compiled closure code, which all closures from that site share.
functions, async generators and module bodies (top-level await) are affected. Only the first activation since the code
was generated: a second one has invalidated the inference already.
Fix
For the body of a generator, an async function or a module,
CodeBlock::setConstantRegistersfinds the clone of aSymbolTable constant by whose code it is and which constant (
JSGlobalObject::resumableCodeSymbolTableClones(), perrealm, weak in the clone: the
UnlinkedFunctionExecutable, which is what code is dropped from and what clones are sharedby today, or the
ModuleProgramExecutable, and the constant's index) instead of by the constant itself(
symbolTableCache, which everything else keeps using). When the clone that is found was made of another constant, thecode has been generated or decoded again since:
SymbolTable::isCloneOfScopePartOf: kind of scope,offsets, arguments, every entry's offset and attributes, private names, type profiling), it becomes the new constant's
clone (
SymbolTable::adoptOriginal), so the environments the new code makes reach the inference that older code holds;SymbolTable::invalidateInferencesOfAbandonedClone: thesingleton and every variable's watchpoint set, including ones nobody watches yet), and the new clone starts with its
singleton invalidated, because the scope has environments it did not see being made. This is rare: the code of such a
body is generated the way it was when it first ran (below), so the shape only differs when two executables that share
the unlinked function are pinned to different modes, when only one of the two constants was prepared for the type
profiler, or when the owner in the key has died and its address is another owner's by now. Every outcome is
conservative (the older environments' inferences are gone and the new clone never claims to be a singleton, or an
unrelated scope of the same shape shares a clone); a debugger would show the older scope's name for a shared one.
Acting where code is linked covers every way unlinked code goes away with one check.
The per-variable watchpoint sets of such bodies have been pre-invalidated at link time since 323583 (
put_to_scopeinCodeBlock::finishCreation), which covered the assignment half of this for function bodies; that is left as it is.Also: a module with a top-level await
ModuleProgramExecutable::getUnlinkedCodeBlocktook the realm's currentCodeGenerationModeevery time. A module thatis suspended at a top-level await has its registers in a generator frame; when its code was generated again for the
debugger (or without it) in the meantime, every variable moved between register and scope and the resumed code read
whatever was in the slots:
slow_path_incon an empty value, a crash. From the moment its body is about to run(
ScriptExecutable::newCodeBlockFor), such a module now keeps the mode that code was generated with, as the body of agenerator does; the two share
ScriptExecutable::codeGenerationModeForResumableBody.ScriptExecutable::clearCodedropped the clone of the module environment's SymbolTable andgetUnlinkedCodeBlockcloned the new constant again, while the module's one
JSModuleEnvironmentkeeps the clone it was made from: after theresume, the body's assignments to top-level bindings notified watchpoint sets that nothing compiled against the
environment was watching (
let x = 1; function f() { return x }...await...x = 2: a compiledfwent on returning1). The clone now stays with the executable and is adopted by, or invalidated against, the new constant like the clones
above.
Tests
stress/suspended-activation-keeps-scope-inference-when-code-is-generated-again.js: generator, async function, asyncarrow function, async generator, a
for (let ...)binding, a nested closure over a binding that is assigned again, abody whose code is generated again twice, and the function scope of later activations;
$vm.deleteAllCodeWhenIdle()while suspended. Default tiers, DFG and FTL forced with the concurrent JIT off, and the bytecode cache. Seven of the
eight shapes read every value wrong in the iterations after the resume without the change (the last is there to stay
right).
stress/suspended-module-resumes-in-code-that-is-generated-again.js: a module suspended at a top-level await in a loopwhile
$vm.enableDebuggerModeWhenIdle()and then$vm.disableDebuggerModeWhenIdle()generate all code again; closuresover the loop's bindings and a function over a top-level binding that is assigned again after each resume. Crashes
without the pin; with the pin and without the rest, both read wrong values.