Skip to content

fix: improve circular dependency detection in chunk optimizer#8371

Merged
graphite-app[bot] merged 1 commit into
mainfrom
fix-8361-2
Feb 18, 2026
Merged

fix: improve circular dependency detection in chunk optimizer#8371
graphite-app[bot] merged 1 commit into
mainfrom
fix-8361-2

Conversation

@IWANABETHATGUY

@IWANABETHATGUY IWANABETHATGUY commented Feb 18, 2026

Copy link
Copy Markdown
Member

closed #8365

Copy link
Copy Markdown
Member Author

How to use the Graphite Merge Queue

Add the label graphite: merge-when-ready to this PR to add it to the merge queue.

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

This stack of pull requests is managed by Graphite. Learn more about stacking.

@netlify

netlify Bot commented Feb 18, 2026

Copy link
Copy Markdown

Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit dda0d48
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6995b887a3494c0007b72127
😎 Deploy Preview https://deploy-preview-8371--rolldown-rs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify project configuration.

@IWANABETHATGUY IWANABETHATGUY changed the title init fix: 8361 Feb 18, 2026
@IWANABETHATGUY IWANABETHATGUY changed the title fix: 8361 fix: improve circular dependency detection in chunk optimizer Feb 18, 2026
@IWANABETHATGUY IWANABETHATGUY added the test: vite-tests Trigger Vite tests workflow on this PR label Feb 18, 2026
@IWANABETHATGUY IWANABETHATGUY marked this pull request as ready for review February 18, 2026 12:58
Copilot AI review requested due to automatic review settings February 18, 2026 12:58

IWANABETHATGUY commented Feb 18, 2026

Copy link
Copy Markdown
Member Author

Merge activity

  • Feb 18, 12:58 PM UTC: The merge label 'graphite: merge-when-ready' was detected. This PR will be added to the Graphite merge queue once it meets the requirements.
  • Feb 18, 1:02 PM UTC: IWANABETHATGUY added this pull request to the Graphite merge queue.
  • Feb 18, 1:13 PM UTC: Merged by the Graphite merge queue.

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.

Pull request overview

Improves chunk optimizer cycle detection to avoid creating circular static imports when merging chunks (regression for issue #8361 / closed via #8365), and adds new integration fixtures/snapshots to lock in the expected output.

Changes:

  • Refines ChunkOptimizationGraph::would_create_circular_dependency to account for dependency rewiring after merges.
  • Adds new tests/rolldown/issues/8361 and 8361_2 fixtures asserting the CJS runtime helper remains callable (prevents __commonJSMin is not a function).
  • Updates relevant Rust/TS snapshots to reflect the new chunking/output.

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
crates/rolldown/src/stages/generate_stage/chunk_optimizer.rs Updates circular-dependency detection logic during chunk merging/optimization.
crates/rolldown/tests/snapshots/integration_rolldown__filename_with_hash.snap Records filename-with-hash outputs for the new issue fixtures.
crates/rolldown/tests/rolldown/issues/8361/_config.json Adds fixture config for issue #8361 regression test.
crates/rolldown/tests/rolldown/issues/8361/_test.mjs Executes built output and asserts CJS wrapper works for #8361.
crates/rolldown/tests/rolldown/issues/8361/artifacts.snap Snapshots build artifacts/warnings for #8361.
crates/rolldown/tests/rolldown/issues/8361/b.js Repro input module graph for #8361.
crates/rolldown/tests/rolldown/issues/8361/cjs.js Repro CJS module for #8361.
crates/rolldown/tests/rolldown/issues/8361/main.js Repro entry for #8361.
crates/rolldown/tests/rolldown/issues/8361_2/_config.json Adds fixture config for variant #8361_2 regression test.
crates/rolldown/tests/rolldown/issues/8361_2/_test.mjs Executes built output and asserts CJS wrapper works for #8361_2.
crates/rolldown/tests/rolldown/issues/8361_2/a.js Variant repro input module graph for #8361_2.
crates/rolldown/tests/rolldown/issues/8361_2/artifacts.snap Snapshots build artifacts/warnings for #8361_2.
crates/rolldown/tests/rolldown/issues/8361_2/b.js Variant repro input module graph for #8361_2.
crates/rolldown/tests/rolldown/issues/8361_2/cjs.js Variant repro CJS module for #8361_2.
crates/rolldown/tests/rolldown/issues/8361_2/main.js Variant repro entry for #8361_2.
packages/rolldown/tests/fixtures/builtin-plugin/import-glob/vite/restore-query-extension/index.ts.snap Updates expected transform snapshot (output changed due to chunking/runtime layout changes).
packages/rolldown/tests/fixtures/builtin-plugin/import-glob/vite/transform/index.ts.snap Updates expected transform snapshot (output changed due to chunking/runtime layout changes).

Comment on lines +189 to +195
// Start BFS from the combined deps of source and target.
let mut queue: VecDeque<ChunkIdx> = self.chunks[source_chunk_idx]
.dependencies
.iter()
.chain(self.chunks[target_chunk_idx].dependencies.iter())
.copied()
.collect();

Copilot AI Feb 18, 2026

Copy link

Choose a reason for hiding this comment

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

would_create_circular_dependency currently seeds the BFS with source.deps ∪ target.deps and immediately returns true if target_chunk_idx is present in that initial set. But merge_chunk_dependencies explicitly removes target from its own dependency set (e.g. when source depends on target), which means target appearing directly in the combined deps is a self-reference that would be eliminated rather than a real cycle. This can produce false positives (skipping otherwise-safe merges) and also makes the new doc comment (“cycle exists iff target is reachable…”) inaccurate. Consider filtering target_chunk_idx out of the initial queue (while still allowing it to be discovered via traversal), and update the doc comment to reflect the self-dependency removal behavior.

Copilot uses AI. Check for mistakes.
@graphite-app graphite-app Bot merged commit dda0d48 into main Feb 18, 2026
35 checks passed
@graphite-app graphite-app Bot deleted the fix-8361-2 branch February 18, 2026 13:13
@github-actions github-actions Bot mentioned this pull request Feb 18, 2026
shulaoda pushed a commit that referenced this pull request Feb 18, 2026
## [1.0.0-rc.5] - 2026-02-18

💡 Smarter `entriesAware` Manual Code Splitting                                                                 
                                             
New `entriesAware` and `entriesAwareMergeThreshold` options for `manualCodeSplitting.groups[]` enable              
entry-reachability-based chunk splitting with automatic small chunk merging.                                       
                                                                                                                   
- `entriesAware: true` splits matched modules by entry reachability — modules reached by the same set of entries are grouped together, providing the most precise loading behavior with less over-fetching
- Chunks now get more readable names reflecting their entry associations (e.g. `vendor-entry-a-entry-b.js`) instead of opaque hashes
- `entriesAwareMergeThreshold` sets a byte-size threshold to merge tiny subgroups into the closest sibling with the fewest extra entries, reducing micro-chunk fragmentation while preserving precision
- Recommended to use together with `maxSize`: merge tiny chunks first to reduce request overhead, then cap large chunks to control payload size

```js
manualCodeSplitting: {
  groups: [{
    name: 'vendor',
    test: /node_modules/,
    entriesAware: true,
    entriesAwareMergeThreshold: 28000, // bytes
  }]
}
```

### 🚀 Features

- add `Visitor` to `rolldown/utils` (#8373) by @sapphi-red
- module-info: add `inputFormat` property to `ModuleInfo` (#8329) by @shulaoda
- default `treeshake.invalid_import_side_effects` to `false` (#8357) by @sapphi-red
- rolldown_utils: add `IndexBitSet` (#8343) by @sapphi-red
- rolldown_utils: add more methods and trait impls to BitSet (#8342) by @sapphi-red
- rolldown_plugin_vite_build_import_analysis: add support for `await import().then((m) => m.prop)` (#8328) by @sapphi-red
- rolldown_plugin_vite_reporter: support custom logger for build infos (#7652) by @shulaoda
- rust/mcs: support `entriesAwareMergeThreshold` (#8312) by @hyf0
- mcs: `maxSize` will split the oversized chunk with taking file relevance into account (#8277) by @hyf0
- rolldown_plugin_vite_import_glob: support template literal in glob import patterns (#8298) by @shulaoda
- rolldown_plugin_chunk_import_map: output importmap without spaces (#8297) by @sapphi-red
- add INEFFECTIVE_DYNAMIC_IMPORT warning in core (#8284) by @shulaoda
- mcs: generate more readable name for `entriesAware` chunks (#8275) by @hyf0
- mcs: support `entriesAware` (#8274) by @hyf0

### 🐛 Bug Fixes

- improve circular dependency detection in chunk optimizer (#8371) by @IWANABETHATGUY
- align `minify.compress: true` and `minify.mangle: true` with `minify: true` (#8367) by @sapphi-red
- rolldown_plugin_esm_external_require: apply conversion to UMD and IIFE outputs (#8359) by @sapphi-red
- cjs: bailout treeshaking on cjs modules that have multiple re-exports (#8348) by @hyf0
- handle member expression and this expression in JSX element name rewriting (#8323) by @IWANABETHATGUY
- pad `encode_hash_with_base` output to fixed length to prevent slice panics (#8320) by @shulaoda
- `xxhash_with_base` skips hashing when input is exactly 16 bytes (#8319) by @shulaoda
- complete `ImportKind::try_from` with missing variants and correct `url-import` to `url-token` (#8310) by @shulaoda
- mark Node.js builtin modules as side-effect-free when resolved via `external` config (#8304) by @IWANABETHATGUY
- mcs: `maxSize` should split chunks correctly based on sizes (#8289) by @hyf0

### 🚜 Refactor

- introduce `RawMangleOptions` and `RawCompressOptions` (#8366) by @sapphi-red
- mcs: refactor `apply_manual_code_splitting` into `ManualSplitter` (#8346) by @hyf0
- rolldown_plugin_vite_reporter: simplify hook registration and remove redundant state (#8322) by @shulaoda
- use set to store user defined entry modules (#8315) by @IWANABETHATGUY
- rust/mcs: collect groups into map at first for having clean and performant operations (#8313) by @hyf0
- mcs: introduce newtype `ModuleGroupOrigin` and `ModuleGroupId` (#8311) by @hyf0
- remove unnecessary `FinalizerMutableState` struct (#8303) by @shulaoda
- move module finalization into `finalize_modules` (#8302) by @shulaoda
- extract `apply_transfer_parts_mutation` into its own module (#8301) by @shulaoda
- move ESM format check into `determine_export_mode` (#8294) by @shulaoda
- remove `warnings` field from `GenerateContext` (#8293) by @shulaoda
- extract util function remove clippy supression (#8290) by @IWANABETHATGUY
- move `is_in_node_modules` to `PathExt` trait in `rolldown_std_utils` (#8286) by @shulaoda
- rolldown_plugin_vite_reporter: remove unnecessary ineffective dynamic import detection logic (#8285) by @shulaoda
- dev: inject hmr runtime to `\0rolldown/runtime.js` (#8234) by @hyf0
- improve naming in chunk_optimizer (#8287) by @IWANABETHATGUY
- simplify PostChunkOptimizationOperation from bitflags to enum (#8283) by @IWANABETHATGUY
- optimize BitSet.index_of_one to return iterator instead of Vec (#8282) by @IWANABETHATGUY

### 📚 Documentation

- change default value in `format` JSDoc from `'esm'` to `'es'` (#8372) by @shulaoda
- in-depth: remove `invalidImportSideEffects` option mention from lazy barrel optimization doc (#8355) by @sapphi-red
- mcs: clarify `minSize` constraints (#8279) by @ShroXd

### ⚡ Performance

- use IndexVec for chunk TLA detection (#8341) by @sapphi-red
- only invoke single resolve call for the same specifier and import kind (#8332) by @sapphi-red
- rolldown_plugin_vite_reporter: skip gzip computation when `report_compressed_size` is disabled (#8321) by @shulaoda

### 🧪 Testing

- use `vi.waitFor` and `expect.poll` instead of custom `waitUtil` function (#8369) by @sapphi-red
- rolldown_plugin_esm_external_require_plugin: add tests (#8358) by @sapphi-red
- add watch file tests (#8330) by @sapphi-red
- rolldown_plugin_vite_build_import_analysis: add test for dynamic import treeshaking (#8327) by @sapphi-red

### ⚙️ Miscellaneous Tasks

- prepare-release: skip workflow on forked repositories (#8368) by @shulaoda
- format more files (#8360) by @sapphi-red
- deps: update oxc to v0.114.0 (#8347) by @camc314
- deps: update test262 submodule for tests (#8354) by @sapphi-red
- deps: update crate-ci/typos action to v1.43.5 (#8350) by @renovate[bot]
- deps: update oxc apps (#8351) by @renovate[bot]
- rolldown_plugin_vite_reporter: remove unnecessary README.md (#8334) by @shulaoda
- deps: update npm packages (#8338) by @renovate[bot]
- deps: update rust crates (#8339) by @renovate[bot]
- deps: update dependency oxlint-tsgolint to v0.13.0 (#8337) by @renovate[bot]
- deps: update github-actions (#8336) by @renovate[bot]
- deps: update napi to v3.8.3 (#8331) by @renovate[bot]
- deps: update dependency oxlint-tsgolint to v0.12.2 (#8325) by @renovate[bot]
- remove unnecessary transform.decorator (#8314) by @IWANABETHATGUY
- deps: update dependency rust to v1.93.1 (#8305) by @renovate[bot]
- deps: update dependency oxlint-tsgolint to v0.12.1 (#8300) by @renovate[bot]
- deps: update oxc apps (#8296) by @renovate[bot]
- docs: don't skip for build runs without cache (#8281) by @sapphi-red
AlonMiz pushed a commit to AlonMiz/rolldown that referenced this pull request Mar 30, 2026
…mizer

The circular dependency check added by rolldown#8371 was correct for chunks
containing the runtime module or runtime-dependent modules (e.g.,
__commonJSMin, __toESM), but overly conservative for regular ESM chunks.

ESM handles circular imports fine — modules are initialized lazily and
circular references are resolved at access time. Only runtime helpers
need to be available synchronously before the importing module executes,
making circular chunk imports harmful only when runtime is involved.

This fix scopes the circular dependency check to only apply when the
source chunk contains:
1. The runtime module itself, OR
2. Modules that depend on runtime helpers (depended_runtime_helper)

For all other pure ESM chunks, the merge is allowed regardless of
whether it would create circular chunk imports.

In large applications, this was causing +53% more JS files and +8%
bundle size because the cycle detection blocked almost all common
chunk merges.

Closes rolldown#8371 regression
Refs: rolldown#8361, rolldown#8886, rolldown#8910, rolldown#8915
IWANABETHATGUY added a commit that referenced this pull request Apr 16, 2026
…tection (#9049)

## Summary

PR #8371 improved circular dependency detection in the chunk optimizer
to fix #8361 (`__commonJSMin is not a function`). However, the fix
introduced an over-approximation that blocks many legitimate chunk
merges, causing a significant regression in bundle size and file count.

Fixes #9093

## Problem

The current algorithm in `would_create_circular_dependency` does a BFS
from `source.deps ∪ target.deps` and simulates post-merge edges for
**every** chunk that depends on source. This causes false positives
because:

1. Starting BFS from `target.deps` means target can trivially "reach
itself" through any transitive dependency that also depends on source
2. The post-merge edge simulation amplifies this by redirecting any
source-dependent chunk back to target

In a large application with ~2,200 entry points, this blocks **1,046
legitimate merges**, producing **+1,224 extra chunks** and **+8% bundle
size**.

## Fix

Split the algorithm into two cases based on whether source has
dependencies:

- **Source has deps**: Only BFS from `source.deps` without post-merge
simulation. This is sufficient because if target is reachable from
source's dependency tree, merging would create a real cycle.

- **Source has no deps** (e.g., runtime chunk): Keep the full algorithm
with `target.deps` BFS and post-merge simulation. This correctly detects
cycles like `target → chunk_A → source(=target after merge)`, which is
the pattern from #8361.

## Results

Tested on a large application (~2,200 entry points):

| Metric | Before (rc.9) | After (this fix) | Improvement |
|--------|--------------|-------------------|-------------|
| JS files | 3,212 | 2,418 | **-794 (-25%)** |
| JS size | 73.13 MB | 63.99 MB | **-9.14 MB (-12.5%)** |

## Testing

- ✅ `#8361` and `#8361_2` integration tests pass (the bug this algorithm
was designed to fix)
- ✅ Full integration test suite: **1,652 passed**, 0 failed (1 skipped
due to missing test262 submodule)
- ✅ New regression test added (`#9049`)
- ✅ Verified on large production application

Fixes vitejs/vite#22007

---------

Co-authored-by: Alon Mizrahi <almizrahi@paloaltonetworks.com>
Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: IWANABETHATGUY <iwanabethatguy@qq.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test: vite-tests Trigger Vite tests workflow on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants