Repository navigation
Description
Describe the bug
On vitest 5, running a project unit tests through vitest's vm pool (used automatically for jsdom/happydom for example) intermittently throws ReferenceError: process is not defined as an unhandled rejection, even though every test passes.
This error comes from the repro repository linked below:
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯Unhandled Rejection ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
ReferenceError: process is not defined
❯ file003.test.ts:14:3
12| }
13|
14| mockedAsyncCall(110).then(() => {
| ^
15| process.on('exit', () => {});
16| });
This error originated in "file001.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running.
This happens when a test (or code that passes through the test) kicks off async work it does not await and that work resolves after the file batch teardown runs.
runVmTests()'s teardown (added in #10854) calls stripDisposedContext(), which deletes every global added to the vm context after an initial snapshot — including process, global, setImmediate, and clearImmediate, since all four get assigned after that snapshot is taken. The PR's body says:
Additionally, runVmTests now clears a disposed context on teardown: globals added by the test file are deleted and document.body/document.head are emptied. Pristine globals are kept so that work queued before the teardown (jsdom events, worker fixture cleanups) still runs.
process and the timer globals aren't file-specific state, so they don't look like they were meant to land in the removable set.
I believe this is an issue on vitest specifically as many async operations are outside the control of the developer authoring the tests, they can be v8 internals (garbage collection), specific libraries internals or angular/RxJS operations.
For what is worth on a big monorepo I'm working on, this is a blocker from migrating to v5 as we have an average of 489 failures across 23 unrelated project all of which are outside our control.
Happy to open a PR moving captureContextKeys() after the process/global/setImmediate/clearImmediate assignments if the team agrees.
Reproduction
https://github.com/francesco-agnoletto/vitest5-vm-strip-repro I built a small repro with the help of claude.
Simply npm install && npm test
| Run | Errors |
|---|---|
| 1 | 1 |
| 2 | 3 |
| 3 | 1 |
| 4 | 1 |
| 5 | 2 |
| 6 | 1 |
| 7 | 1 |
| 8 | 1 |
| 9 | 2 |
| 10 | 2 |
10/10 runs reproduced it, 15 errors total, avg 1.5 per run.
I confirmed this does not happen in vitest@4
System Info
System:
OS: macOS 26.4
CPU: (18) arm64 Apple M5 Pro
Memory: 4.50 GB / 48.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 22.23.2 - /opt/homebrew/bin/node
Yarn: 1.22.22 - /opt/homebrew/bin/yarn
npm: 11.19.1 - /opt/homebrew/bin/npm
pnpm: 11.27.1 - /opt/homebrew/bin/pnpm
bun: 1.4.0 - /Users/francesco.agnoletto/.bun/bin/bun
Browsers:
Chrome: 154.0.8037.57
Safari: 26.4
npmPackages:
vitest: 5.0.2 => 5.0.2Used Package Manager
pnpm
Validations
- Follow our Code of Conduct
- Read the Contributing Guidelines.
- Read the docs.
- Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- The provided reproduction is a minimal reproducible example of the bug.
Activity
sheremet-va commentedon Oct 6, 2026
/approve-user shairez
chore: approve contributor shairez
francesco-agnoletto commentedon Oct 7, 2026
Hello, wanted to update regarding the potential memory issue from this change.
I updated the repro with a few scripts inside the
leak-check/folder,node leak-check/run.mjsruns 120 jsdom files through one worker on vitest@5.0.2 and a "fixed" build where I addedprocess,global,setImmediateandclearImmediatetoinitialContextKeys(the issue I highlighted here).I ran it a few times (5) just to make sure the results are consistent, below the table from the last run, feel free to clone and run yourself to check measurements:
% node leak-check/run.mjs
These checks were run on the machine from system info above they might slightly differ on different machines but I do not see any sign of leaks.
I performed an additional test run in a private monorepo (which I mentioned above) 180 projects, on stock vitest@5.0.2 it averages 500
process is not definederrors in 25 projects. With the patch applied those errors disappear, the entire run took about 10% longer but also ran 6k tests more so I do not see this as a slowdown.TL;DR with those four kept, memory behaviour matches stock in everything I measured, and the error is gone on both the public repro and the private monorepo.
shairez commentedon Oct 7, 2026
Thanks @francesco-agnoletto for the detailed measurements, and for checking worker recycling!
To me, this fix looks reasonable as
process,global,setImmediateandclearImmediatedon't point at the test file's module graph, which is the reason the capture happens before Vitest installs its own globals.The probe uses very small test files (32 MB heap after 120 files), so a leak that depends on file size could stay hidden.
So just to be safe, could you please check a few more cases?
Heavier test files: currently, each file barely allocates. Could you add files that hold large objects, many modules, or large snapshots, and compare worker recycle counts under
vmMemoryLimitwith and without the fix?Heap snapshots: Take one with
v8.writeHeapSnapshot()after N files, with and without the fix, and check what keeps old contexts alive. Counting contexts after GC shows how many are left but not why.Unawaited async work: The bug is about work that finishes after teardown. Please check that this pending work, which can now run, doesn't keep a context alive longer than before.
Other environments: happy-dom in addition to jsdom (and a different OS or Node version if possible, though not a must only if you have an easy way to do it)
Memory on the monorepo: The 10% longer run is hard to read since it also ran 6k more tests. Peak memory or worker counts would be easier to compare.
One more thing I wonder about, though I haven't tested it: nothing calls
useRealTimers()at teardown, so if a test leaves fake timers on,setImmediatestays replaced on the global. With the fix that fake would be kept instead of deleted, along with the clock and callbacks it points at.setTimeoutand Date already behave this way, so it's probably minor.Restoring the original values of those four keys at teardown, instead of only skipping the delete, might cover it. It would be worth a quick test with a file that uses
vi.useFakeTimers()and never restores.Thanks again! 🙏
francesco-agnoletto commentedon Oct 19, 2026
I expanded the repro to cover your points @shairez, the scripts are in
leak-check/and the README has the full write-up. I compared three builds of vitest@5.0.2initialContextKeys(node leak-check/fix.mjs apply)node leak-check/fix.mjs apply-restore)Everything below is macOS, Node 22, jsdom,
maxWorkers: 1. Cells arevmThreads / vmForks.Heavier test files
vmMemoryLimit: 600MBvmMemoryLimit: 80MBvmMemoryLimit: 80MBWorker recycling matches within ±1, and contexts alive stay between 2 and 4 however many files run.
Heap snapshots
After 30 files, all three builds hold the same 2 contexts through the same two chains: a V8 global handle and Node's internal
ContextifyContextlist. No module state from earlier files survives in any build.node leak-check/heap.mjswrites the snapshots and prints the chains.Unawaited async work
80 files, each starting a native timer (20-380 ms) that fires after teardown, reads
process.pid, callssetImmediateand reads the file's module state. On stock it throws (77 files); on kept and restored it runs (78 files). Contexts alive are 3 / 4, 4 / 3 and 3 / 4, and workers used are 13 / 13, 13 / 14 and 14 / 14, so the late work running doesn't keep contexts alive.One case does differ: when the late work registers a
process.on('exit', ...)listener that closes over the file's state. Kept then retains every context (79 of 79, ~830 MB after 80 files), against 4 contexts and 52 MB on stock, because on stock the callback throws before it can register. But the same listener registered during the test retains 79 contexts and 827 MB on stock too. So I think that's a leak in the code itself becoming visible, not a new retention path from this fix.Fake timers left on
Your case,
vi.useFakeTimers()never restored, fake timers pending that close over module state, and late work callingsetImmediate. The context is retained on all three builds, stock included (79 of 79, ~830 MB). The heap snapshot shows the fakeprocess.hrtimeclock holding it, through the same chain on every build, so the fix adds no retention there. What changes is the latesetImmediate: stock throws, kept gets the leftover fake and silently never runs the callback, and restored runs it. So restoring the values is better than only skipping the deleteOther environments
Memory on the monorepo
As I stated above, private project running a very heavy vitest setup. I measured the data here too, below results.
Peak RSS per project run (
/usr/bin/time -l):TL;DR: no difference in worker recycling, heap or retained contexts for heavy files, snapshots, happy-dom or Node 24. The only change is late work that registers a process listener, which leaks the same way on stock when the listener is registered during the test. If that sounds good, I'd open a PR with the restored variant (keep the four keys and reassign them after the strip) plus a test.
shairez commentedon Oct 20, 2026
Thanks @francesco-agnoletto , this is really thorough! 🙏
The results look convincing!
The fake timers result also confirms that restoring the values is the better option, since "kept" silently swallows setImmediate callbacks.
So I'd go with that in the PR as well.
A few things for the PR:
Restore after the strip. In
runVmTests(), right afterstripDisposedContext(), reassign the same values as at setup:process, global = context, setImmediate, clearImmediate. That also covers tests that stubbed or overwrote any of them.Deterministic tests. Can you use the same
maxWorkers: 1but withrunInlineTestswith two files? (and not depend on different timer times as it'll make CI flaky), I'm sure you thought about it, just writing this here just in case.Here are potential tests to verify the fix:
Case 1: late work uses
processandsetImmediate. This covers the reported bug.Case 2: fake timers left on. This covers the "restored" part.
vi.useFakeTimers()and never restores it.Without the restore, case 2 passes silently with the callback never running, so it's the test that would catch someone removing the restore later.
expect / vi.*or callsimport()after teardown will still fail. It would be good to say so in the PR, so people hitting those cases don't think this PR fixes them.Separately, and not for this PR: your data shows that leaving fake timers on keeps every context alive on stock too (79 of 79). We never reset fake timers at teardown, so that might be worth its own issue.
Thanks again for digging into this so carefully!
github-actions commentedon Oct 20, 2026
This issue is approved, so the team accepts a pull request for it. To work on it, open a pull request against
mainand link this issue in its description with a closing keyword, for exampleFixes #11380.The team accepts one pull request per issue: if another pull request for this issue is already open, a new one is closed automatically. See our pull request policy for more context.
fix(vm): keep node globals after teardown (fix vitest-dev#11380) (vit…
⬆️ Update vitest monorepo to v5
Update vitest monorepo to v5.1.0 (#2269)