Skip to content

Commit 44b79d4

Browse files
authored
test(agents): stabilize one-shot host exit wait (#109663)
1 parent 883995f commit 44b79d4

1 file changed

Lines changed: 90 additions & 26 deletions

File tree

‎src/agents/provider-local-service.test.ts‎

Lines changed: 90 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Verifies managed local provider services start, lease, probe, and stop safely.
22
import { spawn } from "node:child_process";
3+
import { once } from "node:events";
34
import fs from "node:fs/promises";
45
import http from "node:http";
56
import net from "node:net";
@@ -23,6 +24,10 @@ import {
2324
stopManagedProviderLocalServicesForTest,
2425
} from "./provider-local-service.js";
2526

27+
const ONE_SHOT_HOST_READY_TIMEOUT_MS = 30_000;
28+
const ONE_SHOT_HOST_EXIT_TIMEOUT_MS = 5_000;
29+
const ONE_SHOT_HOST_READY_KIND = "ready-for-exit";
30+
2631
async function freePort(): Promise<number> {
2732
// Allocate a real loopback port to exercise child process health probes.
2833
return await new Promise((resolve, reject) => {
@@ -104,6 +109,75 @@ async function withSpawnReadyHealthProbe<T>(run: () => Promise<T>): Promise<T> {
104109
}
105110
}
106111

112+
async function waitForReadyOneShotHostExit(
113+
child: ReturnType<typeof spawn>,
114+
readStderr: () => string,
115+
): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
116+
await new Promise<void>((resolve, reject) => {
117+
const cleanup = () => {
118+
clearTimeout(timeout);
119+
child.off("message", onMessage);
120+
child.off("error", onError);
121+
child.off("exit", onExit);
122+
};
123+
const finish = (error?: Error) => {
124+
cleanup();
125+
if (error) {
126+
reject(error);
127+
} else {
128+
resolve();
129+
}
130+
};
131+
const onMessage = (message: unknown) => {
132+
if (
133+
message &&
134+
typeof message === "object" &&
135+
(message as { kind?: unknown }).kind === ONE_SHOT_HOST_READY_KIND
136+
) {
137+
finish();
138+
}
139+
};
140+
const onError = (error: Error) => finish(error);
141+
const onExit = (code: number | null, signal: NodeJS.Signals | null) => {
142+
finish(
143+
new Error(
144+
`one-shot host exited before readiness (code=${String(code)} signal=${String(signal)})${readStderr()}`,
145+
),
146+
);
147+
};
148+
const timeout = setTimeout(() => {
149+
finish(new Error(`one-shot host did not become ready${readStderr()}`));
150+
}, ONE_SHOT_HOST_READY_TIMEOUT_MS);
151+
152+
child.on("message", onMessage);
153+
child.on("error", onError);
154+
child.on("exit", onExit);
155+
});
156+
157+
const exitPromise = waitForOneShotHostExit(child, readStderr);
158+
// The fixture-owned IPC channel gates the exit deadline. Once removed,
159+
// only the managed service's diagnostic pipes can keep this host alive.
160+
child.disconnect();
161+
return await exitPromise;
162+
}
163+
164+
async function waitForOneShotHostExit(
165+
child: ReturnType<typeof spawn>,
166+
readStderr: () => string,
167+
): Promise<{ code: number | null; signal: NodeJS.Signals | null }> {
168+
if (child.exitCode !== null || child.signalCode !== null) {
169+
return { code: child.exitCode, signal: child.signalCode };
170+
}
171+
try {
172+
const [code, signal] = (await once(child, "exit", {
173+
signal: AbortSignal.timeout(ONE_SHOT_HOST_EXIT_TIMEOUT_MS),
174+
})) as [number | null, NodeJS.Signals | null];
175+
return { code, signal };
176+
} catch (error) {
177+
throw new Error(`one-shot host did not exit after readiness${readStderr()}`, { cause: error });
178+
}
179+
}
180+
107181
describe("provider local service", () => {
108182
const tempDirs = useAutoCleanupTempDirTracker(afterEach);
109183

@@ -693,6 +767,8 @@ describe("provider local service", () => {
693767
const script = [
694768
`import fs from "node:fs/promises";`,
695769
`import { ensureProviderLocalService, getManagedProviderLocalServiceDiagnosticsForTest } from ${JSON.stringify(moduleUrl)};`,
770+
`if (!process.send) throw new Error("missing one-shot host IPC");`,
771+
`process.on("disconnect", () => {});`,
696772
`const port = ${port};`,
697773
`const lease = await ensureProviderLocalService({`,
698774
` providerId: "local-unref",`,
@@ -709,37 +785,28 @@ describe("provider local service", () => {
709785
`if (diagnostics.stdoutTail || diagnostics.stderrTail) throw new Error("runtime output was retained");`,
710786
`await fs.writeFile(${JSON.stringify(servicePidPath)}, String(diagnostics.pid));`,
711787
`lease?.release();`,
788+
`process.send({ kind: ${JSON.stringify(ONE_SHOT_HOST_READY_KIND)} });`,
712789
].join("\n");
713790
const parent = spawn(
714791
process.execPath,
715792
["--import", "tsx", "--input-type=module", "-e", script],
716793
{
717794
cwd: process.cwd(),
718-
stdio: ["ignore", "ignore", "pipe"],
795+
stdio: ["ignore", "ignore", "pipe", "ipc"],
719796
},
720797
);
721798
let stderr = "";
722-
parent.stderr.on("data", (chunk: Buffer | string) => {
799+
parent.stderr?.on("data", (chunk: Buffer | string) => {
723800
stderr += chunk.toString();
724801
});
725802
let servicePid: number | undefined;
726-
let exitTimeout: NodeJS.Timeout | undefined;
727803

728804
try {
729-
const result = await Promise.race([
730-
new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {
731-
parent.once("exit", (code, signal) => resolve({ code, signal }));
732-
}),
733-
new Promise<"timeout">((resolve) => {
734-
exitTimeout = setTimeout(() => resolve("timeout"), 5_000);
735-
}),
736-
]);
737-
clearTimeout(exitTimeout);
805+
const result = await waitForReadyOneShotHostExit(parent, () => stderr);
738806
expect(result, stderr).toEqual({ code: 0, signal: null });
739807
servicePid = await readPidFile(servicePidPath);
740808
expect(await waitForPidToExit(servicePid)).toBe(true);
741809
} finally {
742-
clearTimeout(exitTimeout);
743810
killPidIfAlive(parent.pid);
744811
if (servicePid === undefined) {
745812
servicePid = await readPidFile(servicePidPath).catch(() => undefined);
@@ -761,6 +828,8 @@ describe("provider local service", () => {
761828
].join("");
762829
const script = [
763830
`import { ensureProviderLocalService } from ${JSON.stringify(moduleUrl)};`,
831+
`if (!process.send) throw new Error("missing one-shot host IPC");`,
832+
`process.on("disconnect", () => {});`,
764833
`try {`,
765834
` await ensureProviderLocalService({`,
766835
` providerId: "local-failed-unref",`,
@@ -772,32 +841,27 @@ describe("provider local service", () => {
772841
` },`,
773842
` });`,
774843
`} catch {}`,
844+
`process.send({ kind: ${JSON.stringify(ONE_SHOT_HOST_READY_KIND)} });`,
775845
].join("\n");
776846
const parent = spawn(
777847
process.execPath,
778848
["--import", "tsx", "--input-type=module", "-e", script],
779849
{
780850
cwd: process.cwd(),
781-
stdio: ["ignore", "ignore", "ignore"],
851+
stdio: ["ignore", "ignore", "pipe", "ipc"],
782852
},
783853
);
854+
let stderr = "";
855+
parent.stderr?.on("data", (chunk: Buffer | string) => {
856+
stderr += chunk.toString();
857+
});
784858
let servicePid: number | undefined;
785-
let exitTimeout: NodeJS.Timeout | undefined;
786859

787860
try {
788-
const result = await Promise.race([
789-
new Promise<{ code: number | null; signal: NodeJS.Signals | null }>((resolve) => {
790-
parent.once("exit", (code, signal) => resolve({ code, signal }));
791-
}),
792-
new Promise<"timeout">((resolve) => {
793-
exitTimeout = setTimeout(() => resolve("timeout"), 5_000);
794-
}),
795-
]);
796-
clearTimeout(exitTimeout);
797-
expect(result).toEqual({ code: 0, signal: null });
861+
const result = await waitForReadyOneShotHostExit(parent, () => stderr);
862+
expect(result, stderr).toEqual({ code: 0, signal: null });
798863
servicePid = await readPidFile(servicePidPath);
799864
} finally {
800-
clearTimeout(exitTimeout);
801865
killPidIfAlive(parent.pid);
802866
if (servicePid === undefined) {
803867
servicePid = await readPidFile(servicePidPath).catch(() => undefined);

0 commit comments

Comments
 (0)