Skip to content

fix(link): resolve circular star reexports as null - #10445

Merged
hyfdev merged 7 commits into
rolldown:mainfrom
Nic-Polumeyv:fix/circular-reexport-null-paths
Aug 2, 2026
Merged

hyfdev merged 7 commits into
rolldown:mainfrom
Nic-Polumeyv:fix/circular-reexport-null-paths

Conversation

@Nic-Polumeyv

Copy link
Copy Markdown
Contributor

Fixes #9175. A circular star-reexport path now resolves as null per ResolveExport instead of failing the build; CIRCULAR_REEXPORT still fires when a binding has no non-circular resolution.

@codspeed

codspeed Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing Nic-Polumeyv:fix/circular-reexport-null-paths (3031c97) with main (11e008b)2

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

  2. No successful run was found on main (ae86ef6) during the generation of this report, so 11e008b was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

@hyfdev hyfdev self-assigned this Jul 26, 2026
@netlify

netlify Bot commented Jul 26, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs canceled.

Name Link
🔨 Latest commit 3031c97
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6a6f567ab2996f000805b0d9

@IWANABETHATGUY

Copy link
Copy Markdown
Member

Pushed a follow-up commit (6b713cb) to this branch. The approach here is right and the retain is the correct root-cause fix — but letting a cycle fall through to the ambiguity merge made two previously-unreachable paths live, and both panic on input that builds fine on main.

1. unreachable!("symbol should always exist")

When the surviving star branch resolves through an external or CommonJS module the resolution is NormalAndNamespace, not Normal, so it fell past the if let Normal(..) = ret into the unreachable!. Pure-ESM repro ("external": ["ext-pkg"], "format": "cjs"):

// index.js
import { foo } from './a.js';
// a.js
export * from './b.js'; export * from './d.js'; export * from './c.js';
// b.js
export { foo } from './a.js';   // cycle
// c.js
export let foo = 1;
// d.js
export { foo } from 'ext-pkg';

main reports a clean CIRCULAR_REEXPORT; this branch panicked. unreachable! is not compiled out in release, so via napi that aborts the host process. Fixed by extracting the bound symbol through MatchImportKind::bound_symbol(), so namespace-backed resolutions can be reported as ambiguous instead of falling off the end.

2. debug_assert!(!self.files.contains_key(..)) in Diagnostic::add_file

ambiguous_results is declared outside 'tracking: loop but pushed to inside it, so walking a cycle collects the surviving branches once per lap. Those duplicates reached AmbiguousExternalNamespace, whose on_diagnostic calls add_file once per exporter. (The doubled CIRCULAR_REEXPORT messages on main are that same second lap showing through.) Same repro with d.js as export let foo = 2; — no external or CJS needed. Fixed by deduplicating through an insertion-ordered set, which also keeps that scan linear when one name is supplied by many export * sources.

Smaller changes

  • Folded the diagnostic payload into MatchImportKind::Cycle(Box<CircularReexportInfo>). That removes the MatchingContext.circular_reexport side channel, its manual reset, and the expect, so a Cycle can no longer exist without the data needed to report it.
  • pop() → first element, since ResolveExport step 7 makes starResolution the first non-null branch. This one is spec alignment only; no test distinguishes it from pop().

Tests

Two fixtures, both failing on 582aea9 with the duplicate-file assertion and passing after:

  • circular_star_reexport_with_ambiguous_alternatives — pure ESM, cycle + two disagreeing branches
  • circular_star_reexport_with_external_alternative — cycle + an external branch; the only one that pins the unreachable! fix

Worth noting your own fixture already covers the "no duplicated CIRCULAR_REEXPORT" case — on main's linking code that exact input emits the error twice, so a successful build asserts it.

cargo test -p rolldown: 1890 passed, 0 failed, test262_module_code included.

@IWANABETHATGUY

Copy link
Copy Markdown
Member

I didn’t notice you had self-assigned; the fix was written before you self-assigned.

@hyfdev hyfdev left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for digging into this — the spec reading is right and I think it's the direction we want. ResolveExport step 7/8 does treat an in-progress (module, exportName) as null and take the first non-null star branch, and with this change rolldown is actually closer to the spec than esbuild is here (esbuild runs the agreement check unconditionally, so a cycle on the primary branch poisons the whole result).

I can't take it as-is though. The promotion in match_import_with_export has two bugs and they share a root: shift_remove_index(0) lifts a resolution produced by a nested match_import_with_export call and uses it as the outer result — without checking it is a shape the outer caller can handle, and without the outer walk's accumulated state.

  1. A promoted Namespace / NormalAndNamespace reaches a consumer that assumes it is a named export → panic on graphs that error cleanly on main. No external package required; a relative CommonJS star is enough.
  2. A promoted nested Normal carries reexports: vec![] instead of the outer walk's chain → under preserveModules, export { … } silently disappears from the output, and which one disappears depends on the source order of two export * lines.

Repros inline. Everything else I flagged is quality-level and fine as follow-up.

Recording what I checked and found clean, so nobody re-derives it:

  • The core resolution is spec-correct. Hand-traced ResolveExport against all three new fixtures plus a nested-cycle probe; outputs match.
  • CIRCULAR_REEXPORT still fires when no branch survives. The shift_remove_index(0) → None → unwrap_or(ret) path is already covered — rolldown/errors/circular_reexport and esbuild/default/export_infinite_cycle{1,2} contain no export *, so they hit exactly that branch, and their snapshots are untouched and still pass.
  • The shift_remove_index(0) ordering holds. potentially_ambiguous_symbol_refs is built by ordered push in star-record index order (= source order) and lap-1 entries always precede later laps, so index 0 really is the first surviving branch. Deterministic. I went looking for a counterexample and didn't find one — see the note below on making it not depend on that.
  • ctx.tracker_stack is consistent: the cycle break happens before the push, same state the old return left.
  • test262 accounting reconciles: 543 → 545, the 6 removed test262_failures.json lines are exactly the two flipped cases, and the remaining instn-star-binding.js fails for an unrelated reason.
  • Full integration suite on main vs this branch: no test that passes on main fails here.

@Nic-Polumeyv
Nic-Polumeyv requested a review from hyfdev July 27, 2026 20:59
@Nic-Polumeyv

Copy link
Copy Markdown
Contributor Author

Both blockers are fixed in c1e016f; your four graphs are in as fixtures and all fail on the parent commit. One choice to check: when no contributor has the named export, the consumer now reports MISSING_EXPORT
rather than an ambiguity with no exporters. The resolve-set guard, idempotent add_file and ReexportChain newtype are left as follow-ups. The CI red was the refactor commit dropping the pre-existing box_collection expectation; restored.

Nic-Polumeyv and others added 5 commits August 2, 2026 20:26
…sults

Letting a circular star re-export resolve as null made two previously
unreachable paths live, both of which panic on input that builds fine today:

- When the surviving star branch resolves through an external or CommonJS
  module the resolution is `NormalAndNamespace`, which fell past the
  `Normal`-only destructuring into `unreachable!("symbol should always
  exist")`. Extract the bound symbol via `MatchImportKind::bound_symbol()`
  instead, so namespace-backed resolutions can be reported as ambiguous.

- Walking a cycle re-visits the same module once per lap, collecting the
  surviving branches repeatedly. Those duplicates reached
  `AmbiguousExternalNamespace`, whose `on_diagnostic` calls `add_file` once
  per exporter and tripped `debug_assert!(!self.files.contains_key(..))`.
  Deduplicate through an insertion-ordered set, which keeps source order for
  the "first branch wins" rule and avoids a quadratic scan when one name is
  supplied by many `export *` sources.

Also folds the diagnostic payload into `MatchImportKind::Cycle` so a cycle
cannot exist without the data needed to report it, removing the
`MatchingContext` side channel, its manual reset, and the accompanying
`expect`; and takes the first surviving branch rather than the last, matching
`ResolveExport` step 7 where `starResolution` is the first non-null branch.

Both new fixtures fail on the parent commit with the duplicate-file assertion
and pass here.

Claude-Session: https://claude.ai/code/session_01P4VuuUuXBho5iMgWePX832
@hyfdev
hyfdev force-pushed the fix/circular-reexport-null-paths branch from f5a0dcf to 211b860 Compare August 2, 2026 12:26
hyfdev added 2 commits August 2, 2026 22:38
The cycle-promotion cache write targeted the loop-final tracker.importee —
the module where the cycle lap happened to close. Two problems:

- For cycles longer than one named hop that is not the star-exporting
  module whose cached winner points into the cycle, so the stale winner
  survived — under preserveModules the star module silently loses
  `export { foo }` — while an unrelated module's legitimate direct-export
  entry was clobbered, making output depend on which import was matched
  first.

- The ambiguous-branch recursion inherits a clone of the caller's tracker
  stack, so a "cycle" can match a frame belonging to the outer request.
  Resolving that as null is right for the request at hand, but persisting
  it would install a context-dependent winner into the context-free cache:
  standalone, the collection module may resolve the name to a different
  branch or find it ambiguous, and later consumers would silently bind it
  with no diagnostic.

Carry the collection site — the star module and the name requested there —
with each collected branch and write the promoted winner to that slot, and
only when the cycle matched a frame this invocation pushed itself
(`stack_base`). Per slot the write is idempotent; a cycle threading several
star modules still only gets the collection module realigned, which the
comment now records as a known limitation of this cache design.

The two long-cycle fixtures pin the three-hop case from both match orders,
and the inherited-cycle fixture pins the guard — without it the corrupted
cache swallows two of the five ambiguity diagnostics.
All surviving star branches resolve through modules with dynamic exports
(star re-exports of CommonJS), so the ambiguity diagnostic finds no
exporter with a literal named export and falls back to MISSING_EXPORT.
The fallback was introduced with the cycle-promotion fixes but nothing
exercised it.
@hyfdev

hyfdev commented Aug 2, 2026

Copy link
Copy Markdown
Member

I found a issue in case

// a.js
export * from './b.js';
export * from './d.js';
// b.js
export { foo } from './c.js';
// c.js
export { foo } from './a.js';   // closes the circle
// d.js
export let foo = globalThis.SEED;
// z.js
import { foo } from './c.js';
export const zfoo = foo;

If the entry reaches c.js only through z.js, a.js's output file is correct. If the entry also does import { foo } from './a.js' — resolved first — a.js's output loses its interface:

// a.js output — before, entry also imports from a.js
import "./d.js";

// a.js output — before, entry reaches c.js via z.js only (and after, in both orders)
import { foo } from "./d.js";
export { foo };

I pushed the fix andtest into this PR to fix it and avoid back and forth loops.

Overall, Thank you!

@hyfdev
hyfdev enabled auto-merge (squash) August 2, 2026 14:51
@hyfdev
hyfdev merged commit 85d25b4 into rolldown:main Aug 2, 2026
35 checks passed
@rolldown-guard rolldown-guard Bot mentioned this pull request Aug 3, 2026
shulaoda added a commit that referenced this pull request Aug 3, 2026
## [1.2.2] - 2026-08-03

### 🚀 Features

- code-splitting: support inlining of shared deps in dynamic entries (#10526) by @nicolo-ribaudo
- plugin: time the user callbacks configured on the options (#10509) by @IWANABETHATGUY

### 🐛 Bug Fixes

- dev: force `cleanDir` off in dev mode (#10579) by @shulaoda
- dev: keep `?rolldown-lazy` proxy ids out of user `resolveId` hooks (#10580) by @btea
- initialize re-exported wrapped ESM modules at the entry chunk (#10567) by @hyfdev
- link: resolve circular star reexports as null (#10445) by @Nic-Polumeyv
- transform: transformer gate skips newer syntax that oxc can lower (#10564) by @sekyungk
- code-splitting: materialize consumer-local barrel routing when the order-wrap plan is empty (#10544) by @hyfdev
- plugin: measure plugin hooks in JavaScript, report them from Rust (#10508) by @IWANABETHATGUY
- plugin: include external dynamic imports in chunk metadata (#10557) by @hyfdev
- plugin: report plugin timings after closeBundle has run (#10521) by @IWANABETHATGUY
- browser: avoid using node builtin modules (#10542) by @sapphi-red

### 🚜 Refactor

- plugin: give the build's own clocks their own type (#10520) by @shulaoda

### 📚 Documentation

- correct stale `buildStart` comment in `ScanStageCache::merge` (#10577) by @shulaoda
- update outdated pluginutils references (#10574) by @dogledogle

### ⚡ Performance

- external: drop the runtime import from chunks that never wrap (#10517) by @IWANABETHATGUY
- plugin: clock the build only when it is being measured (#10558) by @IWANABETHATGUY

### 🧪 Testing

- vite-tests: drop the dead `@rolldown/pluginutils` pnpm override (#10575) by @IWANABETHATGUY
- transform: group the transform-target fixtures and say why each exists (#10569) by @IWANABETHATGUY
- dev: fix hmr-hot-update-hook-vite fixture on Windows (#10565) by @h-a-n-a
- dev: match Vite's renamed full-reload log (#10547) by @shulaoda

### ⚙️ Miscellaneous Tasks

- deps: update napi (#10576) by @renovate[bot]
- deps: bump `@napi-rs/wasm-runtime` to 1.2.2 (#10570) by @shulaoda
- deps: update npm packages (#10583) by @renovate[bot]
- deps: update dependency rolldown-plugin-dts to ^0.28.0 (#10588) by @renovate[bot]
- deps: update taiki-e/install-action action to v2.85.5 (#10587) by @renovate[bot]
- deps: update codspeedhq/action action to v5 (#10584) by @renovate[bot]
- deps: update github actions (#10582) by @renovate[bot]
- deps: update rust crates (#10581) by @renovate[bot]
- deps: update dependency vite-plus to v0.2.7 (#10568) by @renovate[bot]
- deps: update dependency rolldown-plugin-dts to v0.27.14 (#10531) by @renovate[bot]
- deps: update pnpm to v11.17.0 (#10571) by @renovate[bot]
- deps: update @napi-rs/wasm-runtime to 1.2.1 (#10545) by @sapphi-red

### ❤️ New Contributors

* @sekyungk made their first contribution in [#10564](#10564)
* @nicolo-ribaudo made their first contribution in [#10526](#10526)

Co-authored-by: shulaoda <[email protected]>
hyfdev added a commit that referenced this pull request Oct 28, 2026
Follow-up from
#10445 (comment).
The fixture trips the debug_assert on current main with no cycle
involved: the importing module is also one of the ambiguous exporters,
so on_diagnostic adds its file twice.

Co-authored-by: Yunfei He <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: incorrect CIRCULAR_REEXPORT error

3 participants