fix(browser): preserve terminal verifier startup outcomes (#13228)

This commit is contained in:
morluto authored and GitHub committed 2026-11-21 22:45:18 +00:00
1 parent 60e099848d
commit 39ccb1d3b8
3 files changed
+112 -96

No files matched your search

+22 -21
View File
@@ -73,12 +73,13 @@ export const waitForBrowserDevtoolsPort = async (
const deadline = startedAt + timeoutMs;
try {
while (true) {
const terminalState = currentTerminalState(options.child);
if (terminalState !== null)
throw startupError(options, startedAt, timeoutMs, terminalState);
const terminalState = currentTerminalState(options.child);
if (terminalState !== null)
throw startupError(options, startedAt, timeoutMs, terminalState);
while (true) {
const port = await readDevtoolsPort(options.activePortPath);
if (terminal.failure !== undefined) throw terminal.failure;
if (port !== null) return port;
const remainingMs = deadline - performance.now();
@@ -108,34 +109,34 @@ const childTermination = (
options: BrowserStartupOptions,
startedAt: number,
startupTimeoutMs: number,
): { readonly outcome: Promise<BrowserStartupError>; close(): void } => {
): {
readonly failure: BrowserStartupError | undefined;
readonly outcome: Promise<BrowserStartupError>;
close(): void;
} => {
let failure: BrowserStartupError | undefined;
let onError: (cause: unknown) => void;
let onExit: () => void;
const outcome = new Promise<BrowserStartupError>((resolve) => {
onError = (cause: unknown) => {
resolve(
startupError(options, startedAt, startupTimeoutMs, {
failure: "spawn-error",
cause,
}),
);
const record = (state: TerminalState): void => {
failure ??= startupError(options, startedAt, startupTimeoutMs, state);
resolve(failure);
};
onError = (cause) => record({ failure: "spawn-error", cause });
onExit = () => {
resolve(
startupError(
options,
startedAt,
startupTimeoutMs,
options.child.signalCode === null
? { failure: "exited" }
: { failure: "signalled" },
),
record(
options.child.signalCode === null
? { failure: "exited" }
: { failure: "signalled" },
);
};
options.child.once("error", onError);
options.child.once("exit", onExit);
});
return {
get failure() {
return failure;
},
outcome,
close: () => {
options.child.off("error", onError);
@@ -1,4 +1,5 @@
import { readFile } from "node:fs/promises";
import { ChildProcess } from "node:child_process";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { describe, expect } from "vitest";
@@ -90,35 +91,24 @@ describe("browser process startup", () => {
});
});
it("reports bounded timeout diagnostics", async ({ processes }) => {
const root = await temporaryRoot();
const child = processes.spawn(process.execPath, [
"-e",
"setTimeout(() => {}, 1000)",
]);
try {
const failure = await waitForBrowserDevtoolsPort({
child,
it("reports bounded timeout diagnostics", async () => {
await expect(
waitForBrowserDevtoolsPort({
child: new ChildProcess(),
executable: process.execPath,
activePortPath: join(root, "DevToolsActivePort"),
activePortPath: join(await temporaryRoot(), "DevToolsActivePort"),
stderr: () => "",
timeoutMs: 20,
pollIntervalMs: 5,
}).catch((cause: unknown) => cause);
expect(failure).toBeInstanceOf(BrowserStartupError);
expect(failure).toMatchObject({
failure: "timeout",
exitCode: null,
signalCode: null,
startupTimeoutMs: 20,
});
expect(String(failure)).toContain("stderr=<empty>");
expect(String(failure)).toContain("timeoutMs=20");
} finally {
child.kill("SIGKILL");
expect(await waitForExit(child, 5_000)).toBe(true);
}
}),
).rejects.toMatchObject({
_tag: "BrowserStartupError",
failure: "timeout",
exitCode: null,
signalCode: null,
startupTimeoutMs: 20,
message: expect.stringMatching(/timeoutMs=20.*stderr=<empty>$/u),
});
});
it("names the owner's deadline when a caller omits one", async ({
@@ -148,21 +138,30 @@ describe("browser process startup", () => {
);
});
it("keeps one owner for the DevToolsActivePort deadline", async () => {
expect(BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS).toBe(60_000);
const source = await readFile(
new URL(
"../../../scripts/lib/browser-runtime-fixture-lifecycle.mjs",
import.meta.url,
),
"utf8",
);
expect(source).toContain(
"const deadline = performance.now() + BROWSER_DEVTOOLS_STARTUP_TIMEOUT_MS",
);
expect(source).toContain(
"timeoutMs: Math.max(1, deadline - performance.now())",
);
it("keeps a terminal startup outcome observed during a valid port read", async () => {
const portPath = join(await temporaryRoot(), "DevToolsActivePort");
await writeFile(portPath, "43117\n/devtools/browser/fixture");
const spawnError = new Error("fixture launch failed");
for (const failure of ["exited", "spawn-error"] as const) {
const child = new ChildProcess();
const pending = waitForBrowserDevtoolsPort({
child,
executable: process.execPath,
activePortPath: portPath,
stderr: () => "fixture startup diagnostic",
});
// The file read is in flight and already contains a valid port.
if (failure === "spawn-error") child.emit("error", spawnError);
Object.defineProperty(child, "exitCode", { value: 3 });
child.emit("exit", 3, null);
await expect(pending, failure).rejects.toMatchObject({
_tag: "BrowserStartupError",
failure,
exitCode: failure === "exited" ? 3 : null,
stderr: "fixture startup diagnostic",
...(failure === "spawn-error" ? { cause: spawnError } : {}),
});
}
});
});
@@ -1,8 +1,8 @@
import { ChildProcess } from "node:child_process";
import { createServer } from "node:http";
import { setImmediate } from "node:timers/promises";
import { afterEach, expect, it, vi } from "vitest";
import { z } from "zod";
import { CDP_DISCOVERY_RESPONSE_TIMEOUT_MS } from "../../../src/domain/browserDeadline.js";
import { phaseArrival } from "../../support/lifecycleHarness.js";
const mock = vi.hoisted(() => ({ spawn: vi.fn(), port: vi.fn() }));
@@ -64,23 +64,23 @@ const fixture = async (
mode: "empty targets" | "discovery timeout" | "malformed" | "exited",
) => {
let ready = false;
let requests = 0;
const requests: (string | undefined)[] = [];
const listed = phaseArrival();
const published = phaseArrival();
const stalled = phaseArrival();
const server = createServer((request, response) => {
requests += 1;
if (mode === "exited") {
listed.arrive();
return;
}
requests.push(request.url);
if (mode === "malformed") {
response.end("{broken");
return;
}
if (mode === "discovery timeout" && requests === 1) {
if (
mode === "exited" ||
(mode === "discovery timeout" && requests.length === 1)
) {
response.once("close", () => {
ready = true;
});
stalled.arrive();
return;
}
response.end(
@@ -121,20 +121,17 @@ const fixture = async (
ownership: { processGroupId: 7 },
cleanup,
});
mock.port.mockImplementation(async () => {
published.arrive();
return port;
});
mock.port.mockResolvedValue(port);
return {
origin,
listed,
published,
stalled,
cleanup,
exit: () => child.kill("SIGTERM"),
makeReady: () => {
ready = true;
},
requests: () => requests,
requests,
close: async () => {
server.closeAllConnections();
await new Promise<void>((resolve) => server.close(() => resolve()));
@@ -147,31 +144,50 @@ it.each(["empty targets", "discovery timeout"] as const)(
async (mode) => {
const start = await startFixture();
const server = await fixture(mode);
const responseDeadline = phaseArrival<() => void>();
const schedule = globalThis.setTimeout;
const timer =
mode === "discovery timeout"
? vi
.spyOn(globalThis, "setTimeout")
.mockImplementation((callback, delay, ...args) => {
if (delay === CDP_DISCOVERY_RESPONSE_TIMEOUT_MS)
responseDeadline.arrive(() => callback(...args));
return schedule(callback, delay, ...args);
})
: undefined;
const pending = start(process.execPath, server.origin);
let settled = false;
void pending.then(
() => {
settled = true;
},
() => {
settled = true;
},
);
let completed = false;
try {
await server.published.reached(pending, "fixture port publication");
await setImmediate();
expect(settled).toBe(false);
if (mode === "empty targets") {
await server.listed.reached(pending, "fixture target listing");
expect(settled).toBe(false);
server.makeReady();
} else {
await server.stalled.reached(
pending,
"first fixture discovery request",
);
const expire = await responseDeadline.reached(
pending,
"CDP response deadline",
);
expire();
}
await pending;
expect(server.requests()).toBeGreaterThanOrEqual(3);
completed = true;
expect(server.requests).toEqual(
mode === "empty targets"
? ["/json/version", "/json/list", "/json/version", "/json/list"]
: ["/json/version", "/json/version", "/json/list"],
);
} finally {
server.makeReady();
await (await pending.catch(() => undefined))?.close();
await server.close();
try {
if (!completed) server.exit();
await (await pending.catch(() => undefined))?.close();
} finally {
timer?.mockRestore();
await server.close();
}
}
},
);
@@ -184,7 +200,7 @@ it("preserves malformed discovery and closes the owned fixture", async () => {
await expect(pending).rejects.toMatchObject({
reason: "invalid_endpoint_response",
});
expect(server.requests()).toBe(1);
expect(server.requests).toEqual(["/json/version"]);
expect(server.cleanup).toHaveBeenCalledTimes(1);
} finally {
await (await pending.catch(() => undefined))?.close();
@@ -200,7 +216,7 @@ it("interrupts pending discovery when the owned fixture exits", async () => {
"exited before CDP discovery",
);
try {
await server.listed.reached(pending, "fixture target listing");
await server.stalled.reached(pending, "fixture discovery request");
server.exit();
await rejected;
expect(server.cleanup).toHaveBeenCalledTimes(1);