Skip to content

ReferenceError: process is not defined - Issue on vitest@5 teardown during unfinished async operations #11380

Closed

Description

@francesco-agnoletto

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.2

Used Package Manager

pnpm

Validations

Activity

  1. sheremet-va commented on Oct 6, 2026

    @sheremet-va
    Member

    /approve-user shairez

  2. francesco-agnoletto commented on Oct 7, 2026

    @francesco-agnoletto
    ContributorAuthor

    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.mjs runs 120 jsdom files through one worker on vitest@5.0.2 and a "fixed" build where I added process, global, setImmediate and clearImmediate to initialContextKeys (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

    jsdom, maxWorkers: 1 stock process/global/setImmediate/clearImmediate kept
    8-file repro: runs with the error (of 10 runs) 9 (19 errors) 0 (0 errors)
    120-file probe: vm contexts alive after GC, max (vmThreads / vmForks) 4 / 4 4 / 4
    120-file probe: heap after the last file, MB (vmThreads / vmForks) 32 / 32 32 / 32
    120-file probe: workers used with vmMemoryLimit 100MB (vmThreads / vmForks) 17 / 17 17 / 19
    • The process error is absent in the patched runs.
    • vmContexts alive changes in every run because it depends on gc timing (outside factor) but stays between 2 to 4.
    • heap after last file is reliable across all runs.
    • workers count is also reliable with at max a couple difference between stock and patch.

    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 defined errors 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.

  3. shairez commented on Oct 7, 2026

    @shairez
    Contributor

    Thanks @francesco-agnoletto for the detailed measurements, and for checking worker recycling!

    To me, this fix looks reasonable as process, global, setImmediate and clearImmediate don'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 vmMemoryLimit with 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, setImmediate stays replaced on the global. With the fix that fake would be kept instead of deleted, along with the clock and callbacks it points at. setTimeout and 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! 🙏

  4. francesco-agnoletto commented on Oct 19, 2026

    @francesco-agnoletto
    ContributorAuthor

    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.2

    • stock
    • kept: the four keys added to initialContextKeys (node leak-check/fix.mjs apply)
    • restored: kept, plus the real values put back after the strip, as you suggested (node leak-check/fix.mjs apply-restore)

    Everything below is macOS, Node 22, jsdom, maxWorkers: 1. Cells are vmThreads / vmForks.

    Heavier test files

    Scenario Measurement stock kept restored
    Large objects: 60 files, ~87 MB allocated each, vmMemoryLimit: 600MB workers used 8 / 9 7 / 9 7 / 9
    contexts alive after GC (max) 2 / 4 2 / 4 2 / 4
    Many modules: 60 files, each importing 150 modules, vmMemoryLimit: 80MB workers used 12 / 20 12 / 20 12 / 20
    contexts alive after GC (max) 4 / 4 4 / 4 4 / 4
    Large snapshots: 60 files, each snapshotting 4000 nested objects, vmMemoryLimit: 80MB workers used 10 / 11 11 / 11 11 / 11
    contexts alive after GC (max) 4 / 2 4 / 2 4 / 2

    Worker 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 ContextifyContext list. No module state from earlier files survives in any build. node leak-check/heap.mjs writes 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, calls setImmediate and 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 calling setImmediate. The context is retained on all three builds, stock included (79 of 79, ~830 MB). The heap snapshot shows the fake process.hrtime clock holding it, through the same chain on every build, so the fix adds no retention there. What changes is the late setImmediate: 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 delete

    Other environments

    • happy-dom: the repro errors in 10/10 runs on stock and 0/10 on kept and restored. Contexts, heap and workers match across builds in every scenario. (Side note: on happy-dom, stock already keeps every context alive, 119 of 119 after 120 files, while the heap stays flat at ~49 MB.)
    • Node 24.21 (jsdom, vmThreads): same repro results, and the three builds match each other in the small, large objects, unawaited work and fake timers scenarios.
    • I only ran this on macOS, I have a linux machine in case but I do not think it will differ.

    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):

    • 3 large projects where stock completes the whole suite (2 runs each): stock, kept and restored peak the same within noise (2.2 GB, 2.6 GB, 2.8-3.2 GB), with the same test and worker counts.
    • 5 large projects where stock dies after a few percent of the tests, so stock can't be compared (1 run each): against a build with the strip removed entirely (the v4-style teardown), kept peaks within -10% to +8% (5.4-12.6 GB depending on the project).

    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.

  5. shairez commented on Oct 20, 2026

    @shairez
    Contributor

    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:

    1. Restore after the strip. In runVmTests(), right after stripDisposedContext(), reassign the same values as at setup: process, global = context, setImmediate, clearImmediate. That also covers tests that stubbed or overwrote any of them.

    2. Deterministic tests. Can you use the same maxWorkers: 1 but with runInlineTests with 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 process and setImmediate. This covers the reported bug.

    • The first file starts async work it doesn't await. After the file is torn down, that work reads process and calls setImmediate.
    • The second file waits until that work has actually run, e.g. by polling for a file the work writes.
    • Then check that no unhandled errors were reported.

    Case 2: fake timers left on. This covers the "restored" part.

    • The first file calls vi.useFakeTimers() and never restores it.
    • It also starts unawaited async work that calls setImmediate for the first time after teardown.
    • Then check that the callback actually ran, not just that nothing threw.

    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.

    1. Scope in the description. Late work that uses expect / vi.* or calls import() 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!

  6. added
    p2-edge-case
    approved
    and removed on Oct 20, 2026
  7. github-actions commented on Oct 20, 2026

    @github-actions

    This issue is approved, so the team accepts a pull request for it. To work on it, open a pull request against main and link this issue in its description with a closing keyword, for example Fixes #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.

  8. added a commit that references this issue on Oct 28, 2026
    a57b4d8
  9. added a commit that references this issue on Nov 9, 2026
  10. locked and limited conversation to collaborators on Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    approvedp2-edge-case

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions