Skip to content

bundler: keep a destructured require() local a copy inside an import cycle - #42447

Closed
robobun wants to merge 1 commit into
mainfrom
robobun/57181667/require-destructure-cycle-snapshot
Closed

robobun wants to merge 1 commit into
mainfrom
robobun/57181667/require-destructure-cycle-snapshot

Conversation

@robobun

@robobun robobun commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • const { v } = require("./b.js") copies v. 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 while b.js still initializes. The copy is undefined, but the bundle reads "V". 1.4.0 is correct.
  • Cause: binds_call_item (src/bundler/LinkerContext.rs:4329) refuses only an export that has_been_assigned_to(). An initializer (export var v = f()) is not an assignment.
  • It also binds a re-export of an external module's binding, which that module can change.

Fix

  • A 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.
  • ImportCycles finds the cycles (strongly connected components of the import records, Tarjan) once per link, on first use.
  • Still bound: function declarations, import(), require() outside a cycle. A rule with no cycle search fails ElideWrappedImporterBoundClass.
  • An export that is an import which matching cannot follow (Kind::Import) is not bound to a pattern local.
  • Verified: test/bundler/bundler_dynamic_import_dce.test.ts, 30 new tests, 21 fail on main.

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.
  • The namespace object exports_b 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.
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. A require() 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 second var v = 2, and a for (var v of list) head. For the external re-export, 0 1 became 2 2 in 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 throws ERR_REQUIRE_CYCLE_MODULE.

Repro (1.4.1, 1.4.2 and main print V. 1.4.0, esbuild and bun run entry.js print undefined):

// entry.js
import "./b.js";
// a.js
let get;
export function early() { const { v } = require("./b.js"); get = () => v; }
export function late() { return get(); }
// b.js
import { early, late } from "./a.js";
early();
export var v = String("V");
console.log(late());

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 __esm helper differs, from #41186.

What the bundle matches. It matches the 1.4.0 bundle and esbuild. It matches unbundled code for var. For let, const and class unbundled code throws a ReferenceError (temporal dead zone), and a bundle has none: it read the initialized value before this change, and it reads undefined now, 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 prints await Promise.resolve().then(() => init_b()). The microtask cannot run while init_b is 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 lazy require() 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 __export and __toCommonJS helpers, 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 a require() pattern, or print a copy of the export at the pattern.

Checks beyond the test file:

  • 36 hand-made shapes, run unbundled, as an ESM bundle and as a CJS bundle: each declaration form, re-exports, export *, a cycle through a dependency of the importee, a cycle made of require() calls only, a file that requires itself, a namespace local (const ns = require(); const { a } = ns), and import() in a cycle. All 36 bundles from this branch print what the 1.4.0 bundles print.
  • 400 random projects: 3 to 7 modules, random static imports, and functions that destructure a 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.
  • The Tarjan walk, in a standalone program, against brute-force reachability on 20000 random graphs, and on a chain of 300000 files (the walk does not use native recursion).
  • Three mutations of the new condition, each caught by a test: the rule applied to import() too (ElideCycle fails), no exception for function declarations (ElideRequireCycleFunctionDeclaration fails), each require() taken as a cycle (ElideRequireOfAnotherCycle and ElideWrappedImporterBoundClass fail).

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, and test/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; with import { a } from "./b.js" gives ReferenceError: a is not defined in 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)
ASAN without fix: 21 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 (4ff919377)

test/bundler/bundler_dynamic_import_dce.test.ts:
(pass) bundler > dynamic_import_dce/AwaitDestructure [1043.05ms]
(pass) bundler > dynamic_import_dce/AwaitDestructureAlias [418.88ms]
(pass) bundler > dynamic_import_dce/AwaitDot [639.43ms]
(pass) bundler > dynamic_import_dce/AwaitIndex [551.29ms]
(pass) bundler > dynamic_import_dce/LetBinding [454.30ms]
(pass) bundler > dynamic_import_dce/TwoSitesUnion [454.41ms]
(pass) bundler > dynamic_import_dce/BailoutRest [568.03ms]
(pass) bundler > dynamic_import_dce/BailoutDefault [439.39ms]
(pass) bundler > dynamic_import_dce/BailoutComputed [504.53ms]
(pass) bundler > dynamic_import_dce/SplittingNarrowedExports [562.37ms]
(pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [882.55ms]
(pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [409.14ms]
(pass) bundler > dynamic_import_dce/SplittingAwaitDot [564.71ms]
(pass) bundler > dynamic_import_dce/SplittingThenDestructure [473.04ms]
(pass) bundler > dyna
... (truncated)

release without fix: 21 FAILED
bun test v1.4.3-canary.1 (4ff919377)

test/bundler/bundler_dynamic_import_dce.test.ts:
(pass) bundler > dynamic_import_dce/AwaitDestructure [28.63ms]
(pass) bundler > dynamic_import_dce/AwaitDestructureAlias [17.02ms]
(pass) bundler > dynamic_import_dce/AwaitDot [16.30ms]
(pass) bundler > dynamic_import_dce/AwaitIndex [14.22ms]
(pass) bundler > dynamic_import_dce/LetBinding [17.73ms]
(pass) bundler > dynamic_import_dce/TwoSitesUnion [15.36ms]
(pass) bundler > dynamic_import_dce/BailoutRest [16.33ms]
(pass) bundler > dynamic_import_dce/BailoutDefault [15.51ms]
(pass) bundler > dynamic_import_dce/BailoutComputed [15.83ms]
(pass) bundler > dynamic_import_dce/SplittingNarrowedExports [17.21ms]
(pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [29.87ms]
(pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [17.39ms]
(pass) bundler > dynamic_import_dce/SplittingAwaitDot [17.63ms]
(pass) bundler > dynamic_import_dce/SplittingThenDestructure [18.38ms]
(pass) bundler > dynamic_import_dce/SplittingPromiseAllDestructure [18.02ms]
(pass) bundler > dynamic_import_dce/SplittingPromiseAllThenDestructure [17.08ms]
(pass) bundler > dynamic_import_dce/SplittingProm
... (truncated)
passes on PR (with fix)
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 (4ff919377)

test/bundler/bundler_dynamic_import_dce.test.ts:
(pass) bundler > dynamic_import_dce/AwaitDestructure [967.57ms]
(pass) bundler > dynamic_import_dce/AwaitDestructureAlias [401.76ms]
(pass) bundler > dynamic_import_dce/AwaitDot [399.58ms]
(pass) bundler > dynamic_import_dce/AwaitIndex [460.54ms]
(pass) bundler > dynamic_import_dce/LetBinding [449.75ms]
(pass) bundler > dynamic_import_dce/TwoSitesUnion [520.68ms]
(pass) bundler > dynamic_import_dce/BailoutRest [510.27ms]
(pass) bundler > dynamic_import_dce/BailoutDefault [523.09ms]
(pass) bundler > dynamic_import_dce/BailoutComputed [711.21ms]
(pass) bundler > dynamic_import_dce/SplittingNarrowedExports [485.70ms]
(pass) bundler > dynamic_import_dce/SplittingTwoImportersUnion [919.70ms]
(pass) bundler > dynamic_import_dce/SplittingEscapeKeepsAll [477.29ms]
(pass) bundler > dynamic_import_dce/SplittingAwaitDot [561.19ms]
(pass) bundler > dynamic_import_dce/SplittingThenDestructure [506.89ms]
(pass) bundler > dynam
... (truncated)

release with fix: all passed
$ bun scripts/build.ts --profile=release
[configured] bun-profile → bun (stripped)
  target       linux-x64-gnu
  build type   Release
  build dir    ./build/release
  revision     c78e503d53
  features     baseline

23 deps, 131 codegen, 1172 objects in 1248ms

ninja: Entering directory `/workspace/bun/build/release'
[1/1244] fetch zlib
[zlib] up to date
[2/1244] fetch tinycc
[tinycc] up to date
[3/1243] install /workspace/bun
bun install v1.4.3-canary.1 (4ff919377)

Checked 22 installs across 61 packages (no changes) [51.00ms]
[4/1243] fetch libjpeg-turbo
[libjpeg-turbo] up to date
[5/1216] install /workspace/bun/packages/bun-error
bun install v1.4.3-canary.1 (4ff919377)

Checked 1 install across 2 packages (no changes) [3.00ms]
[6/1216] gen bindgenv2
[7/1216] gen JSBuffer.lut.h
Generating /workspace/bun/build/release/codegen/JSBuffer.lut.h from /workspace/bun/src/jsc/bindings/JSBuffer.cpp
[8/1216] gen ProcessBindingHTTPParser.lut.h
Generating /workspace/bun/build/release/codegen/ProcessBindingHTTPParser.lut.h from /workspace/bun/src/jsc/bindings/ProcessBindingHTTPParser.cpp
[9/1216] install /workspace/bun/src/node-fallbacks
bun install v1.4.3-canary.1 (4ff91937
... (truncated)
diff hotspot
src/bundler/LinkerContext.rs                       | 145 ++++++++++++--
 .../linker_context/scanImportsAndExports.rs        |   2 +
 test/bundler/bundler_dynamic_import_dce.test.ts    | 217 +++++++++++++++++++++
 3 files changed, 353 insertions(+), 11 deletions(-)

gate history · 1 passed · 0 rejected · iteration 0

evidence per changed file
file                                                 reads  edits  tests
src/bundler/LinkerContext.rs                             6      7     16
src/bundler/linker_context/scanImportsAndExports.rs      1      1     16
test/bundler/bundler_dynamic_import_dce.test.ts          3      4     16

…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.
@robobun

robobun commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 2:37 AM PT - Sep 12th, 2026

✅ @robobun, your commit c78e503d533aef04346a1dc06e80c9ed828ab8a6 passed in Build #114649! 🎉


🧪   To try this PR locally:

bunx bun-pr 42447

That installs a local version of the PR into your bun-42447 executable, so you can run:

bun-42447 --bun

@robobun

robobun commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

Status: the fix is pushed, and CI runs.

How I reproduced it:

  1. Three files: entry.js is import "./b.js";. a.js exports early(), which runs const { v } = require("./b.js") and keeps () => v, and late(), which calls that function. b.js imports both, calls early(), then declares export var v = String("V"), then logs late().
  2. bun run entry.js prints undefined. A bundle made by bun 1.4.0 and a bundle made by esbuild 0.28.2 print undefined too.
  3. bun build ./entry.js --target=bun --outdir out && bun out/entry.js prints V with 1.4.3-canary (main). The output has init_b(); get = () => v;, so the read is live.
  4. With this branch the bundle prints undefined, and a.js reads const { v } = (init_b(), __toCommonJS(exports_b)); again.

The new tests in test/bundler/bundler_dynamic_import_dce.test.ts hold this repro and the other shapes. 21 of the 30 fail with the build of main.

@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 72037e5d-2b05-4648-a8de-ce215a8532db

📥 Commits

Reviewing files that changed from the base of the PR and between b993710 and c78e503.

📒 Files selected for processing (3)
  • src/bundler/LinkerContext.rs
  • src/bundler/linker_context/scanImportsAndExports.rs
  • test/bundler/bundler_dynamic_import_dce.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review.


Walkthrough

The 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 require() initialization rules. Tests cover cycle variants and re-export snapshots.

Changes

Import cycle-aware binding

Layer / File(s) Summary
Cycle tracking and matching wiring
src/bundler/LinkerContext.rs, src/bundler/linker_context/scanImportsAndExports.rs
Adds lazy strongly connected-component detection and passes shared cycle state through per-file import matching.
Cycle-aware call-item binding
src/bundler/LinkerContext.rs
Rejects unsafe pattern-local bindings based on export mutation, renaming, import status, symbol kind, and require() cycle timing.
Cycle binding regression coverage
test/bundler/bundler_dynamic_import_dce.test.ts
Adds tests for cycle initialization, hoisting, re-exports, self-require behavior, and snapshot semantics.

Suggested reviewers: jarred-sumner, sosukesuzuki

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to c78e5

The cycle-aware binding change and its regression coverage present no concrete merge-blocking risk.

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely describes the main change: preserving destructured require() locals as copies inside import cycles.
Description check ✅ Passed The description explains the problem, fix, scope, behavior, limitations, and verification results. It does not use the exact template headings, but it provides the required information in equivalent s…

Comment @coderabbitai help to get the list of available commands.

@claude claude Bot 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.

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_item refactor preserves the prior has_been_assigned_to/must_not_be_renamed guards and the non-pattern-local fast path; new Kind::Import and cycle checks only tighten (return false where main returns true).
  • Index safety at is_cycle: call_record_binds already guaranteed record.source_index.is_valid() before binds_call_item runs, and the Tarjan walk bounds-checks target >= file_count for records with invalid targets.
  • SCC is computed lazily once per link via get_or_insert_with, only reached for a require() pattern local whose export is a non-function — the common path pays nothing.
  • New itElides cases 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.

@robobun

robobun commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator Author

Closing: #42471 replaces this PR. It uses one rule for every require() pattern local (bound only to a function declaration or a namespace object), so it covers the callback case of #42449 too, without the cycle search. The cycle tests and the external re-export guard from this PR are ported there.

@robobun robobun closed this Sep 12, 2026
Jarred-Sumner pushed a commit that referenced this pull request Sep 26, 2026
… 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 -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant