Skip to content

Commit bd477dc

Browse files
fix(cli): report non-stdio EPIPE crashes and guard launched browser pipes (#8949)
1 parent 281db3b commit bd477dc

8 files changed

Lines changed: 157 additions & 26 deletions

File tree

‎packages/cli/src/browser/launch.pipeEof.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { spawn } from "node:child_process";
2+
import { EventEmitter } from "node:events";
23
import type { LaunchOptions, PuppeteerNode } from "puppeteer-core";
34
import { expect, it } from "vitest";
45
import { launchManagedBrowser } from "./launch.js";
@@ -22,3 +23,30 @@ it("closes the browser's pipes when it exits, so an orphaned helper cannot hold
2223
.poll(() => child.stdio.every((pipe) => pipe?.destroyed), { timeout: 3000 })
2324
.toBe(true);
2425
});
26+
27+
// fails without the fix: launchOwnedBrowser left child.stdio unguarded after PipeTransport.close.
28+
it("absorbs late EPIPE on the browser's CDP pipe after Puppeteer drops its listener", async () => {
29+
const pipe = new EventEmitter();
30+
const puppeteerListener = () => {};
31+
pipe.on("error", puppeteerListener);
32+
const child = Object.assign(new EventEmitter(), {
33+
stdio: [null, null, null, pipe],
34+
exitCode: null,
35+
signalCode: null,
36+
});
37+
const puppeteer = {
38+
launch: async (_options: LaunchOptions) => ({
39+
process: () => child,
40+
close: async () => {
41+
pipe.off("error", puppeteerListener);
42+
},
43+
newPage: async () => ({}),
44+
}),
45+
} as unknown as PuppeteerNode;
46+
await launchManagedBrowser(puppeteer, { headless: true }, { diagnose: false });
47+
// Simulate PipeTransport.close() disposing its listener when Chrome's read pipe closes.
48+
pipe.off("error", puppeteerListener);
49+
expect(() =>
50+
pipe.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" })),
51+
).not.toThrow();
52+
});

‎packages/cli/src/browser/launch.ts‎

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { ChildProcess } from "node:child_process";
22
import {
3+
absorbBrowserPipeErrors,
34
inAgentSandbox,
45
isOneProcessOverPipe,
56
launchWithChromeSandboxFallback,
@@ -176,15 +177,20 @@ async function launchOwnedBrowser(
176177
const abort = new AbortController();
177178
const signal = options.signal ? AbortSignal.any([options.signal, abort.signal]) : abort.signal;
178179
const launch = untilLaunchOrAbort(
179-
puppeteer.launch({
180-
...options,
181-
args: withHyperframesBrowserMarker(options.args),
182-
env: buildChromeLaunchEnv(options.env),
183-
pipe: true,
184-
signal,
185-
handleSIGINT: false,
186-
handleSIGTERM: false,
187-
}),
180+
puppeteer
181+
.launch({
182+
...options,
183+
args: withHyperframesBrowserMarker(options.args),
184+
env: buildChromeLaunchEnv(options.env),
185+
pipe: true,
186+
signal,
187+
handleSIGINT: false,
188+
handleSIGTERM: false,
189+
})
190+
.then((launched) => {
191+
absorbBrowserPipeErrors(launched);
192+
return launched;
193+
}),
188194
signal,
189195
);
190196
const limit = options.timeout ?? LAUNCH_TIMEOUT_MS;

‎packages/cli/src/cli.lifecycle.test.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,50 @@ describe("CLI lifecycle", () => {
379379
}
380380
});
381381

382+
// fails without the fix: uncaughtException swallowed any EPIPE silently instead of only stdout/stderr.
383+
it("reports a non-stdio EPIPE uncaughtException instead of silently exiting 1", async () => {
384+
const said = vi.spyOn(console, "error").mockImplementation(() => {});
385+
const trackCliError = vi.fn();
386+
// Capture what was written before the first process.exit (a no-op spy otherwise falls through).
387+
let stderrAtExit: string | undefined;
388+
let cliErrorsAtExit: number | undefined;
389+
const exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
390+
if (stderrAtExit === undefined) {
391+
stderrAtExit = saidOnStderr(said);
392+
cliErrorsAtExit = trackCliError.mock.calls.length;
393+
}
394+
return undefined as never;
395+
}) as never);
396+
const priorListeners = process.listeners("uncaughtException");
397+
process.removeAllListeners("uncaughtException");
398+
try {
399+
mockRenderCommand(() => {
400+
process.emit(
401+
"uncaughtException",
402+
Object.assign(new Error("write EPIPE"), { code: "EPIPE" }),
403+
);
404+
});
405+
mockTelemetry({ trackCommandResult: vi.fn(), trackCliError });
406+
process.argv = ["node", "cli.ts", "render"];
407+
await import("./cli.js");
408+
expect(stderrAtExit).toContain("Error: write EPIPE");
409+
expect(cliErrorsAtExit).toBe(1);
410+
expect(trackCliError).toHaveBeenCalledWith(
411+
expect.objectContaining({
412+
kind: "uncaught_exception",
413+
error_message: "write EPIPE",
414+
}),
415+
);
416+
expect(exitSpy).toHaveBeenCalledTimes(1);
417+
expect(exitSpy).toHaveBeenCalledWith(1);
418+
} finally {
419+
process.removeAllListeners("uncaughtException");
420+
for (const listener of priorListeners) process.on("uncaughtException", listener);
421+
said.mockRestore();
422+
exitSpy.mockRestore();
423+
}
424+
});
425+
382426
it("says what an unhandled rejection was before the command delivered", async () => {
383427
const said = vi.spyOn(console, "error").mockImplementation(() => {});
384428
const priorListeners = process.listeners("unhandledRejection");

‎packages/cli/src/cli.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -567,9 +567,6 @@ function exitAfterCliFailure(
567567
}
568568

569569
process.on("uncaughtException", (error) => {
570-
if ((error as NodeJS.ErrnoException).code === "EPIPE") {
571-
handleStreamEpipe();
572-
}
573570
// Post-artifact-validated shutdown throws must not turn a valid render
574571
// into an exit-1 "no final error message" failure. The render command
575572
// sets `renderSucceeded` right after the producer resolves and the

‎packages/engine/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,7 @@ export {
9696
// ── Browser management ─────────────────────────────────────────────────────────
9797
export { chromeMajorCeiling } from "./services/chromeHostCeiling.js";
9898
export {
99+
absorbBrowserPipeErrors,
99100
acquireBrowser,
100101
setHostHandlesSigint,
101102
releaseBrowser,

‎packages/engine/src/services/browserManager.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1867,6 +1867,31 @@ describe("browser pool", () => {
18671867
await second.release();
18681868
});
18691869

1870+
// fails without the fix: launchBrowser left proc.stdio unguarded after PipeTransport.close.
1871+
it("absorbs late EPIPE on a launched browser's CDP pipe after Puppeteer drops its listener", async () => {
1872+
const pipe = new EventEmitter();
1873+
const puppeteerListener = () => {};
1874+
pipe.on("error", puppeteerListener);
1875+
const browser = {
1876+
...makeMockBrowser(),
1877+
process: () => ({ kill: vi.fn(), killed: false, stdio: [null, null, null, pipe] }),
1878+
close: vi.fn(async () => {
1879+
pipe.off("error", puppeteerListener);
1880+
}),
1881+
} as unknown as Browser;
1882+
launchFn.mockResolvedValueOnce(browser);
1883+
1884+
const lease = await acquireBrowser(["--no-sandbox"], {
1885+
enableBrowserPool: false,
1886+
forceScreenshot: true,
1887+
});
1888+
await lease.release();
1889+
1890+
expect(() =>
1891+
pipe.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" })),
1892+
).not.toThrow();
1893+
});
1894+
18701895
it("concurrent acquires via Promise.all trigger exactly one launch", async () => {
18711896
const [a, b, c] = await Promise.all([
18721897
acquireBrowser(["--no-sandbox"], poolCfg),

‎packages/engine/src/services/browserManager.ts‎

Lines changed: 38 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ async function probeHardwareWebGlInfo(
147147
? options.probeLifecycle.launch(ppt, launchOptions)
148148
: ppt.launch(launchOptions);
149149
});
150+
absorbBrowserPipeErrors(probeBrowser);
150151
const browser = probeBrowser;
151152
return await rejectAfter(
152153
readWebGlInfo(browser).then(async (info) => ({
@@ -985,18 +986,25 @@ async function launchBrowser(
985986
protocolTimeout: fingerprint.protocolTimeoutMs,
986987
signal,
987988
});
988-
}).catch(async (error: unknown) => {
989-
throwIfAborted();
990-
const remediation =
991-
process.platform === "darwin" &&
992-
sandboxDeniedRemediation(error instanceof Error ? error.message : "");
993-
if (remediation) throw new Error(remediation, { cause: error });
994-
const defaults = await ppt.defaultArgs({
995-
headless: true,
996-
args: withHyperframesBrowserMarker(attempted),
989+
})
990+
.then((launched) => {
991+
absorbBrowserPipeErrors(launched);
992+
return launched;
993+
})
994+
.catch(async (error: unknown) => {
995+
throwIfAborted();
996+
const remediation =
997+
process.platform === "darwin" &&
998+
sandboxDeniedRemediation(error instanceof Error ? error.message : "");
999+
if (remediation) throw new Error(remediation, { cause: error });
1000+
const defaults = await ppt.defaultArgs({
1001+
headless: true,
1002+
args: withHyperframesBrowserMarker(attempted),
1003+
});
1004+
throw await explainChromeLaunchFailure(error, fingerprint.executablePath, defaults, {
1005+
env,
1006+
});
9971007
});
998-
throw await explainChromeLaunchFailure(error, fingerprint.executablePath, defaults, { env });
999-
});
10001008
};
10011009
const probe = (target: Browser, timeoutMs?: number) =>
10021010
probeBeginFrameSupport(target, timeoutMs).catch((error) => ({
@@ -1055,17 +1063,34 @@ async function launchBrowser(
10551063
}
10561064
}
10571065

1066+
const guardedBrowserPipes = new WeakSet<NodeJS.EventEmitter>();
1067+
1068+
// Puppeteer's PipeTransport.close() drops its pipe error listener; absorb late EPIPE/ECONNRESET on dying browsers.
1069+
export function absorbBrowserPipeErrors(browser: Browser): void {
1070+
const proc = (
1071+
browser as unknown as {
1072+
process?: () => {
1073+
stdio?: ReadonlyArray<NodeJS.EventEmitter | null | undefined>;
1074+
} | null;
1075+
}
1076+
).process?.();
1077+
for (const stream of proc?.stdio ?? []) {
1078+
if (!stream || guardedBrowserPipes.has(stream)) continue;
1079+
guardedBrowserPipes.add(stream);
1080+
stream.on("error", () => {});
1081+
}
1082+
}
1083+
10581084
function forceCloseBrowserProcess(browser: Browser): void {
1085+
absorbBrowserPipeErrors(browser);
10591086
const proc = (
10601087
browser as unknown as {
10611088
process?: () => {
10621089
kill: (signal?: NodeJS.Signals) => boolean;
10631090
killed?: boolean;
1064-
stdio?: ReadonlyArray<NodeJS.EventEmitter | null | undefined>;
10651091
} | null;
10661092
}
10671093
).process?.();
1068-
for (const stream of proc?.stdio ?? []) stream?.on("error", () => {});
10691094
if (proc && !proc.killed) {
10701095
try {
10711096
proc.kill("SIGKILL");

‎packages/engine/src/services/hdrCapture.ts‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,11 @@
2222
import { withHyperframesBrowserMarker } from "@hyperframes/core/browser-marker";
2323
import { buildChromeLaunchEnv } from "@hyperframes/core/chrome-env";
2424
import type { Page, Browser, PuppeteerNode } from "puppeteer-core";
25-
import { resolveFullChromePath, ownedLaunchOptions } from "./browserManager.js";
25+
import {
26+
absorbBrowserPipeErrors,
27+
resolveFullChromePath,
28+
ownedLaunchOptions,
29+
} from "./browserManager.js";
2630
import { openPage } from "./openPage.js";
2731
import {
2832
chromeSandboxArgs,
@@ -263,6 +267,7 @@ export async function launchHdrBrowser(
263267
args: withHyperframesBrowserMarker(args),
264268
}),
265269
);
270+
absorbBrowserPipeErrors(browser);
266271

267272
const page = await openPage(browser);
268273
await page.setViewport({ width, height });

0 commit comments

Comments
 (0)