Skip to content

bundler: build the min-chunk-size dependency graph from the edges that assign chunks - #41164

Closed
robobun wants to merge 3 commits into
mainfrom
robobun/dfc057f1/min-chunk-size-import-cycle
Closed

robobun wants to merge 3 commits into
mainfrom
robobun/dfc057f1/min-chunk-size-import-cycle

Conversation

@robobun

@robobun robobun commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

Problem

  • bun build ./index.html --production --splitting --min-chunk-size=16384 on the Medusa admin dashboard emits static import cycles: a small chunk runs import{r,i}from"./index-….js"; var n=r(i()) and the entry chunk imports it back. i is require_react, a var in the entry chunk, still undefined: TypeError: i is not a function. bundler: assign chunks from live parts, not from every import record #41145 exposed it.
  • The cause is the dependency graph in merge_small_chunks (mergeSmallChunks.rs:698). It followed every live import record, but since bundler: assign chunks from live parts, not from every import record #41145 the entry-bit walk (LinkerContext.rs:2817) skips an import or export ... from of a side-effect-free file. A "sideEffects": false barrel in the entry chunk re-exports card.js, so the stale edge said card.js's chunk is loaded wherever the entry is, and a small pure chunk using Card folded into the entry chunk.

Fix

  • One predicate, file_loaded_by_import, decides which file an import record makes the importer's chunk depend on. The entry-bit walk, merge_small_chunks and inert_chunks use it.
  • fold_creates_cycle rejects a fold when the merged group would import a chunk that reaches it again. Cross-chunk bindings are vars, so the pass must never close a static import cycle.
  • Correct because a dependency edge now implies that the dependency's key is a superset of the importer's, which is what loaded and rule 2 assume.
  • Verified: test/bundler/bundler_splitting.test.ts (MinChunkSizeNoCycleThroughSideEffectFreeReExport, fails on main with require_react is not a function), the other bundler suites (Notes), and the Medusa build: 0 cycles here, 6 on main.

Background

  • Code splitting keys each file by the entry points whose chunk loads it (File.entry_bits); equal keys form one chunk. A static import gives the target every bit of the importer, so a chunk only imports chunks keyed by a superset of its bits: no cycles.
  • --min-chunk-size folds a side-effect-free chunk into a chunk loaded by a superset of its entries (loaded) when everything it imports is loaded there too. loaded comes from the graph this PR fixes.
  • A static import of a CommonJS module prints as a top-level require_x() call on a var in the chunk that holds the module. The first chunk of a cycle to run reads it unassigned.
Notes

Reproduction of the Medusa build: @medusajs/dashboard@2.8.4 ships src/. With an index.html that loads src/main.tsx, stubs for the virtual:medusa/* modules and bun install of its dependencies, bun build ./index.html --production --splitting --min-chunk-size=16384 gives 278 JS files and 6 static cycles on main at 4e1eeff (entry index-rka9fb5j.js, 4.4 MB, and six chunks of 150 to 900 bytes in one strongly connected component). With this branch: 282 JS files, 0 cycles, entry 4.37 MB. The extra chunks are the small pure chunks that now stay with the routes that use them instead of folding into the entry.

With fold_creates_cycle's verdict ignored, the Medusa output is byte for byte the same as with it, so the dependency-graph fix alone removes the cycles there. The guard exists because rule 2 compares loaded sets, not evaluation order: two distinct groups with equal loaded on one dependency path would otherwise still fold into a cycle. fold resolves the merged dependency list so the check walks each group once.

The synthetic test mirrors the Medusa structure: ui is a "sideEffects": false package whose barrel re-exports button.js (used by the entry) and card.js (used by three lazy routes). card.js imports CommonJS react, so its chunk has a top-level require_react() and cannot fold. cards.js is pure, small, used by two routes, and uses Card. Before the fix it folds into entry.js, which then imports the card chunk; the card chunk imports __toESM and require_react from entry.js. After the fix it folds into the card chunk.

inert_chunks (computeCrossChunkDependencies.rs) followed the same stale edges. There the effect was only an extra side-effect import of a chunk that loads nothing the entry runs.

Suites run with the debug build: test/bundler/esbuild/, bundler_splitting, bundler_barrel, bundler_compile_splitting, html-import-manifest, bundler_edgecase, bundler_regressions, bundler_html, bundler_cjs2esm, bundler_dynamic_import_dce, bundler_npm, bundler_browser, bundler_bun, metafile. All pass.

Debug build timings for the Medusa bundle are unchanged within noise (6.4 s with the guard, 6.7 s without).

…t assign chunks

`merge_small_chunks` still followed every live import record when it
collected the static dependencies between chunk groups, while
`mark_file_reachable_for_code_splitting` skips an `import` or
`export ... from` whose target is side-effect free. A barrel in the entry
chunk that re-exports such a file made the pass believe the file's chunk
is loaded wherever the entry is. A small pure chunk that used the file
then folded into the entry chunk, which now imported the file's chunk,
while that chunk imported `require_react` back from the entry: a static
import cycle in which the smaller chunk runs first and calls an
undefined `var`.

One predicate, `file_loaded_by_import`, now decides which file an import
record makes the importer's chunk depend on. The entry-bit walk,
`merge_small_chunks` and `inert_chunks` all use it.

A fold is also rejected when the merged group would import a chunk that
reaches it again, so the pass cannot emit a static import cycle. `fold`
resolves the merged dependency list so the check walks each group once.
@robobun

robobun commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 11:35 PM PT - Sep 1st, 2026

✅ @robobun, your commit 614026d728dea0d4479c5976b32376838ae022f2 passed in Build #109264! 🎉


🧪   To try this PR locally:

bunx bun-pr 41164

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

bun-41164 --bun

@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

  • Run on-demand review

On-demand reviews are free for the next 19 days. After that, they cost $0.25 per reviewed file.

Or wait 1 minute for your next included review.

Check out review usage here.

View limit details

Limit details: You’ve used all 10 included reviews currently available.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Essentials

Run ID: 87fae213-db9b-47e3-aa29-5d9176d6e1b9

📥 Commits

Reviewing files that changed from the base of the PR and between ab4d399 and 614026d.

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

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: bce69a35-cb09-4db5-9541-e179b7e3a3d2

📥 Commits

Reviewing files that changed from the base of the PR and between 1564c1e and ab4d399.

📒 Files selected for processing (4)
  • src/bundler/LinkerContext.rs
  • src/bundler/linker_context/computeCrossChunkDependencies.rs
  • src/bundler/linker_context/mergeSmallChunks.rs
  • test/bundler/bundler_splitting.test.ts

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


Walkthrough

The linker centralizes import filtering, computes merged chunk dependencies, and rejects folds that create static import cycles. Bundler splitting tests validate side-effect-free re-export folding, generated chunk imports, graph acyclicity, and runtime output.

Changes

Chunk cycle prevention

Layer / File(s) Summary
Centralized loaded-import filtering
src/bundler/LinkerContext.rs, src/bundler/linker_context/computeCrossChunkDependencies.rs
file_loaded_by_import filters invalid, external dynamic, and side-effect-free statement imports. Code-splitting and static dependency detection use this method.
Dependency resolution and cycle checks
src/bundler/linker_context/mergeSmallChunks.rs
Chunk folding now computes merged dependencies, removes self-dependencies, and rejects folds that create static import cycles.
Static import graph regression coverage
test/bundler/bundler_splitting.test.ts
The new test validates chunk folding, generated static imports, cycle-free output, and runtime behavior.

Suggested reviewers: jarred-sumner, sosukesuzuki

Merge Risk: ⚪ Minimal · up to ab4d3

This change prevents static import cycles during min-chunk-size code splitting and includes targeted regression coverage; no actionable merge-blocking risk remains beyond normal checks and review.

🚥 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 describes the primary change: building the min-chunk-size dependency graph from chunk-assignment edges. It is concise and specific.
Description check ✅ Passed The description explains the problem, fix, verification steps, regression test, and expected impact. It uses different headings from the template, but it provides the required information under equiva…
Full details: Description check

Explanation

The description explains the problem, fix, verification steps, regression test, and expected impact. It uses different headings from the template, but it provides the required information under equivalent sections.


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.

Nothing blocking. The comments below are optional suggestions. There is no need to push a fix for them before merging.

Comment thread test/bundler/bundler_splitting.test.ts Resolved
Comment thread src/bundler/LinkerContext.rs Resolved
Comment thread src/bundler/LinkerContext.rs Resolved

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

Code review found no issues

No high-confidence issues detected in this change.

Jarred-Sumner added a commit that referenced this pull request Sep 2, 2026
… the static import cycle it could create (#41170)

### What does this PR do?

`--min-chunk-size` (#40430, #40506) folds small side-effect-free
code-splitting chunks into a chunk that a superset of their entry points
already loads, within a per-entry byte budget. This makes it actually
fire on React apps, fixes the crash it caused on the Medusa admin
dashboard after #41145, and makes the pass cheap enough to run by
default later. The default stays 0 (off) in this PR; the option is now
`Option`-plumbed with a per-target default hook so a later release can
turn it on for `--target=browser` (16 KiB is the value the numbers below
use).

**Component files were never candidates.** `import React from "react"`
prints a top-level `require_react()` in the importer, which counted as a
side effect. Such a call is now permitted when the wrapped module lives
in another chunk whose own top level makes the same call: the moved code
imports `require_x` from that chunk, so that chunk has run to completion
first and the call is a no-op. A bare `import "x"` still counts as a
side effect (it exists for the effect), a dependency that starts being
loaded by more entries has to pass the same test, and a file moved this
way no longer anchors where its new chunk sits in the importer's
evaluation order (test: `MinChunkSizeHoistedRequireKeepsChunkOrder`).

**The Medusa cycle.** The pass built its dependency graph from every
live import record; since #41145 chunk assignment skips `import … from`
records into `sideEffects: false` files. A live barrel in the entry
chunk (`react-query/index.js`) re-exporting a route-only module
therefore looked like "the entry loads that module", a small chunk
importing it was allowed into the entry chunk, and the entry chunk
imported a chunk that imports `require_react` back from it: `TypeError:
i is not a function`, blank page. `file_loaded_by_import` is now the one
predicate used by the entry-bit walk, this pass and `inert_chunks`; the
entry chunk's re-export edges are added too; and a reachability check
over topologically numbered groups rejects any fold that would close a
static import cycle. Supersedes #41164 (same root cause; this keeps
those chunks foldable instead of leaving them per-route, and the cycle
check is pruned rather than a full walk per attempt).

**`loaded` and dominators.** An `import()` entry that can only load
after entry `e` (its dominator in the `import()` graph rule 1 already
builds) now counts `e`'s chunks as loaded, so a lazy route's budget and
"already loaded wherever the target is" reflect the page's entry chunk.

**Cost.** Byte budgets are mirrored into per-power-of-two bitsets so
"can every entry in `target.loaded & ~candidate.loaded` afford this" is
a word-wide mask test with exact arithmetic only near the boundary; a
target's `loaded` size is bounded by how many entries can afford the
candidate, and the per-entry lists are sorted by it; groups are sorted
once per pass; a candidate is re-examined only when something that could
give it a target happened (a superset started loading under one of its
entries, an importer's dependency moved, or it failed on `require_*`
coverage and something folded).

### Numbers (release builds, same commit as baseline,
`--min-chunk-size=16384`)

| | main | this PR |
|---|---|---|
| Medusa admin v2.8.4, `bun build ./index.html --production
--splitting`: JS files | 349 (no flag) / blank page (flag) | 245 |
| route navigation, requests median / max | 13 / 75 | 8 / 30 |
| startup requests / bytes | 1 / 4.37 MB | 1 / 4.37 MB |
| static import cycles with the flag | 5 | 0 |
| build time | 272 ms (no flag) | 265 ms (flag) |
| 50-route synthetic React SPA: JS files | 242 (no flag) / 209 (flag) |
123 |
| requests per route navigation | 54 / 25 | 15 |
| route navigation, headless Chrome, LTE / 4G emulation | 535 / 676 ms
(no flag) | 412 / 616 ms |
| adversarial 1000-route / 8000-module synthetic where nothing can fold:
build | 293 ms (no flag), 380 ms (flag) | 306 ms (flag) |

The 50-route app's self-test output is byte-identical to the unfolded
build; Medusa `/login`, `/orders`, `/products` render in headless
Chrome.

### How did you verify your code works?

`test/bundler/bundler_splitting.test.ts`:
- `MinChunkSizeBarrelRecordIsNotAnImport` — the Medusa shape (live
`sideEffects:false` barrel in the entry chunk re-exporting route-only
modules that `require()` a CommonJS module from the entry chunk); on
main the output throws `require_lib is not a function`.
- `MinChunkSizeFoldsImporterOfInitializedWrappedModule` /
`MinChunkSizeKeepsFirstInitializerOfWrappedModule` — a `require_lib()`
importer moves only when `lib`'s own chunk already initializes it.
- `MinChunkSizeHoistedRequireKeepsChunkOrder` — a moved `require_lib()`
does not pull its new chunk's side effects ahead of a sibling import.
- `MinChunkSizeDefault{Browser,BrowserZero,BrowserOn,Bun,BunOn}` — off
unless asked for on every target.
- Two existing expectations updated for folds the dominator change
enables (commented in place).

Also ran `esbuild/splitting`, `bundler_compile_splitting`,
`bundler_html`, `bundler_edgecase`, `bundler_barrel`, `bundler_cjs`,
`bundler_cjs2esm`, `bundler_dynamic_import_dce`, `esbuild/default`,
`esbuild/importstar`, `esbuild/css`, `css-modules`, `metafile`,
`bundler_regressions` on the debug build.
@github-actions github-actions Bot closed this Sep 2, 2026
@github-actions

github-actions Bot commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

Superseded by #41170.

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.

2 participants