fix(pool): terminate stuck orphaned forks workers

Merged
AR
2d ago
+156-18

Fixes https://github.com/vitest-dev/vitest/issues/11915

Adds a new watchdog process that's spawned once by main process when forks or vmForks pools are used. Process ID of each spawned forks runner is passed to the watchdog. If main process is forcefully terminated, it won't close the pool. Watchdog notices this via disconnect event and terminates all test runners with SIGKILL.

This is mainly for the use case of https://github.com/vitest-dev/vitest/issues/11915 where infinite synchronous loops could block the test runner. But it's also good generic improvement, as it makes sure orphan workers are never left hanging.

  Vitest main               vitest-watchdog              forks worker
       |                           |                           |
-- Normal run -----------------------------------------------------------
       |                           |                           |
       |-- fork() -------------------------------------------->|
       |-- fork() 1st time ------->|                           |
       |-- watch(pid) ------------>|                           |
       |                           |                           | runs tests
       |<------------------------ exit ------------------------|
       |-- unwatch(pid) ---------->|                           |
       |  Pool.close()             |                           |
       |-- disconnect() ---------->|                           |
       |                           |  no PIDs left, exits      |


-- Main process dies (SIGKILL, closed terminal, cancelled CI) -----------
       |                           |                           |
       |-- fork() -------------------------------------------->|
       |-- watch(pid) ------------>|                           |
       |                           |                           | while (true) {}
       |                           |                           | event loop blocked
       X  killed                   |                           |
         IPC channel closes ......>|                           |
                                   |  disconnect event         |
                                   |-- SIGKILL --------------->|
                                   |  exits                    X