Repository navigation
perf: avoid copying module code for renderedLength and share chunk.code across plugins - #11342
Conversation
✅ Deploy Preview for rolldown-rs ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
✅ Deploy Preview for rolldown-rs ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
|
/ecosystem-ci run |
@rolldown/browser
@rolldown/debug
rolldown
@rolldown/binding-android-arm-eabi
@rolldown/binding-android-arm64
@rolldown/binding-darwin-arm64
@rolldown/binding-darwin-x64
@rolldown/binding-freebsd-x64
@rolldown/binding-linux-arm-gnueabihf
@rolldown/binding-linux-arm64-gnu
@rolldown/binding-linux-arm64-musl
@rolldown/binding-linux-ppc64-gnu
@rolldown/binding-linux-s390x-gnu
@rolldown/binding-linux-x64-gnu
@rolldown/binding-linux-x64-musl
@rolldown/binding-openharmony-arm64
@rolldown/binding-wasm32-wasi
@rolldown/binding-win32-arm64-msvc
@rolldown/binding-win32-x64-msvc
commit: |
|
📝 Ran ecosystem CI with rolldown
✅ astro, unocss, nitro, vinext, module-federation, marko, vite-plugin-pwa, sveltekit, vike, nuxt, vitepress, laravel, vite-plugin-vue, quasar, vite-plugin-rsc, storybook, vite-environment-examples, vite-setup-catalogue, vite-plugin-react, waku, vite-plugin-svelte, vuepress |
0c98253 to
d02c50a
Compare
Merging this PR will not alter performance1 warning
Comparing Footnotes
|
hyfdev
left a comment
There was a problem hiding this comment.
I'd keep the address; a counter would need bumping everywhere an OutputChunk is created or changed. Could the holder comment also say it keeps update_output_chunk from writing in place (Arc::get_mut fails while it's held)?
internal-docs/cache/implementation.md should also list outputCodeCache.
addressed |
|
@sapphi-red, I checked |
…or JS plugins `renderedLength` joined and copied each module's code to take its length. It now uses `RenderedModule::rendered_utf16_length()`, which counts UTF-16 code units from the source pieces without joining them. Every plugin that read `chunk.code` in `generateBundle` or `writeBundle` copied the whole output out of Rust again. The JS wrapper now keeps one string per chunk per build in `PluginContextData.outputCodeCache`, validated by the identity of the immutable chunk data, so a chunk changed by a plugin is read again by the next one. Prototype: the identity is the address of the shared chunk data, kept valid by the cache entry holding the binding object.
Stacked on the native `renderedLength` change. Replaces the byte loop in `RenderedModule::rendered_utf16_length()` with the workspace crate that `rolldown_error` and `string_wizard` already use.
…declarations `cargo clippy` denied `cast_precision_loss` on `usize as f64`; the identity is now an `i64`, which napi exposes as a JavaScript number too. `rolldown-binding.wasi.d.cts` gets the same declarations as `binding.d.cts`, which CI checks with `git diff --exit-code`.
A plugin that read `chunk.code` and then threw in `generateBundle` returned before `invalidateJsSideCache`, so a failed watch rebuild kept the previous build's chunk strings. The hook now runs on every exit of `bundle_write` and `bundle_generate`, after `writeBundle` too.
Each worker creates its own `PluginContextData` per plugin and a hook call goes to whichever worker is free, so the cache never hit there, and nothing cleared it between watch rebuilds.
- Rename `rendered_length` to `rendered_byte_length`, so the byte count for the package size cannot be mixed up with the UTF-16 count behind `renderedLength`. - Reword the `getCodeIdentity` doc comment, it still said "Prototype". - Turn off the cache in parallel plugin workers through a constructor flag instead of an assignment. - Add a fixture that checks `renderedLength === code.length` on non-ASCII text; the existing assertions are ASCII, where bytes and UTF-16 units agree. - Add a test that a reader sees the `chunk.code` and file name an earlier plugin assigned, in `generateBundle` and `writeBundle`, and that a second build on the same bundler reads the new code.
…the rename With the code change and the rename in one step the reader looked up the new file name, so the cached string was never compared. The code-only step now fails when the identity check is removed.
417bb89 to
e3243cc
Compare
## [1.2.16] - 2026-10-29 ### 🚀 Features - perf-kit: check rendered output against the original build (#11140) by @IWANABETHATGUY - perf-kit: node/deno server startup mode (#10601) by @IWANABETHATGUY - perf-kit: browser page-load perf harness for coding agents (#10365) by @IWANABETHATGUY - devtools: report mode - agent-readable build metrics report (#10364) by @IWANABETHATGUY - inline-common-chunks: print record factories parenthesized so they compile eagerly (#11282) by @mattlewis92 - fold `'key' in ns` on namespace imports with statically known exports (#11333) by @danielroe - inline-common-chunks: inline chunks using `import.meta.hot` in dev mode (#11339) by @hyfdev - support `experimentalInlineCommonChunks` in dev mode (#11335) by @hyfdev - use `INVALID_TLA_FORMAT` error for Rollup compatibility (#11266) by @sapphi-red ### 🐛 Bug Fixes - await bundle.close() in loadConfig and clean up every generated config file (#10347) by @Brooooooklyn - deps: update mimalloc-safe to 0.1.69 (#11376) by @shulaoda - transform: don't crash when the working directory has been deleted (#11352) by @shulaoda - import-glob: follow directory symlinks on the wasm binding (#10624) by @hyfdev - tree-shaking: preserve exported rest bindings from dynamic imports (#11365) by @shuvroroy - transform: report `tsconfigFilePaths` for a tsconfig resolved through `TsconfigCache` (#11346) by @cainrus - tsconfig: don't apply tsconfig when resolving imports from virtual modules (#11089) by @rubas - code-splitting: handle emitted entries the same as `input` entries when placing the runtime (#11353) by @IWANABETHATGUY - error: make Diagnostic::add_file idempotent (#10610) by @Nic-Polumeyv - avoid retaining callable builtin callback owners (#10961) by @IWANABETHATGUY - code-splitting: only host the runtime in a chunk that every consumer's entries load (#11293) by @IWANABETHATGUY - code-splitting: keep the source order of chunk imports (#11298) by @IWANABETHATGUY - dev: don't treat a wrapped module's init as a no-op in dev mode (#11334) by @hyfdev - treat `cwd` as a literal path in relative glob filters (#11291) by @onmax - deps: update emnapi to 2.0.0-beta.2 and pin `@napi-rs/wasm-runtime` to 1.2.6 (#11292) by @IWANABETHATGUY - chunk-import-map: hash stable module ids so keys don't depend on the build folder (#11277) by @mandyheg - respect CPU limits when sizing native runtime workers (#11280) by @Brooooooklyn - deconflict the namespace of a module without module syntax (#11256) by @IWANABETHATGUY - code-splitting: rebuild an absorbed dynamic entry's namespace from what its imports read (#11200) by @mattlewis92 - escape line terminators in debug-info comments (#11258) by @IWANABETHATGUY ### 🚜 Refactor - extract callable builtin hook wrapper (#10964) by @IWANABETHATGUY ### 📚 Documentation - add an in-depth explanation for inline common chunks (#11239) by @hyfdev ### ⚡ Performance - incremental cycle check for `avoidRedundantChunkLoads` (#11320) by @IWANABETHATGUY - avoid copying module code for `renderedLength` and share `chunk.code` across plugins (#11342) by @IWANABETHATGUY - count UTF-16 lengths with `simd-utf16-len` (#11259) by @IWANABETHATGUY - don't load consola when importing rolldown (#11257) by @magurotuna ### 🧪 Testing - dev: cover hot updates that need modules the tab never received (#9647) by @matthewdavis-oai - dev: add dynamic import rebuild test (#7123) by @sapphi-red - code-splitting: import file URLs in fresh-process runtime host tests on Windows (#11354) by @shulaoda - esbuild: mark loader_data_url_base64_invalid_utf8 as an intentional difference (#10790) by @CoderSerio - watch: fix flaky `watch buildDelay` (#11175) by @Brooooooklyn ### ⚙️ Miscellaneous Tasks - install `cmake-core` instead of the `cmake` metapackage on FreeBSD (#11361) by @shulaoda - deps: update oxc to 0.156.0 (#11326) by @Dunqing - stop the Discord notification when the metric workflow fails (#11357) by @IWANABETHATGUY - connect to the Void platform before the docs deploy (#11350) by @shulaoda - deps: update rust crates (#11297) by @renovate[bot] - deps: update dependency vite-plus to v1.4.0 (#11288) by @renovate[bot] - deps: update npm packages (#11296) by @renovate[bot] - deps: update napi (#11287) by @renovate[bot] - deps: update rollup submodule for tests to v4.65.1 (#11331) by @rolldown-guard[bot] - deps: update test262 submodule for tests (#11332) by @rolldown-guard[bot] - deps: update dependency rolldown-plugin-dts to v0.28.8 (#11286) by @renovate[bot] - deps: bump tokio to 1.53.3 (#11317) by @Brooooooklyn ### ❤️ New Contributors * @mattlewis92 made their first contribution in [#11282](#11282) * @shuvroroy made their first contribution in [#11365](#11365) * @cainrus made their first contribution in [#11346](#11346) * @matthewdavis-oai made their first contribution in [#9647](#9647) * @rubas made their first contribution in [#11089](#11089) * @danielroe made their first contribution in [#11333](#11333) * @onmax made their first contribution in [#11291](#11291) * @mandyheg made their first contribution in [#11277](#11277) * @magurotuna made their first contribution in [#11257](#11257) Co-authored-by: shulaoda <[email protected]>
…ks (#11488) ## Why In a large Vite 8 app, the production client build has 2,034 chunks with 143 MB of hidden sourcemaps, and the SSR build has 3,371 chunks with 146 MB. `generateBundle` hooks are expensive enough there that the app limits some of its plugins to the `client` environment to avoid them. A CPU profile of that build shows that most of this cost comes from sending chunks back to Rust after a hook. When a `generateBundle` or `writeBundle` hook assigned any property of a chunk, `collectChangedBundle` sent the chunk back with all of its properties: - Rust serialized the chunk's sourcemap, JavaScript parsed it, and Rust parsed it again. - The code, `moduleIds`, `exports` and other fields were copied both ways. `update_output_chunk` ignores most of them. - Rust replaced the chunk data, so the `outputCodeCache` from #11342 missed, and the next plugin that read `chunk.code` copied it out again. Vite's `vite:css-post` runs `chunk.imports = chunk.imports.filter(...)` on every chunk whenever a build has a pure CSS chunk, and most chunks end up with the same file names. So every chunk took this round trip. In that app's build, `collectChangedBundle` took 720 to 1,015 ms of main-thread time, 607 to 866 ms of it in `chunk.map`. Parsing those maps again in Rust adds more time, which a JavaScript profile does not show. ## What `collectChangedBundle` now sends back only the chunk properties that `update_output_chunk` applies (`code`, `map`, `imports`, `dynamicImports`, `isEntry`, `fileName`). Of those, it sends the ones that the plugin changed: - `code` only when it was assigned. A string the plugin read cannot have changed. - `map` when it was read or assigned, because a read map can be changed in place. - `imports` and `dynamicImports` when they were read or assigned and differ from Rust's array. This also catches changes made in place. - `fileName` and `isEntry` are always sent. They are cheap, and `isEntry` tells a chunk apart from an asset in `Either<JsOutputChunk, JsOutputAsset>`. A chunk with no change is not sent at all. Rust keeps its data, and `outputCodeCache` keeps serving its code. `JsOutputChunk` now has only the applied fields, and every field except `filename` and `isEntry` is optional. `update_output_chunk` keeps any field that is left out. `map: null` still removes the map, with the same `Option<Either<BindingSourcemap, Null>>` pattern that `renderChunk` uses. Assets are unchanged. Plugins should see no difference. Each change reaches the next hook and the written output as before, including changes made in place to a read `imports` array or `map`, `map = null`, renames, and deleted outputs. ## Measured effect Interleaved A/B on release builds (`just build-rolldown-release`): base is `main` at 30a5421, patched is this branch. Each run is a fresh Node process, and each pair alternates which build runs first. The workload is a generated project shaped like that app's client build: 2,182 chunks, 30 MB of minified JS, and 136 MB of hidden sourcemaps. It runs through `rolldown()` and `write()`/`generate()` with these plugins: - two `generateBundle` hooks that only read (`moduleIds` and `imports` of every chunk) - `vite:css-post` with 256 pure CSS chunks - `vite:build-import-analysis`, which reads every chunk's code and rewrites 528 chunks with their maps - `vite:manifest` - the `vite:reporter` `writeBundle` hook The "generateBundle phase" column runs from the first `generateBundle` hook to a final no-op one, so it includes Rust applying each hook's changes. | run | metric | base median | patched median | change | patched faster | base IQR / stdev | |---|---|---:|---:|---:|---:|---:| | 1, `generate()` | generateBundle phase | 1,400 ms | 798 ms | −602 ms (−43.0%) | 11/12 | 235 / 232 ms | | 1, `generate()` | total | 2,722 ms | 2,028 ms | −694 ms (−25.5%) | 11/12 | 589 / 475 ms | | 2, `generate()` | generateBundle phase | 1,256 ms | 752 ms | −504 ms (−40.1%) | 12/12 | 153 / 298 ms | | 2, `generate()` | total | 2,392 ms | 1,862 ms | −530 ms (−22.2%) | 11/12 | 229 / 813 ms | | 3, `write()` | generateBundle phase | 1,036 ms | 644 ms | −392 ms (−37.8%) | 10/10 | 223 / 157 ms | | 3, `write()` | total | 2,860 ms | 2,269 ms | −591 ms (−20.7%) | 9/10 | 831 / 505 ms | The output files had the same hash in every run of both builds. Other jobs were running on this Mac during the runs (load average 10 to 24). That load caused the few lost pairs, and it makes the full range of the base times (up to 2.7 s) wider than the improvement. In the app itself, I ran its production build (`vite build --app`) with each build copied in through `packages/perf-kit/harness.mjs rolldown-install`. CPU profiles of two rounds showed this main-thread time in the output-hook bridge: | | base | patched | |---|---:|---:| | `collectChangedBundle` | 1,015 / 720 ms | 39 / 28 ms | | `chunk.map` getter | 866 / 607 ms | 97 / 86 ms | | `chunk.code` getter | 387 / 335 ms | 189 / 156 ms | With hashes normalized, the patched output matched the base output in all 10,958 files except five. Those five also differ between two base builds: a script the app obfuscates anew on every build (with its map, for client and server) and the client manifest. The bundle objects that each hook creates are not part of this change. `createOutputBundle` still spends 450 to 600 ms in that build. ## Tests - `packages/rolldown/tests/behaviors/output-bundle-changes.test.ts` builds a small project through the public API. One test applies the `vite:css-post` pattern: it assigns every chunk's `imports`, rewrites the importers, and deletes the pure CSS chunk. The test checks that the next hook, `writeBundle`, the written files and the returned output see the new `imports` and `code`, the unread maps unchanged, and the deleted chunk gone. A second test checks that changes made in place to a read `imports` array and `map`, and `map = null`, reach the next hook and the output. - `packages/rolldown/tests/utils/transform-to-rollup-output.test.ts` runs `transformToOutputBundle` and `collectChangedBundle` on stand-ins for the native chunk that record which getters run. The tests check that a chunk assigned the values it had is not sent, that only changed properties are sent, and that no code, map or `moduleIds` is copied out of Rust unless the plugin read it. The behavior tests pass on `main` and on this branch. The unit tests use the new `ChangedOutputs` shape, so they cannot run against `main`. A scratch copy of the same scenario run against `main`'s source showed the old behavior: the unchanged chunk was sent with all of its properties, and the maps, code and `moduleIds` were copied out of Rust. Commands: ```sh just build-rolldown && just build-rolldown-test-dev-server just t-node-rolldown # 1543 passed, 20 skipped; watcher 47 passed just t-node-rollup # 0 failed, 1268 passed just test-rust # all passed just lint-rust && just lint-repo just build-browser && just build-rolldown-debug # regenerates rolldown-binding.wasi.d.cts vp check && vp lint && vp run lint-publint && vp run lint-knip vp run --filter rolldown-tests test:types ``` No `internal-docs/` page covers the output-hook bridge, so this PR has no docs change. The reasons are in the comments on `collectChunkChange` and `JsOutputChunk`. --------- Co-authored-by: Yunfei He <[email protected]>
Reading
chunk.modules[id].renderedLengthjoined and copied the module code out of Rust for every module, and every plugin that readchunk.codeingenerateBundleorwriteBundlecopied the whole output again, so a Vite build with 77,000 modules and 1.1 GB of output spent about 9 s of its main thread in these two getters.Claude measured this with https://github.com/IWANABETHATGUY-reproduction/repro-chunk-code-cost (84,001 modules, 15,100 chunks, 500 MB of output, 2% non-ASCII, same worktree and release profile before and after):
renderedLengthover 82,400 moduleschunk.codefor all chunkscodeThe first
chunk.codecopy per build is unchanged, and parallel plugin workers still copy on every read because their per-plugin caches rarely hit. Each chunk string now lives from its first read until the end of the output stage, so a plugin that reads every chunk ingenerateBundlekeeps one copy of the output on the JavaScript heap untilwriteBundleends, where before each copy died after its hook.renderedLength === code.lengthwas checked on 10,784 modules, and achunk.codeassignment by one plugin is seen by the next plugin.The chunk identity is the address of the shared chunk data. The cache entry keeps that data alive, so the address stays unique and a write cannot change the data in place.