Skip to content

Commit 0f22112

Browse files
authored
fix: preserve private hook checks and diagnostics (#132403)
* fix: preserve private hook checks and diagnostics * fix(test): join graceful Vitest fork shutdown * test: expose Vitest shutdown fixture dependency
1 parent a339a23 commit 0f22112

16 files changed

Lines changed: 970 additions & 127 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/pre-commit/format-staged.sh‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ fi
4242

4343
restage_files=()
4444
for file in "${files[@]}"; do
45-
if ! git check-ignore --no-index -q -- "$file"; then
45+
# check-ignore rejects global literal magic; ./ keeps leading-colon names literal too.
46+
if ! git --no-literal-pathspecs check-ignore --no-index -q -- "./$file"; then
4647
restage_files+=("$file")
4748
fi
4849
done

‎scripts/pre-commit/guard-staged-content.mjs‎

Lines changed: 43 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,20 @@
11
#!/usr/bin/env node
22
import { spawnSync } from "node:child_process";
33
import { readFileSync } from "node:fs";
4+
import { promisify } from "node:util";
45

56
const ruleSetting = "hooks.blockedLiteralsFile";
6-
const decoder = new TextDecoder("utf-8", { fatal: true });
7+
// A leading BOM is a filename character in Git output, not an encoding marker.
8+
const pathDecoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
79
const maxBuffer = 16 * 1024 * 1024;
10+
// Enumerated paths stay literal in both scans and restaging; retain the commit's index/context.
11+
const gitEnv = {
12+
...process.env,
13+
GIT_LITERAL_PATHSPECS: "1",
14+
GIT_GLOB_PATHSPECS: "0",
15+
GIT_NOGLOB_PATHSPECS: "0",
16+
GIT_ICASE_PATHSPECS: "0",
17+
};
818
let rules = [];
919

1020
function redact(text) {
@@ -27,9 +37,15 @@ function redact(text) {
2737
return redacted + text.slice(cursor);
2838
}
2939

40+
class GuardFailure extends Error {
41+
constructor(message, code) {
42+
super(message);
43+
this.code = code;
44+
}
45+
}
46+
3047
function fail(message, code = 1) {
31-
process.stderr.write(redact(`[pre-commit] ${message}\n[pre-commit] FAILED (exit ${code})\n`));
32-
process.exit(code);
48+
throw new GuardFailure(message, code);
3349
}
3450

3551
function nulPaths(bytes) {
@@ -39,11 +55,12 @@ function nulPaths(bytes) {
3955
if (bytes.at(-1) !== 0) {
4056
throw new Error("Invalid path list");
4157
}
42-
return decoder.decode(bytes.subarray(0, -1)).split("\0");
58+
return pathDecoder.decode(bytes.subarray(0, -1)).split("\0");
4359
}
4460

4561
function git(args, input) {
46-
const result = spawnSync("git", ["--no-pager", "--literal-pathspecs", ...args], {
62+
const result = spawnSync("git", ["--no-pager", ...args], {
63+
env: gitEnv,
4764
input,
4865
maxBuffer,
4966
stdio: ["pipe", "pipe", "pipe"],
@@ -132,8 +149,8 @@ try {
132149
}
133150
if (configured.status === 0) {
134151
try {
135-
const rulePath = decoder.decode(configured.stdout).replace(/\n$/, "");
136-
rules = decoder
152+
const rulePath = pathDecoder.decode(configured.stdout).replace(/\n$/, "");
153+
rules = new TextDecoder("utf-8", { fatal: true })
137154
.decode(readFileSync(rulePath))
138155
.split(/\r?\n/)
139156
.filter((line) => line.length > 0);
@@ -152,21 +169,35 @@ try {
152169
// Check before the formatter's sequencer early return or any working-tree restaging.
153170
scan();
154171
const formatted = spawnSync("bash", ["scripts/pre-commit/format-staged.sh"], {
172+
env: gitEnv,
155173
maxBuffer,
156174
stdio: ["inherit", "pipe", "pipe"],
157175
});
158-
process.stdout.write(redact(formatted.stdout?.toString("utf8") ?? ""));
159-
process.stderr.write(redact(formatted.stderr?.toString("utf8") ?? ""));
176+
// An incomplete capture can cut through a literal, making safe redaction impossible.
160177
if (formatted.error || formatted.signal || formatted.status === null) {
161178
fail("Formatter could not complete. Check the formatting helpers and retry.");
162179
}
180+
// Git merges hook stdout/stderr: finish stdout before the terminal stderr diagnostics.
181+
await promisify(process.stdout.write.bind(process.stdout))(
182+
redact(formatted.stdout.toString("utf8")),
183+
);
184+
process.stderr.write(redact(formatted.stderr.toString("utf8")));
163185
if (formatted.status !== 0) {
164186
fail("Formatter failed. Fix the reported error and retry.", formatted.status);
165187
}
166188
// Formatting may change bytes or stage entirely new paths; enumerate the index again.
167189
scan();
168-
} catch {
169-
fail(
170-
`The staged scan could not complete. Check ${ruleSetting} and repository state, then retry.`,
190+
} catch (error) {
191+
const failure =
192+
error instanceof GuardFailure
193+
? error
194+
: new GuardFailure(
195+
`The staged scan could not complete. Check ${ruleSetting} and repository state, then retry.`,
196+
1,
197+
);
198+
process.stderr.write(
199+
redact(`[pre-commit] ${failure.message}\n[pre-commit] FAILED (exit ${failure.code})\n`),
171200
);
201+
// Abort the main flow, then let queued pipe writes drain before terminating.
202+
process.exitCode = failure.code;
172203
}

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

Lines changed: 13 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",
@@ -2253,6 +2262,10 @@ const EXACT_TOOLING_TARGETS = new Map<string, string[]>([
22532262
]);
22542263

22552264
const SEMANTIC_TOOLING_TARGET_PATTERNS: Array<[RegExp, string[]]> = [
2265+
[
2266+
/^(?:git-hooks\/pre-commit|scripts\/pre-commit\/(?:guard-staged-content\.mjs|filter-staged-files\.mjs|format-staged\.sh|run-node-tool\.sh)|test\/git-hooks-pre-commit\.test-support\.ts)$/u,
2267+
["test/git-hooks-pre-commit.test.ts", "test/git-hooks-pre-commit-boundaries.test.ts"],
2268+
],
22562269
[/^scripts\/pr$/u, ["pr-merge", "pr-merge-outcome", "pr-operation-lock", "pr-wrappers"]],
22572270
[
22582271
/^scripts\/pr-lib\/crabbox-gate-contract\.mjs$/u,

0 commit comments

Comments
 (0)