Skip to content

perf(vm): don't prewarm modules the worker never requests - #11033

Merged
sheremet-va merged 3 commits into
vitest-dev:mainfrom
MarshallOfSound:perf/prewarm-skip-mocked-and-dynamic
Aug 24, 2026
Merged

sheremet-va merged 3 commits into
vitest-dev:mainfrom
MarshallOfSound:perf/prewarm-skip-mocked-and-dynamic

Conversation

@MarshallOfSound

Copy link
Copy Markdown
Contributor

Fixes #11032.

The vm-pool prewarm walks every import edge and transforms whatever it finds, including two things the worker never actually asks for:

  • the target of vi.mock(path, factory) (and its whole subtree) — the factory answers instead. hoistMocks already sees these calls, so it now reports them and the walk skips them for that test file. Factories that use importOriginal/importActual, and factory-less vi.mock(path), are left alone.
  • import() targets that aren't also imported statically — they load on demand if the import ever runs.

Both hints are stored in the fs cache entry so warm runs prune the same way. Nothing changes semantically; anything skipped is still served by the normal fetch if a worker wants it.

On the suite from the issue: the repro goes 53 → 2 modules transformed under vmThreads (same as forks), a 387-file shard goes 22,940 → 10,988 (same as 4.1's on-demand count), cold 111 s → 45 s, warm 32 s → 19 s.

Added a vmThreads/vmForks e2e test that fails on main and passes here.

Written with Claude Code; reviewed and benchmarked by me.

Please don't delete this checklist! Before submitting the PR, please make sure you do the following:

  • It's really useful if your PR references an issue where it is discussed ahead of time. If the feature is substantial or introduces breaking changes without a discussion, PR might be closed.
  • Ideally, include a test that fails without this PR but passes with it.
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.
  • Please check Allow edits by maintainers to make review process faster. Note that this option is not available for repositories that are owned by Github organizations.

Tests

  • Run the tests with pnpm test:ci. (test/e2e/test/vm-threads.test.ts, test/unit under --pool=vmThreads; typecheck + eslint clean)

Documentation

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs command. (no user-facing option)

Changesets

  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.

@netlify

netlify Bot commented Aug 22, 2026

Copy link
Copy Markdown

✅ Deploy Preview for vitest-dev ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit 0a22cf4
🔍 Latest deploy log https://app.netlify.com/projects/vitest-dev/deploys/6a89691a9b31e00008779d10
😎 Deploy Preview https://deploy-preview-11033--vitest-dev.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.

@sheremet-va sheremet-va left a comment

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.

The changes are very hard to follow. I don't know what your agent thought to avoid, but it created more issues that it avoided, in my opinion

export interface CachedPrewarmHints {
/** urls this module only imports with `import()` */
dynamicDeps?: string[]
staticMocks?: { method: string; specifier: string; hasFactory: boolean; factoryLoadsOriginal: boolean }[]

@sheremet-va sheremet-va Aug 22, 2026 •

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.

Why not use StaticMockCall that was defined in this pr?

Comment thread packages/mocker/src/node/hoistMocks.ts Outdated
if (specifierNode?.type === 'ImportExpression') {
specifierNode = specifierNode.source
}
if (specifierNode?.type === 'Literal' && typeof specifierNode.value === 'string') {

@sheremet-va sheremet-va Aug 22, 2026 •

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.

I think this ignores templates:

vi.mock(`./some-path.js`)

But of course we can't do anything with:

vi.mock(`./some-${path}.js`)

We could support TemplateLiteral with empty expressions, I guess

* off a transformed node, or restored from the fs module cache on a hit.
*/
export function getPrewarmHints(environment: DevEnvironment, node: EnvironmentModuleNode): CachedPrewarmHints | undefined {
const result = node.transformResult as (TransformResult & { deps?: string[]; dynamicDeps?: string[]; __vitestStaticMocks?: CachedPrewarmHints['staticMocks'] }) | null

@sheremet-va sheremet-va Aug 22, 2026 •

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.

TransformResult already has deps, dynamicDeps

It's also probably better to augment the type for __vitestStaticMocks, like we already do for __vitestTmp

Comment thread packages/vitest/src/node/pools/rpc.ts Outdated
if (child.url == null || seen.has(child.url)) {
continue
}
if (child.id != null && skip.has(child.id)) {

@sheremet-va sheremet-va Aug 22, 2026 •

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.

Having two sets that both basically do the same thing feels like over-engineering - can't we combine them? They use different ids now, but they don't have to

importedUrls,
mappings,
moduleType: fetchResult.moduleType,
prewarm,

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.

Why introduce nesting? What we probably need here instead is deps, dynamicDeps and staticMocks to properly recreate vite's transformResult

}
let dynamicDeps: string[] | undefined
if (result.dynamicDeps?.length) {
const staticDeps = new Set(result.deps)

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.

You are referring to result.deps here, but you only add result.dynamicDeps to cached transform result

Normally both are set by Vite when the module has SSR transform applied to it ("module runner transform")

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.

I guess in your implementation it's fine because dynamicDeps is actually already filtered, but it creates so much mental overhead. I am certain now that we just need to copy deps/dynamicDeps and resolve onlyDynamic when needed

Comment thread packages/vitest/src/node/pools/rpc.ts Outdated
async function walkNode(node: EnvironmentModuleNode, skip: ReadonlySet<string>): Promise<void> {
const children: Promise<unknown>[] = []
// `import()`-only targets are fetched on demand if the import ever runs
const dynamicOnly = getPrewarmHints(environment, node)?.dynamicDeps

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 dynamicDeps is different than dynamicDeps so maybe the property should be named differently to reflect that

}
const staticMocks = result.__vitestStaticMocks
?? (node.id != null
? environment.pluginContainer.getModuleInfo(node.id)?.meta?.vitestStaticMocks as CachedPrewarmHints['staticMocks']

@sheremet-va sheremet-va Aug 22, 2026 •

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.

We could probably pseudo guarantee result.__vitestStaticMocks if we just set it after the module is transformed by fsModuleCache like we do moduleType (inside fetchAndProcess)

Then all we need from this function is filtering dynamic deps which we can just do in walkNode once, no need for a helper function

`Cannot export the result of "${method}". Remove export declaration because "${method}" doesn\'t return anything.`,
)
}
if (options.onStaticMock) {

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.

I like this idea

@MarshallOfSound
MarshallOfSound force-pushed the perf/prewarm-skip-mocked-and-dynamic branch from e4e6993 to ebcd885 Compare August 23, 2026 05:00
prewarmModuleGraph transformed every module reachable from a test file,
including two kinds the worker never fetches: the target (and subtree) of
vi.mock(path, factory), which the factory answers instead, and import()
targets that never run.

hoistMocks now reports the static vi.mock/vi.unmock calls it sees
(onStaticMock); the plugin returns them as transform meta and fetchModule
stamps them on the transform result as __vitestStaticMocks, next to
__vitestModuleType. The fs module cache stores deps, dynamicDeps and
staticMocks with the entry so a cache hit recreates the same transform result.
The walk then skips, for the test file it started from, the urls that file
mocks with an inline factory that does not load the original, and for every
module the dependencies that are only in dynamicDeps (hoisted test files
excepted: their static imports are rewritten to import()). Anything skipped is
still served by the regular fetch if a worker asks for it.
@MarshallOfSound
MarshallOfSound force-pushed the perf/prewarm-skip-mocked-and-dynamic branch from 6a7d0a4 to 810cca5 Compare August 23, 2026 05:03
@MarshallOfSound

Copy link
Copy Markdown
Contributor Author

Thanks reworked it based on those comments, all stored flat and then goes back on the transform result.

Honestly I understood the first one better so this took a bit longer for me to review, but this also seems reasonable.

@MarshallOfSound
MarshallOfSound marked this pull request as ready for review August 23, 2026 08:30
@sheremet-va
sheremet-va merged commit 1e9f80e into vitest-dev:main Aug 24, 2026
49 of 51 checks passed
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 8, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

vm pools: prewarmModuleGraph transforms subtrees that vi.mock(..., factory) replaces

2 participants