Files
hyperframes/packages/engine/src/services/captureFailure.ts
T
James RussoandClaude Opus 5.5 b98718fe93 fix(engine): report a pending setup as a setup timeout, not zero duration (#7211)
* fix(engine): headline a pending setup as a setup timeout, not zero duration

When the runtime never reaches render-ready, __hf.duration reads 0 because
the bridge masks it, so pollHfReady's timeout reported "Composition has zero
duration" even for compositions with a declared data-duration whose
window.__hf.buildReady promise was still pending. Headline that case as
"Composition setup did not finish within <timeout>ms", skip the duration
inference hint that cannot apply yet, and note that the render clock stays
at 0 until the first frame. Keep its transient retry classification and give
it its own CLI diagnostic code.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(engine): name animation frames in the setup-timeout hint

Setup that awaits requestAnimationFrame hits the same render-clock rule as
setup that waits on Date or performance.now: frames only fire on a seek, and
the first seek waits for setup. Say so, and point at the waits that work.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(engine): stop suggesting scheduler.yield() for setup waits

Chrome runs scheduler.yield() continuations ahead of ordinary tasks, so a
setup loop that polls with it starves the setTimeout-driven work it waits on
(Three's compileAsync polls with setTimeout(10)) and never finishes. Plain
headless Chrome 152 hangs on a ten-line page that does exactly that. Point
authors at setTimeout and say why yield-polling does not work.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(engine): point setup waits at the library's readiness promise

HyperFrames guidance is no system timers, so the hint should not tell authors
to wait with setTimeout. Point them at the library's own readiness promise
(Three.js renderer.compileAsync) and keep the warning about scheduler.yield()
polling loops.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(engine): keep the setup-timeout hint to what it can diagnose

A scheduler.yield() polling loop starves the page, so the readiness poll never
returns and the render reports a capture stall instead of this message. Drop
that sentence; the hint covers animation-frame and clock waits only.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-11-05 07:41:04 +00:00

216 lines
7.3 KiB
TypeScript

export type CaptureFailureKind =
| "cancelled"
| "transient_browser"
| "protocol_timeout"
| "memory_exhaustion"
| "verification"
| "authoring"
| "io";
export interface CaptureWorkerDiagnostic {
workerId: number;
framesCaptured: number;
startFrame: number;
endFrame: number;
lines: readonly string[];
}
export class CaptureFailure extends Error {
readonly kind: CaptureFailureKind;
readonly cause: unknown;
readonly workerDiagnostics: readonly CaptureWorkerDiagnostic[];
readonly pageErrorLines: readonly string[];
constructor(input: {
kind: CaptureFailureKind;
message: string;
cause?: unknown;
workerDiagnostics?: readonly CaptureWorkerDiagnostic[];
pageErrorLines?: readonly string[];
}) {
super(input.message);
this.name = "CaptureFailure";
this.kind = input.kind;
this.cause = input.cause;
this.workerDiagnostics = Object.freeze(
(input.workerDiagnostics ?? []).map((diagnostic) =>
Object.freeze({ ...diagnostic, lines: Object.freeze([...diagnostic.lines]) }),
),
);
this.pageErrorLines = Object.freeze([...(input.pageErrorLines ?? [])]);
if (input.cause instanceof Error && input.cause.stack) this.stack = input.cause.stack;
}
}
const TRANSIENT_BROWSER_ERROR_PATTERNS = [
/Navigating frame was detached/i,
/Target closed/i,
/Session closed/i,
/browser has disconnected/i,
/Page crashed/i,
/Execution context was destroyed/i,
/Cannot find context with specified id/i,
/Failed to launch the browser process/i,
/Navigation timeout of \d+ ms exceeded/i,
/ECONNREFUSED/i,
/net::ERR_NETWORK_CHANGED/i,
/Composition has zero duration[\s\S]*Runtime ready: false/,
/Composition setup did not finish/,
// CDP can refuse a capture call outright with this exact wording; timed-out
// variants of the same call hit PROTOCOL_TIMEOUT_PATTERNS, checked first.
// Anchored to this literal reason (not just the CDP method) so an unrelated,
// genuinely deterministic Page.captureScreenshot error isn't swept in too.
/Protocol error \(Page\.captureScreenshot\): Unable to capture screenshot/i,
];
const PROTOCOL_TIMEOUT_PATTERNS = [
/Network\.enable timed out/i,
/Runtime\.callFunctionOn timed out/i,
/Runtime\.evaluate timed out/i,
/Page\.captureScreenshot timed out/i,
/HeadlessExperimental\.beginFrame timed out/i,
/drawElement worker encode timed out \(frame \d+\)/i,
/Protocol error[\s\S]*tim(?:ed|e) out/i,
/Waiting failed:\s*\d+\s*ms exceeded/i,
/Waiting failed[\s\S]*timeout/i,
/timeout exceeded/i,
];
const MEMORY_EXHAUSTION_ERROR_PATTERNS = [
/Set maximum size exceeded/i,
/Map maximum size exceeded/i,
/Invalid (?:array|string) length/i,
/Array buffer allocation failed/i,
/Cannot create a string longer than/i,
/Reached heap limit/i,
/JavaScript heap out of memory/i,
];
// Bun/JSC reports oversized allocations as the bare string "Out of memory".
// Match only the complete message, or the complete worker segment produced by
// parallel capture, so unrelated WebGL diagnostics are not misclassified.
const BUN_MEMORY_EXHAUSTION_EXACT_MESSAGE = /^out of memory\.?$/i;
const BUN_MEMORY_EXHAUSTION_WRAPPED_WORKER_MESSAGE = /\bworker \d+: out of memory\.?(?:;|$)/i;
const VERIFICATION_ERROR_PATTERNS = [
/DrawElementVerificationError/i,
/drawElement self-verify/i,
/verification (?:failed|mismatch)/i,
/blank drawElement frame/i,
];
const AUTHORING_ERROR_PATTERNS = [
/Composition has zero duration[\s\S]*Runtime ready: true/i,
/data-duration/i,
/No root \[data-composition-id\]/i,
/failed to parse/i,
/unparseable/i,
];
function messageOf(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
function matchesAny(message: string, patterns: readonly RegExp[]): boolean {
return patterns.some((pattern) => pattern.test(message));
}
const IO_OPERATION_TOKENS = ["read", "write", "rename", "copy", "open", "file", "directory"];
function hasIoOperationFailure(message: string): boolean {
const normalized = message.toLowerCase();
return normalized.split(/[\r\n]/).some((line) =>
IO_OPERATION_TOKENS.some((operation) => {
const operationIndex = line.indexOf(operation);
if (operationIndex < 0) return false;
const failureStart = operationIndex + operation.length;
return line.indexOf("failed", failureStart) >= 0 || line.indexOf("error", failureStart) >= 0;
}),
);
}
/**
* A write to a pipe whose reader has gone: EPIPE on darwin/linux, EOF on
* win32 (libuv reports a closed named pipe as UV_EOF), ECONNRESET on a
* socket. All three mean the streaming encoder died under us, which is an io
* fact about the host, not an authoring defect in the composition.
*/
const BROKEN_PIPE_MESSAGE = /\bwrite (?:EPIPE|EOF|ECONNRESET)\b/;
function ioError(error: unknown, message: string): boolean {
const code = error instanceof Error ? (error as NodeJS.ErrnoException).code : undefined;
return (
Boolean(
code &&
/^(?:EACCES|ECONNRESET|EEXIST|EIO|EMFILE|ENFILE|ENOENT|ENOSPC|EOF|EPERM|EPIPE|EROFS)$/.test(
code,
),
) ||
BROKEN_PIPE_MESSAGE.test(message) ||
hasIoOperationFailure(message)
);
}
const ORDERED_KIND_RULES: readonly (readonly [CaptureFailureKind, (message: string) => boolean])[] =
[
[
"memory_exhaustion",
(message) =>
BUN_MEMORY_EXHAUSTION_EXACT_MESSAGE.test(message.trim()) ||
BUN_MEMORY_EXHAUSTION_WRAPPED_WORKER_MESSAGE.test(message) ||
matchesAny(message, MEMORY_EXHAUSTION_ERROR_PATTERNS),
],
["verification", (message) => matchesAny(message, VERIFICATION_ERROR_PATTERNS)],
["protocol_timeout", (message) => matchesAny(message, PROTOCOL_TIMEOUT_PATTERNS)],
["transient_browser", (message) => matchesAny(message, TRANSIENT_BROWSER_ERROR_PATTERNS)],
["authoring", (message) => matchesAny(message, AUTHORING_ERROR_PATTERNS)],
];
function classifyKind(
error: unknown,
message: string,
signal: AbortSignal | undefined,
): CaptureFailureKind {
if (signal?.aborted || /(?:render|capture)?_?cancelled|AbortError/i.test(message)) {
return "cancelled";
}
const rule = ORDERED_KIND_RULES.find(([, matches]) => matches(message));
if (rule) return rule[0];
return ioError(error, message) ? "io" : "authoring";
}
export function classifyCaptureFailure(
error: unknown,
options: {
signal?: AbortSignal;
workerDiagnostics?: readonly CaptureWorkerDiagnostic[];
pageErrorLines?: readonly string[];
} = {},
): CaptureFailure {
const prior = error instanceof CaptureFailure ? error : undefined;
if (prior && !(options.workerDiagnostics || options.pageErrorLines || options.signal?.aborted)) {
return prior;
}
const message = messageOf(error);
const kind = classifyKind(error, message, options.signal);
return new CaptureFailure({
kind,
message,
cause: error,
workerDiagnostics: options.workerDiagnostics ?? prior?.workerDiagnostics,
pageErrorLines: options.pageErrorLines ?? prior?.pageErrorLines,
});
}
export function isTransientBrowserError(error: unknown): boolean {
return classifyCaptureFailure(error).kind === "transient_browser";
}
export function isMemoryExhaustionError(error: unknown): boolean {
return classifyCaptureFailure(error).kind === "memory_exhaustion";
}
export function isFatalCaptureFailure(failure: CaptureFailure): boolean {
return !["cancelled", "transient_browser", "protocol_timeout"].includes(failure.kind);
}