Skip to content

Commit 1c0789c

Browse files
committed
fix(test): join graceful Vitest fork shutdown
1 parent 8526829 commit 1c0789c

11 files changed

Lines changed: 559 additions & 7 deletions

‎patches/README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,3 +3,7 @@
33
`@vitest/[email protected]` has an approved temporary pnpm patch for lost trailing task updates. It accepts the exact batching deadline and clears the consumed timer handle before re-entering the throttle, allowing an early callback to rearm. The 100 ms batching interval and immediate-call cancellation stay unchanged; this is not a maintained fork or a reporting SLA.
44

55
Remove the runner patch, its registration, and its exact-version guard exception when upgrading to an upstream fixed version with `test/scripts/vitest-runner-task-updates.test.ts` green. Keep that regression to verify completion delivery without later task events or file-finalization rescue. Generate and register patches through pnpm; never edit installed dependency files manually.
6+
7+
`[email protected]` has an approved temporary patch for graceful fork shutdown. The built-in forks/vmForks transport marks its stopped response with `willExit`, flushes it, and explicitly exits; its parent joins actual exit through the worker's exit observer within the existing 60-second stop deadline, before computing the run result. Custom fork entrypoints that omit this fact retain parent-owned termination; they can explicitly opt in with the response and observer contract. This lets exit cleanup and native CPU/heap profiles finish without racing SIGTERM or its 500 ms escalation. Timeout and abnormal-exit paths still report failure and terminate/join the worker; forced termination retains the existing signal deadline. Threads retain their existing stop protocol. No OpenClaw setup or profiling option changes are needed.
8+
9+
Remove this patch, its registration, and its exact-version guard exception when an upstream version passes `node scripts/run-vitest.mjs test/scripts/vitest-fork-shutdown.test.ts test/scripts/run-vitest-state-cleanup.test.ts`. The regressions cover slow exit cleanup, delayed stop-response delivery during natural exit, custom entrypoint compatibility/opt-in, vmForks, abnormal exits, and bounded hung/forced cleanup with actual installed workers and native profile artifacts. The stop-deadline test clock advances the existing deadline only after the worker reaches its shutdown boundary; it does not change production timeouts.

‎patches/[email protected]‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
diff --git a/dist/chunks/cli-api.CnMVyzaz.js b/dist/chunks/cli-api.CnMVyzaz.js
2+
index 2b8bb8d9cb13dc89892f4983afd404c8594bdcc5..554a865b72deee1bff2d7cbfffda156b451c1316 100644
3+
--- a/dist/chunks/cli-api.CnMVyzaz.js
4+
+++ b/dist/chunks/cli-api.CnMVyzaz.js
5+
@@ -3034 +3034,2 @@ class PoolRunner {
6+
- resolve();
7+
+ // Only the responding transport can promise an explicit graceful exit.
8+
+ resolve(response.willExit ? Promise.resolve().then(() => this.worker.waitForExit?.()) : undefined);
9+
@@ -3049 +3050 @@ class PoolRunner {
10+
- }), STOP_TIMEOUT).finally(() => {
11+
+ }), STOP_TIMEOUT).finally(async () => {
12+
@@ -3050 +3051,3 @@ class PoolRunner {
13+
- stopSpan.end();
14+
+ stopSpan.end();
15+
+ // Deadline/error paths must also terminate and join the worker.
16+
+ await this._traces.$(`vitest.${this.worker.name}.stop`, { context: this._otel?.workerContext }, () => this.worker.stop());
17+
@@ -3052,6 +3054,0 @@ class PoolRunner {
18+
- this._eventEmitter.removeAllListeners();
19+
- this._offCancel();
20+
- this._rpc.$close(/* @__PURE__ */ new Error("[vitest-pool-runner]: Pending methods while closing rpc"));
21+
- // Stop the worker process (this sets _fork/_thread to undefined)
22+
- // Worker's event listeners (error, message) are implicitly removed when worker terminates
23+
- await this._traces.$(`vitest.${this.worker.name}.stop`, { context: this._otel?.workerContext }, () => this.worker.stop());
24+
@@ -3060 +3057,2 @@ class PoolRunner {
25+
- // Ensure we transition to stopped state even on error
26+
+ // Ensure failed graceful shutdown cannot report a successful test run.
27+
+ this.project.vitest.state.catchError(error, "Teardown Error");
28+
@@ -3063 +3061,4 @@ class PoolRunner {
29+
- } finally {
30+
+ } finally {
31+
+ this._eventEmitter.removeAllListeners();
32+
+ this._offCancel();
33+
+ this._rpc.$close(/* @__PURE__ */ new Error("[vitest-pool-runner]: Pending methods while closing rpc"));
34+
@@ -3166 +3167 @@ class ForksPoolWorker {
35+
- async stop() {
36+
+ waitForExit() {
37+
@@ -3167 +3168,13 @@ class ForksPoolWorker {
38+
- const fork = this.fork;
39+
+ const fork = this.fork;
40+
+ return new Promise((resolve, reject) => {
41+
+ const onExit = (code, signal) => {
42+
+ if (code === 0 && signal == null) resolve();
43+
+ else reject(new Error(`Worker exited during graceful shutdown (code: ${code}, signal: ${signal})`));
44+
+ };
45+
+ if (fork.exitCode != null || fork.signalCode != null) onExit(fork.exitCode, fork.signalCode);
46+
+ else fork.once("exit", onExit);
47+
+ });
48+
+ }
49+
+ async stop() {
50+
+ const fork = this._fork;
51+
+ if (!fork) return;
52+
@@ -3169 +3182 @@ class ForksPoolWorker {
53+
- if (fork.exitCode != null) resolve();
54+
+ if (fork.exitCode != null || fork.signalCode != null) resolve();
55+
@@ -3178,4 +3191,6 @@ class ForksPoolWorker {
56+
- const sigkillTimeout = setTimeout(() => fork.kill("SIGKILL"), SIGKILL_TIMEOUT);
57+
- fork.kill();
58+
- await waitForExit;
59+
- clearTimeout(sigkillTimeout);
60+
+ if (fork.exitCode == null && fork.signalCode == null) {
61+
+ const sigkillTimeout = setTimeout(() => fork.kill("SIGKILL"), SIGKILL_TIMEOUT);
62+
+ fork.kill();
63+
+ await waitForExit;
64+
+ clearTimeout(sigkillTimeout);
65+
+ }
66+
@@ -3551 +3566 @@ class Pool {
67+
- this.exitPromises.push(runner.stop({ force: resolver.isRejected }).then(() => clearTimeout(id)).catch((error) => this.logger.error(`[vitest-pool]: Failed to terminate ${task.worker} worker for test files ${formatFiles(task)}.`, error)));
68+
+ this.exitPromises.push(runner.stop({ force: resolver.isRejected }).finally(() => clearTimeout(id)).catch((error) => this.logger.error(`[vitest-pool]: Failed to terminate ${task.worker} worker for test files ${formatFiles(task)}.`, error)));
69+
@@ -3781 +3796,3 @@ function createPool(ctx) {
70+
- }
71+
+ }
72+
+ // Join worker teardown before reporters and the CLI compute the run result.
73+
+ await pool.close();
74+
diff --git a/dist/chunks/init-forks.H5ZuobOQ.js b/dist/chunks/init-forks.H5ZuobOQ.js
75+
index 3a3a5f671e3d503eae1af13c6068e4d18bb8f60b..5754b53fc412909f0697c043c7b29f3846e1e134 100644
76+
--- a/dist/chunks/init-forks.H5ZuobOQ.js
77+
+++ b/dist/chunks/init-forks.H5ZuobOQ.js
78+
@@ -16 +16,6 @@ function workerInit(options) {
79+
- post: (v) => processSend(v),
80+
+ // Flush the response, then exit explicitly while native profiler signal handlers
81+
+ // are still installed. The parent joins actual exit within its stop deadline.
82+
+ post: (v) => {
83+
+ if (v.__vitest_worker_response__ && v.type === "stopped") return processSend({ ...v, willExit: true }, (error) => processExit(error ? 1 : process.exitCode));
84+
+ return processSend(v);
85+
+ },
86+
diff --git a/dist/chunks/reporters.d.DtoKVV2s.d.ts b/dist/chunks/reporters.d.DtoKVV2s.d.ts
87+
index fbe82be6ea7d5dd5e3fa6771c040f0a438f5717f..b60a1abbb785f588bdf04ec1e8ba29baa630d5b1 100644
88+
--- a/dist/chunks/reporters.d.DtoKVV2s.d.ts
89+
+++ b/dist/chunks/reporters.d.DtoKVV2s.d.ts
90+
@@ -2075 +2075,3 @@ interface PoolWorker {
91+
- start: () => Promise<void>;
92+
+ start: () => Promise<void>;
93+
+ /** Observe exit when a stopped response declares willExit; reject abnormal termination. */
94+
+ waitForExit?: () => Promise<void>;
95+
@@ -2141 +2143,3 @@ type WorkerResponse = {
96+
- error?: unknown;
97+
+ error?: unknown;
98+
+ /** The transport will exit itself after sending this response. */
99+
+ willExit?: true;
100+
diff --git a/dist/node.d.ts b/dist/node.d.ts
101+
index 4af12597408d7f46a148003f4425e83272e3ccdd..529b9b837041ed73f3daa2cf810cbe60450611f6 100644
102+
--- a/dist/node.d.ts
103+
+++ b/dist/node.d.ts
104+
@@ -174 +174,2 @@ declare class ForksPoolWorker implements PoolWorker {
105+
- start(): Promise<void>;
106+
+ start(): Promise<void>;
107+
+ waitForExit(): Promise<void>;

‎pnpm-lock.yaml‎

Lines changed: 8 additions & 7 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎pnpm-workspace.yaml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,3 +88,4 @@ packageExtensions:
8888

8989
patchedDependencies:
9090
91+

‎scripts/check-package-patches.mts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { pnpmLockfileDocuments } from "./lib/pnpm-lockfile-documents.mjs";
1111

1212
const ALLOWED_PATCHED_DEPENDENCIES = new Map([
1313
["@vitest/[email protected]", "patches/@[email protected]"],
14+
1415
1516
1617
]);

‎scripts/test-projects.test-support.mts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -539,6 +539,15 @@ const BROAD_CHANGED_FALLBACK_PATTERNS = [
539539
/^test\/helpers\//u,
540540
];
541541
const PRECISE_SOURCE_TEST_TARGETS = new Map<string, string[]>([
542+
[
543+
"patches/[email protected]",
544+
[
545+
"test/scripts/run-vitest-profile.test.ts",
546+
"test/scripts/run-vitest-state-cleanup.test.ts",
547+
"test/scripts/vitest-fork-shutdown.test.ts",
548+
],
549+
],
550+
["test/fixtures/vitest-fork-shutdown.mjs", ["test/scripts/vitest-fork-shutdown.test.ts"]],
542551
...[
543552
"src/system-agent/setup-inference-persist.ts",
544553
"src/agents/embedded-agent-runner/run/attempt-dispatch-preparation.ts",

0 commit comments

Comments
 (0)