Skip to content

Commit 47dcc69

Browse files
committed
fix(test): restart shared gateway after migration convergence
Punchcard-Session: cobalt-valley-meadow-mg
1 parent 1c473ab commit 47dcc69

2 files changed

Lines changed: 148 additions & 17 deletions

File tree

‎test/helpers/openclaw-test-instance.test.ts‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { EventEmitter } from "node:events";
33
import fs from "node:fs/promises";
44
import { tmpdir } from "node:os";
55
import path from "node:path";
6+
import { PassThrough } from "node:stream";
67
import { afterEach, describe, expect, it, vi } from "vitest";
78
import { createOpenClawTestInstance, testing } from "./openclaw-test-instance.js";
89
import { isProcessAlive } from "./process-wait.js";
@@ -64,6 +65,12 @@ if (kind === "resist-after-exit") {
6465
await new Promise((resolve) => resistant.once("message", resolve));
6566
process.stderr.write("unrelated startup failure\\n"); process.exit(1);
6667
}
68+
if (kind === "terminal-drain") {
69+
const draining = spawn(process.execPath, ["-e", 'const fs = require("node:fs");const release = process.argv[1];const deadline = Date.now() + 5_000;const timer = setInterval(() => { if (fs.existsSync(release) || Date.now() >= deadline) clearInterval(timer); }, 10);', tracePath + ".draining-release"], { detached: true, stdio: ["ignore", "ignore", "inherit"] });
70+
draining.unref();
71+
writeFileSync(tracePath + ".draining-pid", String(draining.pid));
72+
process.stderr.write("terminal startup failure\\n"); process.exit(7);
73+
}
6774
if (kind === "near") { process.stderr.write(refusal.slice(0, -1) + " fixture\\n"); process.exit(1); }
6875
if (kind === "stdout") { process.stdout.write(refusal + " fixture\\n"); process.exit(1); }
6976
if (kind === "status2") { process.stderr.write(refusal + " fixture\\n"); process.exit(2); }
@@ -197,6 +204,81 @@ describe("openclaw test instance", () => {
197204
},
198205
);
199206

207+
it.runIf(process.platform !== "win32")(
208+
"reaps terminal children with inherited stdio before starting a new gateway",
209+
async () => {
210+
const { instance, readAttempts, tracePath } = await createFakeGateway(
211+
"terminal-drain,ready",
212+
300,
213+
100,
214+
);
215+
216+
const startupError = await instance.startGateway().catch((error: unknown) => error);
217+
expect(startupError).toBeInstanceOf(Error);
218+
expect((startupError as Error).message).toContain(
219+
"gateway exited before readiness (code=7 signal=null)",
220+
);
221+
expect((startupError as Error).message).toContain("terminal startup failure");
222+
expect(instance.child?.exitCode).toBe(7);
223+
expect(instance.child?.stderr.closed).toBe(false);
224+
const firstAttempt = (await readAttempts())[0];
225+
const drainingPid = Number(await fs.readFile(`${tracePath}.draining-pid`, "utf8"));
226+
expect(isProcessAlive(drainingPid)).toBe(true);
227+
228+
await fs.writeFile(`${tracePath}.draining-release`, "");
229+
await instance.startGateway();
230+
231+
const attempts = await readAttempts();
232+
expect(attempts).toHaveLength(2);
233+
expect(attempts[1]?.pid).not.toBe(firstAttempt?.pid);
234+
expect(instance.child?.pid).toBe(attempts[1]?.pid);
235+
await instance.stopGateway();
236+
expect(instance.child).toBeUndefined();
237+
expect(isProcessAlive(attempts[1]?.pid as number)).toBe(false);
238+
await expect.poll(() => isProcessAlive(drainingPid), { timeout: 500 }).toBe(false);
239+
},
240+
);
241+
242+
it("force-kills Windows gateway descendants before retry cleanup settles", async () => {
243+
const stdout = new PassThrough();
244+
const stderr = new PassThrough();
245+
const child = {
246+
exitCode: 1,
247+
kill: vi.fn(() => true),
248+
pid: 12345,
249+
signalCode: null,
250+
stderr,
251+
stdout,
252+
} as unknown as Parameters<typeof testing.stopGatewayProcess>[0];
253+
const runTaskkill = vi.fn(() => {
254+
stdout.destroy();
255+
stderr.destroy();
256+
return { status: 0 };
257+
});
258+
259+
await expect(
260+
testing.stopGatewayProcess(child, Date.now() + 500, 250, {
261+
forceWindowsTree: true,
262+
platform: "win32",
263+
runTaskkill,
264+
}),
265+
).resolves.toBe(true);
266+
267+
expect(runTaskkill).toHaveBeenCalledOnce();
268+
expect(runTaskkill).toHaveBeenCalledWith(
269+
path.win32.join("C:\\Windows", "System32", "taskkill.exe"),
270+
["/PID", "12345", "/T", "/F"],
271+
{
272+
killSignal: "SIGKILL",
273+
stdio: "ignore",
274+
timeout: 10_000,
275+
},
276+
);
277+
expect(child.kill).not.toHaveBeenCalled();
278+
expect(stdout.closed).toBe(true);
279+
expect(stderr.closed).toBe(true);
280+
});
281+
200282
it("keeps only bounded child output tails in helper logs", () => {
201283
const stdout = testing.createBoundedStringLog();
202284
const stderr = testing.createBoundedStringLog();

‎test/helpers/openclaw-test-instance.ts‎

Lines changed: 66 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
BUILD_STAMP_FILE,
1010
RUNTIME_POSTBUILD_STAMP_FILE,
1111
} from "../../scripts/lib/local-build-metadata-paths.mjs";
12+
import { terminateManagedChild } from "../../scripts/lib/managed-child-process.mjs";
1213
import {
1314
createOpenClawTestState,
1415
type OpenClawTestState,
@@ -87,6 +88,9 @@ type OpenClawTestProcessReadiness = Pick<OpenClawTestProcess, "exitCode" | "sign
8788
once: (event: "exit", listener: () => void) => unknown;
8889
off: (event: "exit", listener: () => void) => unknown;
8990
};
91+
type GatewayProcessStopOptions = NonNullable<Parameters<typeof terminateManagedChild>[2]> & {
92+
forceWindowsTree?: boolean;
93+
};
9094

9195
function createBoundedStringLog(): string[] {
9296
const log = [] as BoundedStringLog;
@@ -335,30 +339,56 @@ async function stopGatewayProcess(
335339
child: OpenClawTestProcess,
336340
deadline: number,
337341
stopTimeoutMs: number,
342+
options: GatewayProcessStopOptions = {},
338343
): Promise<boolean> {
339-
const waitForClose = (deadlineShare: number) =>
344+
const platform = options.platform ?? process.platform;
345+
const waitForClose = (remainingSteps: number) =>
340346
waitForGatewayClose(
341347
child,
342-
Math.min(stopTimeoutMs, Math.max(0, Math.floor((deadline - Date.now()) / deadlineShare))),
348+
Math.min(
349+
stopTimeoutMs,
350+
Math.max(0, Math.floor((deadline - Date.now()) / Math.max(1, remainingSteps))),
351+
),
352+
);
353+
const terminate = (signal: NodeJS.Signals) => {
354+
terminateManagedChild(
355+
child,
356+
signal,
357+
options.runTaskkill
358+
? { platform, runTaskkill: options.runTaskkill }
359+
: {
360+
platform,
361+
},
343362
);
344-
// Reserve enough of the shared deadline for TERM and KILL after natural stdio drain.
345-
if (hasChildExited(child) && (await waitForClose(3))) {
363+
};
364+
const forceWindowsTree = options.forceWindowsTree === true && platform === "win32";
365+
const signals = forceWindowsTree ? (["SIGKILL"] as const) : (["SIGTERM", "SIGKILL"] as const);
366+
367+
if (hasGatewayProcessClosed(child)) {
368+
return true;
369+
}
370+
// An exited leader can leave inherited stdio open in descendants. Let it
371+
// settle briefly, then terminate the owned tree before releasing the slot.
372+
if (!forceWindowsTree && hasChildExited(child) && (await waitForClose(signals.length + 1))) {
346373
return true;
347374
}
348-
for (const signal of ["SIGTERM", "SIGKILL"] as const) {
375+
for (const [index, signal] of signals.entries()) {
349376
if (hasGatewayProcessClosed(child)) {
350377
return true;
351378
}
379+
if (Date.now() >= deadline) {
380+
break;
381+
}
352382
try {
353-
signalOpenClawTestProcess(child, signal);
383+
terminate(signal);
354384
} catch {
355385
// ignore
356386
}
357-
if (await waitForClose(signal === "SIGTERM" ? 2 : 1)) {
387+
if (await waitForClose(signals.length - index)) {
358388
return true;
359389
}
360390
}
361-
return false;
391+
return hasGatewayProcessClosed(child);
362392
}
363393

364394
function hasChildExited(child: Pick<OpenClawTestProcess, "exitCode" | "signalCode">) {
@@ -471,8 +501,9 @@ export async function createOpenClawTestInstance(
471501
const releaseGatewayChild = async (
472502
target: OpenClawTestProcess,
473503
deadline: number,
504+
options: GatewayProcessStopOptions = {},
474505
): Promise<boolean> => {
475-
const closed = await stopGatewayProcess(target, deadline, stopTimeoutMs);
506+
const closed = await stopGatewayProcess(target, deadline, stopTimeoutMs, options);
476507
if (closed && child === target) {
477508
child = undefined;
478509
}
@@ -506,7 +537,7 @@ export async function createOpenClawTestInstance(
506537
});
507538
},
508539
startGateway: async () => {
509-
if (child && !hasGatewayProcessClosed(child)) {
540+
if (child && !hasChildExited(child)) {
510541
return;
511542
}
512543
const entrypoint = await resolveGatewayEntrypoint(cwd);
@@ -523,6 +554,18 @@ export async function createOpenClawTestInstance(
523554
const deadline = Date.now() + (options.startTimeoutMs ?? GATEWAY_START_TIMEOUT_MS);
524555
let restarts = 0;
525556

557+
if (child) {
558+
const staleChild = child;
559+
const closed = await releaseGatewayChild(staleChild, deadline, {
560+
forceWindowsTree: true,
561+
});
562+
if (!closed) {
563+
throw new Error(
564+
`gateway process did not close before restart deadline\n${formatLogs(stdout, stderr)}`,
565+
);
566+
}
567+
}
568+
526569
while (true) {
527570
const remainingMs = deadline - Date.now();
528571
if (remainingMs <= 0) {
@@ -537,19 +580,24 @@ export async function createOpenClawTestInstance(
537580
await waitForGatewayReady(attempt, stdout, stderr, port, remainingMs);
538581
return;
539582
} catch (err) {
540-
const closed = await releaseGatewayChild(attempt, deadline);
583+
const exitCode = attempt.exitCode;
584+
const signalCode = attempt.signalCode;
585+
const closed = await releaseGatewayChild(attempt, deadline, {
586+
forceWindowsTree: true,
587+
});
541588
const shouldRestart =
542-
closed &&
543589
restarts < GATEWAY_MIGRATION_CONVERGENCE_MAX_RESTARTS &&
544590
isGatewayMigrationConvergenceRefusal(
545-
attempt.exitCode,
546-
attempt.signalCode,
591+
exitCode,
592+
signalCode,
547593
readLogBuffer(attemptStderr),
548594
);
549595
if (shouldRestart && Date.now() < deadline) {
550-
restarts += 1;
551-
appendLogChunk(stderr, GATEWAY_MIGRATION_CONVERGENCE_RESTART_MARKER);
552-
continue;
596+
if (closed) {
597+
restarts += 1;
598+
appendLogChunk(stderr, GATEWAY_MIGRATION_CONVERGENCE_RESTART_MARKER);
599+
continue;
600+
}
553601
}
554602
throw err;
555603
}
@@ -651,5 +699,6 @@ export const testing = {
651699
hasChildExited,
652700
isGatewayMigrationConvergenceRefusal,
653701
signalOpenClawTestProcess,
702+
stopGatewayProcess,
654703
waitForGatewayReady,
655704
};

0 commit comments

Comments
 (0)