Skip to content

Commit af49764

Browse files
authored
fix(ci): ignore zombie-only Vitest process groups (#122759)
1 parent f24e164 commit af49764

3 files changed

Lines changed: 416 additions & 36 deletions

File tree

‎scripts/vitest-process-group.mts‎

Lines changed: 142 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Shared Vitest child process-group signal forwarding helpers.
22
import { execFileSync, type ChildProcess } from "node:child_process";
3+
import fs from "node:fs";
34

45
type VitestProcessSignal = "SIGINT" | "SIGKILL" | "SIGTERM";
56
type KillProcess = (pid: number, signal?: VitestProcessSignal | 0) => boolean;
@@ -101,27 +102,141 @@ function isVitestProcessGroupAlive(target: number, kill: KillProcess) {
101102
}
102103
}
103104

104-
export function parseVitestProcessGroupMembers(output: string, processGroupId: number): string {
105-
const members: string[] = [];
106-
for (const line of output.split(/\r?\n/)) {
107-
const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
108-
if (!match || Number(match[3]) !== processGroupId) {
105+
function parseLinuxProcStat(raw: string, expectedId: number) {
106+
const head = /^([1-9]\d*) \(/.exec(raw);
107+
const end = raw.lastIndexOf(") ");
108+
if (!head || end < head[0].length || Number(head[1]) !== expectedId) {
109+
return undefined;
110+
}
111+
const suffix = raw.slice(end + 2).trim();
112+
const fields = suffix.split(/\s+/);
113+
const state = fields[0] ?? "",
114+
ppid = Number(fields[1]),
115+
pgid = Number(fields[2]);
116+
if (
117+
!/^[A-Za-z]$/.test(state) ||
118+
![ppid, pgid].every((value) => Number.isSafeInteger(value) && value >= 0)
119+
) {
120+
return undefined;
121+
}
122+
const comm = raw
123+
.slice(head[0].length, end)
124+
.replace(/\p{Cc}+/gu, " ")
125+
.trim()
126+
.slice(0, 80);
127+
return { comm, pgid, ppid, state };
128+
}
129+
130+
function inspectLinuxVitestProcessGroup(processGroupId: number) {
131+
let pids: string[];
132+
try {
133+
const mounts = fs
134+
.readFileSync("/proc/self/mounts", "utf8")
135+
.trimEnd()
136+
.split(/\r?\n/)
137+
.map((line) => line.split(" "));
138+
const procMounts = mounts.filter((fields) => fields[1] === "/proc" && fields[2] === "proc");
139+
const options = procMounts[0]?.[3]?.split(",") ?? [];
140+
const restricted = options.some((option) =>
141+
/^(?:pidns=|hidepid=(?!0$|off$)|subset=(?!pid$))/u.test(option),
142+
);
143+
if (mounts.some((fields) => fields.length < 6) || procMounts.length !== 1 || restricted) {
144+
return { stopped: false, diagnostics: "unavailable" };
145+
}
146+
pids = fs
147+
.readdirSync("/proc")
148+
.filter((entry) => /^[1-9]\d*$/.test(entry))
149+
.toSorted((left, right) => Number(left) - Number(right));
150+
} catch {
151+
return { stopped: false, diagnostics: "unavailable" };
152+
}
153+
let matching = 0,
154+
allStopped = true;
155+
const diagnostics: string[] = [];
156+
processes: for (const pid of pids) {
157+
try {
158+
const leader = parseLinuxProcStat(fs.readFileSync(`/proc/${pid}/stat`, "utf8"), Number(pid));
159+
if (!leader) {
160+
return { stopped: false, diagnostics: "unavailable" };
161+
}
162+
if (leader.pgid !== processGroupId) {
163+
continue;
164+
}
165+
} catch (error) {
166+
if (errorCode(error) !== "ENOENT") {
167+
return { stopped: false, diagnostics: "unavailable" };
168+
}
109169
continue;
110170
}
111-
members.push(
112-
`pid=${match[1]} ppid=${match[2]} state=${match[4]} comm=${match[5]?.slice(0, 80)}`,
113-
);
114-
if (members.length >= 20) {
115-
break;
171+
172+
const parsedTids = new Set<string>();
173+
const taskRoot = `/proc/${pid}/task`;
174+
for (let scan = 0; scan < 2; scan += 1) {
175+
let tids: string[];
176+
try {
177+
tids = fs.readdirSync(taskRoot).toSorted((left, right) => Number(left) - Number(right));
178+
if (
179+
tids.length === 0 ||
180+
tids.some((tid) => !/^[1-9]\d*$/.test(tid) || (scan === 1 && !parsedTids.has(tid)))
181+
) {
182+
return { stopped: false, diagnostics: "unavailable" };
183+
}
184+
} catch (error) {
185+
if (errorCode(error) !== "ENOENT") {
186+
return { stopped: false, diagnostics: "unavailable" };
187+
}
188+
try {
189+
fs.readFileSync(`/proc/${pid}/stat`, "utf8");
190+
} catch (leaderError) {
191+
if (errorCode(leaderError) === "ENOENT") {
192+
continue processes;
193+
}
194+
}
195+
return { stopped: false, diagnostics: "unavailable" };
196+
}
197+
if (scan === 1) {
198+
continue;
199+
}
200+
for (const tid of tids) {
201+
try {
202+
const task = parseLinuxProcStat(
203+
fs.readFileSync(`${taskRoot}/${tid}/stat`, "utf8"),
204+
Number(tid),
205+
);
206+
if (!task || task.pgid !== processGroupId) {
207+
return { stopped: false, diagnostics: "unavailable" };
208+
}
209+
parsedTids.add(tid);
210+
matching += 1;
211+
allStopped &&= task.state === "Z" || task.state === "X";
212+
if (diagnostics.length < 20) {
213+
diagnostics.push(
214+
`pid=${pid} tid=${tid} ppid=${task.ppid} state=${task.state} comm=${task.comm}`,
215+
);
216+
}
217+
} catch (error) {
218+
if (errorCode(error) !== "ENOENT") {
219+
return { stopped: false, diagnostics: "unavailable" };
220+
}
221+
}
222+
}
116223
}
117224
}
118-
return members.length > 0 ? members.join("; ") : "none";
225+
return { stopped: matching > 0 && allStopped, diagnostics: diagnostics.join("; ") || "none" };
119226
}
120227

121-
function inspectVitestProcessGroup(processGroupId: number, platform: NodeJS.Platform): string {
122-
if (platform === "win32") {
123-
return "unavailable";
124-
}
228+
export function parseVitestProcessGroupMembers(output: string, processGroupId: number): string {
229+
const members = output.split(/\r?\n/).flatMap((line) => {
230+
const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
231+
if (!match || Number(match[3]) !== processGroupId) {
232+
return [];
233+
}
234+
return [`pid=${match[1]} ppid=${match[2]} state=${match[4]} comm=${match[5]?.slice(0, 80)}`];
235+
});
236+
return members.slice(0, 20).join("; ") || "none";
237+
}
238+
239+
function inspectVitestProcessGroup(processGroupId: number): string {
125240
try {
126241
const output = execFileSync("ps", ["-axo", "pid=,ppid=,pgid=,stat=,comm="], {
127242
encoding: "utf8",
@@ -145,17 +260,27 @@ async function joinVitestProcessGroup(
145260
}
146261
forwardSignalToVitestProcessGroup({ child, kill, platform, signal: "SIGKILL" });
147262
const deadlineAt = Date.now() + PROCESS_GROUP_JOIN_TIMEOUT_MS;
148-
while (isVitestProcessGroupAlive(target, kill)) {
263+
let alive = isVitestProcessGroupAlive(target, kill);
264+
if (alive && platform === "linux" && inspectLinuxVitestProcessGroup(child.pid!).stopped) {
265+
return;
266+
}
267+
while (alive) {
149268
const remainingMs = deadlineAt - Date.now();
150269
if (remainingMs <= 0) {
151-
const members = inspectVitestProcessGroup(child.pid!, platform);
270+
const inspection =
271+
platform === "linux" ? inspectLinuxVitestProcessGroup(child.pid!) : undefined;
272+
if (inspection?.stopped || !isVitestProcessGroupAlive(target, kill)) {
273+
return;
274+
}
275+
const members = inspection?.diagnostics ?? inspectVitestProcessGroup(child.pid!);
152276
throw new Error(
153277
`[vitest] process group ${child.pid ?? "unknown"} remained alive ${PROCESS_GROUP_JOIN_TIMEOUT_MS}ms after SIGKILL; members: ${members}.`,
154278
);
155279
}
156280
await new Promise((resolve) => {
157281
setTimeout(resolve, Math.min(25, remainingMs));
158282
});
283+
alive = isVitestProcessGroupAlive(target, kill);
159284
}
160285
}
161286

‎test/scripts/run-vitest.test.ts‎

Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -913,7 +913,7 @@ describe("scripts/run-vitest", () => {
913913
}
914914
});
915915

916-
posixIt("reaps residual process-group descendants before completing", async () => {
916+
posixIt("stops residual process-group descendants before completing", async () => {
917917
const descendantPidPath = nodePath.join(
918918
os.tmpdir(),
919919
`openclaw-run-vitest-residual-${process.pid}-${Date.now()}.pid`,
@@ -959,19 +959,34 @@ describe("scripts/run-vitest", () => {
959959

960960
process.kill(watched.child.pid!, "SIGTERM");
961961
const snapshot = await Promise.race([
962-
watched.completion.then((result) => ({
963-
descendantAlive: isProcessAlive(descendantPid),
964-
groupAlive: isProcessGroupAlive(watched.child.pid!),
965-
result,
966-
})),
962+
watched.completion.then((result) => {
963+
const psArgs =
964+
process.platform === "linux" ? ["-eL", "-o", "pgid=,state="] : ["-axo", "pgid=,state="];
965+
const stateResult = spawnSync("ps", psArgs, {
966+
encoding: "utf8",
967+
});
968+
const rows = stateResult.stdout
969+
.split(/\r?\n/)
970+
.filter(Boolean)
971+
.map((line) => /^\s*(\d+)\s+(\S+)\s*$/.exec(line));
972+
const groupStopped =
973+
!stateResult.error &&
974+
stateResult.signal === null &&
975+
stateResult.stderr.trim() === "" &&
976+
stateResult.status === 0 &&
977+
rows.every(Boolean) &&
978+
rows
979+
.filter((row) => Number(row?.[1]) === watched.child.pid)
980+
.every((row) => /^[ZX]/.test(row?.[2] ?? ""));
981+
return { groupStopped, result };
982+
}),
967983
delay(LOAD_SENSITIVE_PROCESS_TIMEOUT_MS, undefined, { ref: false }).then(() => {
968984
throw new Error("timed out waiting for watched Vitest completion");
969985
}),
970986
]);
971987

972988
expect(snapshot).toEqual({
973-
descendantAlive: false,
974-
groupAlive: false,
989+
groupStopped: true,
975990
result: { code: 0, signal: null },
976991
});
977992
} finally {
@@ -1260,12 +1275,3 @@ function isProcessAlive(pid: number) {
12601275
return false;
12611276
}
12621277
}
1263-
1264-
function isProcessGroupAlive(pgid: number) {
1265-
try {
1266-
process.kill(-pgid, 0);
1267-
return true;
1268-
} catch (error) {
1269-
return (error as NodeJS.ErrnoException).code === "EPERM";
1270-
}
1271-
}

0 commit comments

Comments
 (0)