Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(producer): type the parallel stall, arm its watchdog after init, propagate worker death
Vance Ingalls9acf96d036b0
diff --git a/packages/producer/src/services/render/stages/captureStreamingStage.test.ts b/packages/producer/src/services/render/stages/captureStreamingStage.test.tsindex 66dca5fbc3..9e2044d895 100644--- a/packages/producer/src/services/render/stages/captureStreamingStage.test.ts+++ b/packages/producer/src/services/render/stages/captureStreamingStage.test.ts@@ -27,6 +27,12 @@ const spawnStreamingEncoder = mock(async () => ({let failCaptureFrameToBuffer = false;let failInitializeSession = false;let hangParallelUntilAbort = false;+// Which phase the wedged worker reports. frame_capture = past init, wedged in+// a capture call (the watchdog's job); session_init = still booting (not).+let hangParallelPhase: "session_init" | "frame_capture" = "frame_capture";+let failWorkerTransient = false;+let injectedWorkerFailure: Error | null = null;+const reorderAbortCalls: unknown[] = [];let hangSequentialUntilStall = false;let sessionWorkerEncodeEnabled = false;let captureSessionMode: "drawelement" | "screenshot" = "drawelement";@@ -73,7 +79,9 @@ mock.module("@hyperframes/engine", () => ({createFrameReorderBuffer: () => ({waitForFrame: async () => {},advanceTo: () => {},- abort: () => {},+ abort: (reason: unknown) => {+ reorderAbortCalls.push(reason);+ },}),distributeFrames: () => [],distributeFramesInterleaved: () => [],@@ -86,7 +94,22 @@ mock.module("@hyperframes/engine", () => ({_hook: unknown,signal?: AbortSignal,onProgress?: (progress: unknown) => void,+ _onFrameBuffer?: unknown,+ _config?: unknown,+ hooks?: { onWorkerFailure?: (failure: Error) => void },) => {+ if (failWorkerTransient) {+ // One worker's Chrome died. The engine reports the ORIGINAL failure+ // through the hook, then the pool rejects with its flattened summary.+ injectedWorkerFailure = Object.assign(+ new Error("Protocol error (Page.captureScreenshot): Target closed"),+ { kind: "transient_browser" },+ );+ hooks?.onWorkerFailure?.(injectedWorkerFailure);+ throw new Error(+ "[Parallel] Capture failed: Worker 1: Protocol error (Page.captureScreenshot): Target closed",+ );+ }if (hangParallelUntilAbort) {onProgress?.({totalFrames: 100,@@ -98,7 +121,7 @@ mock.module("@hyperframes/engine", () => ({]),latestWorkerPhase: {workerId: 0,- phase: "session_init",+ phase: hangParallelPhase,browserExecutable: "C:/Chrome/chrome.exe",browserVersion: "Chrome/152.0.7977.30",canvasDrawElement: true,@@ -284,6 +307,7 @@ describe("runCaptureStreamingStage", () => {...baseInput,totalFrames: 100,plan: { ...baseInput.plan, workerCount: 2, forceParallelStream: true },+ parallelCaptureLabel: "screenshot",};let caught: unknown;@@ -299,14 +323,94 @@ describe("runCaptureStreamingStage", () => {expect(caught).toBeInstanceOf(Error);// A stalled render must surface as a stall (→ pinned fallback), never as- // the raw "[Parallel] Capture failed" or a cancellation.+ // the raw "[Parallel] Capture failed" or a cancellation. Typed, so the+ // orchestrator's retry gate recognises it on any routing.+ expect((caught as Error).name).toBe("ParallelCaptureStallError");expect((caught as Error).message).toContain("stalled");- expect((caught as Error).message).toContain("phase=session_init");+ // The label is the caller's capture mode, not a hard-coded "drawElement":+ // screenshot-cohort stalls were being triaged as drawElement bugs.+ expect((caught as Error).message).toContain("Parallel screenshot capture stalled");+ expect((caught as Error).message).not.toContain("drawElement");+ expect((caught as Error).message).toContain("phase=frame_capture");expect((caught as Error).message).toContain("Chrome/152.0.7977.30");// Parent signal never fired, so the orchestrator won't read this as a cancel.expect(input.abortSignal).toBeUndefined();});+ it("does not arm the watchdog while every worker is still initialising", async () => {+ // Browsers launching and sub-composition timelines settling can take+ // longer than the stall window on a heavy composition. Counting that as+ // no-progress made the watchdog fail exactly the long renders it guards.+ hangParallelUntilAbort = true;+ hangParallelPhase = "session_init";+ const prev = process.env.HF_DE_STALL_MS;+ process.env.HF_DE_STALL_MS = "50";+ const controller = new AbortController();+ const { runCaptureStreamingStage } = await import("./captureStreamingStage.js");+ const cfg = { forceScreenshot: false, ffmpegStreamingTimeout: 3_600_000 };+ const baseInput = createInput(cfg);+ const input = {+ ...baseInput,+ totalFrames: 100,+ plan: { ...baseInput.plan, workerCount: 2, forceParallelStream: true },+ abortSignal: controller.signal,+ };++ let caught: unknown;+ const run = runCaptureStreamingStage(input).catch((error: unknown) => {+ caught = error;+ });+ // Five stall windows with no frame and no phase change past init.+ await new Promise((resolve) => setTimeout(resolve, 250));+ controller.abort();+ await run;++ hangParallelUntilAbort = false;+ hangParallelPhase = "frame_capture";+ if (prev === undefined) delete process.env.HF_DE_STALL_MS;+ else process.env.HF_DE_STALL_MS = prev;++ expect(caught).toBeInstanceOf(Error);+ expect((caught as Error).message).not.toContain("stalled");+ });++ it("releases the writer with the dead worker's own error, not a stall", async () => {+ // A transient Chrome death in one interleaved worker. Before, peers parked+ // in the ordered writer until the watchdog relabelled it a stall a minute+ // later; the original transient error — the one the orchestrator knows how+ // to retry — was lost.+ failWorkerTransient = true;+ reorderAbortCalls.length = 0;+ const prev = process.env.HF_DE_STALL_MS;+ process.env.HF_DE_STALL_MS = "600000";+ const { runCaptureStreamingStage } = await import("./captureStreamingStage.js");+ const cfg = { forceScreenshot: false, ffmpegStreamingTimeout: 3_600_000 };+ const baseInput = createInput(cfg);+ const input = {+ ...baseInput,+ totalFrames: 100,+ plan: { ...baseInput.plan, workerCount: 2, forceParallelStream: true },+ };++ let caught: unknown;+ try {+ await runCaptureStreamingStage(input);+ } catch (error) {+ caught = error;+ } finally {+ failWorkerTransient = false;+ if (prev === undefined) delete process.env.HF_DE_STALL_MS;+ else process.env.HF_DE_STALL_MS = prev;+ }++ // The exact failure object the engine reported — not the pool's flattened+ // "[Parallel] Capture failed: …" string, and not a stall.+ expect(caught).toBe(injectedWorkerFailure);+ expect((caught as Error).message).not.toContain("stalled");+ // Parked peers were released with that same error.+ expect(reorderAbortCalls).toEqual([injectedWorkerFailure]);+ });+it("does not relabel a genuine parent-abort as a stall", async () => {hangParallelUntilAbort = true;const prev = process.env.HF_DE_STALL_MS;diff --git a/packages/producer/src/services/render/stages/captureStreamingStage.ts b/packages/producer/src/services/render/stages/captureStreamingStage.tsindex 170c2acfa7..3199074b0b 100644--- a/packages/producer/src/services/render/stages/captureStreamingStage.ts+++ b/packages/producer/src/services/render/stages/captureStreamingStage.ts@@ -95,6 +95,40 @@ import type { SdrStreamingCapturePlan } from "../capturePlan.js";const DEFAULT_CAPTURE_STALL_MS = 60_000;const DE_STALL_POLL_MS = 5_000;+/**+ * The parallel no-progress watchdog tripped. Typed like the sequential stall+ * so the orchestrator retries it on any routing: the untyped Error this+ * replaces failed the render hard on the non-drawElement router while its+ * message promised a fallback. `drain` is the variant raised through the+ * ordered writer (a peer was parked on a missing frame); `pool` is raised+ * when no writer was parked, i.e. every worker was wedged inside a capture+ * call. The two are distinct field signatures and stay distinguishable.+ */+class ParallelCaptureStallError extends Error {+ readonly variant: "drain" | "pool";++ constructor(args: {+ variant: "drain" | "pool";+ captureLabel: string;+ stallTimeoutMs: number;+ lastCapturedFrames: number;+ totalFrames: number;+ phaseSummary: string;+ }) {+ const phases = args.phaseSummary ? ` Last worker phases: ${args.phaseSummary}.` : "";+ super(+ args.variant === "drain"+ ? `[Render] Parallel ${args.captureLabel} capture stalled: no frame progress for ` ++ `${args.stallTimeoutMs}ms (stuck at ${args.lastCapturedFrames}/${args.totalFrames}).${phases}`+ : `[Render] Parallel ${args.captureLabel} capture stalled after ${args.stallTimeoutMs}ms ` ++ `with no frame progress (last frame ${args.lastCapturedFrames}/${args.totalFrames}); ` ++ `retrying on a fresh screenshot session.${phases}`,+ );+ this.name = "ParallelCaptureStallError";+ this.variant = args.variant;+ }+}+export function resolveCaptureStallTimeoutMs(): number {// HF_DE_PARALLEL_STALL_MS is the pre-rename name (this config used to guard// only the parallel path). Bridged for one release so an already-deployed@@ -217,6 +251,14 @@ export interface CaptureStreamingStageInput {outputFormat: string;/** Pre-built encoder options; passed straight to `spawnStreamingEncoder`. */streamingEncoderOptions: StreamingEncoderOptions;+ /**+ * What the parallel workers capture with — "drawElement", "BeginFrame" or+ * "screenshot" — for the stall message. The stage cannot see it (workers+ * open their own sessions), and the message used to hard-code+ * "drawElement", so screenshot-cohort stalls were triaged as drawElement+ * bugs. Defaults to a neutral label when the caller does not know.+ */+ parallelCaptureLabel?: string;buildCaptureOptions: () => CaptureOptions;createRenderVideoFrameInjector: () => BeforeCaptureHook | null;abortSignal: AbortSignal | undefined;@@ -697,6 +739,16 @@ export async function runCaptureStreamingStage(// being swallowed as a cancel. On trip we also abort the reorder buffer// so peer workers parked in `waitForFrame` reject instead of deadlocking// the pool (executeParallelCapture awaits ALL workers).+ //+ // The clock is ARMED, not just reset, by progress: it starts counting+ // only once some worker has reached its first capture call or written+ // a frame. Before that the workers are launching browsers and settling+ // sub-composition timelines and media, which on a heavy composition+ // legitimately takes longer than the stall window — the sequential path+ // starts its clock after initializeSession for the same reason. Init+ // itself is bounded by the engine (browserTimeout, playerReadyTimeout).+ const captureLabel = input.parallelCaptureLabel ?? "worker";+ let watchdogArmed = false;const stallController = new AbortController();const forwardParentAbort = () => stallController.abort();if (abortSignal) {@@ -715,13 +767,16 @@ export async function runCaptureStreamingStage(let stalled = false;const stallTimer = setInterval(() => {- if (Date.now() - lastProgressAt <= stallTimeoutMs) return;+ if (!watchdogArmed || Date.now() - lastProgressAt <= stallTimeoutMs) return;stalled = true;- const stallErr = new Error(- `[Render] Parallel drawElement capture stalled: no frame progress for ${stallTimeoutMs}ms ` +- `(stuck at ${lastCapturedFrames}/${totalFrames}).` +- (workerPhases.size > 0 ? ` Last worker phases: ${phaseSummary()}.` : ""),- );+ const stallErr = new ParallelCaptureStallError({+ variant: "drain",+ captureLabel,+ stallTimeoutMs,+ lastCapturedFrames,+ totalFrames,+ phaseSummary: phaseSummary(),+ });reorderBuffer.abort(stallErr);stallController.abort();},@@ -745,6 +800,10 @@ export async function runCaptureStreamingStage(`browser=${phase.browserExecutable} version=${phase.browserVersion} ` +`CanvasDrawElement=${phase.canvasDrawElement} gpu=${phase.gpuBackend}`;workerPhases.set(phase.workerId, detail);+ if (phase.phase === "frame_capture" && !watchdogArmed) {+ watchdogArmed = true;+ lastProgressAt = Date.now();+ }log.info("[Render] Parallel capture worker phase", {workerId: phase.workerId,phase: phase.phase,@@ -759,6 +818,7 @@ export async function runCaptureStreamingStage(if (progress.capturedFrames > lastCapturedFrames) {lastCapturedFrames = progress.capturedFrames;lastProgressAt = Date.now();+ watchdogArmed = true;}job.framesRendered = progress.capturedFrames;const frameProgress = progress.capturedFrames / progress.totalFrames;@@ -786,6 +846,19 @@ export async function runCaptureStreamingStage(// Chromium's internal frame-production scheduling on ALL platforms,// NOT the Linux-only HeadlessExperimental.beginFrame capture mode.deParallelStream ? { ...captureCfg, enableBrowserPool: false } : captureCfg,+ {+ // A worker died (Target closed, Page crashed, launch failure).+ // Its frames are gone and peers are parked in waitForFrame on the+ // first of them; release them with the ORIGINAL failure so the+ // orchestrator sees a transient browser error it knows how to+ // retry, not the stall the watchdog would have raised a minute+ // later. First failure wins, same as the drain guard above.+ onWorkerFailure: (failure) => {+ if (parallelDrainError) return;+ parallelDrainError = failure;+ reorderBuffer.abort(failure);+ },+ },);} catch (err) {// Surface the TYPED drain error (DrawElementVerificationError) so the@@ -798,12 +871,14 @@ export async function runCaptureStreamingStage(// NOT fire) so the orchestrator's pinned fallback re-renders via// screenshot instead of masking a 5-min hang.if (stalled && abortSignal?.aborted !== true) {- throw new Error(- `[Render] Parallel drawElement capture stalled after ${stallTimeoutMs}ms with no ` +- `frame progress (last frame ${lastCapturedFrames}/${totalFrames}); ` +- `falling back to screenshot.` +- (workerPhases.size > 0 ? ` Last worker phases: ${phaseSummary()}.` : ""),- );+ throw new ParallelCaptureStallError({+ variant: "pool",+ captureLabel,+ stallTimeoutMs,+ lastCapturedFrames,+ totalFrames,+ phaseSummary: phaseSummary(),+ });}throw err;} finally {