Skip to content

Commit c40faef

Browse files
authored
fix(test): wait for gateway readiness and isolate reset-heavy suite (#117725)
* fix(ci): isolate gateway readiness and subagent reset tests * fix(ci): isolate gateway readiness and subagent reset tests * fix(test): wait for gateway readiness in shared fixture * test(agents): isolate announce loop guard suite * fix(test): observe gateway exit during readiness * test: narrow gateway readiness process contract
1 parent 37c4a55 commit c40faef

3 files changed

Lines changed: 139 additions & 25 deletions

File tree

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

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// OpenClaw test instance tests cover spawned test instance lifecycle.
2+
import { EventEmitter } from "node:events";
23
import fs from "node:fs/promises";
34
import path from "node:path";
45
import { describe, expect, it, vi } from "vitest";
@@ -14,6 +15,16 @@ async function expectPathMissing(targetPath: string): Promise<void> {
1415
throw new Error(`Expected missing path: ${targetPath}`);
1516
}
1617

18+
function createGatewayProcessState(
19+
overrides: Partial<{ exitCode: number | null; signalCode: NodeJS.Signals | null }> = {},
20+
) {
21+
return Object.assign(new EventEmitter(), {
22+
exitCode: null as number | null,
23+
signalCode: null as NodeJS.Signals | null,
24+
...overrides,
25+
});
26+
}
27+
1728
describe("openclaw test instance", () => {
1829
it("keeps only bounded child output tails in helper logs", () => {
1930
const stdout = testing.createBoundedStringLog();
@@ -40,8 +51,67 @@ describe("openclaw test instance", () => {
4051

4152
it("fails startup waits immediately after signaled gateway exits", async () => {
4253
await expect(
43-
testing.waitForPortOpen({ exitCode: null, signalCode: "SIGTERM" }, [], [], 1, 10_000),
44-
).rejects.toThrow("gateway exited before listening");
54+
testing.waitForGatewayReady(
55+
createGatewayProcessState({ signalCode: "SIGTERM" }),
56+
[],
57+
[],
58+
1,
59+
10_000,
60+
),
61+
).rejects.toThrow("gateway exited before readiness");
62+
});
63+
64+
it("waits until the gateway readiness probe reports ready", async () => {
65+
const fetchImpl = vi
66+
.fn<typeof fetch>()
67+
.mockResolvedValueOnce(
68+
new Response('{"ready":false,"failing":["startup-sidecars"]}', { status: 503 }),
69+
)
70+
.mockResolvedValueOnce(new Response('{"ready":true,"failing":[]}', { status: 200 }));
71+
72+
await expect(
73+
testing.waitForGatewayReady(createGatewayProcessState(), [], [], 12345, 1_000, fetchImpl),
74+
).resolves.toBeUndefined();
75+
76+
expect(fetchImpl).toHaveBeenCalledTimes(2);
77+
expect(fetchImpl.mock.calls[0]?.[0]).toBe("http://127.0.0.1:12345/readyz");
78+
});
79+
80+
it("keeps stalled readiness probes inside the startup deadline", async () => {
81+
const fetchImpl = vi.fn<typeof fetch>((_url, init) => {
82+
return new Promise((_resolve, reject) => {
83+
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
84+
});
85+
});
86+
const startedAt = Date.now();
87+
88+
await expect(
89+
testing.waitForGatewayReady(createGatewayProcessState(), [], [], 12345, 25, fetchImpl),
90+
).rejects.toThrow("timeout waiting for gateway readiness");
91+
92+
expect(fetchImpl).toHaveBeenCalledOnce();
93+
expect(Date.now() - startedAt).toBeLessThan(500);
94+
});
95+
96+
it("aborts a stalled readiness probe when the gateway exits", async () => {
97+
const processState = createGatewayProcessState();
98+
const fetchImpl = vi.fn<typeof fetch>((_url, init) => {
99+
return new Promise((_resolve, reject) => {
100+
init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true });
101+
});
102+
});
103+
const startedAt = Date.now();
104+
setTimeout(() => {
105+
processState.signalCode = "SIGTERM";
106+
processState.emit("exit", null, "SIGTERM");
107+
}, 25);
108+
109+
await expect(
110+
testing.waitForGatewayReady(processState, [], [], 12345, 5_000, fetchImpl),
111+
).rejects.toThrow("gateway exited before readiness");
112+
113+
expect(fetchImpl).toHaveBeenCalledOnce();
114+
expect(Date.now() - startedAt).toBeLessThan(500);
45115
});
46116

47117
it("signals test instance process groups on POSIX", () => {

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

Lines changed: 66 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,10 @@ type BoundedStringLog = string[] & {
7878
};
7979

8080
type OpenClawTestChildProcess = Pick<OpenClawTestProcess, "kill" | "pid">;
81+
type OpenClawTestProcessReadiness = Pick<OpenClawTestProcess, "exitCode" | "signalCode"> & {
82+
once: (event: "exit", listener: () => void) => unknown;
83+
off: (event: "exit", listener: () => void) => unknown;
84+
};
8185

8286
function createBoundedStringLog(): string[] {
8387
const log = [] as BoundedStringLog;
@@ -213,44 +217,83 @@ const getFreePort = async () => {
213217
return addr.port;
214218
};
215219

216-
async function waitForPortOpen(
217-
proc: Pick<OpenClawTestProcess, "exitCode" | "signalCode">,
220+
async function waitForGatewayReady(
221+
proc: OpenClawTestProcessReadiness,
218222
chunksOut: string[],
219223
chunksErr: string[],
220224
port: number,
221225
timeoutMs: number,
226+
fetchImpl: typeof fetch = fetch,
222227
) {
228+
const exitedBeforeReadinessError = () =>
229+
new Error(
230+
`gateway exited before readiness (code=${String(proc.exitCode)} signal=${String(
231+
proc.signalCode,
232+
)})\n${formatLogs(chunksOut, chunksErr)}`,
233+
);
223234
const startedAt = Date.now();
224235
while (Date.now() - startedAt < timeoutMs) {
225236
if (hasChildExited(proc)) {
226-
throw new Error(
227-
`gateway exited before listening (code=${String(proc.exitCode)} signal=${String(
228-
proc.signalCode,
229-
)})\n${formatLogs(chunksOut, chunksErr)}`,
230-
);
237+
throw exitedBeforeReadinessError();
231238
}
232239

240+
const remainingMs = timeoutMs - (Date.now() - startedAt);
241+
const attemptTimeoutMs = Math.min(1_000, Math.max(1, remainingMs));
242+
const probeAbort = new AbortController();
243+
let attemptTimeout: ReturnType<typeof setTimeout> | undefined;
244+
let handleExit = () => {};
245+
const exitPromise = new Promise<never>((_resolve, reject) => {
246+
handleExit = () => {
247+
const error = exitedBeforeReadinessError();
248+
probeAbort.abort(error);
249+
reject(error);
250+
};
251+
proc.once("exit", handleExit);
252+
});
253+
const timeoutPromise = new Promise<never>((_resolve, reject) => {
254+
attemptTimeout = setTimeout(() => {
255+
const error = new Error("gateway readiness probe timed out");
256+
probeAbort.abort(error);
257+
reject(error);
258+
}, attemptTimeoutMs);
259+
attemptTimeout.unref?.();
260+
});
233261
try {
234-
await new Promise<void>((resolve, reject) => {
235-
const socket = net.connect({ host: "127.0.0.1", port });
236-
socket.once("connect", () => {
237-
socket.destroy();
238-
resolve();
239-
});
240-
socket.once("error", (err) => {
241-
socket.destroy();
242-
reject(err);
243-
});
244-
});
245-
return;
262+
// A dead child cannot complete readiness. Race the owner lifecycle against
263+
// both HTTP headers and body parsing so a stuck probe never hides its exit.
264+
const ready = await Promise.race([
265+
(async () => {
266+
const response = await fetchImpl(`http://127.0.0.1:${port}/readyz`, {
267+
signal: probeAbort.signal,
268+
});
269+
const readiness: unknown = await response.json();
270+
return response.ok && isRecord(readiness) && readiness.ready === true;
271+
})(),
272+
exitPromise,
273+
timeoutPromise,
274+
]);
275+
if (ready) {
276+
return;
277+
}
246278
} catch {
279+
if (hasChildExited(proc)) {
280+
throw exitedBeforeReadinessError();
281+
}
247282
// keep polling
283+
} finally {
284+
if (attemptTimeout) {
285+
clearTimeout(attemptTimeout);
286+
}
287+
proc.off("exit", handleExit);
248288
}
249289

250-
await sleep(10);
290+
const delayMs = Math.min(10, timeoutMs - (Date.now() - startedAt));
291+
if (delayMs > 0) {
292+
await sleep(delayMs);
293+
}
251294
}
252295
throw new Error(
253-
`timeout waiting for gateway to listen on port ${port}\n${formatLogs(chunksOut, chunksErr)}`,
296+
`timeout waiting for gateway readiness on port ${port}\n${formatLogs(chunksOut, chunksErr)}`,
254297
);
255298
}
256299

@@ -415,7 +458,7 @@ export async function createOpenClawTestInstance(
415458
child.stderr?.on("data", (d) => appendLogChunk(stderr, d));
416459

417460
try {
418-
await waitForPortOpen(
461+
await waitForGatewayReady(
419462
child,
420463
stdout,
421464
stderr,
@@ -539,5 +582,5 @@ export const testing = {
539582
formatLogs,
540583
hasChildExited,
541584
signalOpenClawTestProcess,
542-
waitForPortOpen,
585+
waitForGatewayReady,
543586
};

‎test/vitest/vitest.agents-paths.mjs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ const coreIsolatedFiles = [
1414
"src/agents/model-selection.plugin-runtime.test.ts",
1515
"src/agents/models-config.runtime-source-snapshot.test.ts",
1616
"src/agents/openai-transport-stream.streaming.test.ts",
17+
"src/agents/subagent-registry.announce-loop-guard.test.ts",
1718
"src/agents/subagent-registry-restart-recovery.test.ts",
1819
"src/agents/video-generation-task-status.test.ts",
1920
];

0 commit comments

Comments
 (0)