Skip to content

fix(chunk-optimizer): preserve external stars after facade elimination - #10492

Closed
hyfdev wants to merge 1 commit into
mainfrom
fix/optimizer-external-star-namespace
Closed

hyfdev wants to merge 1 commit into
mainfrom
fix/optimizer-external-star-namespace

Conversation

@hyfdev

@hyfdev hyfdev commented Jul 27, 2026 •

Copy link
Copy Markdown
Member

When chunk optimization eliminates a dynamically imported entry facade, an ESM external star can disappear from the namespace returned by import(). This reproduces on main without strict execution order: local exports remain, but exports reached through export * from "external" become undefined.

const namespace = await import("./target.js");
namespace.x;             // 1
namespace.externalValue; // undefined before, 42 after

Problem

Rolldown delivers an entry's export * from "external" to import() callers through one of two shapes, chosen exclusively per record:

  • File-level — when the entry owns an output file, that file carries a plain export * from "external" statement, free at runtime. A generate-stage walk picks this shape by marking the record EntryLevelExternal, which tells the namespace renderer to skip the runtime merge.
  • Object-level — when callers receive a materialized namespace object instead, the renderer emits import * as ns from "external" plus __reExport(entry_exports, ns) to copy the external's properties in at runtime.

Facade elimination breaks the either/or assumption: the optimizer deletes the entry's file — the file-level statement has nowhere to live — and hands callers a namespace object synthesized in the implementation chunk, but the EntryLevelExternal mark set for the file-level shape still suppresses the object-level merge. Neither shape is emitted; the external names silently vanish.

Skipping eliminated facades during the walk would not be enough, because the mark lives on the shared import record and the has_dynamic_exports re-propagation behind it is transitive: a live entry reaching the same internal barrel legitimately marks the same record for its own file-level shape, and an unrelated invalidation seed can pull a simulated barrel into its importer closure — either way the recomputation treats the marked record as static and severs an upstream __reExport the synthesized namespace still needs.

There is a second, independent loss on the object-level path: the synthesized import * as ns from "external" came from an AST factory that never emitted a with-clause, so an original export * from "external" with { ... } lost its import attributes.

Fix

Teach the pipeline that a namespace standing in for an eliminated facade is an object-level consumer. When the optimizer replaces a dynamic facade with a namespace in its implementation chunk, it walks the internal export * chain that carries dynamic exports and marks every participating module's namespace with SimulateFacadeChunk — "this namespace stands in for a deleted entry file".

That reason drives both halves of the decision. On the renderer side, the shared emission predicate treats SimulateFacadeChunk like a genuinely observed namespace, so the synthesized namespace regains its runtime import * as + __reExport merge. On the propagation side, invalidation seed selection and recursive has_dynamic_exports propagation both use the new LinkingMetadata::entry_level_external_star_keeps_dynamic_exports helper: an EntryLevelExternal record keeps counting as a dynamic source exactly when its owning module's namespace is genuinely observed (Unknown) or simulates an eliminated facade. The flag therefore always agrees with what the finalizer will emit, no matter how the importer closure grows — a live entry sharing the same barrel keeps its free file-level export *, while the eliminated facade's namespace keeps the runtime merge, both at once.

The two predicates stay deliberately separate: the helper decides whether a namespace chain must remain dynamic (materialized and merged), while ns_star_external_re_export_emitted still decides how an already-materialized namespace merges the external in ESM versus CJS/IIFE/UMD. Ordinary entries continue to use their file-level export * without growing namespace proxy chains.

The synthesized runtime namespace import now rebuilds the original record's import attributes, preserving with versus assert, identifier versus string keys, and values.

This is the pre-existing optimizer bug called out in #10485. It is based directly on main, does not depend on #10485, and does not change facade-elimination eligibility or chunk topology.

Validation

  • Direct and transitive eliminated-facade fixtures fail before the fix with undefined !== 42 and pass after it while preserving initialization order.
  • The transitive fixture includes the importer-closure counterexample from review: live -> x creates a normal invalidation seed, barrel imports x, and the snapshot still contains both the barrel external merge and __reExport(target_exports, barrel_exports). Runtime assertions cover both live and eliminated-facade namespaces.
  • A separate shared-record fixture keeps both paths at once: the live entry emits chunk-level export * from "external", while the eliminated dynamic facade emits runtime import * plus __reExport; both namespaces expose externalValue === 42.
  • An import-attributes fixture is red before the fix and snapshots import * as ... from "external" with { type: "json" } after it.
  • The CI-reported CJS preserveModules fixtures for issues Transitive export * statements not re-exported in cjs with preserveModules #7115 and [Bug] CJS Bundles redeclaring duplicate variable names #7233, including the chained case, retain their existing output without extra namespace proxies.
  • Existing strict external-facade and attribute fixtures, CJS external re-export, facade elimination, issue [Bug]: rolldown/runtime is false-positively injected #9374, and runtime-sweep fixtures remain unchanged.
  • All 103 rolldown library tests, targeted rolldown clippy across all targets, Rust formatting, diff checks, and targeted spelling checks pass.

@netlify

netlify Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs canceled.

Name Link
🔨 Latest commit 478c1a8
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6a6811dcbec0880008b44fc0

@hyfdev hyfdev changed the title fix(code-splitting): preserve external stars after facade elimination fix(chunk-optimizer): preserve external stars after facade elimination Jul 27, 2026
@hyfdev

This comment was marked as resolved.

@hyfdev
hyfdev force-pushed the fix/optimizer-external-star-namespace branch from 1f0f0fb to a4a360c Compare July 28, 2026 02:05
@hyfdev
hyfdev force-pushed the fix/optimizer-external-star-namespace branch from a4a360c to 478c1a8 Compare July 28, 2026 02:20
@hyfdev

This comment was marked as resolved.

@hyfdev
hyfdev marked this pull request as ready for review July 28, 2026 02:54
Copilot AI review requested due to automatic review settings July 28, 2026 02:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codspeed

codspeed Bot commented Jul 28, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 3.09%

⚡ 1 improved benchmark
✅ 6 untouched benchmarks
⏩ 10 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
⚡ bundle@multi-duplicated-top-level-symbol 259.5 ms 251.7 ms +3.09%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing fix/optimizer-external-star-namespace (478c1a8) with main (c909488)

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

@shulaoda

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 478c1a8d97

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

graphite-app Bot pushed a commit that referenced this pull request Jul 28, 2026
…#10485)

With strict execution order, a dynamically imported entry can still emit a one-purpose facade file even when every live import can initialize it directly. This PR removes those redundant files in both strict modes while preserving the value and initialization observed by the importing promise.

```js
// before: the import loads a separate file whose only effect is activation
await import("./page-b2.js");
// page-b2.js
import { t as init_page_b } from "./page-b.js";
init_page_b();

// after: the import activates the implementation directly
await import("./page-b.js").then((n) => (n.t(), n.n));
// page-b2.js is not emitted
```

## Problem

Each affected dynamic entry adds one emitted chunk and an extra module load without adding user code. On LobeHub wrap-all, #10456 still emits 1577 chunks, 59 more than the non-strict build; 58 of those are these activation-only facades.

The extra file appears when strict execution order wraps a pure dynamic entry whose implementation still owns its entry chunk. It can happen in both wrap-all and on-demand modes; wrap-all reaches it more often because it wraps every eligible module.

Strict lowering has two ways for such a facade to survive. The restore pass (which revives a facade removed by chunk optimization) already uses the call-site trigger policy from #10456. The creation pass, `create_order_wrap_entry_facades` (which splits an inline entry initializer into its own file), still decides from chunk loading alone and never asks whether every live `import()` can carry that initializer. The same output shape therefore keeps or removes a facade depending on which pass produced it.

Collapsing the facade also means the implementation chunk must publish the namespace value that the facade used to return. That interface cannot be reconstructed from a stale retained-symbol set: aliases can widen it beyond the dynamic import's actual export usage, and a getter such as `x: () => x` can be rendered even when `x` is neither declared nor imported in the chunk. Reading or spreading that namespace then throws a `ReferenceError`.

Non-strict builds are unaffected. Strict builds still retain a real facade for user or emitted entries, entries without a live `import()` call site, two-argument `import()`, TLA-tainted targets, host namespaces that may expose callable `then`, entries whose direct or transitive export-star chain reaches an external module, and facades already restored because another collapse proof failed.

For the dynamic entries that do collapse, output-hook metadata changes with the file topology: the implementation is reported as a common chunk, so `isDynamicEntry` becomes `false`, `facadeModuleId` becomes `null`, and `exports` reports the common chunk's emitted linkage names instead of the facade's entry export list. Manifest and plugin consumers that key on entry metadata will therefore stop seeing a separate dynamic entry for exactly these removed facades; this is the same contract choice already made for optimizer-removed facades in #10456.

## Fix

Use the same call-site proof when creating and restoring strict entry facades. When a pure dynamic entry has an initializer and every surviving `import()` can be rewritten safely, its implementation becomes a common chunk, each import points to that chunk and runs the initializer before resolving, and no separate facade is emitted.

Removing the facade also removes the namespace object it would have exported. Strict lowering now records the exact export names selected by `DynamicImportExportsUsage` and materializes that narrowed interface in the implementation chunk. Its synthetic statement references every non-inlined binding behind those getters, allowing normal cross-chunk linking to keep, export, and import each getter target after the entry becomes a common chunk. Smart inline constants omit that reference only when the individual binding is actually safe to inline. If the namespace also has a real semantic consumer, that complete interface overrides the narrowing. This keeps the `ExportAll` runtime demand without turning a synthetic narrow namespace into an opaque user namespace read or initializing unrelated re-exports.

Entry-level external stars are rendered on the facade chunk and keep that facade in every format. ESM would lose its chunk-level `export * from "external"` statement after reclassification. CJS-like formats would replace the facade's deduplicated `Object.keys` merge with one module-local `__reExport` per direct record; that differs for primitive module values and duplicate records, while a transitive external star is not available from the entry module's direct records at all. The provisional chunk's `entry_level_external_module_idx` covers both direct and transitive chains, so one format-independent guard preserves the complete interface and its existing merge behavior.

This deliberately takes the same ordering tradeoff as #10456: the initializer runs in the rewritten import's promise continuation, one microtask after the host chunk settles, instead of during facade-module evaluation. The importing promise still resolves only after initialization, but a microtask queued during host evaluation can observe the target before it runs. Keeping the facade would preserve that timing but keep all 58 files; using different timing solely based on which lowering pass produced the facade would be inconsistent.

Entries with no `import()` call site, including the remaining LobeHub HTML entry, are intentionally unchanged. LobeHub therefore moves from 1577 to 1519 chunks rather than to the 1518-chunk non-strict baseline.

The analogous external-star loss in the pre-existing non-strict chunk optimizer is not changed here. It already reproduces on `main` without strict execution order and is being fixed independently in #10492, rather than adding another dependency to this stack.

## Validation

- `retained_star_renamed_cycle` now spreads the emitted synthetic namespace at runtime and asserts its exact keys are `['_', 'common']`. This fails on the reviewed revision because the namespace contains a dangling `x` getter and an alias-widened `commonLeaf` getter.
- New `retained_star_opaque_cycle` spreads the source-level dynamic namespace and asserts the complete interface. Its snapshots pin the cross-chunk import that backs `x`, so a genuine semantic namespace consumer cannot be accidentally narrowed.
- New `retained_star_smart_constant_cycle` pins the smart inline-constant boundary in both strict modes: a getter's backing reference is omitted only when that exact constant can actually be inlined.
- The direct and transitive ESM external-star fixtures are red without the guard because the resolved `import()` namespace loses `externalValue`. With the guard, each snapshot retains a facade carrying `export * from "external"`, and runtime assertions observe `x === 1`, `externalValue === 42`, and the expected initialization order.
- New `cjs_dynamic_entry_external_star_keeps_facade` pins why direct CJS stars also keep the facade: a duplicated Proxy external is enumerated once, while a primitive external contributes its enumerable `0` and `1` keys. A collapsed module-local namespace would enumerate the Proxy twice and omit the primitive keys.
- New `cjs_dynamic_entry_transitive_external_star` reproduces the reported `target -> barrel -> external` loss. It is red before the guard with `undefined !== 42`; the fixed snapshot retains the facade's chunk-level external merge and the runtime assertion observes `externalValue === 42`.
- The related retained-star, fanout, namespace, and external-star fixtures pass, as do all 12 strict-order invariant tests.
- LobeHub wrap-all emits 1518 `.js` files and one `.mjs`; all 1519 pass `node --check`. Expanding the external-star guard to every format does not change this ESM measurement, so all 58 chunk reductions remain. This measurement covers production output topology and syntax, not browser E2E behavior.
- The output-hook metadata change is source-verified but is not pinned by a dedicated plugin or manifest fixture in this PR.
- Targeted clippy for Rolldown, the all-features workspace check, Rust and repository formatting, filename lint, and `git diff --check` pass. Full-workspace clippy remains locally blocked by the pre-existing reasonless `#[ignore]` generated in the isolated-declaration test.

Part of #10294.
@hyfdev

hyfdev commented Jul 30, 2026

Copy link
Copy Markdown
Member Author

Feel like too niche.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants