Skip to content

Commit 6e87d3b

Browse files
authored
test: gateway and CLI process-test hygiene (#118042)
* test: gateway and CLI process-test hygiene * test: preserve CLI process timeout diagnostics
1 parent c40180b commit 6e87d3b

5 files changed

Lines changed: 107 additions & 40 deletions

File tree

‎src/cli/help-exit.process.test.ts‎

Lines changed: 87 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
11
// Process coverage for CLI help exits and route-first fallback validation.
2-
import { execFile } from "node:child_process";
2+
import { spawn } from "node:child_process";
3+
import { once } from "node:events";
34
import fs from "node:fs/promises";
45
import path from "node:path";
56
import { pathToFileURL } from "node:url";
6-
import { promisify } from "node:util";
77
import { Command, CommanderError } from "commander";
88
import { afterEach, describe, expect, it } from "vitest";
99
import { useAutoCleanupTempDirTracker } from "../../test/helpers/temp-dir.js";
10+
import { DEFAULT_VITEST_TEST_TIMEOUT_MS } from "../../test/vitest/vitest.timeouts.js";
1011
import { registerCoreCliByName } from "./program/command-registry.js";
1112
import { createProgramContext } from "./program/context.js";
1213
import { registerSubCliByName } from "./program/register.subclis.js";
1314

14-
const execFileAsync = promisify(execFile);
1515
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
1616
// This is a deadlock guard, not a startup SLO. Fork CI can take over a minute
1717
// to cold-load the CLI graph on shared hosted runners, while still exiting correctly.
18-
// It must stay below Vitest's 120s testTimeout so a hung child fails through
19-
// execFile with captured stdout/stderr instead of a blind vitest test timeout.
20-
const CHILD_PROCESS_TIMEOUT_MS = 100_000;
18+
// Keep the default guard below the shared Vitest deadline so it always reports
19+
// captured child output before the framework can replace it with an opaque timeout.
20+
const DEFAULT_CHILD_PROCESS_TIMEOUT_MS = DEFAULT_VITEST_TEST_TIMEOUT_MS - 20_000;
21+
const SLOW_DOTENV_CHILD_PROCESS_TIMEOUT_MS = 240_000;
22+
const SLOW_DOTENV_TEST_TIMEOUT_MS = SLOW_DOTENV_CHILD_PROCESS_TIMEOUT_MS + 10_000;
2123
const LAZY_GROUP_HELP_CASES = [
2224
{ group: "backup", usageCommand: "backup", registry: "core" },
2325
{ group: "capability", usageCommand: "infer|capability", registry: "subcli" },
@@ -141,6 +143,7 @@ async function runCliProcess(params: {
141143
loggingViaInclude?: boolean;
142144
loggingViaRootInclude?: boolean;
143145
stateEnv?: (stateDir: string) => Record<string, string>;
146+
timeoutMs?: number;
144147
}) {
145148
const fixture = await createHelpProcessFixture(
146149
params.config,
@@ -153,7 +156,7 @@ async function runCliProcess(params: {
153156
);
154157
await fs.writeFile(path.join(fixture.stateDir, ".env"), `${lines.join("\n")}\n`);
155158
}
156-
const result = await execFileAsync(
159+
const child = spawn(
157160
process.execPath,
158161
[
159162
...(params.forbidTlsImport
@@ -174,14 +177,13 @@ async function runCliProcess(params: {
174177
],
175178
{
176179
cwd: path.resolve("."),
177-
encoding: "utf8",
178180
env: {
179181
...process.env,
180182
HOME: fixture.root,
181183
// CI shard runners export NODE_COMPILE_CACHE; in a source checkout entry.ts
182184
// then respawns a detached grandchild that shares this child's stdio pipes.
183185
// If the deadlock guard SIGKILLs the parent, the orphan keeps the pipes open
184-
// and execFile never settles, turning any slow child into a blind vitest
186+
// and the process wait never settles, turning any slow child into a blind vitest
185187
// timeout with no diagnostics. Keep these children single-process; the
186188
// compile-cache respawn contract has dedicated entry.compile-cache coverage.
187189
NODE_DISABLE_COMPILE_CACHE: "1",
@@ -195,11 +197,55 @@ async function runCliProcess(params: {
195197
VITEST: undefined,
196198
...params.env,
197199
},
198-
killSignal: "SIGKILL",
199-
timeout: CHILD_PROCESS_TIMEOUT_MS,
200+
stdio: ["ignore", "pipe", "pipe"],
200201
},
201202
);
202-
return { ...result, fixture };
203+
child.stdout.setEncoding("utf8");
204+
child.stderr.setEncoding("utf8");
205+
let stdout = "";
206+
let stderr = "";
207+
child.stdout.on("data", (chunk: string) => {
208+
stdout += chunk;
209+
});
210+
child.stderr.on("data", (chunk: string) => {
211+
stderr += chunk;
212+
});
213+
214+
const stdoutEnded = once(child.stdout, "end");
215+
const stderrEnded = once(child.stderr, "end");
216+
let timeout: NodeJS.Timeout | undefined;
217+
const exit = await Promise.race([
218+
Promise.all([once(child, "exit"), stdoutEnded, stderrEnded]).then(([[code, signal]]) => ({
219+
code: code as number | null,
220+
signal: signal as NodeJS.Signals | null,
221+
})),
222+
new Promise<never>((_, reject) => {
223+
timeout = setTimeout(() => {
224+
child.kill("SIGKILL");
225+
reject(
226+
Object.assign(new Error("CLI process did not exit before the deadlock guard"), {
227+
code: child.exitCode,
228+
signal: child.signalCode,
229+
stderr,
230+
stdout,
231+
}),
232+
);
233+
}, params.timeoutMs ?? DEFAULT_CHILD_PROCESS_TIMEOUT_MS);
234+
timeout.unref();
235+
}),
236+
]).finally(() => {
237+
if (timeout) {
238+
clearTimeout(timeout);
239+
}
240+
});
241+
if (exit.code !== 0) {
242+
throw Object.assign(new Error(`CLI process exited with code ${exit.code}`), {
243+
...exit,
244+
stderr,
245+
stdout,
246+
});
247+
}
248+
return { stderr, stdout, fixture };
203249
}
204250

205251
function parseJsonLines(stdout: string): Array<Record<string, unknown>> {
@@ -603,32 +649,37 @@ describe("JSON console style process output", () => {
603649
);
604650
});
605651

606-
it("loads dotenv before formatting entry validation diagnostics", async () => {
607-
let failure: CliProcessFailure | undefined;
608-
try {
609-
await runCliProcess({
610-
args: ["--container"],
611-
config: {
612-
logging: {
613-
consoleStyle: "${OPENCLAW_TEST_CONSOLE_STYLE}",
614-
level: "silent",
652+
it(
653+
"captures exact exit code 2 after loading dotenv for entry validation diagnostics",
654+
async () => {
655+
let failure: CliProcessFailure | undefined;
656+
try {
657+
await runCliProcess({
658+
args: ["--container"],
659+
config: {
660+
logging: {
661+
consoleStyle: "${OPENCLAW_TEST_CONSOLE_STYLE}",
662+
level: "silent",
663+
},
615664
},
616-
},
617-
env: { OPENCLAW_TEST_CONSOLE_STYLE: undefined },
618-
stateEnv: () => ({ OPENCLAW_TEST_CONSOLE_STYLE: "json" }),
619-
});
620-
} catch (error) {
621-
failure = error as CliProcessFailure;
622-
}
665+
env: { OPENCLAW_TEST_CONSOLE_STYLE: undefined },
666+
stateEnv: () => ({ OPENCLAW_TEST_CONSOLE_STYLE: "json" }),
667+
timeoutMs: SLOW_DOTENV_CHILD_PROCESS_TIMEOUT_MS,
668+
});
669+
} catch (error) {
670+
failure = error as CliProcessFailure;
671+
}
623672

624-
expect(failure?.code).toBe(2);
625-
expect(parseJsonLines(failure?.stderr ?? "")).toEqual([
626-
expect.objectContaining({
627-
level: "error",
628-
message: expect.stringContaining("--container requires a value"),
629-
}),
630-
]);
631-
});
673+
expect(failure?.code).toBe(2);
674+
expect(parseJsonLines(failure?.stderr ?? "")).toEqual([
675+
expect.objectContaining({
676+
level: "error",
677+
message: expect.stringContaining("--container requires a value"),
678+
}),
679+
]);
680+
},
681+
SLOW_DOTENV_TEST_TIMEOUT_MS,
682+
);
632683

633684
it("loads eligible dotenv before formatting a run-main import failure", async () => {
634685
let failure: CliProcessFailure | undefined;

‎src/gateway/server-startup-model-runtime.event-loop.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,6 @@ describe("Gateway prepared model runtime startup", () => {
150150
startup: {
151151
sidecar: false,
152152
memory: false,
153-
deferConfiguredChannelFullLoadUntilAfterListen: false,
154153
agentHarnesses: [],
155154
},
156155
compat: [],

‎src/gateway/server.startup-websocket-race.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Startup WebSocket race tests ensure upgrade handlers are attached before the
22
// gateway reports its listen step as ready.
3-
import { afterEach, describe, expect, it, vi } from "vitest";
3+
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
44
import { WebSocket } from "ws";
55
import { tryListenOnPort } from "../infra/ports-probe.js";
66
import { getFreePort, installGatewayTestHooks, startGatewayServer } from "./test-helpers.js";
@@ -11,6 +11,17 @@ type GatewayServerForTest = Awaited<ReturnType<StartGatewayServer>>;
1111

1212
installGatewayTestHooks({ scope: "suite" });
1313

14+
let loopbackAliasBindable = false;
15+
16+
beforeAll(async () => {
17+
try {
18+
await tryListenOnPort({ host: "127.0.0.2", port: 0, exclusive: true });
19+
loopbackAliasBindable = true;
20+
} catch {
21+
loopbackAliasBindable = false;
22+
}
23+
});
24+
1425
async function connectWebSocket(url: string): Promise<WebSocket> {
1526
const ws = new WebSocket(url);
1627
return await new Promise<WebSocket>((resolve, reject) => {
@@ -90,7 +101,11 @@ describe("gateway startup websocket readiness", () => {
90101
}
91102
});
92103

93-
it("serves a specific IPv4 bind and its required loopback alias", async () => {
104+
it("serves a specific IPv4 bind and its required loopback alias", async ({ skip }) => {
105+
if (!loopbackAliasBindable) {
106+
skip("127.0.0.2 is not bindable on this host");
107+
return;
108+
}
94109
const previousMinimal = process.env.OPENCLAW_TEST_MINIMAL_GATEWAY;
95110
process.env.OPENCLAW_TEST_MINIMAL_GATEWAY = "0";
96111
let server: GatewayServerForTest | undefined;

‎test/vitest/vitest.shared.config.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
} from "./vitest.bundled-plugin-paths.ts";
2323
import { loadVitestExperimentalConfig } from "./vitest.performance-config.ts";
2424
import { shouldPrintVitestThrottle } from "./vitest.system-load.ts";
25+
import { DEFAULT_VITEST_TEST_TIMEOUT_MS } from "./vitest.timeouts.ts";
2526

2627
export type OpenClawVitestPool = "forks" | "threads";
2728

@@ -555,7 +556,7 @@ export const sharedVitestConfig = {
555556
},
556557
test: {
557558
dir: repoRoot,
558-
testTimeout: 120_000,
559+
testTimeout: DEFAULT_VITEST_TEST_TIMEOUT_MS,
559560
hookTimeout: isWindows ? 180_000 : 120_000,
560561
unstubEnvs: true,
561562
unstubGlobals: true,

‎test/vitest/vitest.timeouts.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export const DEFAULT_VITEST_TEST_TIMEOUT_MS = 120_000;

0 commit comments

Comments
 (0)