Skip to content

Write HTML. Render video. Built for agents.

fix(render): retry drawElement failures on a fresh screenshot page

Vance Ingalls6a206ffea637
diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts
index 6137591552..6a84ab9069 100644
--- a/packages/engine/src/index.ts
+++ b/packages/engine/src/index.ts
@@ -416,3 +416,8 @@ export {
PROVENANCE_VERSION,
type RenderProvenance,
} from "./utils/renderProvenance.js";
+
+export {
+ DrawElementCaptureError,
+ isDrawElementCaptureError,
+} from "./services/drawElementCaptureError.js";
diff --git a/packages/engine/src/services/drawElementCaptureError.ts b/packages/engine/src/services/drawElementCaptureError.ts
new file mode 100644
index 0000000000..a61bb9fba6
--- /dev/null
+++ b/packages/engine/src/services/drawElementCaptureError.ts
@@ -0,0 +1,25 @@
+/** A drawElement page cannot supply trusted pixels; retry on a fresh screenshot page. */
+export class DrawElementCaptureError extends Error {
+ readonly frameIndex: number;
+
+ constructor(frameIndex: number, reason: string, cause?: unknown) {
+ super(
+ `drawElement capture failed at frame ${frameIndex}: ${reason}; fresh screenshot capture required`,
+ { cause },
+ );
+ this.name = "DrawElementCaptureError";
+ // Consumed structurally across package/worker error boundaries.
+ Object.defineProperty(this, "deCaptureFailure", { value: true, enumerable: true });
+ this.frameIndex = frameIndex;
+ }
+}
+
+/** Structural matching survives engine/producer copies and worker error wrappers. */
+export function isDrawElementCaptureError(error: unknown): boolean {
+ let current = error;
+ for (let depth = 0; depth < 5 && typeof current === "object" && current !== null; depth++) {
+ if ("deCaptureFailure" in current && current.deCaptureFailure === true) return true;
+ current = "cause" in current ? current.cause : undefined;
+ }
+ return false;
+}
diff --git a/packages/engine/src/services/frameCapture-freshFallback.test.ts b/packages/engine/src/services/frameCapture-freshFallback.test.ts
new file mode 100644
index 0000000000..62fee23174
--- /dev/null
+++ b/packages/engine/src/services/frameCapture-freshFallback.test.ts
@@ -0,0 +1,149 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import {
+ captureFrameToBuffer,
+ captureFrameToBufferPipelined,
+ captureFramesBatchPipelined,
+ createCaptureSession,
+} from "./frameCapture.js";
+import {
+ captureDrawElementFrame,
+ produceDrawElementFrame,
+ produceDrawElementFrameBatch,
+ DE_CANVAS_NOT_INITIALIZED_CODE,
+} from "./drawElementService.js";
+import { pageScreenshotCapture } from "./screenshotService.js";
+import { DrawElementCaptureError, isDrawElementCaptureError } from "./drawElementCaptureError.js";
+
+vi.mock("./browserManager.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./browserManager.js")>()),
+ resolveBrowserGpuMode: async () => "hardware",
+ acquireBrowser: async () => ({
+ captureMode: "screenshot",
+ browser: {
+ version: async () => "Chrome/150.0.0.0",
+ newPage: async () => ({
+ evaluateOnNewDocument: async () => {},
+ setViewport: async () => {},
+ evaluate: async () => undefined,
+ screenshot: async () => {
+ throw new Error("diagnostic screenshot unavailable");
+ },
+ }),
+ },
+ }),
+}));
+vi.mock("./drawElementService.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./drawElementService.js")>()),
+ captureDrawElementFrame: vi.fn(),
+ produceDrawElementFrame: vi.fn(),
+ produceDrawElementFrameBatch: vi.fn(),
+}));
+vi.mock("./screenshotService.js", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("./screenshotService.js")>()),
+ pageScreenshotCapture: vi.fn(),
+}));
+
+const dirs: string[] = [];
+async function session() {
+ const dir = mkdtempSync(join(tmpdir(), "hf-fresh-fallback-"));
+ dirs.push(dir);
+ const result = await createCaptureSession(
+ "http://localhost:0",
+ dir,
+ {
+ width: 1920,
+ height: 1080,
+ fps: { num: 30, den: 1 },
+ format: "jpeg",
+ },
+ null,
+ { forceScreenshot: true },
+ );
+ result.isInitialized = true;
+ result.captureMode = "drawelement";
+ return result;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubEnv("HF_FORCE_DRAWELEMENT", "0");
+ vi.stubEnv("HF_FAST_CAPTURE_BOUNDARY_SS", "false");
+});
+afterEach(() => {
+ vi.unstubAllEnvs();
+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+describe("fresh screenshot fallback", () => {
+ for (const [name, capture, produce] of [
+ ["serial", captureFrameToBuffer, captureDrawElementFrame],
+ ["pipelined", captureFrameToBufferPipelined, produceDrawElementFrame],
+ ] as const) {
+ it.each(["No cached paint record for element", DE_CANVAS_NOT_INITIALIZED_CODE])(
+ `${name} rejects untrusted capture instead of returning the injected canvas`,
+ async (message) => {
+ vi.mocked(produce).mockRejectedValueOnce(new Error(message));
+ const s = await session();
+ await expect(capture(s, 7, 7 / 30)).rejects.toBeInstanceOf(DrawElementCaptureError);
+ expect(pageScreenshotCapture).not.toHaveBeenCalled();
+ expect(s.deNcprFallbacks).toBe(1);
+ },
+ );
+ it(`${name} routes explicit boundary screenshots through a fresh page`, async () => {
+ vi.stubEnv("HF_FAST_CAPTURE_BOUNDARY_SS", "true");
+ const s = await session();
+ s.clipBoundaryFrames = new Set([7]);
+ await expect(capture(s, 7, 7 / 30)).rejects.toThrow("boundary screenshot requested");
+ expect(pageScreenshotCapture).not.toHaveBeenCalled();
+ expect(produce).not.toHaveBeenCalled();
+ });
+ }
+
+ it("rejects a suspect tiny frame without substituting a stale screenshot", async () => {
+ vi.mocked(captureDrawElementFrame).mockResolvedValueOnce(Buffer.alloc(100));
+ await expect(captureFrameToBuffer(await session(), 7, 7 / 30)).rejects.toThrow(
+ "suspect small frame",
+ );
+ expect(pageScreenshotCapture).not.toHaveBeenCalled();
+ });
+
+ it("returns a normal drawElement frame unchanged", async () => {
+ const buffer = Buffer.alloc(30_000);
+ vi.mocked(captureDrawElementFrame).mockResolvedValueOnce(buffer);
+ expect((await captureFrameToBuffer(await session(), 7, 7 / 30)).buffer).toBe(buffer);
+ expect(pageScreenshotCapture).not.toHaveBeenCalled();
+ });
+
+ it.each(["No cached paint record for element", DE_CANVAS_NOT_INITIALIZED_CODE])(
+ "rejects a failed batch and safely abandons pending prefix encodes",
+ async (error) => {
+ let rejectPrefix: (error: Error) => void = () => {};
+ const prefix = new Promise<Buffer>((_, reject) => {
+ rejectPrefix = reject;
+ });
+ vi.mocked(produceDrawElementFrameBatch).mockResolvedValueOnce({
+ encodeResults: [prefix],
+ failedAt: 1,
+ error,
+ });
+ await expect(
+ captureFramesBatchPipelined(await session(), [6, 7], [6 / 30, 7 / 30]),
+ ).rejects.toThrow("frame 7");
+ rejectPrefix(new Error("worker closed during fallback"));
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(pageScreenshotCapture).not.toHaveBeenCalled();
+ expect(produceDrawElementFrame).not.toHaveBeenCalled();
+ },
+ );
+
+ it("recognizes wrapped structural errors without misclassifying generic failures", () => {
+ expect(isDrawElementCaptureError({ cause: { cause: { deCaptureFailure: true } } })).toBe(true);
+ expect(isDrawElementCaptureError(new Error("No cached paint record for element"))).toBe(false);
+ const cycle: { cause?: unknown } = {};
+ cycle.cause = cycle;
+ expect(isDrawElementCaptureError(cycle)).toBe(false);
+ });
+});
diff --git a/packages/engine/src/services/frameCapture.ts b/packages/engine/src/services/frameCapture.ts
index 1fafae7111..4a3e257624 100644
--- a/packages/engine/src/services/frameCapture.ts
+++ b/packages/engine/src/services/frameCapture.ts
@@ -18,6 +18,8 @@ import {
type RawAuthoredTiming,
} from "@hyperframes/core";
+import { DrawElementCaptureError } from "./drawElementCaptureError.js";
+
// ── Extracted modules ───────────────────────────────────────────────────────
import {
acquireBrowser,
@@ -224,7 +226,7 @@ export interface CaptureSession {
deFallbackTrigger?: string;
/** Wall-clock ms spent capturing self-verification ground truth at init (telemetry). */
deVerifyInitMs?: number;
- /** Count of per-frame "No cached paint record" screenshot fallbacks (telemetry). */
+ /** Count of paint-record/canvas failures requiring fresh screenshot capture (telemetry). */
deNcprFallbacks?: number;
/**
* Count of drawElement frame captures that blew `HF_DE_FRAME_TIMEOUT_MS`
@@ -3630,19 +3632,10 @@ async function captureFrameCore(
session.clipBoundaryFrames?.has(frameIndex) &&
process.env.HF_FAST_CAPTURE_BOUNDARY_SS === "true"
) {
- // Lim 6 (serial path): proactively screenshotting clip-boundary frames is now
- // OPT-IN (was default-on). It is net-harmful: drawElement renders most boundary
- // frames correctly, but Page.captureScreenshot in drawElement mode captures the
- // injected canvas (unpainted at render start → white; mid-render → ~1-frame
- // stale), so the "fallback" REPLACES good frames with damaged ones (validated:
- // 35e8fa9f 462→0 damaged frames, 4001da8e 11→0, when this is off). The two real
- // boundary failure modes are now caught reactively below — the throw case by
- // isRecoverableDrawElementError, the silent-solid-black case by the small-frame
- // blank-guard (a solid frame is a tiny JPEG) — without touching frames drawElement
- // handles. Force the old behavior with HF_FAST_CAPTURE_BOUNDARY_SS=true. The worker
- // path keeps proactive boundary-SS (it has no blank-guard); see
- // captureFrameToBufferPipelined and docs/fast-capture-limitations.md.
- screenshotBuffer = await pageScreenshotCapture(page, options);
+ throw new DrawElementCaptureError(
+ frameIndex,
+ "boundary screenshot requested on an injected canvas page",
+ );
} else if (session.captureMode === "drawelement") {
// Advance compositor state via BeginFrame when available (Linux headless-shell);
// on macOS the compositor advances naturally without BeginFrame.
@@ -3667,49 +3660,32 @@ async function captureFrameCore(
// a fresh snapshot, and no further paint would arrive during a wait.
session.beginFrameTimeTicks === 0,
);
- // Silent-blank-drop guard: drawElement occasionally returns a blank/dropped
- // frame WITHOUT throwing (paint-record miss; the throw case is handled below).
- // Such a frame's JPEG is anomalously tiny vs the comp's running median (a blank
- // 1080p frame ~5-9 KB; content frames 50 KB-1 MB). Re-capture via screenshot
- // (ground truth) — harmless for legitimately simple frames (screenshot matches).
- // Catches scattered intermittent drops (e.g. 4001da8e: 11 blanks in 9300 frames,
- // 9.7 dB) that no static gate can see. PNG/transparent excluded (alpha sizing
- // differs and that path is its own).
+ // A tiny JPEG may be a dropped paint record. Never screenshot this page:
+ // its injected canvas can still hold the preceding frame's bitmap.
+ // Restart on a fresh screenshot page even if this was a simple valid frame.
if ((options.format ?? "jpeg") !== "png" && process.env.HF_FORCE_DRAWELEMENT !== "1") {
const sizes = (session.deFrameSizes ??= []);
const sorted = sizes.length >= 12 ? [...sizes].sort((a, b) => a - b) : null;
const median = sorted ? (sorted[sorted.length >> 1] ?? 0) : 0;
const floor = Math.max(20000, median * 0.12);
if (screenshotBuffer.length < floor) {
- console.log(
- `[engine] fast capture: frame ${frameIndex} — drawElement frame anomalously ` +
- `small (${screenshotBuffer.length}B < ${Math.round(floor)}B, likely a silent ` +
- `paint-record drop); screenshot fallback (see fast-capture-limitations.md)`,
+ throw new DrawElementCaptureError(
+ frameIndex,
+ `suspect small frame (${screenshotBuffer.length}B < ${Math.round(floor)}B)`,
);
- screenshotBuffer = await pageScreenshotCapture(page, options);
} else {
if (sizes.length >= 60) sizes.shift();
sizes.push(screenshotBuffer.length);
}
}
} catch (err) {
- // drawElementImage throws `InvalidStateError: No cached paint record for
- // element` when an element in the subtree has no paint record this frame
- // (display toggled / detached / freshly-shown at a clip-cut boundary), and
- // `canvas not initialized` when the injected capture canvas isn't set up yet
- // (observed at frame 0 on some macOS/Chrome combinations, see #3423). Both
- // are per-frame conditions, not whole-comp ones — fall back to screenshot for
- // THIS frame instead of aborting the render. See fast-capture-limitations.md.
+ // Missing paint records/canvas state require a new screenshot page.
if (isRecoverableDrawElementError(err)) {
session.deNcprFallbacks = (session.deNcprFallbacks ?? 0) + 1;
const reason = isCanvasNotInitializedError(err)
? "drawElement canvas not initialized"
: "No cached paint record";
- console.log(
- `[engine] fast capture: frame ${frameIndex} — ${reason}; ` +
- `screenshot fallback for this frame (see fast-capture-limitations.md)`,
- );
- screenshotBuffer = await pageScreenshotCapture(page, options);
+ throw new DrawElementCaptureError(frameIndex, reason, err);
} else {
throw err;
}
@@ -3877,35 +3853,14 @@ export async function captureFrameToBufferPipelined(
);
void quantizedTime;
- // Lim 6: clip-cut boundary frame — screenshot ONLY when opt-in, matching the serial
- // path (captureFrameCore). Proactive boundary screenshots in drawElement mode are
- // net-HARMFUL: with `<canvas layoutsubtree>` the child composition root is laid out
- // but not painted to screen — only the canvas 2D bitmap is visible — so
- // Page.captureScreenshot captures the injected canvas holding the LAST drawElement
- // frame (stale by ≥1 scene at a hard cut), REPLACING a good frame with a stale one.
- // Measured on 0531c45f: worker boundary frames showed the previous scene's video.
- // Default OFF → boundary frames fall through to produceDrawElementFrame, which draws
- // the CURRENT frame into the canvas. (Force old behavior with
- // HF_FAST_CAPTURE_BOUNDARY_SS=true.) See captureFrameCore for the serial rationale.
if (
session.clipBoundaryFrames?.has(frameIndex) &&
process.env.HF_FAST_CAPTURE_BOUNDARY_SS === "true"
) {
- const buffer = await pageScreenshotCapture(page, options);
- session.capturePerf.frames += 1;
- session.capturePerf.seekMs += seekMs;
- session.capturePerf.beforeCaptureMs += beforeCaptureMs;
- {
- const boundaryMs = Date.now() - startTime;
- session.capturePerf.totalMs += boundaryMs;
- session.capturePerf.frameMs.push(boundaryMs);
- }
- const boundaryResult = Promise.resolve(buffer);
- if (session.staticFrames) {
- session.lastEncodeResult = boundaryResult;
- session.lastEncodeResultFrame = frameIndex;
- }
- return { encodeResult: boundaryResult, captureTimeMs: Date.now() - startTime };
+ throw new DrawElementCaptureError(
+ frameIndex,
+ "boundary screenshot requested on an injected canvas page",
+ );
}
// Worker-encode is gated to the macOS GPU path (beginFrameTimeTicks === 0,
@@ -3938,22 +3893,13 @@ export async function captureFrameToBufferPipelined(
return { encodeResult, captureTimeMs };
} catch (captureError) {
- // Per-frame `No cached paint record` or `canvas not initialized` (#3423): fall
- // back to screenshot for THIS frame instead of aborting the render (clip-cut
- // boundary / freshly-shown element / capture canvas not yet set up). The worker
- // isn't involved for this frame; return a resolved encodeResult so the pipeline
- // loop writes it like any other. See fast-capture-limitations.md.
+ // The viewport can contain the last injected bitmap, not the sought frame.
if (isRecoverableDrawElementError(captureError)) {
session.deNcprFallbacks = (session.deNcprFallbacks ?? 0) + 1;
const reason = isCanvasNotInitializedError(captureError)
? "drawElement canvas not initialized"
: "No cached paint record";
- console.log(
- `[engine] fast capture: frame ${frameIndex} — ${reason}; ` +
- `screenshot fallback for this frame (see fast-capture-limitations.md)`,
- );
- const buffer = await pageScreenshotCapture(page, options);
- return { encodeResult: Promise.resolve(buffer), captureTimeMs: Date.now() - startTime };
+ throw new DrawElementCaptureError(frameIndex, reason, captureError);
}
// Mirror captureFrameCore: capture per-frame diagnostics (frame-error
// PNG/HTML/JSON + console tail) before rethrowing so pipelined-path
@@ -3977,9 +3923,8 @@ export async function captureFrameToBufferPipelined(
* drain time:
* - the static-dedup fast path returns session.lastEncodeResult, which by
* drain time can hold a frame several indices AHEAD of the suspect frame;
- * - the per-frame recoverable-error screenshot fallback ("No cached paint
- * record" or "canvas not initialized") captures the viewport — which may
- * hold the LAST drawn drawElement frame, not this one.
+ * - a screenshot of the injected page may hold the LAST drawn drawElement
+ * frame, not this one. Capture failures therefore require a fresh page.
* Any failure here throws; the caller treats that as verification failure and
* falls back the whole render (correct, never wrong-frame).
*/
@@ -4011,11 +3956,9 @@ export async function recaptureDrawElementFrameForVerify(
* handling depends on whether the failure is one of the recoverable
* per-frame drawElement conditions (canvas-not-initialized / no-cached-paint-
* record, #3423):
- * - Recoverable: capture the remaining frames directly via screenshot,
- * same as the per-frame paths' own fallback (avoids re-attempting a
- * drawElement produce that the batch call just told us will fail again —
- * review finding: audit this path explicitly rather than relying on the
- * incidental retry-then-catch behavior below).
+ * - Recoverable: reject the batch with DrawElementCaptureError so the producer
+ * re-renders on a fresh screenshot page. The injected canvas is not a valid
+ * screenshot fallback surface.
* - Anything else (unrecognized error): fall through to
* {@link captureFrameToBufferPipelined}, which re-attempts drawElement (so
* a genuinely transient, non-drawElement-specific failure still gets a
@@ -4044,6 +3987,10 @@ export async function captureFramesBatchPipelined(
options.quality ?? 80,
);
+ // A later batch failure abandons this prefix. Its asynchronous encodes can
+ // still reject while session cleanup shuts the worker down.
+ for (const result of encodeResults) void result.catch(() => {});
+
const okCount = failedAt === null ? frameIndices.length : failedAt;
const elapsed = Date.now() - startTime;
session.capturePerf.frames += okCount;
@@ -4076,34 +4023,8 @@ export async function captureFramesBatchPipelined(
const reason = isCanvasNotInitializedError(error)
? "drawElement canvas not initialized"
: "No cached paint record";
- console.log(
- `[engine] fast capture: batch produce failed at frame ` +
- `${frameIndices[failedAt] ?? "?"} (${reason}); ` +
- `screenshot fallback for ${frameIndices.length - failedAt} frame(s) ` +
- `(see fast-capture-limitations.md)`,
- );
- for (let i = failedAt; i < frameIndices.length; i++) {
- const frameIndex = frameIndices[i];
- const time = times[i];
- if (frameIndex === undefined || time === undefined) break;
- session.deNcprFallbacks = (session.deNcprFallbacks ?? 0) + 1;
- // Each remaining frame still needs its own seek/prepare — the batch
- // produce call left the page composited for whichever frame it last
- // attempted, not this one. Without this, every fallback screenshot in
- // the loop captures the SAME (stale) frame instead of advancing.
- // Deliberately reuse prepareFrameForCapture rather than routing
- // through captureFrameToBufferPipelined here, since that would
- // re-attempt produceDrawElementFrame — which the batch call already
- // told us will fail again for these frames (see function doc above).
- await prepareFrameForCapture(session, frameIndex, time);
- const buffer = await pageScreenshotCapture(page, options);
- const encodeResult = Promise.resolve(buffer);
- if (session.staticFrames) {
- session.lastEncodeResult = encodeResult;
- session.lastEncodeResultFrame = frameIndex;
- }
- results.push({ frameIndex, encodeResult });
- }
+ session.deNcprFallbacks = (session.deNcprFallbacks ?? 0) + 1;
+ throw new DrawElementCaptureError(frameIndices[failedAt] ?? failedAt, reason, error);
} else {
console.log(
`[engine] fast capture: batch produce failed at frame ` +
@@ -4447,47 +4368,20 @@ export function percentileOf(samples: number[], p: number): number {
return Math.round(sorted[idx] ?? 0);
}
-/**
- * Fraction of captured frames above which a fast-capture render is treated as
- * "drawElement effectively didn't engage" rather than "recovered a handful of
- * edge-case frames" (see the cross-PR-seam warning in
- * {@link getCapturePerfSummary}). Not currently a hard gate — see that
- * function's comment for why — just the threshold for the loud diagnostic.
- */
+/** Threshold for surfacing paint-record/canvas failures in partial-session diagnostics. */
const DE_FALLBACK_RATIO_WARN_THRESHOLD = 0.5;
export function getCapturePerfSummary(session: CaptureSession): CapturePerfSummary {
const frames = Math.max(1, session.capturePerf.frames);
const ncprFallbacks = session.deNcprFallbacks ?? 0;
- // Cross-PR seam (#3423 per-frame screenshot fallback vs #3429 artifact
- // validation): #3429's artifact validation only checks that the render
- // produced the right frame COUNT and duration — it has no visibility into
- // HOW each frame was captured. If a composition is so incompatible with
- // drawElement that most/all frames take the per-frame screenshot fallback
- // added here, the render still reports "complete" with a correct frame
- // count, even though drawElement effectively never engaged for it. That's
- // not itself a correctness bug — screenshot capture is the platform's
- // normal, well-tested baseline, so the SHIPPED PIXELS are fine — but a
- // near-100% fallback ratio is a strong signal that fast-capture silently
- // failed to engage for the whole render (e.g. a persistent canvas-injection
- // problem) rather than recovering a handful of expected edge-case frames,
- // and today nothing surfaces that distinction to telemetry or to a human.
- //
- // Deliberately NOT a circuit breaker: aborting/failing the render here
- // would make a render that reliably succeeds via the well-tested screenshot
- // path fail instead, which is a worse outcome than a slow-but-correct
- // render. Whether artifact validation (or this session) should eventually
- // gate on the ratio — and where that decision belongs — is tracked as an
- // explicit follow-up: https://github.com/heygen-com/hyperframes/issues/3482
- // ("Fast-capture: fallback-ratio guard for #3423 x #3429 seam"), rather
- // than decided unilaterally in this review-response commit.
+ // These now reject capture and require a fresh screenshot page. Keep the
+ // counter for failed-session telemetry; it no longer represents usable
+ // per-frame screenshots from the injected canvas page.
if (frames > 0 && ncprFallbacks / frames > DE_FALLBACK_RATIO_WARN_THRESHOLD) {
const pct = Math.round((ncprFallbacks / frames) * 100);
console.warn(
- `[engine] fast capture: ${ncprFallbacks}/${frames} frame(s) (${pct}%) fell back to ` +
- `screenshot capture (canvas-not-initialized / no-cached-paint-record) — ` +
- `drawElement likely failed to engage for this render rather than recovering a few ` +
- `edge-case frames; see fast-capture-limitations.md.`,
+ `[engine] fast capture: ${ncprFallbacks}/${frames} frame(s) (${pct}%) rejected ` +
+ `due to missing canvas/paint records; fresh screenshot capture required.`,
);
}
return {
diff --git a/packages/producer/src/services/render/capturePlan.test.ts b/packages/producer/src/services/render/capturePlan.test.ts
index 8e8352de42..87ddfd9e30 100644
--- a/packages/producer/src/services/render/capturePlan.test.ts
+++ b/packages/producer/src/services/render/capturePlan.test.ts
@@ -140,27 +140,30 @@ describe("CapturePlan", () => {
});
});
- it("forces screenshot on a disk-plan drawElement verify failure (PRINFRA-352 recovery)", () => {
- // Parallel disk workers under the explicit fast-capture opt-in verify their
- // own captured samples; a breach must re-render the DISK plan on the
- // screenshot baseline (not throw, and not stay on drawElement).
- const disk = createCapturePlan({
- workerCount: 2,
- forceScreenshot: false,
- useStreamingEncode: false,
- useLayeredComposite: false,
- usePageSideCompositing: false,
- hasHdrContent: false,
- needsAlpha: false,
- });
- const next = replanAfterFailure(disk, { kind: "draw_element_verification" });
- expect(next).toMatchObject({
- kind: "sdr_disk",
- forceScreenshot: true,
- forceParallelStream: false,
- workerCount: 2,
- });
- });
+ it.each(["draw_element_verification", "draw_element_capture"] as const)(
+ "forces screenshot on a disk-plan %s failure",
+ (kind) => {
+ // Parallel disk workers under the explicit fast-capture opt-in verify their
+ // own captured samples; a breach must re-render the DISK plan on the
+ // screenshot baseline (not throw, and not stay on drawElement).
+ const disk = createCapturePlan({
+ workerCount: 2,
+ forceScreenshot: false,
+ useStreamingEncode: false,
+ useLayeredComposite: false,
+ usePageSideCompositing: false,
+ hasHdrContent: false,
+ needsAlpha: false,
+ });
+ const next = replanAfterFailure(disk, { kind });
+ expect(next).toMatchObject({
+ kind: "sdr_disk",
+ forceScreenshot: true,
+ forceParallelStream: false,
+ workerCount: 2,
+ });
+ },
+ );
it("rejects a streaming transition from a non-streaming plan", () => {
const disk = createCapturePlan({
diff --git a/packages/producer/src/services/render/capturePlan.ts b/packages/producer/src/services/render/capturePlan.ts
index 6e04857124..3a1e563ed9 100644
--- a/packages/producer/src/services/render/capturePlan.ts
+++ b/packages/producer/src/services/render/capturePlan.ts
@@ -66,6 +66,7 @@ export interface CreateCapturePlanInput {
export type CapturePlanFailure =
| Readonly<{ kind: "streaming_unavailable" }>
| Readonly<{ kind: "draw_element_verification" }>
+ | Readonly<{ kind: "draw_element_capture" }>
| Readonly<{ kind: "capture_failure"; memoryExhaustion: boolean }>;
function assertWorkerCount(workerCount: number): void {
@@ -127,7 +128,10 @@ export function replanAfterFailure(plan: CapturePlan, failure: CapturePlanFailur
// Disk-path drawElement self-verification (parallel disk workers under the
// explicit fast-capture opt-in) can also trip — the retry stays on the disk
// path but forces the screenshot baseline.
- if (plan.kind === "sdr_disk" && failure.kind === "draw_element_verification") {
+ if (
+ plan.kind === "sdr_disk" &&
+ (failure.kind === "draw_element_verification" || failure.kind === "draw_element_capture")
+ ) {
return createCapturePlan({
...plan,
forceScreenshot: true,
diff --git a/packages/producer/src/services/renderOrchestrator.test.ts b/packages/producer/src/services/renderOrchestrator.test.ts
index 13fb4e8182..48afd01c29 100644
--- a/packages/producer/src/services/renderOrchestrator.test.ts
+++ b/packages/producer/src/services/renderOrchestrator.test.ts
@@ -3,7 +3,12 @@ import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync
import { join, win32 } from "node:path";
import { tmpdir } from "node:os";
import type { CaptureOptions, EngineConfig, ExtractedFrames } from "@hyperframes/engine";
-import { DEFAULT_CONFIG, executeParallelCapture, mergeWorkerFrames } from "@hyperframes/engine";
+import {
+ DEFAULT_CONFIG,
+ DrawElementCaptureError,
+ executeParallelCapture,
+ mergeWorkerFrames,
+} from "@hyperframes/engine";
import type { CompiledComposition } from "./htmlCompiler.js";
// Replace only the two engine functions the adaptive-retry loop uses to touch
@@ -208,6 +213,40 @@ describe("executeDiskCaptureWithAdaptiveRetry — zero-progress bail (integratio
vi.mocked(mergeWorkerFrames).mockReset();
});
+ it("propagates an untrusted drawElement frame even if all disk frames exist", async () => {
+ const workDir = mkdtempSync(join(tmpdir(), "hf-de-untrusted-"));
+ const framesDir = join(workDir, "frames");
+ mkdirSync(framesDir);
+ const error = new Error("capture stage failed", {
+ cause: new DrawElementCaptureError(0, "No cached paint record"),
+ });
+ vi.mocked(executeParallelCapture).mockRejectedValueOnce(error);
+ vi.mocked(mergeWorkerFrames).mockImplementationOnce(async () => {
+ writeFileSync(join(framesDir, "frame_000000.jpg"), Buffer.alloc(100));
+ });
+ try {
+ await expect(
+ executeDiskCaptureWithAdaptiveRetry({
+ serverUrl: "http://localhost:0",
+ workDir,
+ framesDir,
+ totalFrames: 1,
+ initialWorkerCount: 1,
+ allowRetry: true,
+ frameExt: "jpg",
+ captureOptions: { width: 64, height: 64, fps: { num: 30, den: 1 } },
+ createBeforeCaptureHook: () => null,
+ cfg: DEFAULT_CONFIG,
+ log: makeLog(),
+ dedupPerfs: [],
+ }),
+ ).rejects.toBe(error);
+ expect(executeParallelCapture).toHaveBeenCalledTimes(1);
+ } finally {
+ rmSync(workDir, { recursive: true, force: true });
+ }
+ });
+
it("runs exactly one attempt (no worker-halving retries) when an attempt captures zero frames", async () => {
// Capture writes nothing -> framesDir stays empty -> every frame still missing.
vi.mocked(executeParallelCapture).mockResolvedValue([]);
@@ -2516,6 +2555,26 @@ describe("resolveParallelRouterRetryPlan (self-verify retry rollback)", () => {
});
describe("shouldRetryViaPinnedFallback (widen the self-verify retry to generic capture failures, including OOM)", () => {
+ it.each([
+ [false, false, true],
+ [true, false, false],
+ [false, true, false],
+ ])(
+ "routes an untrusted drawElement page unless cancelled/interrupted",
+ (isCancellation, isEncoderInterrupted, expected) => {
+ expect(
+ shouldRetryViaPinnedFallback({
+ isVerifyError: false,
+ isDeCaptureError: true,
+ isCancellation,
+ isEncoderInterrupted,
+ deWorkerInversion: undefined,
+ deParallelRouter: undefined,
+ }),
+ ).toBe(expected);
+ },
+ );
+
// PRINFRA-488: a wedged renderer must be retryable on ANY routing. Before this,
// a comp that engaged drawElement on the ordinary single-worker path had no
// whole-render fallback, so one stalled frame failed the entire render.
diff --git a/packages/producer/src/services/renderOrchestrator.ts b/packages/producer/src/services/renderOrchestrator.ts
index 4a0f0a883b..ad4abc2d35 100644
--- a/packages/producer/src/services/renderOrchestrator.ts
+++ b/packages/producer/src/services/renderOrchestrator.ts
@@ -88,6 +88,7 @@ import {
cloneCaptureWarning,
isMemoryExhaustionError,
isDrawElementVerificationError,
+ isDrawElementCaptureError,
getDrawElementVerificationDetails,
augmentProtocolTimeoutError,
augmentPageNavigationTimeoutError,
@@ -1161,8 +1162,9 @@ export async function executeDiskCaptureWithAdaptiveRetry(options: {
// `cancelled` guard; a worker-halving retry here would only re-run
// drawElement and re-damage). Structural detection walks the aggregated
// CaptureFailure → worker CaptureFailure → DrawElementVerificationError
- // cause chain.
- if (isDrawElementVerificationError(error)) {
+ // cause chain. Missing canvas/paint records also require this fresh-page
+ // recovery; their completed prefix must not make the attempt look valid.
+ if (isDrawElementVerificationError(error) || isDrawElementCaptureError(error)) {
throw error;
}
const remaining = findMissingFrameRanges(
@@ -1882,6 +1884,8 @@ export function resolveParallelRouterRetryPlan(args: {
*/
export function shouldRetryViaPinnedFallback(args: {
isVerifyError: boolean;
+ /** An injected drawElement page cannot supply trusted pixels. */
+ isDeCaptureError?: boolean;
isCancellation: boolean;
isEncoderInterrupted?: boolean;
deWorkerInversion: "inverted" | "reverted" | undefined;
@@ -1900,7 +1904,7 @@ export function shouldRetryViaPinnedFallback(args: {
isSequentialCaptureStall?: boolean;
}): boolean {
if (args.isCancellation || args.isEncoderInterrupted) return false;
- if (args.isVerifyError) return true;
+ if (args.isVerifyError || args.isDeCaptureError) return true;
if (args.isDeRendererStall === true || args.isSequentialCaptureStall === true) return true;
return args.deWorkerInversion === "inverted" || args.deParallelRouter === "routed";
}
@@ -3672,6 +3676,7 @@ async function executeRenderPipeline(input: {
// probeSession (if any) was consumed by it. See
// shouldRetryViaPinnedFallback for exactly which errors qualify.
const isVerifyError = isDrawElementVerificationError(err);
+ const isDeCaptureError = isDrawElementCaptureError(err);
const isDeStall = isDeRendererStallError(err);
const isSequentialStall = isSequentialCaptureStallError(err);
const isCancellation =
@@ -3679,6 +3684,7 @@ async function executeRenderPipeline(input: {
if (
!shouldRetryViaPinnedFallback({
isVerifyError,
+ isDeCaptureError,
isCancellation,
isEncoderInterrupted: err instanceof EncoderInterruptedError,
deWorkerInversion,
@@ -3710,7 +3716,7 @@ async function executeRenderPipeline(input: {
? "[Render] drawElement renderer stalled; re-rendering via screenshot"
: isSequentialStall
? "[Render] sequential capture stalled; retrying on a fresh screenshot session"
- : "[Render] capture failed on the pinned worker count; re-rendering via screenshot",
+ : "[Render] capture failed; re-rendering via a fresh screenshot session",
{ error: err instanceof Error ? err.message : String(err) },
);
observability.checkpoint(
@@ -3721,7 +3727,7 @@ async function executeRenderPipeline(input: {
? "drawElement renderer stalled; retrying with forceScreenshot"
: isSequentialStall
? "sequential capture stalled; retrying with a fresh screenshot session"
- : "capture failed on pinned worker count; retrying with forceScreenshot",
+ : "capture failed; retrying with a fresh screenshot session",
);
const failedRouting = capturePlan.routing.kind;
capturePlan = replanAfterFailure(
@@ -3870,32 +3876,31 @@ async function executeRenderPipeline(input: {
try {
captureRes = await invokeDiskCapture(capturePlan);
} catch (err) {
- // Disk-path drawElement self-verification tripped (a parallel disk
- // worker's sampled frame diverged from its pre-injection ground
- // truth — reachable only under the explicit fast-capture opt-in).
+ // Disk-path drawElement verification or capture failed. A canvas
+ // or paint-record failure cannot use the injected page as ground truth.
// Same recovery contract as the streaming drain: re-render on the
// screenshot baseline. Anything else keeps its existing semantics.
if (
- !isDrawElementVerificationError(err) ||
+ (!isDrawElementVerificationError(err) && !isDrawElementCaptureError(err)) ||
err instanceof RenderCancelledError ||
executionSignal?.aborted === true
) {
throw err;
}
- deSelfVerifyFallback = true;
+ deSelfVerifyFallback = isDrawElementVerificationError(err);
const t = deVerifyFallbackTelemetry(err);
- deFallbackReason = t.reason;
+ deFallbackReason = deSelfVerifyFallback ? t.reason : "capture_error";
deFallbackFailedDb = t.failedDb;
deFallbackFrameIndex = t.frameIndex;
deFallbackThresholdDb = t.thresholdDb;
log.warn(
- "[Render] drawElement self-verification failed on the parallel disk path; " +
+ "[Render] drawElement capture failed on the parallel disk path; " +
"re-rendering via screenshot",
{ error: err instanceof Error ? err.message : String(err) },
);
observability.checkpoint(
"capture_disk",
- "drawElement self-verify failed; retrying with forceScreenshot",
+ "drawElement capture failed; retrying with a fresh screenshot session",
);
// The failed attempt's frames are untrusted BUT satisfy the
// completeness check — wipe them so the retry re-captures everything
@@ -3916,7 +3921,9 @@ async function executeRenderPipeline(input: {
probeSession = null;
await closeOrphanedProbeForRetry(orphaned, closeCaptureSession, log, "disk verify");
}
- capturePlan = replanAfterFailure(capturePlan, { kind: "draw_element_verification" });
+ capturePlan = replanAfterFailure(capturePlan, {
+ kind: deSelfVerifyFallback ? "draw_element_verification" : "draw_element_capture",
+ });
syncCapturePlan();
updateCaptureObservability({
forceScreenshot: capturePlan.forceScreenshot,