Skip to content

Commit 057a85e

Browse files
committed
fix(qa): stop zombie-only gateway process groups
Punchcard-Session: amber-orchard-valley-s4
1 parent 8d29969 commit 057a85e

2 files changed

Lines changed: 229 additions & 40 deletions

File tree

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

Lines changed: 120 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1375,26 +1375,131 @@ describe("buildQaRuntimeEnv", () => {
13751375
testing.stopQaGatewayChildProcessTree(child as never, {
13761376
gracefulTimeoutMs: 1,
13771377
forceTimeoutMs: 1,
1378+
inspectLinuxProcessGroup: () => null,
13781379
}),
1379-
).rejects.toThrow("qa gateway process tree remained alive after forced shutdown");
1380+
).rejects.toThrow(
1381+
process.platform === "linux"
1382+
? "qa gateway process tree remained alive after forced shutdown: pgid=12345 members=unknown (/proc unavailable) childExitRecorded=false"
1383+
: "qa gateway process tree remained alive after forced shutdown: pid=12345 childExitRecorded=false",
1384+
);
13801385
},
13811386
);
13821387

1383-
it("treats Linux process groups with only dead members as stopped", () => {
1384-
const stats = [
1388+
it("reports Linux process-tree diagnostics when forced shutdown times out", async () => {
1389+
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
1390+
Object.defineProperty(process, "platform", { value: "linux", configurable: true });
1391+
const child = Object.assign(new EventEmitter(), {
1392+
pid: 12345,
1393+
exitCode: null as number | null,
1394+
signalCode: null as string | null,
1395+
kill: vi.fn(() => true),
1396+
});
1397+
vi.spyOn(process, "kill").mockImplementation(() => true);
1398+
try {
1399+
await expect(
1400+
testing.stopQaGatewayChildProcessTree(child as never, {
1401+
gracefulTimeoutMs: 1,
1402+
forceTimeoutMs: 1,
1403+
inspectLinuxProcessGroup: () => ({
1404+
alive: true,
1405+
diagnostics:
1406+
'pgid=12345 members=[pid=12345 state=Z command="gateway", pid=12346 state=S command="worker"]',
1407+
}),
1408+
}),
1409+
).rejects.toThrow(
1410+
'qa gateway process tree remained alive after forced shutdown: pgid=12345 members=[pid=12345 state=Z command="gateway", pid=12346 state=S command="worker"] childExitRecorded=false',
1411+
);
1412+
} finally {
1413+
if (platformDescriptor) {
1414+
Object.defineProperty(process, "platform", platformDescriptor);
1415+
}
1416+
}
1417+
});
1418+
1419+
it("classifies Linux zombie-only process groups as stopped", () => {
1420+
const inspection = testing.inspectLinuxProcessGroupStats(123, [
13851421
"123 (gateway child) Z 1 123 123 0 -1 0",
13861422
"124 (helper (worker)) X 1 123 123 0 -1 0",
13871423
"125 (unrelated) S 1 999 999 0 -1 0",
1388-
];
1424+
]);
1425+
1426+
expect(inspection).toEqual({
1427+
alive: false,
1428+
diagnostics:
1429+
'pgid=123 members=[pid=123 state=Z command="gateway child", pid=124 state=X command="helper (worker)"]',
1430+
});
1431+
});
13891432

1390-
expect(testing.classifyLinuxProcessGroupStats(123, stats)).toBe(false);
1433+
it("classifies Linux process groups with a runnable descendant as alive", () => {
1434+
const inspection = testing.inspectLinuxProcessGroupStats(123, [
1435+
"123 (gateway child) Z 1 123 123 0 -1 0",
1436+
"126 (live helper) D 1 123 123 0 -1 0",
1437+
]);
1438+
1439+
expect(inspection).toEqual({
1440+
alive: true,
1441+
diagnostics:
1442+
'pgid=123 members=[pid=123 state=Z command="gateway child", pid=126 state=D command="live helper"]',
1443+
});
1444+
});
1445+
1446+
it("classifies an empty Linux process-group snapshot as unknown", () => {
13911447
expect(
1392-
testing.classifyLinuxProcessGroupStats(123, [
1393-
...stats,
1394-
"126 (live helper) D 1 123 123 0 -1 0",
1395-
]),
1396-
).toBe(true);
1397-
expect(testing.classifyLinuxProcessGroupStats(456, stats)).toBeNull();
1448+
testing.inspectLinuxProcessGroupStats(123, ["125 (unrelated) S 1 999 999 0 -1 0"]),
1449+
).toEqual({
1450+
alive: null,
1451+
diagnostics: "pgid=123 members=[]",
1452+
});
1453+
});
1454+
1455+
it("bounds Linux process-group diagnostics", () => {
1456+
const stats = Array.from(
1457+
{ length: 300 },
1458+
(_, index) => `${index + 1} (${`worker-${index}`.padEnd(32, "x")}) S 1 123 123 0 -1 0`,
1459+
);
1460+
1461+
const inspection = testing.inspectLinuxProcessGroupStats(123, stats);
1462+
1463+
expect(inspection.alive).toBe(true);
1464+
expect(inspection.diagnostics.length).toBeLessThanOrEqual(2_048);
1465+
expect(inspection.diagnostics).toMatch(/\.\.\.$/u);
1466+
});
1467+
1468+
it("trusts Linux runnable-member inspection before child exit metadata settles", () => {
1469+
const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform");
1470+
Object.defineProperty(process, "platform", { value: "linux", configurable: true });
1471+
const processKill = vi.spyOn(process, "kill").mockImplementation(() => true);
1472+
const child = {
1473+
pid: 12345,
1474+
exitCode: null,
1475+
signalCode: null,
1476+
};
1477+
try {
1478+
expect(
1479+
testing.isQaGatewayChildProcessTreeAlive(child as never, () => ({
1480+
alive: false,
1481+
diagnostics: 'pgid=12345 members=[pid=12345 state=Z command="gateway"]',
1482+
})),
1483+
).toBe(false);
1484+
expect(
1485+
testing.isQaGatewayChildProcessTreeAlive(child as never, () => ({
1486+
alive: true,
1487+
diagnostics: 'pgid=12345 members=[pid=12346 state=S command="worker"]',
1488+
})),
1489+
).toBe(true);
1490+
expect(
1491+
testing.isQaGatewayChildProcessTreeAlive(child as never, () => ({
1492+
alive: null,
1493+
diagnostics: "pgid=12345 members=[]",
1494+
})),
1495+
).toBe(true);
1496+
expect(testing.isQaGatewayChildProcessTreeAlive(child as never, () => null)).toBe(true);
1497+
expect(processKill).toHaveBeenCalledWith(-12345, 0);
1498+
} finally {
1499+
if (platformDescriptor) {
1500+
Object.defineProperty(process, "platform", platformDescriptor);
1501+
}
1502+
}
13981503
});
13991504

14001505
it("force-kills Windows gateway process trees when graceful taskkill fails", () => {
@@ -1479,6 +1584,10 @@ describe("buildQaRuntimeEnv", () => {
14791584
{
14801585
gracefulTimeoutMs: 1,
14811586
forceTimeoutMs: 50,
1587+
inspectLinuxProcessGroup: () => ({
1588+
alive: !sawForceKill || postKillLivenessChecks < 2,
1589+
diagnostics: 'pgid=12346 members=[pid=12347 state=S command="worker"]',
1590+
}),
14821591
},
14831592
);
14841593

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

Lines changed: 109 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,7 @@ const QA_GATEWAY_CHILD_GRACEFUL_SHUTDOWN_TIMEOUT_MS = 30_000;
8888
// Loaded Docker runners can take several seconds to reap a force-killed process group.
8989
const QA_GATEWAY_CHILD_FORCE_SHUTDOWN_TIMEOUT_MS = 10_000;
9090
const QA_GATEWAY_LOG_CLOSE_TIMEOUT_MS = 5_000;
91+
const QA_GATEWAY_PROCESS_TREE_DIAGNOSTIC_MAX_CHARS = 2_048;
9192
const QA_MOCK_OPENAI_API_KEY = ["qa", "mock", "openai", "key"].join("-");
9293
const QA_GATEWAY_CHILD_BLOCKED_SECRET_ENV_VARS = Object.freeze([
9394
"OPENCLAW_QA_CONVEX_SECRET_CI",
@@ -692,7 +693,8 @@ export const testing = {
692693
signalQaGatewayChildProcessTree,
693694
resolveQaGatewayChildStopTimeouts,
694695
stopQaGatewayChildProcessTree,
695-
classifyLinuxProcessGroupStats,
696+
inspectLinuxProcessGroupStats,
697+
isQaGatewayChildProcessTreeAlive,
696698
closeWriteStream,
697699
};
698700

@@ -705,36 +707,73 @@ function isProcessAlreadyExitedError(error: unknown): boolean {
705707
}
706708

707709
function parseLinuxProcessStat(raw: string) {
710+
const commandStart = raw.indexOf("(");
708711
const commandEnd = raw.lastIndexOf(")");
709-
if (commandEnd < 0) {
712+
if (commandStart <= 0 || commandEnd <= commandStart) {
710713
return null;
711714
}
715+
const pid = Number.parseInt(raw.slice(0, commandStart).trim(), 10);
712716
const fields = raw
713717
.slice(commandEnd + 1)
714718
.trim()
715719
.split(/\s+/u);
716720
const state = fields[0];
717721
const processGroupId = Number.parseInt(fields[2] ?? "", 10);
718-
if (!state || !Number.isSafeInteger(processGroupId) || processGroupId <= 0) {
722+
if (
723+
!Number.isSafeInteger(pid) ||
724+
pid <= 0 ||
725+
!state ||
726+
!Number.isSafeInteger(processGroupId) ||
727+
processGroupId <= 0
728+
) {
719729
return null;
720730
}
721-
return { processGroupId, state };
731+
return {
732+
command: raw.slice(commandStart + 1, commandEnd),
733+
pid,
734+
processGroupId,
735+
state,
736+
};
737+
}
738+
739+
function boundQaGatewayProcessTreeDiagnostics(details: string) {
740+
if (details.length <= QA_GATEWAY_PROCESS_TREE_DIAGNOSTIC_MAX_CHARS) {
741+
return details;
742+
}
743+
return `${sliceUtf16Safe(details, 0, QA_GATEWAY_PROCESS_TREE_DIAGNOSTIC_MAX_CHARS - 3)}...`;
722744
}
723745

724-
function classifyLinuxProcessGroupStats(processGroupId: number, stats: readonly string[]) {
746+
function inspectLinuxProcessGroupStats(processGroupId: number, stats: readonly string[]) {
725747
const members = stats
726748
.map((raw) => parseLinuxProcessStat(raw))
727749
.filter(
728750
(entry): entry is NonNullable<ReturnType<typeof parseLinuxProcessStat>> =>
729751
entry?.processGroupId === processGroupId,
730-
);
731-
if (members.length === 0) {
732-
return null;
733-
}
734-
return members.some((entry) => entry.state !== "Z" && entry.state !== "X");
752+
)
753+
.toSorted((left, right) => left.pid - right.pid);
754+
const diagnostics = members
755+
.map(
756+
(member) =>
757+
`pid=${member.pid} state=${member.state} command=${JSON.stringify(member.command)}`,
758+
)
759+
.join(", ");
760+
return {
761+
alive:
762+
members.length === 0
763+
? null
764+
: members.some((entry) => entry.state !== "Z" && entry.state !== "X"),
765+
diagnostics: boundQaGatewayProcessTreeDiagnostics(
766+
`pgid=${processGroupId} members=[${diagnostics}]`,
767+
),
768+
};
735769
}
736770

737-
function inspectLinuxProcessGroupLiveness(processGroupId: number) {
771+
type QaLinuxProcessGroupInspection = ReturnType<typeof inspectLinuxProcessGroupStats>;
772+
type QaLinuxProcessGroupInspector = (
773+
processGroupId: number,
774+
) => QaLinuxProcessGroupInspection | null;
775+
776+
function inspectLinuxProcessGroup(processGroupId: number): QaLinuxProcessGroupInspection | null {
738777
if (process.platform !== "linux") {
739778
return null;
740779
}
@@ -751,14 +790,20 @@ function inspectLinuxProcessGroupLiveness(processGroupId: number) {
751790
}
752791
try {
753792
stats.push(readFileSync(path.join("/proc", entry.name, "stat"), "utf8"));
754-
} catch {
793+
} catch (error) {
755794
// Processes can exit while /proc is being scanned.
795+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
796+
return null;
797+
}
756798
}
757799
}
758-
return classifyLinuxProcessGroupStats(processGroupId, stats);
800+
return inspectLinuxProcessGroupStats(processGroupId, stats);
759801
}
760802

761-
function isQaGatewayChildProcessTreeAlive(child: ChildProcess) {
803+
function isQaGatewayChildProcessTreeAlive(
804+
child: ChildProcess,
805+
inspectLinuxProcessGroupFn: QaLinuxProcessGroupInspector = inspectLinuxProcessGroup,
806+
) {
762807
if (!child.pid) {
763808
return false;
764809
}
@@ -767,12 +812,12 @@ function isQaGatewayChildProcessTreeAlive(child: ChildProcess) {
767812
}
768813
try {
769814
process.kill(-child.pid, 0);
770-
if (!hasChildExited(child)) {
771-
return true;
815+
if (process.platform === "linux") {
816+
// Linux can retain zombie-only process groups after SIGKILL while Node's
817+
// child metadata is still unsettled. Runnable /proc members are the owner.
818+
return inspectLinuxProcessGroupFn(child.pid)?.alive ?? true;
772819
}
773-
// Container PID 1 can leave killed descendants as zombies. They cannot
774-
// retain ports or execute work, so do not make release QA wait forever.
775-
return inspectLinuxProcessGroupLiveness(child.pid) ?? true;
820+
return true;
776821
} catch (error) {
777822
if (!isProcessAlreadyExitedError(error) && !hasChildExited(child)) {
778823
return true;
@@ -838,43 +883,78 @@ function signalQaGatewayChildProcessTree(
838883
}
839884
}
840885

841-
async function waitForQaGatewayChildExit(child: ChildProcess, timeoutMs: number) {
886+
async function waitForQaGatewayChildExit(
887+
child: ChildProcess,
888+
timeoutMs: number,
889+
inspectLinuxProcessGroupFn: QaLinuxProcessGroupInspector,
890+
) {
842891
const deadline = Date.now() + timeoutMs;
843892
while (Date.now() <= deadline) {
844-
if (!isQaGatewayChildProcessTreeAlive(child)) {
893+
if (!isQaGatewayChildProcessTreeAlive(child, inspectLinuxProcessGroupFn)) {
845894
return true;
846895
}
847896
await sleep(Math.min(25, Math.max(0, deadline - Date.now())));
848897
}
849-
return !isQaGatewayChildProcessTreeAlive(child);
898+
return !isQaGatewayChildProcessTreeAlive(child, inspectLinuxProcessGroupFn);
850899
}
851900

852-
function resolveQaGatewayChildStopTimeouts(opts?: {
901+
type QaGatewayChildStopOptions = {
853902
gracefulTimeoutMs?: number;
854903
forceTimeoutMs?: number;
855-
}) {
904+
inspectLinuxProcessGroup?: QaLinuxProcessGroupInspector;
905+
};
906+
907+
function resolveQaGatewayChildStopTimeouts(opts?: QaGatewayChildStopOptions) {
856908
return {
857909
gracefulTimeoutMs: opts?.gracefulTimeoutMs ?? QA_GATEWAY_CHILD_GRACEFUL_SHUTDOWN_TIMEOUT_MS,
858910
forceTimeoutMs: opts?.forceTimeoutMs ?? QA_GATEWAY_CHILD_FORCE_SHUTDOWN_TIMEOUT_MS,
859911
};
860912
}
861913

914+
function formatQaGatewayProcessTreeDiagnostics(
915+
child: ChildProcess,
916+
inspectLinuxProcessGroupFn: QaLinuxProcessGroupInspector,
917+
) {
918+
const childExitRecorded = hasChildExited(child);
919+
if (process.platform !== "linux" || !child.pid) {
920+
return `pid=${child.pid ?? "unknown"} childExitRecorded=${childExitRecorded}`;
921+
}
922+
const inspection = inspectLinuxProcessGroupFn(child.pid);
923+
const processGroupDetails =
924+
inspection?.diagnostics ?? `pgid=${child.pid} members=unknown (/proc unavailable)`;
925+
return boundQaGatewayProcessTreeDiagnostics(
926+
`${processGroupDetails} childExitRecorded=${childExitRecorded}`,
927+
);
928+
}
929+
862930
async function stopQaGatewayChildProcessTree(
863931
child: ChildProcess,
864-
opts?: { gracefulTimeoutMs?: number; forceTimeoutMs?: number },
932+
opts?: QaGatewayChildStopOptions,
865933
) {
866-
if (!isQaGatewayChildProcessTreeAlive(child)) {
934+
const inspectLinuxProcessGroupFn = opts?.inspectLinuxProcessGroup ?? inspectLinuxProcessGroup;
935+
if (!isQaGatewayChildProcessTreeAlive(child, inspectLinuxProcessGroupFn)) {
867936
return;
868937
}
869938
const timeouts = resolveQaGatewayChildStopTimeouts(opts);
870939
signalQaGatewayChildProcessTree(child, "SIGTERM");
871-
if (await waitForQaGatewayChildExit(child, timeouts.gracefulTimeoutMs)) {
940+
if (
941+
await waitForQaGatewayChildExit(child, timeouts.gracefulTimeoutMs, inspectLinuxProcessGroupFn)
942+
) {
872943
return;
873944
}
874945
signalQaGatewayChildProcessTree(child, "SIGKILL");
875-
const stopped = await waitForQaGatewayChildExit(child, timeouts.forceTimeoutMs);
946+
const stopped = await waitForQaGatewayChildExit(
947+
child,
948+
timeouts.forceTimeoutMs,
949+
inspectLinuxProcessGroupFn,
950+
);
876951
if (!stopped) {
877-
throw new Error("qa gateway process tree remained alive after forced shutdown");
952+
throw new Error(
953+
`qa gateway process tree remained alive after forced shutdown: ${formatQaGatewayProcessTreeDiagnostics(
954+
child,
955+
inspectLinuxProcessGroupFn,
956+
)}`,
957+
);
878958
}
879959
}
880960

0 commit comments

Comments
 (0)