Repository navigation
fix(vm): stop retaining every finished test file in vm pool workers - #10854
Merged
Merged
Conversation
…ntion Node never garbage-collects a vm context in which multiple scripts installed closures, and vm.SourceTextModule instances are pinned by the realm's base object list (Environment -> principal_realm -> base_object_list -> ModuleWrap -> SourceTextModule). Both reproduce in pure Node (20/22/24/26) with no vitest involved: a discarded context retains roughly its full contents through forced full GCs. In a long-lived vm worker every finished test file therefore accumulates on the heap until the worker hits vmMemoryLimit and is recycled, which also destroys the worker's compile caches. On a large real-world suite (zammad, 638 files) this put GC at ~30% of worker CPU and recycled workers 19 times per run. This mitigation clears everything a test file added to the context's global object (plus document body/head) after the environment teardown, so a pinned context retains its shell and the externalized ES module graph instead of the whole test-file world. Pristine globals are kept untouched: work queued before the teardown (jsdom events that fire after window.close(), worker-scoped fixture cleanups) still runs against an intact environment. This does not release payload that is also reachable from pinned SourceTextModules (externalized ESM deps); that requires either an upstream Node fix or avoiding SourceTextModule for externalized modules.
…egistries Three isolate/worker-level registries kept every finished test file's module graph (and through it the vm context and DOM) reachable for the lifetime of a vm pool worker: - Vite's `prepareStackTrace` interceptor holds `evaluatedModules` of every module runner in a module-level cache until the runner is closed. vm pools create a runner per test file and never closed it, so each file's whole module registry accumulated. `runVmTests` now closes the runner after the environment teardown. - `@vitest/expect` defined the `matchers-object` and `asymmetric-matchers-object` global accessors without `configurable: true` (unlike `$$jest-matchers-object`), and `runVmTests` defined `__vitest_index__` non-configurable. The getters capture the expect state, so a leaked context shell kept the whole test-file world reachable, and the teardown strip could not remove them. They are now configurable. The strip itself now preserves pristine globals (snapshot taken after environment setup) so late work queued before the teardown - jsdom events firing after `window.close()`, worker-scoped fixture cleanups - still runs against an intact environment. Known remaining retention, reproduced in pure Node and out of vitest's reach: V8's isolate-level compilation cache pins evaluated `vm.SourceTextModule`s (only memory-pressure GCs clear it; `--no-compilation-cache` eliminates it), and a residual ModuleWrap/base-object pin that only manifests with the full external ESM executor pattern.
Continues the vm pool retention work with three more severed edges, each found via heap-snapshot retainer analysis on a real-world suite: - `initializeImportMeta`/`importModuleDynamically` closures captured the per-file `ExternalModulesExecutor`. Node keeps them registered in its ESM callback registry for as long as the module's host-defined-options symbol is alive, so the registration outlives the test file. The ESM callbacks are now static and recover the executor from the module's own context at call time; the CJS callback holds the executor through a WeakRef. - worker-scoped fixture cleanups registered through `onCleanupWorkerContext` are in-context closures accumulated in the worker-lifetime cleanup listener set until worker teardown. The vm pool now runs them at the end of their own test file - their fixture contexts cannot survive the file's vm context anyway - and `cleanup()` clears the set so teardown does not re-run stale closures. - the pristine-globals snapshot for the teardown strip is now taken before vitest installs its own globals (worker state, console, mocker, executor symbol), so the strip removes them from disposed contexts instead of treating them as pristine.
The dynamic import callback was the only per-context state baked into a compiled commonjs script: it captured the test file's executor, which both kept the file's world registered in Node's per-script callback registry and forced every fresh vm context to compile its own copy of every commonjs module (with only the V8 code cache amortizing the cost). vm pools run one test file - and so one executor - at a time, so the callback can be a static function that resolves the active executor when a dynamic import actually happens. Compiled scripts then hold no per-context state at all and are cached for the lifetime of the worker, like inlined module scripts already are; each context only pays for the evaluation. The active executor is cleared when the file's context is torn down, so a late dynamic import from a disposed context fails with a clear error instead of resolving into the wrong context.
…test worlds The last two references that kept every finished test file's world alive in vm pool workers: - `onCancel` subscriptions were never removed: the worker-lifetime callback array accumulated one closure per test file, each capturing that file's test runner and through it the module runner, executor and vm context. `onCancel` now returns an unsubscribe function and both run entries dispose their subscription when the file's run is over. - V8's isolate-level compilation cache pins evaluated `vm.SourceTextModule`s: the module registry entry (whose value holds `callbackReferrer`, the module itself) stays alive because the compiled script's host-defined-options symbol survives in the cache, and only memory-pressure GCs clear it. vm workers now disable the compilation cache; the compiled-code reuse it provided is already covered by the worker's script and code caches. With these, a 638-file jsdom suite runs vm pools at a flat heap (~250MB per worker) instead of accumulating ~40-55MB per test file until the `vmMemoryLimit` recycle.
✅ Deploy Preview for vitest-dev ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
Module sources cannot change within a worker's lifetime: watch mode reruns destroy the worker, so the cache only needs the filename key.
sheremet-va
commented
Jul 30, 2026
| this.esm = new EsmExecutor(this, { | ||
| context: this.context, | ||
| }) | ||
| setActiveVmExecutor(this) |
Member
Author
There was a problem hiding this comment.
Tracking the active executor allows us to cache CJS new Script - otherwise importModuleDynamically was bound to the executor
Worker-scoped fixtures are downgraded to file scope in vm pools, so the hook registered by startTests never has anything to tear down there. It was still registered for every test file, and since the runner modules are evaluated inside the file's vm context, each registration stored an in-context closure in the worker-lifetime cleanup listener set, pinning the file's module graph until the worker died. VitestTestRunner now exposes onCleanupWorkerContext only for non-vm pools, which replaces the previous approach of draining and clearing the listener set at the end of every vm test file.
The probe environment lives in the worker realm, keeps a WeakRef to every test file's vm context and forces GC when the next file starts. A worker-lifetime reference into per-file worlds (the regression class fixed by this branch) retains every previous context, so with 10 files the alive count reaches 9 and fails the bound of 4. The bound tolerates the retention vitest does not control: Node's ESM callback registry keeps the youngest world or two, occasionally also the worker's first world, reachable until later registrations replace them. Reverting any single fix from this branch makes the test fail with "5 of 5 vm contexts of finished test files were not released" on both vm pools; on the branch it passes both pools consistently.
The field typed `fn | undefined` broke consumers compiling with exactOptionalPropertyTypes against the VitestRunner interface, where the hook is declared optional. Assign it in the constructor for non-vm pools and leave it absent otherwise.
Member
Author
|
With these changes I managed to half the time it takes to run tests in https://github.com/zammad/zammad Down from 162s to 88s with Interestingly enough, the |
sheremet-va
marked this pull request as ready for review
July 31, 2026 08:00
will-ness-ai
added a commit
to will-ness-ai/skills
that referenced
this pull request
Aug 18, 2026
* Add code-story skill Builds a wizard-style HTML page that teaches how and why a change works, one chapter at a time. A chapter answers one question and pulls hunks from whichever files hold that mechanism, so the reader meets the change as a narrative rather than as a file list. The skill file stays small; the two reference files carry the work: - references/template.html — copied to the output path. Holds the CSS, the page shell, and the script. The chapter rail, chapter numbering, progress, note numbering and the note-to-code link all compute themselves from the <article> blocks, so the agent writes chapters and nothing else. Diff markup is deliberately terse: line numbers come from a CSS counter and the +/- signs from ::after, so a line costs about half the characters it would otherwise. - references/example.html — a finished six-chapter story about a real 25-file PR (vitest-dev/vitest#10854). This is the specification: it sets chapter size, how much diff a chapter shows, the voice of the notes, which changes earn a diagram, and how the 16 files that earn no chapter get named and dismissed in a line each. It is written for a reader who is new to the repo, because that is who runs this skill. Mermaid works in both output branches from one file: an Artifact renders <pre class="mermaid"> natively and its CSP blocks the CDN tag, so the window.mermaid guard no-ops there; a local file loads the script instead. * Simplify the example prose, and say who a code story is for Two changes, both about the reader. SKILL.md now states the purpose and the audience in two sentences. The audience was the load-bearing decision behind the whole example, and the skill file never said it: write for someone who joined the repo today, fluent in the language and new to the codebase. The example's prose went through the claudish-to-english prompt, run against a local gemma4:26b via ollama, with a written brief on what the PR does so the model had the facts it needed to keep. 80 prose fragments in six batches, one per chapter. Code, diagrams, line notes, markers and structure are untouched. Guards on the pass: inline tags were normalised, every fragment's tag sequence had to match its original or the original was kept, and numbers and identifiers were diffed before and after. No fragment needed the fallback and no facts were lost. * State the purpose as the why, and the audience as a day-one contributor The previous wording framed the purpose around size — a change too large to hold in your head. That is a symptom, not the job. A code story explains why the code changed the way it did. It also pitched the audience too narrowly: fluent in the language, new to the codebase. A day-one contributor knows nothing yet about the domain or the architecture either, and that is what decides how much a chapter has to explain before its diff means anything. * Say how a code story is told: around code, with prose and diagrams supporting The skill said what a chapter is and who reads it, but never how the story is carried. Without it, an agent can write an essay that mentions code. The wording guards one trap the example already avoids: the story is built around code, not around the diff. Three of the example's fifteen code blocks sit outside the PR entirely — one in a dependency, one inside Node, one an unchanged line — and they carry the payoff of three of its six chapters.
will-ness-ai
added a commit
to will-ness-ai/skills
that referenced
this pull request
Aug 20, 2026
The repertoire only explained the change as written. Nothing showed the shape it left behind, so a reviewer could follow every hunk and still not know what now reaches what. Two of the five devices already worked and were simply unnamed — example.html uses sequenceDiagram once and flowchart twice, so call graphs and dependency graphs needed a name, not code. New in template.html: - `.diff.tree` — call tree, call hierarchy, or file tree. Reuses every .diff mechanism: data-n badges, <mark>, hover pairing, the a/d/c line classes. Only the line-number ::before switches off, so the JS that pairs notes to lines (`.diff [data-n]`) needs no change at all. - `.tb` — a behaviour table: one row per case, input / before / after. example.html gains a real file tree over all 25 files of vitest-dev/vitest#10854. Status came from the API, not from reading the diff: 12 added, 13 modified, and every one of the additions is the leak-probe fixture. The tree makes that visible in a way the existing supporting-cast list cannot. Checks: check-skills.sh passes. Both files parse with no mismatched tags. <style> and <script> are byte-identical between them again — the file tree needs the new rules to render, so the example had to carry them too. CSS cascade verified by specificity: .diff.tree wins for tree lines and plain .diff and .diff.base blocks are untouched.
will-ness-ai
added a commit
to will-ness-ai/skills
that referenced
this pull request
Aug 20, 2026
* Say that a code story runs in narrative order `SKILL.md` named the parts of a code story but never said the chapters run in sequence, so "cuts a change into chapters" left the order open. It now says the story is narrative and the chapters are sequential. Three smaller edits in the same paragraphs: - `<request>` is a **change**. The four examples (PR, diff, branch, commit) now read as instances of one thing, not a list of four. - A chapter pulls out a **slice** of the change. The term was missing, so the spanning-several-files point had nothing to attach to. - Voice: Simplified Technical English, written as a technical writer. This pairs with the "short, plain sentences" rule already there. `scripts/check-skills.sh` passes. * Frame the chapters as a stack of PRs * Add shape devices: trees, graphs, and a behaviour table The repertoire only explained the change as written. Nothing showed the shape it left behind, so a reviewer could follow every hunk and still not know what now reaches what. Two of the five devices already worked and were simply unnamed — example.html uses sequenceDiagram once and flowchart twice, so call graphs and dependency graphs needed a name, not code. New in template.html: - `.diff.tree` — call tree, call hierarchy, or file tree. Reuses every .diff mechanism: data-n badges, <mark>, hover pairing, the a/d/c line classes. Only the line-number ::before switches off, so the JS that pairs notes to lines (`.diff [data-n]`) needs no change at all. - `.tb` — a behaviour table: one row per case, input / before / after. example.html gains a real file tree over all 25 files of vitest-dev/vitest#10854. Status came from the API, not from reading the diff: 12 added, 13 modified, and every one of the additions is the leak-probe fixture. The tree makes that visible in a way the existing supporting-cast list cannot. Checks: check-skills.sh passes. Both files parse with no mismatched tags. <style> and <script> are byte-identical between them again — the file tree needs the new rules to render, so the example had to carry them too. CSS cascade verified by specificity: .diff.tree wins for tree lines and plain .diff and .diff.base blocks are untouched. * Prefer a picture to a paragraph The device paragraph led with what prose cannot do, which framed the visual devices as a fallback. It now leads with the choice itself, and states the default plainly: reach for a picture first. Two other places said the opposite and had to move with it. - SKILL.md called prose and diagrams peers — "prose sets up the question and diagrams show shape; both are there". That sentence made device choice a second source of truth, so it is gone; the paragraph below it now owns the decision. - template.html gated diagrams behind "only where a picture shows something the code cannot", which is the previous default written as a rule. It now reads "reach for one before writing a paragraph". example.html still runs 13 prose blocks to 5 visual devices, so it argues for the old default by example. That is a real gap and this commit does not close it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
vm pool workers retained the memory of every finished test file (module graphs, vm context, DOM, user state) until the worker reached
vmMemoryLimitand was recycled. On a 638-file jsdom suite (zammad), each worker leaked 40-55MB per test file, spent roughly 30% of its CPU in GC, and was recycled 19 times per run, losing its compile caches every time.The retention has several independent causes. Each commit removes one:
prepareStackTraceinterceptor kept every runner'sevaluatedModulesin a module-level cache.runVmTestsnow callsmoduleRunner.close()after the environment teardown.@vitest/expectdefinedmatchers-objectandasymmetric-matchers-objectas non-configurable global accessors ($$jest-matchers-objectalready hadconfigurable: true), andrunVmTestsdefined__vitest_index__non-configurable. The getters capture the expect state, and non-configurable properties cannot be removed from a disposed context. They are now configurable.onCancelsubscriptions were never removed: the worker-lifetime callback array accumulated one closure per test file, each capturing that file's test runner.onCancelnow returns an unsubscribe function and both run entries dispose their subscription when the run is over.startTestsregisters a worker-context cleanup hook throughrunner.onCleanupWorkerContext. In vm pools worker-scoped fixtures are downgraded to file scope, so the hook has nothing to tear down there, but it was still registered for every test file: the runner modules are evaluated inside the file's vm context, so each registration stored an in-context closure in the worker-lifetime cleanup listener set, pinning the file's module graph.VitestTestRunnerno longer exposes the hook in vm pools.initializeImportMeta/importModuleDynamicallyclosures captured the per-file executor and stayed registered in Node's ESM callback registry beyond the file's lifetime. They are now static functions: the executor is resolved from the module's own context (ESM) or from the worker's active executor (CJS).vm.SourceTextModules: the compiled script's host-defined-options symbol keeps Node's registry entry alive, and the entry'scallbackReferrerholds the module and everything its module state references. Only memory-pressure GCs clear this cache. vm workers now disable it withv8.setFlagsFromString('--no-compilation-cache'); the reuse it provided is already covered by the worker's script and code caches. This reproduces in plain Node 20-26 and will be reported upstream.Additionally,
runVmTestsnow clears a disposed context on teardown: globals added by the test file are deleted anddocument.body/document.headare emptied. Pristine globals are kept so that work queued before the teardown (jsdom events, worker fixture cleanups) still runs.Because the dynamic import callback no longer captures per-file state, compiled commonjs scripts are now cached per worker and shared between contexts, like inlined module scripts already were; each context only pays for evaluation.
Numbers from the zammad suite (638 files, jsdom,
--pool=vmThreads, 10 cores): worker heap is flat at ~250MB instead of climbing to the recycle limit; full run 487s before, 235s after (forks: ~162s); cumulative import time 1547s before, 587s after.A regression test covers the whole class: a probe environment in the worker realm keeps a WeakRef to every test file's vm context, forces GC when the next file starts, and fails when the number of surviving contexts exceeds a small bound. Reverting any single fix from this branch retains every previous world and trips the bound on both vm pools.
Review notes:
--no-compilation-cacheis a process-global V8 flag: invmThreadsit also affects the main thread's isolate. I measured no regression from this, but it may warrant a config option.onCancelonWorkerGlobalStatenow returns a dispose function; the browser client signature was updated to match.Please don't delete this checklist! Before submitting the PR, please make sure you do the following:
pnpm-lock.yamlunless you introduce a new test example.Tests
pnpm test:ci.