Skip to content

Commit 5f14acd

Browse files
committed
test: enforce gateway retry and drain ordering
1 parent 44646bb commit 5f14acd

1 file changed

Lines changed: 92 additions & 27 deletions

File tree

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

Lines changed: 92 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// OpenClaw test instance tests cover spawned test instance lifecycle.
2-
import { EventEmitter } from "node:events";
2+
import { EventEmitter, once } from "node:events";
33
import fs from "node:fs/promises";
44
import { createServer } from "node:http";
55
import { tmpdir } from "node:os";
@@ -9,7 +9,7 @@ import { setTimeout as delay } from "node:timers/promises";
99
import { afterEach, describe, expect, it, vi } from "vitest";
1010
import { createOpenClawTestInstance, testing } from "./openclaw-test-instance.js";
1111
import { isProcessAlive } from "./process-wait.js";
12-
import { createDeferred } from "./promise.js";
12+
import { createDeferred, withTestTimeout } from "./promise.js";
1313

1414
const MIGRATION_CONVERGENCE_REFUSAL =
1515
"OpenClaw plugin migration inputs changed during startup convergence;";
@@ -189,7 +189,11 @@ const kind = (process.env.OPENCLAW_FAKE_GATEWAY_SEQUENCE || "ready").split(",")[
189189
process.stdout.write("fake gateway attempt " + attempt + "\\n");
190190
const refusal = ${JSON.stringify(MIGRATION_CONVERGENCE_REFUSAL)};
191191
if (kind === "refuse") { process.stderr.write(refusal + " fixture\\n"); process.exit(1); }
192-
if (kind === "late-refuse") { const delayed = spawn(process.execPath, ["-e", 'setTimeout(() => process.stderr.write(process.argv[1]), 50)', refusal + " delayed fixture\\n"], { stdio: ["ignore", "ignore", "inherit"] }); recordFixtureProcess(delayed.pid); process.exit(1); }
192+
if (kind === "late-refuse") {
193+
const delayed = spawn(process.execPath, ["-e", 'require("node:http").get(process.argv[1] + "/wait", (response) => { response.resume(); response.on("end", () => process.stderr.write(process.argv[2], () => process.exit(0))); });', controlUrl, refusal + " delayed fixture\\n"], { stdio: ["ignore", "ignore", "inherit"] });
194+
recordFixtureProcess(delayed.pid);
195+
process.exit(1);
196+
}
193197
if (kind === "resist-after-exit") {
194198
const resistant = spawn(process.execPath, ["-e", 'const fs = require("node:fs");fs.writeFileSync(process.argv[1], String(process.pid));process.on("SIGTERM", () => fs.appendFileSync(process.argv[2], "SIGTERM"));process.send("ready");setInterval(() => {}, 1_000);', tracePath + ".resistant-pid", tracePath + ".signals"], { stdio: ["ignore", "ignore", "inherit", "ipc"] });
195199
await new Promise((resolve) => resistant.once("message", resolve));
@@ -394,8 +398,41 @@ describe("openclaw test instance", () => {
394398
it.each(["refuse", "late-refuse"])(
395399
"restarts one %s refusal with identical launch state and owns the ready child",
396400
async (refusalAction) => {
397-
const { instance, readAttempts } = await createFakeGateway(`${refusalAction},ready`);
398-
await instance.startGateway();
401+
const control = refusalAction === "late-refuse" ? await createGatewayControl() : undefined;
402+
const { instance, readAttempts } = await createFakeGateway(
403+
`${refusalAction},ready`,
404+
1_000,
405+
1_500,
406+
control,
407+
);
408+
const exited = createDeferred<{ code: number | null; signal: NodeJS.Signals | null }>();
409+
if (control) {
410+
control.observers.onLaunch = () => {
411+
if (control.launches.length !== 1) return;
412+
const leader = instance.child;
413+
if (!leader) {
414+
exited.reject(new Error("fixture launched without a process owner"));
415+
return;
416+
}
417+
leader.once("exit", (code, signal) => exited.resolve({ code, signal }));
418+
};
419+
}
420+
const startup = trackOperation(instance.startGateway());
421+
try {
422+
if (control) {
423+
expect(await Promise.race([exited.promise, startup])).toEqual({ code: 1, signal: null });
424+
await Promise.race([control.reached, startup]);
425+
expect(instance.child?.stderr.closed).toBe(false);
426+
expect(instance.logs()).not.toContain(MIGRATION_CONVERGENCE_REFUSAL);
427+
// /launch installs the exit observer before the leader proceeds. Only
428+
// release its waiting stderr writer after that native exit, never a timer.
429+
await control.release();
430+
}
431+
await startup;
432+
} finally {
433+
control?.unblock();
434+
await Promise.allSettled([startup]);
435+
}
399436
const attempts = await readAttempts();
400437
expect(attempts).toHaveLength(2);
401438
expect(attempts[0]?.pid).not.toBe(attempts[1]?.pid);
@@ -511,35 +548,63 @@ describe("openclaw test instance", () => {
511548
it.runIf(process.platform !== "win32")(
512549
"reaps terminal children with inherited stdio before starting a new gateway",
513550
async () => {
551+
const stopTimeoutMs = 100;
514552
const { instance, readAttempts, tracePath } = await createFakeGateway(
515553
"terminal-drain,ready",
516554
300,
517-
100,
555+
stopTimeoutMs,
518556
);
519557

520-
const startupError = await instance.startGateway().catch((error: unknown) => error);
521-
expect(startupError).toBeInstanceOf(Error);
522-
expect((startupError as Error).message).toContain(
523-
"gateway exited before readiness (code=7 signal=null)",
524-
);
525-
expect((startupError as Error).message).toContain("terminal startup failure");
526-
expect(instance.child?.exitCode).toBe(7);
527-
expect(instance.child?.stderr.closed).toBe(false);
528-
const firstAttempt = (await readAttempts())[0];
529-
const drainingPid = Number(await fs.readFile(`${tracePath}.draining-pid`, "utf8"));
530-
expect(isProcessAlive(drainingPid)).toBe(true);
558+
const startup = trackOperation(instance.startGateway());
559+
try {
560+
const startupError = await startup.catch((error: unknown) => error);
561+
expect(startupError).toBeInstanceOf(Error);
562+
expect((startupError as Error).message).toContain(
563+
"gateway exited before readiness (code=7 signal=null)",
564+
);
565+
expect((startupError as Error).message).toContain("terminal startup failure");
566+
const firstChild = instance.child;
567+
expect(firstChild?.exitCode).toBe(7);
568+
expect(firstChild?.stderr.closed).toBe(false);
569+
if (!firstChild) throw new Error("terminal fixture lost its process owner");
570+
const firstAttempt = (await readAttempts())[0];
571+
const drainingPid = Number(await fs.readFile(`${tracePath}.draining-pid`, "utf8"));
572+
expect(isProcessAlive(drainingPid)).toBe(true);
531573

532-
await fs.writeFile(`${tracePath}.draining-release`, "");
533-
await instance.startGateway();
574+
// Keep the inherited pipe held through a complete failed restart: eventual
575+
// replacement after release alone cannot prove that stale ownership blocked it.
576+
await expect(trackOperation(instance.startGateway())).rejects.toThrow(
577+
new Error(`gateway process did not close before stop deadline\n${instance.logs()}`),
578+
);
579+
expect(instance.child).toBe(firstChild);
580+
expect(firstChild.stderr.closed).toBe(false);
581+
expect(isProcessAlive(drainingPid)).toBe(true);
582+
expect(await readAttempts()).toHaveLength(1);
534583

535-
const attempts = await readAttempts();
536-
expect(attempts).toHaveLength(2);
537-
expect(attempts[1]?.pid).not.toBe(firstAttempt?.pid);
538-
expect(instance.child?.pid).toBe(attempts[1]?.pid);
539-
await instance.stopGateway();
540-
expect(instance.child).toBeUndefined();
541-
expect(isProcessAlive(attempts[1]?.pid as number)).toBe(false);
542-
await expect.poll(() => isProcessAlive(drainingPid), { timeout: 500 }).toBe(false);
584+
// Register before release, but charge only post-release drain to the stop budget.
585+
const closed = trackOperation(once(firstChild, "close"));
586+
await fs.writeFile(`${tracePath}.draining-release`, "");
587+
await withTestTimeout(
588+
closed,
589+
stopTimeoutMs * 2,
590+
"terminal fixture did not close after release",
591+
);
592+
expect(firstChild.stdout.closed).toBe(true);
593+
expect(firstChild.stderr.closed).toBe(true);
594+
await trackOperation(instance.startGateway());
595+
596+
const attempts = await readAttempts();
597+
expect(attempts).toHaveLength(2);
598+
expect(attempts[1]?.pid).not.toBe(firstAttempt?.pid);
599+
expect(instance.child?.pid).toBe(attempts[1]?.pid);
600+
await instance.stopGateway();
601+
expect(instance.child).toBeUndefined();
602+
expect(isProcessAlive(attempts[1]?.pid as number)).toBe(false);
603+
await expect.poll(() => isProcessAlive(drainingPid), { timeout: 500 }).toBe(false);
604+
} finally {
605+
await fs.writeFile(`${tracePath}.draining-release`, "");
606+
await Promise.allSettled([startup]);
607+
}
543608
},
544609
);
545610

0 commit comments

Comments
 (0)