Repository navigation
fix(code-splitting): only split an entry facade when something else can load its chunk - #10441
Conversation
✅ Deploy Preview for rolldown-rs canceled.
|
Merging this PR will improve performance by 4.01%
Performance Changes
Tip Curious why this is faster? Comment Comparing Footnotes
|
I reviewed this PR focusing on whether the fix approach is sound — specifically, whether gating the facade decision on a pre-facade run of the real link computation can ever miss a needed facade (the dangerous direction; an unnecessary facade is only a wasted file). Conclusion: the approach is sound and the implementation matches its stated invariants. What was independently verified, keyed to code: The scoped query's rollback is complete. The only shared-state mutation inside The pre-facade snapshot argument holds. Enumerating the edge sources in No dangerous input skew between the query and the final pass. Between them the state changes are facade creation (above), The restore-before-query ordering is load-bearing, as its comment claims. Tests pin both directions. The shape tests assert no facade for self-contained lazy routes and a retained facade when another chunk imports the entry's chunk, each under wrap-all and on-demand; the new fixture executes under Node asserting Non-blocking nit. In the The extra strict-mode link pass (+~6% wrap-all on the 120-route benchmark) is a reasonable trade for the 45% chunk-count reduction and is honestly flagged in the PR body. |
|
Both nits addressed in f2b2aa2. Skipping the query when nothing can need a facade. One correction to the motivation, though: I could not measure a win. My first attempt benchmarked the 120-route app from the PR body, which turns out never to reach that path —
With an empty plan and a single chunk, the link pass is cheap next to parsing and rendering 600 modules. So the change stands on doing strictly less work and on making the branch's reasoning explicit, not on a measured speedup. The implicit invariant. Now stated in the empty-plan branch: it may skip the three passes hoisted ahead of the query because an empty plan makes each one a no-op — nothing demands an order-wrap runtime helper, restoring is filtered by the plan, and Both changes are refactor-only: full fixture suite 1896 passed / 0 failed, zero snapshot drift. |
How to use the Graphite Merge QueueAdd the label graphite: merge-when-ready to this PR to add it to the merge queue. You must have a Graphite account in order to use the merge queue. Sign up using this link. An organization admin has enabled the Graphite Merge Queue in this repository. Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue. This stack of pull requests is managed by Graphite. Learn more about stacking. |
) ## Summary `preserveModules` emits one chunk per module, and the export-naming pass in `compute_cross_chunk_links` relies on that: to decide whether a chunk export should be named `default`, it reaches for `chunk.entry_module(&self.link_output.module_table).unwrap()`. Synthetic chunks break the assumption. `strictExecutionOrder` splits the shared `rolldown-runtime` chunk that holds `__esmMin`; that chunk mirrors no user module and is `ChunkKind::Common`, so the lookup returns `None`: ``` thread 'rolldown-worker' panicked at crates/rolldown/src/stages/generate_stage/compute_cross_chunk_links.rs:1299:65: called `Option::unwrap()` on a `None` value ``` Any `preserveModules` build with `strictExecutionOrder` and more than one emitted chunk hits it — a two-module entry is enough: ```js // dep.js export default function dep() { return 'D'; } // main.js import dep from './dep.js'; console.log(dep()); ``` ```js await (await rolldown({ input: './main.js' })) .generate({ format: 'esm', preserveModules: true, strictExecutionOrder: true }); // panics ``` ## Fix A chunk with no entry module has no module default export to rename, so ask the question instead of asserting the answer — `is_some_and` in place of `unwrap`. Behaviour for chunks that *do* mirror a module is unchanged: the condition is identical whenever `entry_module()` is `Some`, and no existing snapshot moves. The only chunks reaching the new branch are ones that previously panicked. The sibling `entry_module(...).expect(...)` a little earlier in the same function is already guarded by an `if let ChunkKind::EntryPoint { .. }`, so it is sound and left alone. ## Tests New fixture `misc/preserve_modules/strict_execution_order_runtime_chunk`, run under both wrap-all and `onDemandWrapping`. It builds a static import with a default export plus a dynamic import, so the output has a per-module file, a `default` export to name, and the split runtime chunk. `_test.mjs` asserts the modules evaluate in source order. Without the source change the fixture panics at the line above; with it, it passes. `dep.js` still exports `default`, so the naming path this code exists for is covered rather than merely bypassed. Full Rust integration suite: 1892 passed, with the only 4 failures (`cjs_module_lexer_compat` ×3, `npm_packages/util_deprecate`) failing identically on unpatched `main` in the same tree — they need npm packages this worktree does not have installed. ## Relationship to #10441 Independent, and this PR is based on `main` rather than stacked. The panicking chunk is the synthetic runtime chunk, which #10441 does not touch; the panic reproduces identically with and without that PR, and the fix is in a different function. One thing reviewers should know: this fixture's snapshot shows `preserveModules` currently emitting *two* files for an order-wrapped entry — `main.js` plus `_virtual/main.js` — because the entry facade splits unconditionally. That contradicts the one-file-per-module contract, and it is exactly what #10441 fixes. Whichever lands second will regenerate this snapshot with the facades gone. That is a snapshot update, not a conflict.
IWANABETHATGUY
left a comment
There was a problem hiding this comment.
Model review — findings generated and verified by Claude Fable 5 (
claude-fable-5); posted by the reviewer.
Two P2 findings, both verified against f2b2aa2 by reproducing locally: a residual case of the over-split this PR removes (dead dynamic imports still count as loads — reproduction, one-line fix, and a drop-in regression fixture in the inline comment), and a doc-sync obligation (internal-docs/code-splitting/design.md still documents the unconditional/predicted-edges rule this PR replaces). Neither changes the verdict from the earlier review — the approach and its soundness argument hold.
f2b2aa2 to
7b5fe95
Compare
…bservable load Under `output.strictExecutionOrder`, order-wrapping an entry whose chunk the post-chunk optimizer merged away does not defer anything. It makes `restore_order_wrap_entry_facades` resurrect a file for that entry, because a merged entry has nowhere else to put its trigger. On an app that declares a lazy entry per route, that is one extra chunk per route. This skips the wrapper in the one case where it cannot buy anything: no module in the entry's own static load closure is order-sensitive, so running that whole closure early is not observable. lobehub, same Vite, only the rolldown package swapped: | | JS files | raw | gzip | brotli | | --- | ---: | ---: | ---: | ---: | | `strictExecutionOrder` off | 1518 | — | — | — | | before | 2585 (+1067) | +0.80% | +2.12% | +2.04% | | after | 1600 (+82) | +0.42% | +0.94% | +0.91% | ComfyUI_frontend and plane are byte-identical before and after — neither has an entry the optimizer merged away, so nothing is skipped. The chunk growth is a regression against released behaviour, not an inherent cost of the guarantee. `order_wrapping.rs` does not exist at `v1.2.0`; it arrived with #10104. Released 1.2.0 emits 1471 JS files on lobehub with `strictExecutionOrder` on, 47 *fewer* than with it off. Current `main` emits 2585. Nor is the growth the price of the correctness fixes in that series. #10441 gates `create_order_wrap_entry_facades` on the real cross-chunk edges, and on lobehub that gate creates 59 facades. The other 1008 files come from `restore_order_wrap_entry_facades`, whose candidate set is every order-wrapped entry with no necessity test — and the default plan wraps every entry. Restoring is not the thing to gate. A resurrected chunk is the only place a merged entry's trigger can live: - Dropping the restore leaves the entry with no trigger at all, so it never initializes. That is a missing evaluation, not a mis-ordering, which is why gating it broke `optimization/chunk_merging/dynamic_entry_merged_in_user_defined_entry`. - One file can host only one entry's top-level trigger, so two merged entries sharing a host chunk cannot share one. - Moving the trigger to the `import()` call site fires a microtask too late even when the host chunk's top level is inert. `function/strict_execution_order_invariants/m4_dynamic_facade_race` pins that with a fully wrapped host chunk. So the wrapper is what to skip, and it is safe to skip exactly when the entry's execution position is unobservable. `is_order_sensitive` already answers that per module from module content — `EcmaViewMeta::ExecutionOrderSensitive`, plus eagerly triggering an interop module. When no module in the entry's static load closure is order-sensitive, an unwrapped body inline in the host chunk runs that closure whenever the chunk loads and nothing an importer can observe differs. That question reads module content, never chunk reachability, so it does not approximate a graph that does not exist yet when the plan is built — the failure mode that sank three earlier attempts at narrowing this cost, recorded in #10294. `issues/9463` is the fixture this facade mechanism exists for: entry `b` must not run entry `a`'s top-level side effect. Its `shared.js` is a dynamic-import target the optimizer merged into the shared chunk, so it was order-wrapped and restored as its own file: ```js // shared.js — resurrected so this call has somewhere to live import { i as init_shared, r as foo } from "./common~a~b~shared.js"; init_shared(); export { foo }; ``` `init_shared` was `__esmMin((() => {}))`. `shared.js` only declares a function, so the wrapper deferred nothing and the file existed to call an empty init. Afterwards the module is a namespace object in the host chunk and the dynamic import collapses to a same-chunk `Promise.resolve()`. `init_a` and `init_b` are untouched, and the fixture's `_test.mjs` — which asserts that loading `b` never runs `a`'s side effect — still passes. `optimization/chunk_merging/dynamic_entry_merged_in_user_defined_entry` goes from three emitted files to one for the same reason. `add_top_level_eager_order_reasons` ran only when `experimental.onDemandWrapping` was set, which left `ExecutionOrderSensitive` less complete in the default plan than in the selective one. Any decision about what a wrapper buys reads that flag, so the reasons are now collected whenever `strictExecutionOrder` is on. Measured on its own, with the entry rule disabled: ComfyUI_frontend and plane byte-identical, lobehub raw byte-identical with gzip and brotli moving by 30 and 59 bytes out of 19 MB. - The selective wrapping plan stays behind `experimental.onDemandWrapping`. The predicted chunk edges, the expected-versus-actual order comparison and the emergent-cycle fixpoint are untouched, and which non-entry modules the default plan defers is unchanged. - The default plan is not brought to parity with the selective one on bytes. Both emit 1600 files on lobehub, but the selective plan is 28 KB smaller raw there, and on ComfyUI_frontend it is +4.13% raw against this PR's +7.12%. That remainder is wrapper code rather than chunk proliferation. - 1471 is not a target. Counting execution-order violations directly in the emitted output — a chunk whose inline `__esm` init another chunk statically imports, so loading that other chunk runs it — gives 58 for `strictExecutionOrder` off (pre-existing, from interop wrapping), 56 for released 1.2.0, and 0 both before and after this PR. Part of why the released file count is lower is that the build was not emitting those triggers. `test_extended_top_level_reasons_do_not_leak_to_the_non_strict_default` replaces `..._do_not_leak_to_default_or_wrap_all`: the reasons still must not reach a non-strict build, and both strict plans now collect the same ones. The snapshot updates are the fixtures whose entries the rule now leaves unwrapped.
|
Rebased onto The one real conflict34 of the 35 conflicted files were snapshots. The one that mattered was #10414's Resolved by splitting the two. One further ordering change fell out of it:
|
Merge activity
|
…an load its chunk (#10441) ## Summary Under `strictExecutionOrder` (SEO), an entry's body moves into `init_E()` and the entry chunk carries a top-level `init_E()` call. That inline trigger is only safe while the chunk hosting `E` is loaded *solely to enter* `E`. Once another chunk imports that chunk, the entry's program runs during an unrelated load — which is exactly what SEO exists to prevent. The facade split moves the trigger into its own file when that happens. `create_order_wrap_entry_facades` asked that question only of interop-wrapped entries, and only under `onDemandWrapping`. **Every order-wrapped entry split unconditionally**, so each one cost an extra chunk even when nothing but the entry itself could ever load it — including every dynamic entry, i.e. one extra file per lazy route. This PR gates all three facade sources on one predicate — *can anything else load this chunk?* — answered from the real cross-chunk link computation instead of a prediction. Measured on a generated 120-lazy-route app: | | `main` | this PR | | --- | --- | --- | | SEO off | 146 chunks | 146 | | `strictExecutionOrder` (wrap-all) | **268** (+122) | **147** (+1) | | `strictExecutionOrder` + `onDemandWrapping` | **267** (+121) | **147** (+1) | Raw JS bytes in wrap-all: 96,326 → 82,870 (−14%). The `+1` in both fixed columns is the runtime chunk. The executed output of all three modes is byte-identical before and after. Relates to #10294. Independent of #10433, which addresses a different facade case. ## Why the decision could not read facts before The facade decision sits in `finalize_chunk_plan`, which runs *before* `compute_cross_chunk_links`. The only edge set available was `predicted_static_import_edges` — computed with an **empty** `OrderWrapState`, i.e. "what would the edges be if nothing were wrapped" — and in wrap-all mode not computed at all (`wrap_all_order_analysis` filled `import_edges` with empty sets, which the `!on_demand ||` short-circuit papered over). ## Alternatives explored Two ways of re-deriving the missing edges were tried and rejected, both unsound in the same way: 1. **Scan the module graph** for chunks that some included module in another chunk statically imports into. Misses `init_*` obligations that reach their target *through a non-included forwarder* — `collect_order_wrap_esm_init_targets` descends into the import records of a tree-shaken forwarder, so both hops have a non-included endpoint and the scan skips them. Produces an entry whose program runs during another entry's load. 2. **Reuse `post_lowering_import_edges`** (the emergent-cycle fixpoint's projection). That projection deliberately omits interop `WrapKind::Esm` overlay edges and consumption-gated hops, because for *cycle detection* projecting them would fabricate a cycle and over-wrap. Omissions that are safe there are unsafe here: it drops a needed facade and breaks `retained_star_renamed_cycle` at runtime. The lesson is that any hand-rolled reachability scan silently misses an edge source, and a missed edge is an execution-order bug with no signal. So this PR asks the real computation rather than re-deriving it. ## How the query is made possible `collect_depended_symbols` does not only read the chunk graph — it writes each declared symbol's owning chunk back into the shared symbol database, and `compute_chunk_imports` reads that ownership back to resolve which chunk a depended symbol is imported from. The write is load-bearing *within* one pass, so the pass cannot be made read-only by dropping it. It can be scoped instead. `SymbolChunkOwnership::Scoped` records the previous owner of every symbol the pass assigns; the caller restores them afterwards, leaving the symbol database exactly as it found it. `lowered_static_import_edges` drives the pass with the fully lowered `OrderWrapState` and the real final init metadata, so every edge source the final pass registers — value references, `init_*` forwarding, retained re-export overlays, transitive init obligations — is present, with no approximation. **Why deciding before the facades exist is sound.** A facade is an empty chunk that takes over the entry role from the implementation chunk: it adds exactly one importer of that chunk (itself), and it inherits — never widens — the outgoing edges the implementation chunk had as an entry chunk. So for every *other* chunk the relation "some chunk other than me imports me" is unchanged, and all facade decisions can be taken together from one pre-facade snapshot. ## Ordering changes Three passes move ahead of the query, none of which depends on facades existing: - `ensure_runtime_module_for_order_wraps` — resolving a depended symbol to its chunk requires the runtime module to already sit in one, and order wrappers demand runtime helpers. A facade chunk copies its implementation chunk's bits, so the runtime chunk's bit union is unchanged. - `restore_order_wrap_entry_facades` — `compute_chunk_imports` **skips chunks marked `Removed`**, so restoring afterwards would hide the edge from a resurrected facade to the chunk hosting its implementation, and an entry sharing that chunk would keep an inline trigger that the restored facade's load then fires. This one is not hypothetical: an earlier revision of this PR hit it, and the fixture suite did not catch it. - `finalized_module_namespace_ref_usage` — so the query sees the namespaces the final link pass will see rather than the provisional pre-lowering set. No output changes from this today; it closes the gap rather than fixing an observed failure. Restoring stays **ungated**. Unlike splitting, it exists because a chunk can host only one entry's top-level trigger, so an entry merged into another entry's chunk has no trigger at all without its own file. ## Tests ### The regression test that was missing The over-split was invisible to every existing test, and that is the more important thing to fix: an output-correctness test cannot see it, because the over-split bundle still *runs* correctly — it just ships one extra file per entry. `packages/rolldown/tests/behaviors/strict-execution-order-entry-facade.test.ts` pins the **shape** of the output instead, keying on the property that defines a facade: a chunk holding zero modules, existing only to host an entry's `init_*()` trigger. Both directions are pinned, so the budget check cannot be satisfied by simply never splitting: | | assertion | | --- | --- | | six lazy routes over a shared library | no facade, and no chunk beyond the shared runtime | | two entries, one sharing a chunk with a module the other imports | the facade is still emitted, and the chunk holding the entry's own module is no longer an entry chunk | Each runs under wrap-all and `onDemandWrapping`. **Against the parent commit all four fail** — seven facades for the lazy-route app, and `['b', 'e']` instead of `['e']` for the shared-chunk app. The manual group in the lazy-route app is load-bearing: it makes the chunk-driven evaluation order differ from source order, which is what puts modules on the on-demand plan. Without it on-demand finds no hazard, wraps nothing, and the shape does not exercise entry splitting at all. ### Execution-order coverage New fixture `function/experimental/strict_execution_order/entry_shared_chunk_facade`: entry `e` shares a chunk with `shared.js`, which entry `b` imports. The facade must be kept, and `_test.mjs` asserts `e`'s program does not run while `b` is loading. Forcing the predicate to return an empty edge set makes it fail with `['E body', 'S body', 'B body S']` — the violation this PR must not introduce. Existing coverage that pins the discrimination in both directions: `m4_dynamic_facade_race` keeps `target.js`'s facade (its chunk also hosts `observer.js`) while dropping `a2.js`/`b2.js`; `dynamic_target_in_entry_chunk` keeps `a.js`'s and drops `c.js`'s. 89 snapshots update, removing 207 emitted assets. No fixture loses a facade it needs — every strict fixture executes its output under Node. - Rust integration suite: 1896 passed / 0 failed, identical to `main` on the same machine. - Node suite: 913 passed / 0 failed. ## Reviewer attention - **The soundness argument for a pre-facade snapshot** (the "How the query is made possible" section) is the load-bearing claim. If a facade can widen the set of chunks that import some *other* chunk, the decision would need a fixpoint. - **The restore/query ordering** — the removed-chunk skip in `compute_chunk_imports` is easy to miss and produces a silent wrong answer. - **Build time.** Strict mode now runs one extra `compute_wrapped_esm_init_metadata` and one extra `compute_cross_chunk_link_state`. On the 120-route app, wrap-all median 63.9ms → 67.6ms (~+6%); SEO-off is unchanged. Partly offset downstream by 45% fewer chunks to name, render and hash; the balance on a large app is worth a look. ## Unrelated pre-existing bug found while testing `preserveModules` + `strictExecutionOrder` panics on `main` at `chunk.entry_module(...).unwrap()` in `render_chunk_exports`, because strict lowering demotes an entry chunk to `Common` while `preserve_modules` assumes every chunk has an entry module. Behaviour is identical before and after this PR; filing separately.
944a3ea to
9c1c54f
Compare
…bservable load Under `output.strictExecutionOrder`, order-wrapping an entry whose chunk the post-chunk optimizer merged away does not defer anything. It makes `restore_order_wrap_entry_facades` resurrect a file for that entry, because a merged entry has nowhere else to put its trigger. On an app that declares a lazy entry per route, that is one extra chunk per route. This skips the wrapper in the one case where it cannot buy anything: no module in the entry's own static load closure is order-sensitive, so running that whole closure early is not observable. lobehub, same Vite, only the rolldown package swapped: | | JS files | raw | gzip | brotli | | --- | ---: | ---: | ---: | ---: | | `strictExecutionOrder` off | 1518 | — | — | — | | before | 2585 (+1067) | +0.80% | +2.12% | +2.04% | | after | 1600 (+82) | +0.42% | +0.94% | +0.91% | ComfyUI_frontend and plane are byte-identical before and after — neither has an entry the optimizer merged away, so nothing is skipped. The chunk growth is a regression against released behaviour, not an inherent cost of the guarantee. `order_wrapping.rs` does not exist at `v1.2.0`; it arrived with #10104. Released 1.2.0 emits 1471 JS files on lobehub with `strictExecutionOrder` on, 47 *fewer* than with it off. Current `main` emits 2585. Nor is the growth the price of the correctness fixes in that series. #10441 gates `create_order_wrap_entry_facades` on the real cross-chunk edges, and on lobehub that gate creates 59 facades. The other 1008 files come from `restore_order_wrap_entry_facades`, whose candidate set is every order-wrapped entry with no necessity test — and the default plan wraps every entry. Restoring is not the thing to gate. A resurrected chunk is the only place a merged entry's trigger can live: - Dropping the restore leaves the entry with no trigger at all, so it never initializes. That is a missing evaluation, not a mis-ordering, which is why gating it broke `optimization/chunk_merging/dynamic_entry_merged_in_user_defined_entry`. - One file can host only one entry's top-level trigger, so two merged entries sharing a host chunk cannot share one. - Moving the trigger to the `import()` call site fires a microtask too late even when the host chunk's top level is inert. `function/strict_execution_order_invariants/m4_dynamic_facade_race` pins that with a fully wrapped host chunk. So the wrapper is what to skip, and it is safe to skip exactly when the entry's execution position is unobservable. `is_order_sensitive` already answers that per module from module content — `EcmaViewMeta::ExecutionOrderSensitive`, plus eagerly triggering an interop module. When no module in the entry's static load closure is order-sensitive, an unwrapped body inline in the host chunk runs that closure whenever the chunk loads and nothing an importer can observe differs. That question reads module content, never chunk reachability, so it does not approximate a graph that does not exist yet when the plan is built — the failure mode that sank three earlier attempts at narrowing this cost, recorded in #10294. `issues/9463` is the fixture this facade mechanism exists for: entry `b` must not run entry `a`'s top-level side effect. Its `shared.js` is a dynamic-import target the optimizer merged into the shared chunk, so it was order-wrapped and restored as its own file: ```js // shared.js — resurrected so this call has somewhere to live import { i as init_shared, r as foo } from "./common~a~b~shared.js"; init_shared(); export { foo }; ``` `init_shared` was `__esmMin((() => {}))`. `shared.js` only declares a function, so the wrapper deferred nothing and the file existed to call an empty init. Afterwards the module is a namespace object in the host chunk and the dynamic import collapses to a same-chunk `Promise.resolve()`. `init_a` and `init_b` are untouched, and the fixture's `_test.mjs` — which asserts that loading `b` never runs `a`'s side effect — still passes. `optimization/chunk_merging/dynamic_entry_merged_in_user_defined_entry` goes from three emitted files to one for the same reason. `add_top_level_eager_order_reasons` ran only when `experimental.onDemandWrapping` was set, which left `ExecutionOrderSensitive` less complete in the default plan than in the selective one. Any decision about what a wrapper buys reads that flag, so the reasons are now collected whenever `strictExecutionOrder` is on. Measured on its own, with the entry rule disabled: ComfyUI_frontend and plane byte-identical, lobehub raw byte-identical with gzip and brotli moving by 30 and 59 bytes out of 19 MB. - The selective wrapping plan stays behind `experimental.onDemandWrapping`. The predicted chunk edges, the expected-versus-actual order comparison and the emergent-cycle fixpoint are untouched, and which non-entry modules the default plan defers is unchanged. - The default plan is not brought to parity with the selective one on bytes. Both emit 1600 files on lobehub, but the selective plan is 28 KB smaller raw there, and on ComfyUI_frontend it is +4.13% raw against this PR's +7.12%. That remainder is wrapper code rather than chunk proliferation. - 1471 is not a target. Counting execution-order violations directly in the emitted output — a chunk whose inline `__esm` init another chunk statically imports, so loading that other chunk runs it — gives 58 for `strictExecutionOrder` off (pre-existing, from interop wrapping), 56 for released 1.2.0, and 0 both before and after this PR. Part of why the released file count is lower is that the build was not emitting those triggers. `test_extended_top_level_reasons_do_not_leak_to_the_non_strict_default` replaces `..._do_not_leak_to_default_or_wrap_all`: the reasons still must not reach a non-strict build, and both strict plans now collect the same ones. The snapshot updates are the fixtures whose entries the rule now leaves unwrapped.
… link data (#10449) Asking the cross-chunk link computation a question used to change the state it answers from: the what-if passes — the wrapping prediction and the entry-facade edge query of #10441 — had to write into the shared ownership records they read, then undo their own writes by hand. This PR makes asking side-effect-free by construction: a pass derives ownership as data local to itself, only the final pass commits it, and the compiler now enforces what a doc comment used to promise. ```rust // before — the edge query undoes its own writes, in reverse, by hand let mut journal = Vec::new(); let state = self.compute_cross_chunk_link_state(…, Scoped(&mut journal)); for (symbol_ref, previous_chunk_idx) in journal.into_iter().rev() { symbols.get_mut(symbol_ref).chunk_idx = previous_chunk_idx; } // after — asking cannot write, so there is nothing to undo let state = self.compute_cross_chunk_link_state(…); // &self ``` ## Motivation The cost of the old shape was a silent-failure class, not a bug today. The undo was complete only while the pass contained exactly one write; nothing stopped a future edit from adding a second one the journal does not cover. An incomplete undo leaves values behind that later reads can pick up, and what ships is misresolved cross-chunk imports or a wrong facade decision — with no test signal unless a fixture happens to traverse the exact path. Reviewing #10441 meant manually enumerating every mutation site in the pass to prove the undo complete, and that proof expires with every future edit to the pass. The old shape also leaked between passes even when nothing went wrong. The prediction pass committed provisional ownership it had no way to retract, so stale values sat in the shared records until the final pass overwrote them — the runtime-module spot-clean exists solely to patch the cases where overwriting was not enough (its three call sites now overwrite `None` with `None`; see non-goals). The coupling itself: the collect step (`collect_depended_symbols`, which derives each declared symbol's owning chunk) wrote its derivation into the shared symbol database because the import-resolution step (`compute_chunk_imports`) reads ownership back later in the same pass. The write was load-bearing within one pass, so no caller could simply skip it — every caller had to either keep it (and pollute) or undo it (and be provably complete). Emitted output is unaffected. The downstream consumers of committed ownership — the CJS cross-chunk reference rendering in the module finalizer and the chunk-export generator — read identical values at identical times. ## Change Ownership becomes a value the pass returns instead of state it writes, and committing becomes the final caller's single explicit act. The collect step builds that value — a pass-local `SymbolChunkTable` — from the per-chunk symbol lists it already materialized. - The import-resolution step resolves a depended symbol through the table, falling back to the database value on a miss — exactly the write-then-read union it replaces, so behavior is unchanged by construction. - A pass whose answer is never committed (the prediction, the facade edge query) drops its table on return. The `SymbolChunkOwnership` enum, the journal, and its reverse replay are deleted. - The final `compute_cross_chunk_links` flushes its table in one place, ahead of every downstream reader, and the whole pass chain down from `compute_cross_chunk_link_state` (including `analyze_execution_order`) becomes `&self`. - The one-chunk-per-symbol debug assert now checks within the pass's own derivation instead of against whatever an earlier pass left behind, removing its only false-positive source. Alternative weighed: a two-impl ownership view — the committing pass reading the flushed database directly, monomorphized separately from the table-reading query — would keep the final pass's resolve a direct field read instead of an `FxHashMap` probe. Not taken: it doubles the read-path surface for a cost that should be noise (one probe per depended-symbol resolve plus one map build per pass). CodSpeed on this PR is the check, and the view design stays the escalation path if the strict-mode benchmarks disagree. Non-goal: removing the now-inert runtime-module spot-clean (`clear_module_symbol_chunk_indices`). With no provisional writes left to clean up, its three call sites overwrite `None` with `None`; deleting them wants its own verification, so they stay untouched here. ## Validation A behavior-preserving refactor pins itself on the existing suite, and the suite is built to catch exactly the drift this change could introduce: any output difference surfaces as a snapshot diff. 1896 integration tests pass with zero snapshot modifications; `cargo clippy --all-targets` and `cargo fmt --check` are clean. (`test262_module_code` fails locally only because this worktree has no test262 submodule checkout — the panic fires before any bundling runs; CI executes it with submodules.) Unverified locally and delegated to CI: the CodSpeed benchmarks for the probe-vs-field-read cost above. Stacked on #10441.
## [1.2.1] - 2026-07-29 ### 🚀 Features - dev: support `hotUpdate` hook (#10305) by @h-a-n-a - dev: expose `disableWatcher` through the dev engine bindings (#10474) by @shulaoda - plugin: surface output-option callbacks in [PLUGIN_TIMINGS] (#10411) by @IWANABETHATGUY - `import.meta.ROLLDOWN_FILE_URL_<referenceId>_<urlId>` support to pass context to `resolveFileUrl` hook (#10297) by @sapphi-red - dev: skip the HMR update when a module's rebuilt output is unchanged (#10333) by @h-a-n-a - code-splitting: wrap strict execution order modules on demand (#10104) by @hyfdev - support `import.meta.ROLLDOWN_FILE_URL_*` (#10296) by @sapphi-red - implement `resolveFileUrl` plugin hook (#10291) by @sapphi-red - magic-string: support storeName on overwrite/update (#10312) by @IWANABETHATGUY ### 🐛 Bug Fixes - external: keep `__toESM` when the importing module is tree-shaken (#10516) by @IWANABETHATGUY - dev: resolve re-exports from externals through a real import (#10489) by @tbvjaos510 - code-splitting: route CJS barrel initialization per consumer (#10488) by @hyfdev - error: align filename-pattern diagnostics with Rollup's wording (#10501) by @IWANABETHATGUY - plugin: validate emitted prebuilt-chunk file names (#10399) by @IWANABETHATGUY - code-splitting: point a two-argument dynamic import at the chunk that holds the module (#10479) by @hyfdev - common: align is_path_fragment with Rollup's isPathFragment (#10398) by @IWANABETHATGUY - code-splitting: never name an internal chunk export `then` (#10480) by @hyfdev - code-splitting: avoid creating call-site-triggered entry facades (#10485) by @hyfdev - code-splitting: collect top-level eager order reasons in every strict build (#10463) by @hyfdev - code-splitting: let a cross-chunk dynamic importer carry the order trigger (#10456) by @hyfdev - code-splitting: avoid the dynamic-entry facade when the same-chunk collapse carries the trigger (#10433) by @hyfdev - binding: forward resolveId options.kind to callable builtin plugins (#10440) by @martijnwalraven - dev: keep the export name of `export * as ns from` (#10476) by @tbvjaos510 - code-splitting: only split an entry facade when something else can load its chunk (#10441) by @hyfdev - code-splitting: fold the runtime chunk back after order lowering (#10414) by @hyfdev - runtime: don't leave default undefined for cjs that fakes __esModule (#10453) by @IWANABETHATGUY - import-glob: escape generated string literals (#10438) by @shantanuraj - preserve-modules: don't assume every chunk mirrors a module (#10442) by @hyfdev - filter: treat missing hook inputs as non-matches, not panics (#10443) by @IWANABETHATGUY - code-splitting: keep CommonJS modules wrapped under strict execution order (#10405) by @hyfdev - code-splitting: align dynamicImports metadata with the rewritten import() specifier (#10430) by @hyfdev - dev: skip user plugin hooks for ?rolldown-lazy proxy modules (#10426) by @unknownjedi - treeshake: preserve side-effect-free spread arguments in manual-pure chains (#10432) by @IWANABETHATGUY - treeshake: preserve eagerly evaluated child effects of manual pure chains (#10427) by @Nic-Polumeyv - code-splitting: initialize pure definers behind star re-export barrels under strict execution order (#10409) by @hyfdev - resolveId: reject string `id` filters (must be a RegExp) (#10412) by @IWANABETHATGUY - code-splitting: collect eager order reasons for on-demand wrapping (#10387) by @hyfdev - rolldown: apply output.paths to CJS export-star of external modules (#10406) by @IWANABETHATGUY - dev: sourcemaps of lazily compiled chunks (#10386) by @tbvjaos510 - plugin: validate emitted file names at emitFile time (#10377) by @Nic-Polumeyv - guarantee tokio runtime release when close rejects (#10381) by @shulaoda - code-splitting: make strict transitive init registration deterministic and constant-time (#10320) by @hyfdev - pair tokio runtime acquire and release on wasm to prevent premature shutdown (#10363) by @shulaoda - don't body-demand modules from simulated facade chunk includes (#10351) by @IWANABETHATGUY - tracing: invalid RD_LOG filter and RD_LOG_OUTPUT=json no longer panic (#10343) by @Brooooooklyn - code-splitting: treat class definition-time global reads as order-sensitive (#10322) by @hyfdev - code-splitting: deconflict force-included runtime helper statements (#10336) by @hyfdev - binding: forward all missing parallel JS plugin hooks (#10345) by @Brooooooklyn - code-splitting: re-derive chunk exec order after the runtime sweep (#10334) by @hyfdev - types: add undefined to ExistingRawSourceMap optional properties (#10355) by @ocavue - magic-string: validate relocate ranges before rewiring (#10327) by @IWANABETHATGUY - add EMPTY_IMPORT_META warning for non-node CJS output (#10222) by @sapphi-red - call `resolveFileUrl` in a deterministic order (#10330) by @sapphi-red - magic-string: refuse repeated sendMagicString on a consumed instance (#10331) by @IWANABETHATGUY - magic-string: refuse to use a MagicString after sendMagicString consumed it (#10326) by @IWANABETHATGUY - magic-string: reject non-contiguous moves before rewiring the chunk list (#10311) by @IWANABETHATGUY - handle `./foo/bar` glob pattern the same as `foo/bar` (#10313) by @sapphi-red - magic-string: throw instead of panicking when append/prepend splits an edited chunk (#10301) by @IWANABETHATGUY - output: skip separator for empty hoisted functions (#10310) by @hyfdev - magic-string: don't report a change when edits cancel out (#10299) by @IWANABETHATGUY - sourcemap: map wrapped imported callees (#10288) by @hyfdev - magic-string: count positional inserts at index 0 on an empty source (#10306) by @IWANABETHATGUY - magic-string: return UTF-16 code units from length() (#10295) by @IWANABETHATGUY - output: skip separator for empty import prelude (#10289) by @hyfdev ### 🚜 Refactor - dev: make it easier to customize the runtime (#10338) by @sapphi-red - code-splitting: declare CJS carrier namespaces initializer-free (#10513) by @hyfdev - rollup-tests: avoid relying on `NODE_PATH` env var resolution (#10496) by @sapphi-red - code-splitting: derive symbol chunk ownership as pass-local link data (#10449) by @hyfdev - plugin: share asset emission helpers between copy_module and asset_module (#10450) by @Nic-Polumeyv - plugin: dedupe hook binding boilerplate (#10428) by @Nic-Polumeyv - plugin: share the oxc parse preamble between import-glob and dynamic-import-vars (#10452) by @Nic-Polumeyv - implement `GetAstBuilder` on visitor/pass types (#10424) by @overlookmotel - pass arrays to AST builder methods (#10419) by @overlookmotel - shorten AST builder code (#10418) by @overlookmotel - centralize final ESM init metadata (#10376) by @hyfdev - descriptor-based parallel-plugin detection (getParallelPluginInfo) (#10349) by @Brooooooklyn - remove AstFactory in favor of new_* construction traits (#10353) by @Boshen - enable oxc_ast's `disable_old_builder` feature (#10316) by @Boshen ### 📚 Documentation - development-guide: update config.json link line reference (#10523) by @dogledogle - clarify slash normalization for id hook filter (#10511) by @sapphi-red - code-splitting: record the thenable-namespace rule (#10502) by @hyfdev - clarify that `esmExternalRequirePlugin` must own its externals (#10439) by @TheAlexLichter - add troubleshooting entry for the @rolldown/binding-... resolution error (#10390) by @Nic-Polumeyv - add Code Splitting API reference category (#10382) by @vittorioexp ### ⚡ Performance - use VisitJsMut in JavaScript-only AST passes (#10507) by @Boshen - cache the resolved glob matcher for Id/ImporterId filters (#10410) by @IWANABETHATGUY - scope_hoisting: remove `alloc` field from `ScopeHoistingFinalizer` (#10425) by @overlookmotel - reduce string allocations (#10423) by @overlookmotel - hmr: remove unnecessary string allocations (#10422) by @overlookmotel - avoid allocating static strings via custom builder methods (#10421) by @overlookmotel - pass string literals to AST builder methods (#10420) by @overlookmotel - use VisitJs in JavaScript-only AST passes (#10396) by @Boshen - plugin: shrink erased plugin debug vtables (#10370) by @Boshen - reuse normalized path buffers (#10315) by @hyfdev ### 🧪 Testing - code-splitting: pin CJS barrel fallback triggers and flag-off equivalence (#10514) by @hyfdev - plugin: cover chunk fileName, absolute chunk name, and Windows drive names (#10400) by @IWANABETHATGUY - code-splitting: cover a single-chunk dynamic import of a wrapped module (#10505) by @hyfdev - file: remove the unused .dynamic_import fixture (#10481) by @hyfdev - treeshake: reduce manual-pure fixture to a minimal smoke test, move matrix to unit tests (#10436) by @IWANABETHATGUY - dev: run vite playgrounds under bundled dev (test-serve-bundled) (#10434) by @h-a-n-a - stop snapshots from silently hiding user code inside the runtime region (#10431) by @hyfdev - wasi: add tokio runtime lifecycle regression test (#10379) by @shulaoda - dev: expect preserved hot.data in hmr-whole-chain-dispose (#10380) by @h-a-n-a - code-splitting: pin flag-off wrapped-esm init emission (#10324) by @hyfdev - sourcemap: fix Windows-only failures in composition fixtures (#10368) by @shulaoda - generated-code: mark assert external in symbols_ns2 for deterministic output (#10339) by @hyfdev - code-splitting: cover entries-aware strict init cycle (#10307) by @hyfdev - make `just setup-vite` the only entry point that touches `vite/` (#10332) by @shulaoda - vite-tests: reuse the shared root vite checkout (#10325) by @shulaoda - test-dev-server: drop the vite submodule, track rolldown-canary (#10319) by @shulaoda - vite-tests: track the latest rolldown-canary rebased onto vite main (#10318) by @shulaoda - unify Vite in vite-test and test-dev-server (#10293) by @h-a-n-a ### ⚙️ Miscellaneous Tasks - scope the binding artifact download to `bindings-*` (#10525) by @shulaoda - deps: update napi (#10506) by @renovate[bot] - deps: update rollup submodule for tests to v4.62.3 (#10494) by @rolldown-guard[bot] - deps: upgrade oxc to 0.142.0 (#10497) by @shulaoda - deps: update test262 submodule for tests (#10495) by @rolldown-guard[bot] - deps: update github actions (#10460) by @renovate[bot] - deps: update rust crates (#10462) by @renovate[bot] - deps: update npm packages (#10461) by @renovate[bot] - metric: alert Discord when the metric workflow fails (#10447) by @IWANABETHATGUY - metric: mint a short-lived GitHub App token instead of a PAT (#10446) by @IWANABETHATGUY - repo: repair dangling CLAUDE.md symlink (#10451) by @hanayashiki - publint/package-metadata fixes and small correctness fixes (#10344) by @Brooooooklyn - deps: update dependency vite-plus to v0.2.6 (#10404) by @renovate[bot] - add Semgrep scan workflow (#10395) by @Boshen - enable Windows CI with a PR label (#10375) by @hyfdev - deps: upgrade oxc to 0.141.0 (#10373) by @camc314 - deps: update napi (#10369) by @renovate[bot] - deps: update test262 submodule for tests (#10367) by @rolldown-guard[bot] - deps: update taiki-e/install-action action to v2.83.3 (#10358) by @renovate[bot] - deps: update rust crates (#10357) by @renovate[bot] - deps: update npm packages (#10359) by @renovate[bot] - deps: update rust crate syn to v3 (#10362) by @renovate[bot] - deps: update rust crate oxc_sourcemap to v8.1.2 (#10356) by @renovate[bot] - deps: update dependency vite-plus to v0.2.5 (#10329) by @renovate[bot] - docs: migrate Netlify redirects to Void config (#10282) by @tux-tn - deps: update dependency rust to v1.97.1 (#10317) by @renovate[bot] - runtime: remove unused `runtime/index.js` (#10302) by @IWANABETHATGUY ### ❤️ New Contributors * @dogledogle made their first contribution in [#10523](#10523) * @tbvjaos510 made their first contribution in [#10489](#10489) * @martijnwalraven made their first contribution in [#10440](#10440) * @shantanuraj made their first contribution in [#10438](#10438) * @Nic-Polumeyv made their first contribution in [#10450](#10450) * @hanayashiki made their first contribution in [#10451](#10451) * @unknownjedi made their first contribution in [#10426](#10426) * @vittorioexp made their first contribution in [#10382](#10382) * @tux-tn made their first contribution in [#10282](#10282) Co-authored-by: shulaoda <[email protected]>

Summary
Under
strictExecutionOrder(SEO), an entry's body moves intoinit_E()and the entry chunk carries a top-levelinit_E()call. That inline trigger is only safe while the chunk hostingEis loaded solely to enterE. Once another chunk imports that chunk, the entry's program runs during an unrelated load — which is exactly what SEO exists to prevent. The facade split moves the trigger into its own file when that happens.create_order_wrap_entry_facadesasked that question only of interop-wrapped entries, and only underonDemandWrapping. Every order-wrapped entry split unconditionally, so each one cost an extra chunk even when nothing but the entry itself could ever load it — including every dynamic entry, i.e. one extra file per lazy route.This PR gates all three facade sources on one predicate — can anything else load this chunk? — answered from the real cross-chunk link computation instead of a prediction.
Measured on a generated 120-lazy-route app:
mainstrictExecutionOrder(wrap-all)strictExecutionOrder+onDemandWrappingRaw JS bytes in wrap-all: 96,326 → 82,870 (−14%). The
+1in both fixed columns is the runtime chunk. The executed output of all three modes is byte-identical before and after.Relates to #10294. Independent of #10433, which addresses a different facade case.
Why the decision could not read facts before
The facade decision sits in
finalize_chunk_plan, which runs beforecompute_cross_chunk_links. The only edge set available waspredicted_static_import_edges— computed with an emptyOrderWrapState, i.e. "what would the edges be if nothing were wrapped" — and in wrap-all mode not computed at all (wrap_all_order_analysisfilledimport_edgeswith empty sets, which the!on_demand ||short-circuit papered over).Alternatives explored
Two ways of re-deriving the missing edges were tried and rejected, both unsound in the same way:
init_*obligations that reach their target through a non-included forwarder —collect_order_wrap_esm_init_targetsdescends into the import records of a tree-shaken forwarder, so both hops have a non-included endpoint and the scan skips them. Produces an entry whose program runs during another entry's load.post_lowering_import_edges(the emergent-cycle fixpoint's projection). That projection deliberately omits interopWrapKind::Esmoverlay edges and consumption-gated hops, because for cycle detection projecting them would fabricate a cycle and over-wrap. Omissions that are safe there are unsafe here: it drops a needed facade and breaksretained_star_renamed_cycleat runtime.The lesson is that any hand-rolled reachability scan silently misses an edge source, and a missed edge is an execution-order bug with no signal. So this PR asks the real computation rather than re-deriving it.
How the query is made possible
collect_depended_symbolsdoes not only read the chunk graph — it writes each declared symbol's owning chunk back into the shared symbol database, andcompute_chunk_importsreads that ownership back to resolve which chunk a depended symbol is imported from. The write is load-bearing within one pass, so the pass cannot be made read-only by dropping it.It can be scoped instead.
SymbolChunkOwnership::Scopedrecords the previous owner of every symbol the pass assigns; the caller restores them afterwards, leaving the symbol database exactly as it found it.lowered_static_import_edgesdrives the pass with the fully loweredOrderWrapStateand the real final init metadata, so every edge source the final pass registers — value references,init_*forwarding, retained re-export overlays, transitive init obligations — is present, with no approximation.Why deciding before the facades exist is sound. A facade is an empty chunk that takes over the entry role from the implementation chunk: it adds exactly one importer of that chunk (itself), and it inherits — never widens — the outgoing edges the implementation chunk had as an entry chunk. So for every other chunk the relation "some chunk other than me imports me" is unchanged, and all facade decisions can be taken together from one pre-facade snapshot.
Ordering changes
Three passes move ahead of the query, none of which depends on facades existing:
ensure_runtime_module_for_order_wraps— resolving a depended symbol to its chunk requires the runtime module to already sit in one, and order wrappers demand runtime helpers. A facade chunk copies its implementation chunk's bits, so the runtime chunk's bit union is unchanged.restore_order_wrap_entry_facades—compute_chunk_importsskips chunks markedRemoved, so restoring afterwards would hide the edge from a resurrected facade to the chunk hosting its implementation, and an entry sharing that chunk would keep an inline trigger that the restored facade's load then fires. This one is not hypothetical: an earlier revision of this PR hit it, and the fixture suite did not catch it.finalized_module_namespace_ref_usage— so the query sees the namespaces the final link pass will see rather than the provisional pre-lowering set. No output changes from this today; it closes the gap rather than fixing an observed failure.Restoring stays ungated. Unlike splitting, it exists because a chunk can host only one entry's top-level trigger, so an entry merged into another entry's chunk has no trigger at all without its own file.
Tests
The regression test that was missing
The over-split was invisible to every existing test, and that is the more important thing to fix: an
output-correctness test cannot see it, because the over-split bundle still runs correctly — it just
ships one extra file per entry.
packages/rolldown/tests/behaviors/strict-execution-order-entry-facade.test.tspins the shape of the output instead, keying on the property that defines a facade: a chunk
holding zero modules, existing only to host an entry's
init_*()trigger.Both directions are pinned, so the budget check cannot be satisfied by simply never splitting:
Each runs under wrap-all and
onDemandWrapping. Against the parent commit all four fail — sevenfacades for the lazy-route app, and
['b', 'e']instead of['e']for the shared-chunk app.The manual group in the lazy-route app is load-bearing: it makes the chunk-driven evaluation order
differ from source order, which is what puts modules on the on-demand plan. Without it on-demand
finds no hazard, wraps nothing, and the shape does not exercise entry splitting at all.
Execution-order coverage
New fixture
function/experimental/strict_execution_order/entry_shared_chunk_facade: entryeshares a chunk withshared.js, which entrybimports. The facade must be kept, and_test.mjsassertse's program does not run whilebis loading. Forcing the predicate to return an empty edge set makes it fail with['E body', 'S body', 'B body S']— the violation this PR must not introduce.Existing coverage that pins the discrimination in both directions:
m4_dynamic_facade_racekeepstarget.js's facade (its chunk also hostsobserver.js) while droppinga2.js/b2.js;dynamic_target_in_entry_chunkkeepsa.js's and dropsc.js's.89 snapshots update, removing 207 emitted assets. No fixture loses a facade it needs — every strict fixture executes its output under Node.
mainon the same machine.Reviewer attention
compute_chunk_importsis easy to miss and produces a silent wrong answer.compute_wrapped_esm_init_metadataand one extracompute_cross_chunk_link_state. On the 120-route app, wrap-all median 63.9ms → 67.6ms (~+6%); SEO-off is unchanged. Partly offset downstream by 45% fewer chunks to name, render and hash; the balance on a large app is worth a look.Unrelated pre-existing bug found while testing
preserveModules+strictExecutionOrderpanics onmainatchunk.entry_module(...).unwrap()inrender_chunk_exports, because strict lowering demotes an entry chunk toCommonwhilepreserve_modulesassumes every chunk has an entry module. Behaviour is identical before and after this PR; filing separately.