Skip to content

Commit 83a0756

Browse files
vincentkocRomneyDa
authored andcommitted
fix(qa): settle Unix commands after PGID cleanup
Punchcard-Session: cobalt-valley-meadow-mg
1 parent 74500f3 commit 83a0756

11 files changed

Lines changed: 1206 additions & 494 deletions

‎extensions/qa-lab/src/gateway-child.ts‎

Lines changed: 8 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
11
// Qa Lab plugin module implements gateway child behavior.
22
import { spawn, spawnSync, type ChildProcess } from "node:child_process";
33
import { randomUUID } from "node:crypto";
4-
import {
5-
createWriteStream,
6-
existsSync,
7-
readFileSync,
8-
readdirSync,
9-
type WriteStream,
10-
} from "node:fs";
4+
import { createWriteStream, existsSync, type WriteStream } from "node:fs";
115
import fs from "node:fs/promises";
126
import net from "node:net";
137
import os from "node:os";
@@ -54,6 +48,11 @@ import {
5448
import { startQaGatewayRpcClient } from "./gateway-rpc-client.js";
5549
import { splitQaModelRef, type QaProviderMode } from "./model-selection.js";
5650
import { resolveQaNodeExecPath } from "./node-exec.js";
51+
import {
52+
inspectLinuxProcessGroup,
53+
inspectLinuxProcessGroupStats,
54+
type QaLinuxProcessGroupInspector,
55+
} from "./posix-process-group.js";
5756
import { readProcessTreeCpuMs, readProcessTreeRssBytes } from "./process-tree-cpu.js";
5857
import {
5958
normalizeQaProviderModeEnv,
@@ -89,7 +88,6 @@ const QA_GATEWAY_CHILD_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 30_000;
8988
// Loaded Docker runners can take several seconds to reap a force-killed process group.
9089
const QA_GATEWAY_CHILD_FORCE_SHUTDOWN_TIMEOUT_MS = 10_000;
9190
const QA_GATEWAY_LOG_CLOSE_TIMEOUT_MS = 5_000;
92-
const QA_GATEWAY_PROCESS_TREE_DIAGNOSTIC_MAX_CHARS = 2_048;
9391
const QA_MOCK_OPENAI_API_KEY = ["qa", "mock", "openai", "key"].join("-");
9492
const QA_GATEWAY_CHILD_BLOCKED_SECRET_ENV_VARS = Object.freeze([
9593
"OPENCLAW_QA_CONVEX_SECRET_CI",
@@ -794,98 +792,11 @@ function isProcessAlreadyExitedError(error: unknown): boolean {
794792
return (error as NodeJS.ErrnoException | undefined)?.code === "ESRCH";
795793
}
796794

797-
function parseLinuxProcessStat(raw: string) {
798-
const commandStart = raw.indexOf("(");
799-
const commandEnd = raw.lastIndexOf(")");
800-
if (commandStart <= 0 || commandEnd <= commandStart) {
801-
return null;
802-
}
803-
const pid = Number.parseInt(raw.slice(0, commandStart).trim(), 10);
804-
const fields = raw
805-
.slice(commandEnd + 1)
806-
.trim()
807-
.split(/\s+/u);
808-
const state = fields[0];
809-
const processGroupId = Number.parseInt(fields[2] ?? "", 10);
810-
if (
811-
!Number.isSafeInteger(pid) ||
812-
pid <= 0 ||
813-
!state ||
814-
!Number.isSafeInteger(processGroupId) ||
815-
processGroupId <= 0
816-
) {
817-
return null;
818-
}
819-
return {
820-
command: raw.slice(commandStart + 1, commandEnd),
821-
pid,
822-
processGroupId,
823-
state,
824-
};
825-
}
826-
827795
function boundQaGatewayProcessTreeDiagnostics(details: string) {
828-
if (details.length <= QA_GATEWAY_PROCESS_TREE_DIAGNOSTIC_MAX_CHARS) {
796+
if (details.length <= 2_048) {
829797
return details;
830798
}
831-
return `${sliceUtf16Safe(details, 0, QA_GATEWAY_PROCESS_TREE_DIAGNOSTIC_MAX_CHARS - 3)}...`;
832-
}
833-
834-
function inspectLinuxProcessGroupStats(processGroupId: number, stats: readonly string[]) {
835-
const members = stats
836-
.map((raw) => parseLinuxProcessStat(raw))
837-
.filter(
838-
(entry): entry is NonNullable<ReturnType<typeof parseLinuxProcessStat>> =>
839-
entry?.processGroupId === processGroupId,
840-
)
841-
.toSorted((left, right) => left.pid - right.pid);
842-
const diagnostics = members
843-
.map(
844-
(member) =>
845-
`pid=${member.pid} state=${member.state} command=${JSON.stringify(member.command)}`,
846-
)
847-
.join(", ");
848-
return {
849-
alive:
850-
members.length === 0
851-
? null
852-
: members.some((entry) => entry.state !== "Z" && entry.state !== "X"),
853-
diagnostics: boundQaGatewayProcessTreeDiagnostics(
854-
`pgid=${processGroupId} members=[${diagnostics}]`,
855-
),
856-
};
857-
}
858-
859-
type QaLinuxProcessGroupInspection = ReturnType<typeof inspectLinuxProcessGroupStats>;
860-
type QaLinuxProcessGroupInspector = (
861-
processGroupId: number,
862-
) => QaLinuxProcessGroupInspection | null;
863-
864-
function inspectLinuxProcessGroup(processGroupId: number): QaLinuxProcessGroupInspection | null {
865-
if (process.platform !== "linux") {
866-
return null;
867-
}
868-
let entries;
869-
try {
870-
entries = readdirSync("/proc", { withFileTypes: true });
871-
} catch {
872-
return null;
873-
}
874-
const stats: string[] = [];
875-
for (const entry of entries) {
876-
if (!entry.isDirectory() || !/^\d+$/u.test(entry.name)) {
877-
continue;
878-
}
879-
try {
880-
stats.push(readFileSync(path.join("/proc", entry.name, "stat"), "utf8"));
881-
} catch (error) {
882-
// Processes can exit while /proc is being scanned.
883-
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
884-
return null;
885-
}
886-
}
887-
}
888-
return inspectLinuxProcessGroupStats(processGroupId, stats);
799+
return `${sliceUtf16Safe(details, 0, 2_045)}...`;
889800
}
890801

891802
function isQaGatewayChildProcessTreeAlive(

‎extensions/qa-lab/src/live-transports/matrix/scenarios/scenario-runtime-cli-stream-error.test.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,13 @@ describe("Matrix QA CLI runtime stream errors", () => {
115115
childProcessMocks.spawn.mockClear();
116116
});
117117

118-
it.each(["stdout", "stderr"] as const)(
119-
"rejects after cleaning up when %s emits a stream error",
120-
async (streamName) => {
118+
it.each([
119+
["stdout", false],
120+
["stderr", false],
121+
["stdout", true],
122+
] as const)(
123+
"rejects after cleaning up when %s emits a stream error (after exit: %s)",
124+
async (streamName, afterExit) => {
121125
const { grandchildPidPath, grandchildReadyPath, root } = await createCliRoot();
122126
let child: ChildProcess | undefined;
123127
let grandchildPid: number | undefined;
@@ -142,7 +146,13 @@ describe("Matrix QA CLI runtime stream errors", () => {
142146
grandchildPid = await waitForPidFile(grandchildPidPath, 2_000);
143147
await waitForFile(grandchildReadyPath, 2_000);
144148

145-
child[streamName]?.emit("error", new Error(`${streamName} pipe failed`));
149+
const streamError = new Error(`${streamName} pipe failed`);
150+
if (afterExit) {
151+
child.once("exit", () => child?.[streamName]?.emit("error", streamError));
152+
child.kill("SIGTERM");
153+
} else {
154+
child[streamName]?.emit("error", streamError);
155+
}
146156

147157
await expect(session.wait()).rejects.toThrow(
148158
`${streamName} stream error: ${streamName} pipe failed`,

‎extensions/qa-lab/src/live-transports/matrix/scenarios/scenario-runtime-cli.ts‎

Lines changed: 60 additions & 134 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { setTimeout as sleep } from "node:timers/promises";
77
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
88
import { redactSensitiveText } from "openclaw/plugin-sdk/logging-core";
99
import { resolvePreferredOpenClawTmpDir } from "openclaw/plugin-sdk/temp-path";
10+
import { createQaPosixCommandSettlement } from "../../../posix-command-settlement.js";
1011
import {
1112
killMatrixQaCliChild,
1213
resolveMatrixQaOpenClawCliEntryPath,
@@ -100,20 +101,6 @@ function formatMatrixQaCliTimeoutError(result: MatrixQaCliRunResult, timeoutMs:
100101
.join("\n");
101102
}
102103

103-
function isMatrixQaCliChildProcessGroupRunning(
104-
child: ReturnType<typeof startOpenClawCliProcess>,
105-
): boolean {
106-
if (process.platform === "win32" || !child.pid) {
107-
return false;
108-
}
109-
try {
110-
process.kill(-child.pid, 0);
111-
return true;
112-
} catch {
113-
return false;
114-
}
115-
}
116-
117104
export function startMatrixQaOpenClawCli(params: {
118105
allowNonZero?: boolean;
119106
args: string[];
@@ -129,11 +116,6 @@ export function startMatrixQaOpenClawCli(params: {
129116
let closed = false;
130117
let closeError: Error | undefined;
131118
let closeResult: MatrixQaCliRunResult | undefined;
132-
let killRequested = false;
133-
let timedOut = false;
134-
let forceKillTimeout: NodeJS.Timeout | undefined;
135-
let forceSettleTimeout: NodeJS.Timeout | undefined;
136-
let streamFailure: Error | undefined;
137119
let settleWait:
138120
| {
139121
reject: (error: Error) => void;
@@ -167,120 +149,67 @@ export function startMatrixQaOpenClawCli(params: {
167149
settleWait.resolve(result);
168150
}
169151
};
170-
const finishTimeout = (result: MatrixQaCliRunResult) => {
171-
finish(result, new Error(formatMatrixQaCliTimeoutError(result, params.timeoutMs)));
172-
};
173-
const finishResult = (result: MatrixQaCliRunResult) => {
174-
if (result.exitCode !== 0 && params.allowNonZero !== true) {
175-
finish(result, new Error(formatMatrixQaCliExitError(result)));
176-
return;
177-
}
178-
finish(result);
179-
};
180-
const clearForcedTimeouts = () => {
181-
if (forceKillTimeout) {
182-
clearTimeout(forceKillTimeout);
183-
forceKillTimeout = undefined;
184-
}
185-
if (forceSettleTimeout) {
186-
clearTimeout(forceSettleTimeout);
187-
forceSettleTimeout = undefined;
188-
}
189-
};
190-
const finishForcedCleanup = (result: MatrixQaCliRunResult) => {
191-
if (timedOut) {
192-
finishTimeout(result);
193-
return;
194-
}
195-
if (streamFailure) {
196-
finish(result, streamFailure);
197-
return;
198-
}
199-
finishResult(result);
200-
};
201-
const scheduleForcedCleanup = () => {
202-
if (forceKillTimeout || forceSettleTimeout) {
203-
return;
204-
}
205-
forceKillTimeout = setTimeout(() => {
206-
forceKillTimeout = undefined;
207-
killMatrixQaCliChild(child, "SIGKILL");
208-
forceSettleTimeout = setTimeout(() => {
209-
forceSettleTimeout = undefined;
210-
finishForcedCleanup(
211-
buildMatrixQaCliResult({
212-
args: params.args,
213-
exitCode: 1,
214-
output: readOutput(),
215-
}),
216-
);
217-
}, MATRIX_QA_CLI_TIMEOUT_FORCE_SETTLE_MS);
218-
}, MATRIX_QA_CLI_TIMEOUT_KILL_GRACE_MS);
219-
};
220-
221-
const timeout = setTimeout(() => {
222-
timedOut = true;
223-
killMatrixQaCliChild(child, "SIGTERM");
224-
scheduleForcedCleanup();
225-
}, params.timeoutMs);
226-
const handleStreamError = (stream: "stderr" | "stdout", error: Error) => {
227-
if (closed || timedOut || killRequested) {
228-
return;
229-
}
230-
clearTimeout(timeout);
231-
killRequested = true;
232-
streamFailure = new Error(`${stream} stream error: ${formatErrorMessage(error)}`, {
233-
cause: error,
234-
});
235-
// Keep stream failures on the normal kill path so detached descendants are gone
236-
// before the session reports the parent-side pipe failure.
237-
killMatrixQaCliChild(child, "SIGTERM");
238-
scheduleForcedCleanup();
239-
};
240-
241-
child.stdout.on("data", (chunk) => stdout.push(Buffer.from(chunk)));
242-
child.stdout.on("error", (error) => handleStreamError("stdout", error));
243-
child.stderr.on("data", (chunk) => stderr.push(Buffer.from(chunk)));
244-
child.stderr.on("error", (error) => handleStreamError("stderr", error));
245-
if (params.stdin !== undefined) {
246-
child.stdin.end(params.stdin);
247-
}
248-
child.on("error", (error) => {
249-
if (streamFailure) {
250-
// Forced cleanup owns settlement after a stream failure. Finishing here could
251-
// reject before detached descendants are proven gone.
252-
return;
253-
}
254-
clearTimeout(timeout);
255-
clearForcedTimeouts();
256-
finish(
257-
buildMatrixQaCliResult({
152+
const isWindows = process.platform === "win32";
153+
const settlement = createQaPosixCommandSettlement({
154+
child,
155+
settlementFailureMessage: `${formatMatrixQaCliCommand(params.args)} settlement failed`,
156+
forceKillAfterMs: MATRIX_QA_CLI_TIMEOUT_KILL_GRACE_MS,
157+
initialSignal: "SIGTERM",
158+
...(isWindows
159+
? {
160+
windowsCleanup: {
161+
closeCompletesCleanup: true,
162+
signal: (signal: NodeJS.Signals) => {
163+
try {
164+
killMatrixQaCliChild(child, signal);
165+
return undefined;
166+
} catch (error) {
167+
return error instanceof Error ? error : new Error(String(error));
168+
}
169+
},
170+
},
171+
}
172+
: {}),
173+
executionTimeoutMs: params.timeoutMs,
174+
onSettled: (outcome) => {
175+
const primary = outcome.primary;
176+
const result = buildMatrixQaCliResult({
258177
args: params.args,
259-
exitCode: 1,
178+
exitCode: primary.type === "exit" ? (primary.exitCode ?? 1) : 1,
260179
output: readOutput(),
261-
}),
262-
error,
263-
);
264-
});
265-
child.on("close", (exitCode) => {
266-
clearTimeout(timeout);
267-
const result = buildMatrixQaCliResult({
268-
args: params.args,
269-
exitCode: exitCode ?? 1,
270-
output: readOutput(),
271-
});
272-
if (timedOut || killRequested) {
273-
// A closed parent is not proof that detached, ignored-stdio descendants are gone.
274-
if (isMatrixQaCliChildProcessGroupRunning(child)) {
275-
return;
276-
}
277-
clearForcedTimeouts();
278-
finishForcedCleanup(result);
279-
return;
280-
}
281-
clearForcedTimeouts();
282-
finishResult(result);
180+
});
181+
const primaryError =
182+
primary.type === "spawn-error"
183+
? primary.error
184+
: primary.type === "stream-error"
185+
? new Error(`${primary.stream} stream error: ${formatErrorMessage(primary.error)}`, {
186+
cause: primary.error,
187+
})
188+
: primary.type === "timeout"
189+
? new Error(formatMatrixQaCliTimeoutError(result, params.timeoutMs))
190+
: result.exitCode !== 0 && params.allowNonZero !== true
191+
? new Error(formatMatrixQaCliExitError(result))
192+
: undefined;
193+
finish(
194+
result,
195+
outcome.settlementFailure
196+
? primaryError
197+
? new AggregateError(
198+
[primaryError, outcome.settlementFailure],
199+
"Matrix QA CLI command and settlement failed",
200+
)
201+
: outcome.settlementFailure
202+
: primaryError,
203+
);
204+
},
205+
onStderrData: (chunk) => stderr.push(Buffer.from(chunk)),
206+
onStdoutData: (chunk) => stdout.push(Buffer.from(chunk)),
207+
processGroupId: isWindows ? undefined : child.pid,
208+
verifyAfterMs: MATRIX_QA_CLI_TIMEOUT_FORCE_SETTLE_MS,
283209
});
210+
if (params.stdin !== undefined) {
211+
child.stdin.end(params.stdin);
212+
}
284213

285214
return {
286215
args: params.args,
@@ -335,10 +264,7 @@ export function startMatrixQaOpenClawCli(params: {
335264
},
336265
kill: () => {
337266
if (!closed) {
338-
clearTimeout(timeout);
339-
killRequested = true;
340-
killMatrixQaCliChild(child, "SIGTERM");
341-
scheduleForcedCleanup();
267+
settlement.requestCleanup();
342268
}
343269
},
344270
};

0 commit comments

Comments
 (0)