Skip to content

feat: add experimental persistent scan cache - #11671

Open
h-a-n-a wants to merge 17 commits into
mainfrom
persistent-scan-cache
Open

h-a-n-a wants to merge 17 commits into
mainfrom
persistent-scan-cache

Conversation

@h-a-n-a

@h-a-n-a h-a-n-a commented Nov 12, 2026 •

Copy link
Copy Markdown
Member

This PR adds an experimental persistent scan cache. With experimental.cache, Rolldown saves the result of the resolveId, load and transform hooks of each module on disk. After a restart, a full scan reuses a saved result when its keys match, so these hooks do not run again for the module.

The option is hidden (@hidden not ready for public usage yet).

Usage

export default {
  plugins: [
    {
      name: 'my-plugin',
      transform: {
        cache: true, // the hook gives the same result for the same input
        handler(code, id) {},
      },
    },
  ],
  experimental: {
    cache: {
      dir: 'node_modules/.cache/rolldown',
      buildDependencies: ['rolldown.config.js'],
    },
  },
}

Design

The design is in rolldown/cache: 0002 Persistent scan cache and 0003 Module meta and moduleSideEffects.

Where to look

  • Rust: crates/rolldown/src/persistent_cache/ (keys, lookup, save) and crates/rolldown_cache_store/ (files on disk).
  • Recording and replay: ModuleCacheRecorder and PluginDriver::replay_cache_actions in crates/rolldown_plugin.
  • Options hash: crates/rolldown_common/src/inner_bundler_options/cache_hash.rs.
  • JavaScript side: packages/rolldown/src/plugin/savable-meta.ts and plugin-context-data.ts.
  • Code map: internal-docs/persistent-cache/implementation.md.

Tests

  • Rust: crates/rolldown/tests/rolldown/topics/persistent_cache/ and crates/rolldown_testing/tests/persistent_cache_vite.rs (Vite's native plugins).
  • JavaScript: packages/rolldown/tests/persistent-cache/.

AI disclosure: The code, the tests and this description were written with Claude Code (Claude Opus 5.5 High).

🤖 Generated with Claude Code

@netlify

netlify Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

✅ Deploy Preview for rolldown-rs ready!

Name Link
🔨 Latest commit 6fe681f
🔍 Latest deploy log https://app.netlify.com/projects/rolldown-rs/deploys/6b07dd097033675778bd3aa9
😎 Deploy Preview https://deploy-preview-11671--rolldown-rs.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

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

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 12, 2026 •

Copy link
Copy Markdown

🚀 Deploying Preview to Cloudflare 🚀

Preview URL: https://persistent-scan-cache-rolldown-rs.voidzero-docs.workers.dev (commit 6fe681f)

This URL reflects your latest Preview deployment

Preview Deployments by commit

Status Deployment URL Commit Updated (UTC) See this deployment's details
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://947d71fb-rolldown-rs.voidzero-docs.workers.dev 6fe681f 2026-11-26T07:19:45.714Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://2fc8d5c4-rolldown-rs.voidzero-docs.workers.dev 42416ec 2026-11-24T09:00:23.775Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://f7646141-rolldown-rs.voidzero-docs.workers.dev 6b796bc 2026-11-24T08:51:54.470Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://8f8a1af5-rolldown-rs.voidzero-docs.workers.dev e419b22 2026-11-24T08:31:39.335Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://d79ca3f0-rolldown-rs.voidzero-docs.workers.dev d419586 2026-11-23T10:14:40.877Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://87619bf5-rolldown-rs.voidzero-docs.workers.dev 56d5094 2026-11-23T09:47:06.408Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://25c45884-rolldown-rs.voidzero-docs.workers.dev ef68968 2026-11-23T06:58:28.444Z Visit the dashboard ↗
  • Build: In progress 🔵

View logs ↗
cb90bfe 2026-11-23T06:54:28.315Z View logs ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://8424975f-rolldown-rs.voidzero-docs.workers.dev efba530 2026-11-20T11:43:06.927Z Visit the dashboard ↗
  • Build: Success ✅
  • Deployment: Success ✅

View logs ↗
https://8983b221-rolldown-rs.voidzero-docs.workers.dev 1c2fc9d 2026-11-20T10:28:12.405Z Visit the dashboard ↗

View all previews: View all previews ↗

@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch from f8f5851 to 5ae931d Compare November 18, 2026 16:55
@h-a-n-a
h-a-n-a changed the base branch from main to align-module-options-with-rollup November 18, 2026 16:55
@h-a-n-a
h-a-n-a added this pull request to stack #11793 November 18, 2026 17:01
@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch from 337175a to e29fcdf Compare November 19, 2026 09:24
@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch from 402977f to 4d99b9a Compare November 19, 2026 18:59

h-a-n-a commented Nov 19, 2026

Copy link
Copy Markdown
Member Author

Warning

This pull request is not mergeable via GitHub because a downstack PR is open. Once all requirements are satisfied, merge this PR as a stack on Graphite.
Learn more


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.

@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch 2 times, most recently from 6da95ad to df17b58 Compare November 19, 2026 19:11
@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch 6 times, most recently from efba530 to cb90bfe Compare November 23, 2026 06:54
Base automatically changed from align-module-options-with-rollup to main November 23, 2026 06:56
h-a-n-a added a commit that referenced this pull request Nov 23, 2026
…ns (#11792)

This PR makes Rolldown follow Rollup's rules for the `meta` and
`moduleSideEffects` that plugins set on a module. The rules are in
[`internal-docs/module-meta-and-side-effects/design.md`](https://github.com/rolldown/rolldown/blob/align-module-options-with-rollup/internal-docs/module-meta-and-side-effects/design.md),
so please start the review there. The persistent scan cache in #11671
depends on them ([rolldown/cache
0003](rolldown/cache#16)).

## The rules

1. **Creation.** The first resolution of an id that reaches the module
loader creates the module and sets its first `meta` (a top-level copy)
and `moduleSideEffects`. Later resolutions, `this.resolve`, and
`this.load` options for an existing module do not change it.
2. **Hook results.** Each object result of the module's own `load` and
`transform` replaces `moduleSideEffects` when it is not `null` or
`undefined`, and merges `meta` at the top level.
3. **Writes.** Any hook can change the values through
`this.getModuleInfo(id)`. Writing `null` to `moduleSideEffects` clears
it. Writes up to the end of `buildEnd` reach tree shaking. Rolldown
ignores a `moduleSideEffects` write after `buildEnd`, so a later read
and the next build do not see it, and warns about the first one in a
build (`MODULE_SIDE_EFFECTS_WRITE_AFTER_BUILD_END`).
4. **Reading `moduleSideEffects`.** A read returns the decided value, or
else a default value. The order of the defaults is in the design doc.
From the time the module is created, a read never returns `null`.
5. **Lifetime.** A full build starts every module fresh. A partial scan
(HMR, incremental rebuild, lazy compile) starts each changed module
again from the resolution that created it.

```
a.js: resolveId('./x.css') → meta { from: 'a.js' }   first → creates x.css
b.js: resolveId('./x.css') → meta { from: 'b.js' }   x.css exists → not used (before: merged)
```

## What changes for plugins

| Case | Before | After |
| --- | --- | --- |
| A second importer resolves the same id | Merged into the module |
Ignored |
| `this.resolve` | Changed the target module and returned its live
`meta` | Returns only its own resolution: its `meta`, and its hook value
or the default `moduleSideEffects` |
| `this.load` options for an existing module | Merged | Ignored |
| `meta` that a hook returns | Kept as the plugin's object | Kept as a
top-level copy |
| `getModuleInfo(id).moduleSideEffects` before the module is parsed, or
after a write of `null` | `null` | The default value |
| A write in `buildEnd`, or to an external | Changed only JS, or skipped
| Reaches tree shaking |
| A `moduleSideEffects` write after `buildEnd` | No warning | Ignored,
with one warning per build |
| HMR and incremental rebuild | A changed module could lose its values |
Starts again from its creating resolution |
| Lazy compilation | A lazy virtual module could get an empty chunk |
Resolves the original import again |

`moduleSideEffects` now lives only in Rust. `deferSyncScanData` and
`invalidate` are removed.

The default values for an external module and for `treeshake: false`
come from #11422, which is on main.

## Differences from Rollup

- The importer whose module task ends first creates the module (Rollup:
the resolution that ends first).
- When the option and `package.json` both give a value, the option wins.
In Rollup, `@rollup/plugin-node-resolve` returns the `package.json`
value as a hook value, so it wins.
- An external Node.js built-in, such as `node:fs`, reads `false`
(Rollup: `true`).
- A read can return the `package.json` `sideEffects` value.
- Writing `null` clears the value (Rollup stores `null` and treats it as
`false`).
- Writes after `buildEnd` are ignored, and Rolldown warns about the
first one. In Rollup, a later read shows the written value.

## Impact

- Vite needs vitejs/vite#24135 in the same release or before. Without
it, the entry script of `<script type="module" src>` can be dropped when
another importer creates it first. This can already happen today, and
happens more often with this PR.
- `@vitejs/plugin-vue` 6.0.10, `@vitejs/plugin-react` 6.0.2 and several
Vite playgrounds give the same output.

## Performance

Release builds, 10 runs each, M4 Pro (noise about 2%). The output was
byte-identical.

| Build | Change |
| --- | --- |
| Plain builds of 6 benchmark apps | None |
| Vite with `@vitejs/plugin-react`, 5,000 modules | None |
| Stress case, 10,000 modules | 3–5% slower (+45–55 ms of 1.1 s) |

The stress case is not a usual build. Every relative import is resolved
by a JS `resolveId` that returns `meta`, and `moduleSideEffects` of
every module is read in `moduleParsed`, `renderChunk` and a
`codeSplitting.groups` `name` function. The cost comes from:

1. One call into JS per module that a JS `resolveId` creates, so JS can
set the first `meta` (`TaskContext::create_js_module_options`): about 2
µs per module.
2. A call into Rust per read of `moduleSideEffects` in the chunking
context: about 0.6 µs per read.

Possible fixes, not in this PR, are listed in
`internal-docs/cache/implementation.md`.

## Where to look

- JS: `createModuleOptions`, `saveResolutionOptions`,
`resetModuleOptions` in
`packages/rolldown/src/plugin/plugin-context-data.ts`.
- Rust:
`crates/rolldown_common/src/types/module_side_effects_overrides.rs`,
`declared_side_effects_without_hook` in
`crates/rolldown/src/ecmascript/ecma_module_view_factory.rs`,
`try_spawn_new_task` in
`crates/rolldown/src/module_loader/module_loader.rs`.
- Machinery: the JS side cache section of
`internal-docs/cache/implementation.md`.

## Tests

New fixtures under
`packages/rolldown/tests/fixtures/plugin/{context,resolve-id,transform}`.
Rollup's `empty-module-no-treeshake` and
`module-side-effects@resolve-id-external` tests now pass.

## Known gaps

- The synchronous Rust chunking getter cannot call a JS
`treeshake.moduleSideEffects` function.
- A JS `treeshake.moduleSideEffects` function can run two times for one
module; the first result is kept.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: andrew <[email protected]>
Co-authored-by: 翠 <[email protected]>
@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch from cb90bfe to ef68968 Compare November 23, 2026 06:56
@h-a-n-a
h-a-n-a marked this pull request as ready for review November 23, 2026 09:23
@codspeed

codspeed Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Merging this PR will not alter performance

1 warning

⚠️ 4 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 7 untouched benchmarks
⏩ 10 skipped benchmarks1


Comparing persistent-scan-cache (6fe681f) with main (6739546)

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports. ↩

h-a-n-a added a commit to rolldown/cache that referenced this pull request Nov 23, 2026
… moduleSideEffects (#16)

- **0003 (new):** how the persistent scan cache saves and reuses module
`meta` and `moduleSideEffects`. It builds on the rules without the cache
in Rolldown's
[`internal-docs/module-meta-and-side-effects/design.md`](https://github.com/rolldown/rolldown/blob/main/internal-docs/module-meta-and-side-effects/design.md)
(rolldown/rolldown#11792).
- **0002 (updated):** changes from the M1 implementation
(rolldown/rolldown#11671). The rules for `meta` and `moduleSideEffects`
moved to 0003.
- **meta-frameworks/vite.md (new):** how Vite works with the cache.
- **glossary.md and milestones.md:** new terms, and the known untracked
inputs under M2.

**AI disclosure:** These documents and this description were written
with Claude Code (Claude Opus 5.5).

🤖 Generated with [Claude Code](https://claude.com/claude-code)
@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch from d419586 to e419b22 Compare November 24, 2026 08:29
h-a-n-a added a commit to rolldown/cache that referenced this pull request Nov 24, 2026
Rolldown now has `declaredModuleSize` (rolldown/rolldown#11844). A
`load` or `transform` hook can return it to declare the size of a
module. Size-based code splitting uses this value instead of the size of
the module's code.

This PR adds it to the "State after `transform`" table in [0002 What a
saved result
holds](https://github.com/rolldown/cache/blob/save-declared-module-size/design-docs/0002-persistent-scan-cache.md#what-a-saved-result-holds).

The section's rule already covers it: a value from a skipped hook is
saved when a later stage reads it. Code splitting reads
`declaredModuleSize`, so a saved result must hold it. Without it, a
cache hit gives a different output:

```js
transform(code, id) {
  if (id.endsWith('b.js')) return { code, declaredModuleSize: 1001 };
}
// output.codeSplitting.groups: [{ name: 'small', test: /b\.js$/, maxModuleSize: 1000 }]
// Without the cache: no "small" chunk, because 1001 > 1000.
// Cache hit without the saved value: Rolldown measures the code of b.js, so a "small" chunk appears.
```

The implementation is in rolldown/rolldown#11671:
`SavedResult::declared_module_size` in
`crates/rolldown/src/persistent_cache/saved_result.rs`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)
h-a-n-a and others added 17 commits November 26, 2026 15:01
With `experimental.cache`, each module task saves the result of its `load`,
`transform` and `resolveId` hooks to disk. After a restart, a full scan
reuses a saved result when its keys match, and does the recorded side
effects again (watch files, emitted files, logs).

- `experimental.cache` option and a per-hook `cache` flag for Rust and
  JavaScript plugins.
- `rolldown_cache_store`: immutable segment files with checksums.
- Options hash, keys, saved results, and the recorder for side effects.
- Inner plugins: cacheable hooks get `cache: true`; the `resolveId` hooks of
  `data_url`, `lazy_compilation` and `copy_module` stay uncached.

Design: https://github.com/rolldown/cache/blob/main/design-docs/0002-persistent-scan-cache.md
A property with the value undefined deep inside meta is left out by JSON,
so a reused module had other meta than in a build without the cache. Such
meta now gives the module no saved result and a warning, like other values
that JSON changes.
Vite calls this.markNotCacheable when a cached hook does something that
Rolldown cannot repeat on reuse, such as a message to Vite's logger.
Without it, a Vite build with the cache on fails. The API is internal and
experimental, and can change with the design of the cache.
A getter, a setter, or a frozen or sealed object deep inside meta, and a
log with an Error in it, came back changed after a reuse. Such meta or logs
now give the module no saved result, like other values that JSON changes.
Without experimental.cache, these places now work as before the cache:
- tsconfig watching for a module, and for the native Vite transform plugin
- the module meta and the count of the Vite reporter
- the copy of an emitted file for the recorder
- the ctx.inner() calls in the load and transform hooks
A build with the persistent cache must watch the same files as a build
without it. So the tsconfig of every module is watched and is a
transform dependency, whether the cache is on or off. This is the design
in rolldown/cache 0002 (Side effects).
@h-a-n-a
h-a-n-a force-pushed the persistent-scan-cache branch from 42416ec to 6fe681f Compare November 26, 2026 07:17
.collect()
}

fn restore_resolved_id<Fs: FileSystem>(

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A restart fails if the file that an import resolved to was renamed or deleted. This function reads the package.json again, but it does not check that the file of saved.id still exists. So the importer reuses its saved result, and every build fails until the importer itself changes or someone deletes the cache directory.

Example: main.js has import { b } from './b'. Build with the cache, rename b.js to b.ts, and build again. The second build fails with UNLOADABLE_DEPENDENCY: Could not load b.js. Without the cache, ./b resolves to b.ts. Editing b.ts does not help, because the key of main.js does not depend on it. The test below reproduces this. Add it to topics/persistent_cache/mod.rs.

This is worse than the gap listed under "Inputs that M1 does not track". That gap gives a stale result. An example is the b/index.ts → b.ts case in Future work 1, which I also reproduced: the build keeps using b/index.js. Here the build fails, and a restart does not fix it. Extensionless imports make it easy to hit. For example, someone moves b.js to b.ts or to b/index.js, or switches to a branch that renamed a file.

A possible fix inside M1: treat a resolved file that no longer exists like a package.json that cannot be read. Then restore_resolved_ids returns None, and the importer runs its hooks. Check only the paths that existed when the result was saved. Otherwise, an importer whose resolveId hook returns a path with no file would miss on every restart. For Future work 1, oxc_resolver 11.24.3, which is already in Cargo.lock, has resolve_with_context. It fills ResolveContext { file_dependencies, missing_dependencies }.

Test (fails on 6fe681f)
#[tokio::test(flavor = "multi_thread")]
async fn a_renamed_resolve_target_is_resolved_again() {
  let project = Project::new(&[
    ("main.js", "import { b } from './b';\nconsole.log(b);\n"),
    ("b.js", "export const b = 'js';\n"),
  ]);
  build(project.options(Some(project.cache())), vec![]).await;
  project.remove("b.js");
  project.write("b.ts", "export const b: string = 'ts';\n");
  // `main.js` reuses its saved resolution of `./b` to `b.js`, which no longer exists.
  let warm = build(project.options(Some(project.cache())), vec![]).await;
  let clean = build(project.options(None), vec![]).await;
  assert_eq!(warm.files, clean.files);
}

Reviewed with Claude Opus 5.5.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This also breaks watch mode, not only a restart. rolldown.watch rebuilds with ScanMode::Full (watch_task.rs:123), so the rebuild that the rename triggers reuses the saved result of main.js too. I checked it with a second generate on the same bundler, after clear_resolver_cache() as the watcher does. It fails with the same UNLOADABLE_DEPENDENCY. Without the cache, that rebuild resolves ./b to b.ts.

Reviewed with Claude Opus 5.5.

dependencies.sort_unstable();
dependencies.dedup();
let dependencies: Arc<[String]> = dependencies.into();
let key2 = self.dependency_key(fs, &dependencies).await;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A file that changes during the build can leave the result of its old content under the key of its new content. Key 2 hashes each dependency here, when the result is saved, but the hook read the file earlier. Sometimes no lookup in this scan has hashed the dependency yet. That happens on a cold cache, and for a dependency that is new to the module. Then key 2 gets the state of the file at save time. Save runs after parse, transform_ast and the resolution of all imports, so the window is longer than the hook itself. If the file changes in that window, the result from the old content is saved as valid for the new content.

CacheStore::put makes this stick. It skips a (key1, key2) that is already on disk or pending (rolldown_cache_store/src/lib.rs:275-281), so a later correct result does not replace it. A full scan reads it before it would compute anything. So restarts get the old content, and so do rebuilds in watch mode. rolldown.watch rebuilds with ScanMode::Full (watch_task.rs:123), so the rebuild that the change itself triggers still shows the old content. Only a change to the module or to the dependency fixes it. A user can hit this by saving a file during a long build, or when a formatter writes the file twice on save.

In the test below, a transform hook reads dep.txt ("old"), registers it with add_watch_file, and then the file becomes "new". The next build with the cache gives "old", and a build without the cache gives "new". A second generate of the same bundler also gives "old".

A possible fix: hash a dependency when the hook adds it (add_watch_file / this.addWatchFile), hash it again at save, and skip the save if the two differ. A plugin usually adds a file right after it reads it, so this closes most of the window. An mtime check against the start time of the task would close all of it. But FileSystem::metadata has no mtime today.

Test (fails on 6fe681f)
/// Reads `dep.txt` in `transform`, then changes it, as when a user saves the file during a build.
#[derive(Debug)]
struct ChangesItsDependency {
  dep: PathBuf,
}

impl Plugin for ChangesItsDependency {
  fn name(&self) -> Cow<'static, str> {
    "changes-its-dependency".into()
  }

  fn register_hook_usage(&self) -> HookUsage {
    HookUsage::Transform
  }

  async fn transform(
    &self,
    ctx: SharedTransformPluginContext,
    args: &HookTransformArgs<'_>,
  ) -> HookTransformReturn {
    if !args.id.ends_with("main.js") {
      return Ok(None);
    }
    let value = std::fs::read_to_string(&self.dep).unwrap();
    ctx.add_watch_file(&self.dep.to_string_lossy());
    if value == "old" {
      std::fs::write(&self.dep, "new").unwrap();
    }
    Ok(Some(HookTransformOutput {
      code: Some(format!("{}console.log({value:?});\n", args.code)),
      ..Default::default()
    }))
  }

  fn transform_meta(&self) -> Option<PluginHookMeta> {
    Some(PluginHookMeta { order: None, cache: Some(true) })
  }
}

#[tokio::test(flavor = "multi_thread")]
async fn a_dependency_that_changes_during_the_build_is_not_reused() {
  let project = Project::new(&[("main.js", "console.log('main');\n"), ("dep.txt", "old")]);
  let plugins = || -> Vec<SharedPluginable> {
    vec![ChangesItsDependency::new_shared(ChangesItsDependency { dep: project.path("dep.txt") })]
  };
  // The hook reads "old", and then `dep.txt` becomes "new" before the result is saved.
  build(project.options(Some(project.cache())), plugins()).await;
  let warm = build(project.options(Some(project.cache())), plugins()).await;
  let clean = build(project.options(None), plugins()).await;
  assert_eq!(warm.files, clean.files);
}

Reviewed with Claude Opus 5.5.

_ => None,
})
.collect();
if let Some(tsconfig_path) = self.governing_tsconfig() {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

A change to a tsconfig that the governing tsconfig extends is not seen, so a restart keeps the old paths and compiler options. Only the path from discover_tsconfig_file goes into the dependency list here. The design doc lists this under "Inputs that M1 does not track". I think it is worth fixing in M1. In a monorepo, paths and compiler options such as jsx or experimentalDecorators usually live in a shared tsconfig.base.json, and the tsconfig.json of each package often has little more than extends.

In the test below, tsconfig.json extends tsconfig.base.json, which maps @x to ./a.js. Then the base maps @x to ./b.js. A build without the cache gives "b", and a restart with the cache still gives "a". Nothing warns, and the output stays wrong until the module or the governing tsconfig.json changes.

This needs much less than Future work 1. oxc_resolver already walks the whole chain in load_tsconfig (tsconfig_resolver.rs:199 in 11.24.3). But it holds the paths only in TsconfigResolveContext::extended_configs while it loads, and the merged TsConfig keeps only the raw extends specifiers. A possible fix: let oxc_resolver keep the resolved paths of the extended configs on TsConfig, which is a small upstream change. Then add them here and in watch_module_files next to the governing tsconfig. Watching them also makes watch mode rebuild when the base changes.

Test (fails on 6fe681f)
#[tokio::test(flavor = "multi_thread")]
async fn a_changed_extended_tsconfig_makes_its_modules_run_again() {
  let project = Project::new(&[
    ("main.js", "import { x } from '@x';\nconsole.log(x);\n"),
    ("a.js", "export const x = 'a';\n"),
    ("b.js", "export const x = 'b';\n"),
    ("tsconfig.json", r#"{ "extends": "./tsconfig.base.json", "compilerOptions": { "allowJs": true } }"#),
    ("tsconfig.base.json", r#"{ "compilerOptions": { "paths": { "@x": ["./a.js"] } } }"#),
  ]);
  build(project.options(Some(project.cache())), vec![]).await;
  project.write("tsconfig.base.json", r#"{ "compilerOptions": { "paths": { "@x": ["./b.js"] } } }"#);
  let warm = build(project.options(Some(project.cache())), vec![]).await;
  let clean = build(project.options(None), vec![]).await;
  assert_eq!(warm.files, clean.files);
}

Reviewed with Claude Opus 5.5.

Some(rolldown_plugin::PluginHookMeta { order: Some(rolldown_plugin::PluginOrder::Pre) })
Some(rolldown_plugin::PluginHookMeta {
order: Some(rolldown_plugin::PluginOrder::Pre),
cache: None,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Three builtin plugins make every module miss: this one, replacePlugin and the new injectPlugin (#11290). None of them has cache: true, and none has a hook filter. So their hooks are called for every module, and check_cacheable_call marks every module as not cacheable. With this plugin and external: ["node:fs"], a restart runs every load, resolveId and transform again, even though nothing imports node:fs. replacePlugin({ __X__: '1' }) and injectPlugin do the same. The test below checks all three.

The hooks look safe to cache. They read only the hook arguments, the options of the plugin, which the host covers as for any plugin, and options that are in the options hash. The resolve_id here reads ctx.options().format. The filter of inject reads ctx.cwd(). The transform of replace does not use its context. So cache: Some(true) looks safe for both hooks here and for transform in the other two. Today the only way to get hits with them is assumeCacheableHooks, and that also covers every JavaScript plugin.

The reason is recorded too: "hook transform of plugin builtin:replace does not have cache: true". But nothing calls ModuleCacheRecorder::not_cacheable_reason(), so a user sees no hits and no explanation. A debug log of the first reason per plugin would make this easy to find.

Test (fails on 6fe681f)
// Needs `rolldown_plugin_replace`, `rolldown_plugin_inject` and
// `rolldown_plugin_esm_external_require` in the dev-dependencies of `rolldown`.
use rolldown_plugin_esm_external_require::EsmExternalRequirePlugin;
use rolldown_plugin_inject::{InjectPlugin, InjectPluginOptions};
use rolldown_plugin_replace::ReplacePlugin;
use rolldown_utils::pattern_filter::StringOrRegex;

#[tokio::test(flavor = "multi_thread")]
async fn builtin_plugins_keep_modules_cacheable() {
  let builtin = |name: &str| -> SharedPluginable {
    match name {
      "replace" => ReplacePlugin::new_shared(
        ReplacePlugin::new([("__X__".to_string(), "1".to_string())].into_iter().collect()).unwrap(),
      ),
      "inject" => InjectPlugin::new_shared(InjectPlugin::new(InjectPluginOptions {
        injects: vec![rolldown_common::InjectImport::named(
          "x".into(),
          Some("$x".into()),
          "./b.js".into(),
        )],
        include: vec![],
        exclude: vec![],
        cwd: None,
      })),
      _ => EsmExternalRequirePlugin::new_shared(EsmExternalRequirePlugin {
        external: vec![StringOrRegex::String("node:fs".into())],
        skip_duplicate_check: true,
      }),
    }
  };
  for name in ["replace", "inject", "esm_external_require"] {
    let project = basic_project();
    let (plugin, calls) = Recorder::new("p", Some(true));
    let with_builtin = || {
      let mut list = plugins(&[&plugin]);
      list.push(builtin(name));
      list
    };
    build(project.options(Some(project.cache())), with_builtin()).await;
    calls.take();
    build(project.options(Some(project.cache())), with_builtin()).await;
    assert_eq!(calls.take(), Vec::<String>::new(), "{name}: no hook of a saved module runs again");
  }
}

Reviewed with Claude Opus 5.5.

let mut usage = HookUsage::empty();
if self.log_info.is_some() {
usage |= HookUsage::Transform
usage |= HookUsage::ModuleParsed

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Minor, and only the printed count: a build without log_info saves results without the transformed mark, so later builds print a smaller "N modules transformed". Without log_info, the reporter registers no transform, so the saved results have no TRANSFORMED_MARK. A later build with log_info reuses them. It runs no transform, and the replay sets no mark. The plugin name is the same, so key 1 does not change. Vite passes logInfo only when logLevel is at least info (buildReporterPlugin in Vite 8.3.8). It does not pass logLevel to Rolldown, so the options hash does not change either. In the test below, a build that is quiet, as with vite build --logLevel warn, followed by a normal build prints 3 instead of 7. A reused result is not saved again, so the count stays low until the modules change.

A possible fix: register Transform also without log_info, and then set only the mark when the cache is on. The hook is cheap. A more general guard: put the hook usage of each plugin into key 1 next to its name. Then a plugin whose hooks depend on its options would miss instead of reusing results from another set of hooks.

Test (fails on 6fe681f, in crates/rolldown_testing/tests/persistent_cache_vite.rs)
// `Setup` gets `quiet_reporter: bool` (false in `Setup::client()`), and `Setup::plugins` does:
//   let mut r = reporter(&root, transformed_count, &self.progress_count);
//   if self.quiet_reporter { r.reporter.log_info = None; }
//   SharedReporter::new_shared(r),

#[tokio::test(flavor = "multi_thread")]
async fn the_reporter_counts_the_same_modules_after_a_build_without_log_info() {
  let project = vite_project();
  // As `vite build --logLevel warn`: the reporter has no `log_info`, so it registers no hooks.
  build(&project, &Setup { quiet_reporter: true, ..Setup::client() }).await;
  let second = build(&project, &Setup::client()).await;
  let clean = build(&project, &Setup { no_cache: true, ..Setup::client() }).await;
  assert_eq!(second.transformed_count, clean.transformed_count); // 3 != 7
}

Reviewed with Claude Opus 5.5.


/// The input of every key 1. The Rolldown version stands in for a cache version: a new version
/// can change the result of a module in ways that no other input shows.
const ROLLDOWN_VERSION: &str = env!("CARGO_PKG_VERSION");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Preview builds share a cache version with the release that they come from. The pkg.pr.new builds of main, and of a PR with trigger: preview, run bump-version.js commit. It changes only the package.json versions, to 1.3.3+commit.<sha> (scripts/misc/bump-version.js:44-46), and it does not touch Cargo.toml. So CARGO_PKG_VERSION here is 1.3.3 in each of them, and a build from another commit reuses the saved results of the 1.3.3 release. SAVED_RESULT_FORMAT covers only the encoding, not a change in what a module gives.

This can show up during triage. A user tries the pkg.pr.new build of a fix in the resolver or in a builtin transform, and the cache returns the old result, so the fix looks like it does not work.

A possible fix: also hash the JS VERSION (packages/rolldown/src/constants/version.ts) into key 1, passed with the cache options. It has the commit for previews. Local builds of contributors would still share 1.3.3. A commit hash from build.rs would cover them too, but the npm version already covers what users install.

Reviewed with Claude Opus 5.5.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants