Repository navigation
Conversation
…cycle A pattern copies the value an export holds when it runs. The linker binds the local to the export when nothing assigns the export, so later reads are live. The initializer of a declaration is not an assignment to the parser. In an import cycle, require() can return while the importee is still initializing, before that initializer runs. The local then read the initialized value, where the copy is undefined. binds_call_item now leaves such a local unbound when the importee imports the importer back, directly or through other files. The pattern reads the namespace object, as in 1.4.0. ImportCycles finds the cycles (strongly connected components of the import records) once per link, on demand. A function declaration stays bound: it has its value from the start. import() stays bound: its promise settles after the importee initialized. A local that matches a re-export of an external module's binding stays unbound too, for import() and require(): that binding changes where the link cannot see.
|
Updated 2:37 AM PT - Sep 12th, 2026
✅ @robobun, your commit c78e503d533aef04346a1dc06e80c9ed828ab8a6 passed in 🧪 To try this PR locally: bunx bun-pr 42447That installs a local version of the PR into your bun-42447 --bun |
|
Status: the fix is pushed, and CI runs. How I reproduced it:
The new tests in |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Essentials Run ID: 📒 Files selected for processing (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. WalkthroughThe linker now memoizes import-cycle detection with iterative Tarjan traversal. Import matching shares this state, and call-item binding applies cycle, symbol, reassignment, renaming, and ChangesImport cycle-aware binding
Suggested reviewers: Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to The cycle-aware binding change and its regression coverage present no concrete merge-blocking risk. 🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
Comment |
There was a problem hiding this comment.
I reviewed this PR and didn't find any bugs. Because it changes the linker's symbol-binding semantics for require() pattern locals and adds a new SCC pass over the import graph, a human look at the bundler correctness reasoning would still be worthwhile.
What was reviewed:
binds_call_itemrefactor preserves the priorhas_been_assigned_to/must_not_be_renamedguards and the non-pattern-local fast path; newKind::Importand cycle checks only tighten (returnfalsewhere main returnstrue).- Index safety at
is_cycle:call_record_bindsalready guaranteedrecord.source_index.is_valid()beforebinds_call_itemruns, and the Tarjan walk bounds-checkstarget >= file_countfor records with invalid targets. - SCC is computed lazily once per link via
get_or_insert_with, only reached for arequire()pattern local whose export is a non-function — the common path pays nothing. - New
itElidescases cover the mutation matrix the description names (cycle snapshot, hoisted fn still bound, require-of-another-cycle, self-require, external re-export in both formats).
Extended reasoning...
Overview
This PR fixes a bundler DCE correctness regression introduced in 1.4.1 (#41186): when a destructured require() local participates in an import cycle, the linker was merging the local with the export symbol, turning what should be a snapshot copy (possibly undefined mid-initialization) into a live binding. The fix adds an ImportCycles struct in src/bundler/LinkerContext.rs that lazily computes strongly connected components over the import-record graph via an iterative Tarjan's algorithm, threads it through step 4 of scan_imports_and_exports, and extends binds_call_item to refuse binding when (a) the matched export is itself a Kind::Import symbol (external re-export, changes out of sight), or (b) the record is ImportKind::Require, the export is not a hoisted function, and importer/importee share an SCC. ~217 lines of new itElides/itBundled cases in test/bundler/bundler_dynamic_import_dce.test.ts cover the variant matrix.
Security risks
None. This is a pure bundler-output correctness change with no auth, crypto, network, filesystem, or user-input parsing surface. All new state is local Vec<u32> derived from already-parsed import records.
Level of scrutiny
High. The linker's import/export matching is a load-bearing correctness path — a wrong binds_call_item verdict silently changes what a bundle prints at runtime. The change also introduces an algorithm implementation (iterative Tarjan) rather than reusing an existing helper, and the semantic argument for exactly which three cases stay bound (function declarations, import(), require() outside a cycle) is subtle enough that a bundler-domain reviewer should confirm the reasoning and the acknowledged limitation (callback-mediated cycles the SCC cannot see). I checked that the refactor of binds_call_item from a single boolean expression to early returns is behavior-preserving for all pre-existing branches, that record.source_index is provably valid at the is_cycle call site (guarded upstream by call_record_binds), and that the Tarjan walk bounds-checks record targets and uses an explicit stack (no native recursion on a 300k-file chain).
Other factors
The PR description documents unusually thorough validation: differential runs against 1.4.0 bundles on 36 hand-made shapes and 400 random projects, brute-force reachability checks on 20k random graphs, mutation testing of the three-way condition, and passing sibling bundler suites. The 30 new tests include 9 that guard the still-bound cases against over-tightening. The SCC pass is gated on the exact condition needing it (lazy get_or_insert_with, only reached for non-function require() pattern locals), so the common-case cost is zero. Given the semantic subtlety and that this restores 1.4.0 output for a shape Node itself refuses (ERR_REQUIRE_CYCLE_MODULE), I'm deferring rather than approving so a maintainer can sign off on the binding-rule change and the tracking-issue limitation.
… has its value from the start (#42471) ### Problem - `const { v } = require("./b.js")` copies `v` when the pattern runs. Since #41186 (1.4.1) the bundler binds the local to the export when nothing assigns the export, so each later read is live. A `require()` can run while `b.js` still initializes. Then the copy is `undefined`, but the bundle reads `"V"`. 1.4.0 prints `undefined`. - Cause: `binds_call_item` (`src/bundler/LinkerContext.rs:4329`) refuses only an export that `has_been_assigned_to()`. The initializer of `export var v = f()` is not an assignment, and it runs after the pattern when the importee reaches the pattern while it initializes. - #42447 finds the import cycles that make this happen. An importee can also reach the pattern through a callback (#42449). No import graph shows that path. This PR replaces #42447. ### Fix - A `require()` pattern local is bound only to an export that has its value before the importee initializes: a function declaration, or a namespace object. The bundle prints both outside the `__esm` wrapper. A re-export of an external module's binding is never bound (from #42447). - Any other export reads through the namespace object when the pattern runs, as in 1.4.0: `const { v } = (init_b(), __toCommonJS(exports_b))`. That object lists only the names the pattern reads, so unused exports are still dropped. - This retires part of #41186 on purpose: the elision for a `require()` pattern of a `var`, `let`, `const` or `class` export. `import()` locals stay bound. Its promise settles after the importee initialized. - Verified: `test/bundler/bundler_dynamic_import_dce.test.ts` (328 tests, 54 new, 37 of them fail on 1.4.3). Also 12 other bundler suites (list in Notes). ### Background - A wrapped ES module is `var init_b = __esm(() => { ... })`. The first `init_b()` runs the body. A nested call during that run returns at once. Function declarations and the namespace object `exports_b` are printed before the wrapper. - The namespace object has a getter for each export. A pattern that reads it copies the current value. - To bind a local, the linker merges its symbol with the export's symbol. The pattern prints as `init_b();` and each read prints the export. That is a live read. <details><summary>Notes</summary> Repro from the issue. `bun run entry.js`, 1.4.0 and this branch print `undefined`. 1.4.1, 1.4.2, 1.4.3 and main print `V`. ```js // entry.js import { register } from "./registry.js"; import { early, late } from "./a.js"; register(early); require("./b.js"); console.log(late()); // registry.js let callback; export function register(fn) { callback = fn; } export function fire() { callback(); } // a.js let get; export function early() { const { v } = require("./b.js"); get = () => v; } export function late() { return get(); } // b.js import { fire } from "./registry.js"; fire(); export var v = String("V"); ``` Relation to #42447. That PR keeps the binding for a `require()` outside an import cycle and finds cycles with a search over the import records. This rule does not need the search: it treats every `require()` the same, because a callback can make any `require()` run during the initializer. The cycle tests of #42447 are ported here. `RequireOfAnotherCycle` now keeps the namespace object. Its `Kind::Import` guard for an external re-export is ported too, with its test: without the guard, `ExternalReExportDestructureIsSnapshot_esm` prints `2 1` on this branch. Cost, measured minified with `--target=bun`. A file with one `require()` pattern of a `const` export: 268 bytes on 1.4.3, 851 bytes here (1.4.0 prints the same shape). The difference is the `__export`, `__toCommonJS` and `__defProp` helpers, once per bundle. A second such pattern adds 22 bytes. Each run of a pattern reads a getter instead of a variable. Tree shaking of the importee is not affected: the object lists only the names the pattern reads. `import()` patterns, which #41186 was written for, are unchanged. Follow-up, not in this PR. The other direction from #42449 keeps the binding and prints a copy where the pattern runs (`init_b(); const v2 = v;`). That needs a symbol state the linker records without a merge, and printer changes for the pattern, the local statement, and the hoisting of top-level locals out of a wrapper. It restores the elision for `require()` if that matters. Test changes. `ElideInitThrows`, `ElideWrappedImporter` and the class case of `ElideWrappedImporterBoundClass` (now `ElideWrappedImporterClassIsCopy`) keep their `const` and `class` exports and now expect the namespace object. `ElideWrappedImporterBoundFunction` and `ElideWrappedImporterDoesNotRedeclareBoundName` are the same shapes with a function export, which is still bound. `ElideRequireDuringInit*` are the callback shapes from the issue. `ElideImportDuringInitThroughCallbackStaysBound` guards `import()`. Other suites that pass: `esbuild/default`, `esbuild/dce`, `esbuild/importstar`, `esbuild/importstar_ts`, `bundler_edgecase`, `bundler_cjs`, `bundler_cjs2esm`, `bundler_regressions`, `bundler_barrel`, `bundler_splitting`, `bundler_minify`, `bundler_promiseall_deadcode`, and `test/regression/issue/cyclic-imports-async-bundler.test.js`. Self-reviewed: 3 changes asked for, 3 made. They are the external re-export guard with its test, the ported cycle tests, and the original forms of the three adjusted tests kept next to the function variants. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 2 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 37 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_dynamic_import_dce.test.ts bun test v1.4.3 (6a92015) test/bundler/bundler_dynamic_import_dce.test.ts: (pass) bundler > dynamic_import_dce/AwaitDestructure [1148.86ms] (pass) bundler > dynamic_import_dce/AwaitDestructureAlias [530.45ms] (pass) bundler > dynamic_import_dce/AwaitDot [600.55ms] (pass) bundler > dynamic_import_dce/AwaitIndex [555.72ms] (pass) bundler > dynamic_import_dce/LetBinding [579.90ms] (pass) bundler > dynamic_import_dce/TwoSitesUnion [581.74ms] (pass) bundler > dynamic_import_dce/BailoutRest [668.62ms] (pass) bundler > dynamic_import_dce/BailoutDefault [854.17ms] (pass) bundler > dynamic_import_dce/BailoutComputed [650.63ms] (pass) bundler > dynamic_import_dce/SplittingNarrowedExports [622.19ms] (pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [918.75ms] (pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [617.29ms] (pass) bundler > dynamic_import_dce/SplittingAwaitDot [543.06ms] (pass) bundler > dynamic_import_dce/SplittingThenDestructure [582.49ms] (pass) bundler > dyna ... (truncated) release without fix: 37 FAILED bun test v1.4.3-canary.1 (6a92015) test/bundler/bundler_dynamic_import_dce.test.ts: (pass) bundler > dynamic_import_dce/AwaitDestructure [34.56ms] (pass) bundler > dynamic_import_dce/AwaitDestructureAlias [19.14ms] (pass) bundler > dynamic_import_dce/AwaitDot [25.20ms] (pass) bundler > dynamic_import_dce/AwaitIndex [19.40ms] (pass) bundler > dynamic_import_dce/LetBinding [13.13ms] (pass) bundler > dynamic_import_dce/TwoSitesUnion [21.14ms] (pass) bundler > dynamic_import_dce/BailoutRest [61.83ms] (pass) bundler > dynamic_import_dce/BailoutDefault [22.37ms] (pass) bundler > dynamic_import_dce/BailoutComputed [22.90ms] (pass) bundler > dynamic_import_dce/SplittingNarrowedExports [21.37ms] (pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [38.20ms] (pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [30.68ms] (pass) bundler > dynamic_import_dce/SplittingAwaitDot [27.77ms] (pass) bundler > dynamic_import_dce/SplittingThenDestructure [25.14ms] (pass) bundler > dynamic_import_dce/SplittingPromiseAllDestructure [27.85ms] (pass) bundler > dynamic_import_dce/SplittingPromiseAllThenDestructure [23.31ms] (pass) bundler > dynamic_import_dce/SplittingProm ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/bundler_dynamic_import_dce.test.ts bun test v1.4.3 (6a92015) test/bundler/bundler_dynamic_import_dce.test.ts: (pass) bundler > dynamic_import_dce/AwaitDestructure [1382.02ms] (pass) bundler > dynamic_import_dce/AwaitDestructureAlias [914.33ms] (pass) bundler > dynamic_import_dce/AwaitDot [575.03ms] (pass) bundler > dynamic_import_dce/AwaitIndex [575.13ms] (pass) bundler > dynamic_import_dce/LetBinding [570.68ms] (pass) bundler > dynamic_import_dce/TwoSitesUnion [627.64ms] (pass) bundler > dynamic_import_dce/BailoutRest [647.56ms] (pass) bundler > dynamic_import_dce/BailoutDefault [621.54ms] (pass) bundler > dynamic_import_dce/BailoutComputed [696.97ms] (pass) bundler > dynamic_import_dce/SplittingNarrowedExports [613.14ms] (pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [1114.32ms] (pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [733.44ms] (pass) bundler > dynamic_import_dce/SplittingAwaitDot [658.49ms] (pass) bundler > dynamic_import_dce/SplittingThenDestructure [678.30ms] (pass) bundler > dyn ... (truncated) release with fix: all passed $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 834ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [1/139] gen JS modules (bundle-modules) Preprocess modules (10951ms) Bundle modules (65ms) Postprocesss modules (1007ms) Bundle Functions (771ms) Generate Code (55ms) [12.86s] Bundled "src/js" for production 2600 kb 197 internal modules 13 native modules 50 internal functions across 16 files [1/139] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_output_tags v0.0.0 (/workspace/bun/src/bun_output_tags) �[1m�[92m Compiling�[0m bun_core v0.0.0 (/workspace/bun/src/bun_core) �[1m�[92m Compiling�[0m bun_dispatch v0.0.0 (/workspace/bun/src/dispatch) �[1m�[92m Compiling�[0m bun_opaque v0.0.0 (/workspace/bun/src/opaque) �[1m�[92m Compiling�[0m bun_wyhash v0.0.0 (/workspace/bun/src/wyhash) �[1m�[92m Compiling�[0m bun_highway v0.0.0 (/workspace/bun/src/highway) �[1m�[92m Compiling�[0m bun_simdutf_sys v0.0.0 (/workspace/bun/src/simdutf_sys) �[1m�[92m Compiling�[0m bun_core_macros v0.0.0 (/workspace/bun/src/bun_core_macros) �[1m�[92m Compiling�[0m bun_mimalloc_sys v0.0.0 (/ ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/bundler/LinkerContext.rs | 41 ++- test/bundler/bundler_dynamic_import_dce.test.ts | 385 +++++++++++++++++++++++- 2 files changed, 413 insertions(+), 13 deletions(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/bundler/LinkerContext.rs 4 8 17 test/bundler/bundler_dynamic_import_dce.test.ts 2 11 17 ``` </details> **root cause** · written by the author bot `binds_call_item` in `src/bundler/LinkerContext.rs` bound the local of a destructured `require()` pattern to the export whenever nothing assigned that export, but a `require()` can run while the importee is still initializing (for example through a callback, which no import path reveals), so the bound local read the later initialized value instead of the `undefined` that a plain copy would hold. The fix restricts that binding to exports that already have their value before initialization completes, namely function declarations and ESM namespace references, and treats every other `require()`… <!-- robobun:evidence:end -->
Problem
const { v } = require("./b.js")copiesv. Since bundler: read import() / require() exports without a namespace object #41186 (1.4.1) the bundler binds the local to the export when nothing assigns the export, so later reads are live. In an import cycle,require()can return whileb.jsstill initializes. The copy isundefined, but the bundle reads"V". 1.4.0 is correct.binds_call_item(src/bundler/LinkerContext.rs:4329) refuses only an export thathas_been_assigned_to(). An initializer (export var v = f()) is not an assignment.Fix
require()pattern local stays unbound when the importee imports the importer back, directly or through other files. The pattern reads the namespace object, as in 1.4.0.ImportCyclesfinds the cycles (strongly connected components of the import records, Tarjan) once per link, on first use.import(),require()outside a cycle. A rule with no cycle search failsElideWrappedImporterBoundClass.Kind::Import) is not bound to a pattern local.test/bundler/bundler_dynamic_import_dce.test.ts, 30 new tests, 21 fail on main.Background
var init_b = __esm(() => { ... }). The firstinit_b()runs the body. A nested call during that run returns at once.exports_bhas a getter for each export. A pattern that reads it copies the current value.init_b();and each read prints the export.Notes
Why the three cases stay bound. A function declaration has its value before the importee initializes. The promise of an
import()settles after the importee initialized. Arequire()outside a cycle returns after the importee initialized. The 9 new tests that pass on main guard these cases. Other forms that the parser does not record as an assignment: a secondvar v = 2, and afor (var v of list)head. For the external re-export,0 1became2 2in ESM output.No user reported this. Another session found it by a read of the code, and a differential run confirmed it. Node.js does not have the shape: its
require()of an ES module in a cycle throwsERR_REQUIRE_CYCLE_MODULE.Repro (1.4.1, 1.4.2 and main print
V. 1.4.0, esbuild andbun run entry.jsprintundefined):bun build ./entry.js --target=bun --outdir out && bun out/entry.js. The same occurs with--format=cjs. With this change the module code of the bundle is the same as in the 1.4.0 bundle. Only the__esmhelper differs, from #41186.What the bundle matches. It matches the 1.4.0 bundle and esbuild. It matches unbundled code for
var. Forlet,constandclassunbundled code throws aReferenceError(temporal dead zone), and a bundle has none: it read the initialized value before this change, and it readsundefinednow, as in 1.4.0. A bundle also hoists a literal initializer (export var v = "V") out of the wrapper, in 1.4.0 too.Why
import()needs no check: the bundle printsawait Promise.resolve().then(() => init_b()). The microtask cannot run whileinit_bis on the stack. For an importee with top-level await,init_b()returns the promise of the whole run.require()of such a module is a build error.Why the importer and the direct importee are the pair to compare: the importer has a record for the importee, so the two are in one cycle exactly when the importee reaches the importer. If the export comes from a third file through
export { v } from "./c.js", a path from that file to the importer also puts the importee in the cycle, because the importee has a record for that file.Cost. A
require()pattern inside an import cycle that reads a variable, a class or a constant prints as in 1.4.0 again. That includes a lazyrequire()that a function uses to break a cycle. A minimal example goes from 163 to 758 bytes minified (1.4.0: 748). Most of that is the__exportand__toCommonJShelpers, one time for each bundle. Each call of such a function pays for the pattern again: about 70 ns, where the bound form took 2 ns and 1.4.0 took 50 ns. On a random graph of 10000 files with 10 records each, the cycle search takes 1.6 ms.Limit. The check sees import cycles only. Suppose the importee calls a callback while it initializes, the callback reached it through a third module, and the callback runs the
require(). Then the local is still bound and reads live. #42449 tracks that case, with a repro. The two ways to close it both cost more than this change: never bind arequire()pattern, or print a copy of the export at the pattern.Checks beyond the test file:
export *, a cycle through a dependency of the importee, a cycle made ofrequire()calls only, a file that requires itself, a namespace local (const ns = require(); const { a } = ns), andimport()in a cycle. All 36 bundles from this branch print what the 1.4.0 bundles print.require()(pattern, namespace local, renamed key) and run during initialization. The oracle is the bundle that bun 1.4.0 makes, because 1.4.0 never binds a pattern local. All 800 bundles from this branch print what the oracle prints. With the bundler of main, 266 of the first 300 differ.import()too (ElideCyclefails), no exception for function declarations (ElideRequireCycleFunctionDeclarationfails), eachrequire()taken as a cycle (ElideRequireOfAnotherCycleandElideWrappedImporterBoundClassfail).Other suites that pass on this branch:
esbuild/default,esbuild/dce,esbuild/importstar,esbuild/importstar_ts,bundler_edgecase,bundler_cjs,bundler_cjs2esm,bundler_regressions,bundler_barrel,bundler_splitting,bundler_minify,bundler_promiseall_deadcode, andtest/regression/issue/cyclic-imports-async-bundler.test.js.Self-reviewed: 4 changes asked for, 4 made. They are the external re-export case, three more fixtures (a top-level
require(), a cycle through a re-export, a file that requires itself), the tracking issue, and the corrections to this text.Found on the way, not changed here:
export var a = 1; var a = 2;withimport { a } from "./b.js"givesReferenceError: a is not definedin the bundle. Tree shaking drops both declarations. 1.4.0 does the same.[human-review] gate passed · iteration 0 · 3 files touched
fails on main (without fix)
passes on PR (with fix)
diff hotspot
gate history · 1 passed · 0 rejected · iteration 0
evidence per changed file