Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(producer): add harness mode --mode=distributed-simulated
James415ad8b5a69c
diff --git a/packages/producer/package.json b/packages/producer/package.jsonindex b93b35ebe3..5a76bed35a 100644--- a/packages/producer/package.json+++ b/packages/producer/package.json@@ -44,10 +44,12 @@"bench:hdr": "tsx src/benchmark.ts --tags hdr","test": "tsx src/regression-harness.ts --exclude-tags transparency","test:update": "tsx src/regression-harness.ts --update --exclude-tags transparency",+ "test:distributed": "tsx src/regression-harness.ts --exclude-tags transparency --mode=distributed-simulated","test:transparency": "tsx src/transparency-test.ts","docker:build:test": "docker build -f ../../Dockerfile.test -t hyperframes-producer:test ../..","docker:test": "docker run --rm --security-opt seccomp=unconfined --shm-size=2g -v ./tests:/app/packages/producer/tests hyperframes-producer:test","docker:test:update": "docker run --rm --security-opt seccomp=unconfined --shm-size=2g -v ./tests:/app/packages/producer/tests hyperframes-producer:test --update",+ "docker:test:distributed": "docker run --rm --security-opt seccomp=unconfined --shm-size=2g -v ./tests:/app/packages/producer/tests hyperframes-producer:test --mode=distributed-simulated","prepublishOnly": "echo skip"},"dependencies": {diff --git a/packages/producer/src/regression-harness-distributed.test.ts b/packages/producer/src/regression-harness-distributed.test.tsnew file mode 100644index 0000000000..209bb3b4bc--- /dev/null+++ b/packages/producer/src/regression-harness-distributed.test.ts@@ -0,0 +1,123 @@+/**+ * Unit tests for the harness mode plumbing — `parseHarnessModeFlag`,+ * `checkDistributedSupport`, and `resolveMinPsnrForMode`.+ *+ * These do NOT exercise the render pipeline itself. The byte-identical-retry+ * contract is covered by `services/distributed/renderChunk.test.ts` and the+ * PSNR contract is covered by `Dockerfile.test` running the harness with+ * `--mode=distributed-simulated` against the smallest existing fixture.+ * What lives here is the dispatch logic that decides which mode runs and+ * which fixtures skip.+ */++import { describe, expect, it } from "bun:test";+import {+ checkDistributedSupport,+ DISTRIBUTED_SIMULATED_MIN_PSNR_DB,+ parseHarnessModeFlag,+ resolveMinPsnrForMode,+} from "./regression-harness-distributed.js";++describe("parseHarnessModeFlag()", () => {+ it("parses --mode=in-process", () => {+ expect(parseHarnessModeFlag("--mode=in-process")).toBe("in-process");+ });++ it("parses --mode=distributed-simulated", () => {+ expect(parseHarnessModeFlag("--mode=distributed-simulated")).toBe("distributed-simulated");+ });++ it("returns null for tokens that aren't --mode", () => {+ expect(parseHarnessModeFlag("--update")).toBeNull();+ expect(parseHarnessModeFlag("font-variant-numeric")).toBeNull();+ expect(parseHarnessModeFlag("--exclude-tags")).toBeNull();+ });++ it("throws on a known prefix with a bad value", () => {+ expect(() => parseHarnessModeFlag("--mode=foo")).toThrow(/--mode must be/);+ expect(() => parseHarnessModeFlag("--mode=")).toThrow(/--mode must be/);+ });+});++describe("checkDistributedSupport()", () => {+ it("accepts mp4 SDR at 24 / 30 / 60 fps", () => {+ for (const fpsNum of [24, 30, 60]) {+ const result = checkDistributedSupport({ fps: { num: fpsNum, den: 1 } });+ expect(result.supported).toBe(true);+ }+ });++ it("accepts explicit format=mp4", () => {+ const result = checkDistributedSupport({ fps: { num: 30, den: 1 }, format: "mp4" });+ expect(result.supported).toBe(true);+ });++ it("rejects fps with non-1 denominator (NTSC)", () => {+ const result = checkDistributedSupport({ fps: { num: 30000, den: 1001 } });+ expect(result.supported).toBe(false);+ if (!result.supported) {+ expect(result.reason).toMatch(/non-integer fps/);+ }+ });++ it("rejects fps outside the {24,30,60} set", () => {+ for (const fpsNum of [12, 25, 48, 50, 120]) {+ const result = checkDistributedSupport({ fps: { num: fpsNum, den: 1 } });+ expect(result.supported).toBe(false);+ if (!result.supported) {+ expect(result.reason).toMatch(/not in \{24, 30, 60\}/);+ }+ }+ });++ it("rejects format=webm", () => {+ const result = checkDistributedSupport({ fps: { num: 30, den: 1 }, format: "webm" });+ expect(result.supported).toBe(false);+ if (!result.supported) {+ expect(result.reason).toMatch(/webm/);+ }+ });++ it("rejects hdr=true", () => {+ const result = checkDistributedSupport({ fps: { num: 30, den: 1 }, hdr: true });+ expect(result.supported).toBe(false);+ if (!result.supported) {+ expect(result.reason).toMatch(/hdr/);+ }+ });++ it("accepts hdr=false (or unset)", () => {+ expect(checkDistributedSupport({ fps: { num: 30, den: 1 }, hdr: false }).supported).toBe(true);+ expect(checkDistributedSupport({ fps: { num: 30, den: 1 } }).supported).toBe(true);+ });+});++describe("resolveMinPsnrForMode()", () => {+ it("in-process mode uses the fixture's own threshold verbatim", () => {+ expect(resolveMinPsnrForMode("in-process", 30)).toBe(30);+ expect(resolveMinPsnrForMode("in-process", 50)).toBe(50);+ expect(resolveMinPsnrForMode("in-process", 60)).toBe(60);+ });++ it("distributed-simulated raises sub-50 thresholds to the determinism floor", () => {+ expect(resolveMinPsnrForMode("distributed-simulated", 30)).toBe(+ DISTRIBUTED_SIMULATED_MIN_PSNR_DB,+ );+ expect(resolveMinPsnrForMode("distributed-simulated", 45)).toBe(+ DISTRIBUTED_SIMULATED_MIN_PSNR_DB,+ );+ });++ it("distributed-simulated leaves fixture thresholds ≥ 50 unchanged", () => {+ expect(resolveMinPsnrForMode("distributed-simulated", 50)).toBe(50);+ expect(resolveMinPsnrForMode("distributed-simulated", 55)).toBe(55);+ expect(resolveMinPsnrForMode("distributed-simulated", 80)).toBe(80);+ });++ it("DISTRIBUTED_SIMULATED_MIN_PSNR_DB matches the §5.1 determinism contract", () => {+ // Pinning the constant keeps the contract in sync with the design doc.+ // Changing it from 50 dB requires updating+ // `DISTRIBUTED-RENDERING-PLAN.md` §5.1 first.+ expect(DISTRIBUTED_SIMULATED_MIN_PSNR_DB).toBe(50);+ });+});diff --git a/packages/producer/src/regression-harness-distributed.ts b/packages/producer/src/regression-harness-distributed.tsnew file mode 100644index 0000000000..010c25c1d7--- /dev/null+++ b/packages/producer/src/regression-harness-distributed.ts@@ -0,0 +1,218 @@+/**+ * Distributed-render path for the regression harness.+ *+ * The regression harness has two modes:+ *+ * - `in-process` (default) — calls `executeRenderJob`, the same path the+ * `hyperframes render` CLI takes. This is what produced every existing+ * `tests/<name>/output/output.mp4` golden baseline.+ *+ * - `distributed-simulated` — calls `plan()` → `renderChunk()` per chunk+ * → `assemble()` from `@hyperframes/producer/distributed`. No Temporal+ * or Lambda involvement: the controller and chunk worker are both this+ * process, but they go through the same artifact (planDir + frozen+ * `meta/encoder.json` + per-chunk concat-copy) that a real fan-out+ * would. Validates the determinism contract from §5.1 — the distributed+ * pipeline's output must be PSNR ≥ 50 dB against the in-process+ * baseline (the contract isn't byte-identical because streaming-encode+ * fusion is unavailable when chunks are encoded separately).+ *+ * Not every fixture can run in distributed-simulated mode. Distributed mode+ * refuses webm, HDR mp4, NTSC framerates, and non-{24,30,60} fps at plan+ * time. Fixtures that don't meet the constraints are skipped — the harness+ * logs the reason and the fixture is treated as "passed (skipped)" in+ * distributed-simulated mode. The full determinism contract lands when the+ * Phase 4 fixtures (`tests/distributed/<name>/`) cover every supported+ * format and adapter.+ */++import { existsSync } from "node:fs";+import { join } from "node:path";+import type { Fps } from "@hyperframes/core";+import { assemble, plan, renderChunk } from "./distributed.js";++/** Two-mode contract that backs `--mode=<value>` on the regression harness CLI. */+export type HarnessMode = "in-process" | "distributed-simulated";++/**+ * Minimum PSNR (in dB) at which a distributed-simulated render is considered+ * equivalent to its in-process baseline. Comes straight from the determinism+ * contract in §5.1 of `DISTRIBUTED-RENDERING-PLAN.md`: distributed-vs-in-process+ * is PSNR-equivalent (≥50 dB), not byte-equal — distributed loses+ * streaming-encode fusion.+ *+ * Fixtures with `minPsnr > 50` use their own (higher) threshold; we never go+ * below 50.+ */+export const DISTRIBUTED_SIMULATED_MIN_PSNR_DB = 50;++/** Result of {@link checkDistributedSupport}. */+export type DistributedSupportResult = { supported: true } | { supported: false; reason: string };++/**+ * Decide whether a fixture's `renderConfig` is one the distributed pipeline+ * can actually run. The four hard gates:+ *+ * - fps must be `{ num: 24|30|60, den: 1 }`. `DistributedRenderConfig.fps`+ * accepts only the three integer values, and rationals like+ * `{ num: 30000, den: 1001 }` (NTSC) trip the type system at the call+ * site. We surface this gate in code rather than only in TS so the+ * harness can skip the fixture cleanly instead of throwing.+ * - format must not be `webm`. `plan()` refuses webm with+ * `FORMAT_NOT_SUPPORTED_IN_DISTRIBUTED`.+ * - hdr must not be `true`. Distributed mode is SDR-only at v1.+ *+ * Callers that want the structured reason can read it off the returned+ * `reason` field; the message is intended to be log-friendly.+ */+export function checkDistributedSupport(renderConfig: {+ fps: Fps;+ format?: "mp4" | "webm";+ hdr?: boolean;+}): DistributedSupportResult {+ if (renderConfig.fps.den !== 1) {+ return {+ supported: false,+ reason: `non-integer fps ${renderConfig.fps.num}/${renderConfig.fps.den} (distributed mode requires fps.den=1)`,+ };+ }+ const fpsNum = renderConfig.fps.num;+ if (fpsNum !== 24 && fpsNum !== 30 && fpsNum !== 60) {+ return {+ supported: false,+ reason: `fps ${fpsNum} not in {24, 30, 60} (DistributedRenderConfig.fps is a closed set)`,+ };+ }+ const format = renderConfig.format ?? "mp4";+ if (format === "webm") {+ return {+ supported: false,+ reason: "format=webm refused in distributed mode (VP9+matroska concat-copy is unstable)",+ };+ }+ if (renderConfig.hdr === true) {+ return {+ supported: false,+ reason: "hdr=true refused in distributed mode (HDR signaling re-apply not implemented)",+ };+ }+ return { supported: true };+}++/**+ * Inputs for {@link runDistributedSimulatedRender}. The harness has already+ * prepared `projectDir` (a working copy of the fixture's `src/` directory)+ * and `tempRoot` (where the harness writes its scratch artifacts).+ */+export interface RunDistributedSimulatedInput {+ /** Working copy of the fixture's `src/` — contains `index.html`. */+ projectDir: string;+ /** Scratch root for plan + chunks; must be a directory the harness owns. */+ tempRoot: string;+ /** Where to write the assembled final mp4 / mov / png-sequence directory. */+ renderedOutputPath: string;+ /** From the fixture's renderConfig — must pass `checkDistributedSupport`. */+ fps: 24 | 30 | 60;+ format: "mp4" | "mov" | "png-sequence";+ /** Optional chunkSize override; defaults to the plan's 240. */+ chunkSize?: number;+ /** Optional maxParallelChunks override; defaults to the plan's 16. */+ maxParallelChunks?: number;+ /** Forwarded to `plan()` and re-applied by `renderChunk()` at boot. */+ variables?: Record<string, unknown>;+}++/**+ * Run the distributed pipeline against a single fixture as if a fan-out+ * adapter were driving it. The three activities run serially in this+ * process — there is no Temporal, no Lambda, no S3 — so the planDir,+ * chunk outputs, and assembled output all live under `tempRoot`.+ *+ * Width and height are required by `DistributedRenderConfig` for cross-call+ * sanity but are not consulted at render time — `plan()` reads the+ * composition's `data-width` / `data-height` attributes and overrides+ * whatever the config carried. The harness passes a dummy 1920×1080 here+ * for that reason; if the contract ever changes, the fixture's authored+ * dimensions will flow through `PlanResult` and we can switch to using+ * those instead.+ */+export async function runDistributedSimulatedRender(+ input: RunDistributedSimulatedInput,+): Promise<void> {+ const planDir = join(input.tempRoot, "plan");+ const chunksDir = join(input.tempRoot, "chunks");+ const { mkdirSync } = await import("node:fs");+ mkdirSync(planDir, { recursive: true });+ mkdirSync(chunksDir, { recursive: true });++ // Step A: plan.+ const planResult = await plan(+ input.projectDir,+ {+ fps: input.fps,+ // Required-by-type but overridden by the composition's own attrs;+ // see docstring above. Any positive integer works.+ width: 1920,+ height: 1080,+ format: input.format,+ chunkSize: input.chunkSize,+ maxParallelChunks: input.maxParallelChunks,+ // Force the SDR path explicitly — `auto` would still resolve to+ // force-sdr in distributed mode, but pinning it here keeps the+ // harness's behavior independent of any future auto-detect changes.+ hdrMode: "force-sdr",+ },+ planDir,+ );++ // Step B: render every chunk. Sequential to keep the harness predictable —+ // adapters in production are free to fan out; this code path's job is to+ // exercise the per-chunk activity itself.+ const chunkPaths: string[] = [];+ for (let i = 0; i < planResult.chunkCount; i++) {+ const chunkPath =+ input.format === "png-sequence"+ ? join(chunksDir, `chunk-${String(i).padStart(4, "0")}`)+ : join(chunksDir, `chunk-${String(i).padStart(4, "0")}.${input.format}`);+ await renderChunk(planDir, i, chunkPath);+ chunkPaths.push(chunkPath);+ }++ // Step C: assemble. `audio.aac` only exists when the composition has+ // audio — pass null otherwise so `assemble()` doesn't try to mux silence.+ const audioPath = join(planDir, "audio.aac");+ const audioForAssemble = existsSync(audioPath) ? audioPath : null;+ await assemble(planDir, chunkPaths, audioForAssemble, input.renderedOutputPath);+}++/**+ * Pick the PSNR threshold for a fixture given the harness mode. In-process+ * uses the fixture's authored `minPsnr` (which may be as low as 30 dB to+ * absorb per-fixture jitter). Distributed-simulated tightens to the+ * §5.1 contract floor (50 dB) but never goes below the fixture's own+ * threshold — a fixture that demands ≥55 dB in-process stays at ≥55 dB+ * distributed.+ */+export function resolveMinPsnrForMode(mode: HarnessMode, fixtureMinPsnr: number): number {+ if (mode === "in-process") return fixtureMinPsnr;+ return Math.max(fixtureMinPsnr, DISTRIBUTED_SIMULATED_MIN_PSNR_DB);+}++/**+ * Parse `--mode=<value>` from a single CLI token. Returns the parsed mode+ * when the token matches the expected shape, `null` otherwise so the+ * caller can pass the token through to the next handler. Throws on a+ * known prefix with a bad value (`--mode=foo`) — surfacing a typo at+ * parse time is cheaper than discovering at render time.+ */+export function parseHarnessModeFlag(token: string): HarnessMode | null {+ if (token === "--mode=in-process") return "in-process";+ if (token === "--mode=distributed-simulated") return "distributed-simulated";+ if (token.startsWith("--mode=")) {+ const value = token.slice("--mode=".length);+ throw new Error(+ `regression-harness: --mode must be 'in-process' or 'distributed-simulated' (got ${JSON.stringify(value)})`,+ );+ }+ return null;+}diff --git a/packages/producer/src/regression-harness.ts b/packages/producer/src/regression-harness.tsindex 69c4f1aa2e..d7e0a4698b 100644--- a/packages/producer/src/regression-harness.ts+++ b/packages/producer/src/regression-harness.ts@@ -20,6 +20,13 @@ import { validateCompilation } from "./services/compilationTester.js";import { extractMediaMetadata } from "./utils/ffprobe.js";import { buildRmsEnvelope, compareAudioEnvelopes } from "./utils/audioRegression.js";import { parseFps, fpsToNumber } from "@hyperframes/core";+import {+ checkDistributedSupport,+ type HarnessMode,+ parseHarnessModeFlag,+ resolveMinPsnrForMode,+ runDistributedSimulatedRender,+} from "./regression-harness-distributed.js";// ── Types ────────────────────────────────────────────────────────────────────@@ -51,6 +58,18 @@ type TestMetadata = {* and these overrides. Omit when the test doesn't exercise variables.*/variables?: Record<string, unknown>;+ /**+ * Chunk size in frames for `--mode=distributed-simulated`. Forwarded+ * to `DistributedRenderConfig.chunkSize`. Ignored in `--mode=in-process`.+ * Default is the plan's own default (240 frames).+ */+ chunkSize?: number;+ /**+ * Cap on parallel chunks for `--mode=distributed-simulated`. Forwarded+ * to `DistributedRenderConfig.maxParallelChunks`. Ignored in+ * `--mode=in-process`. Default is the plan's own default (16).+ */+ maxParallelChunks?: number;};};@@ -67,11 +86,26 @@ type CliOptions = {update: boolean;sequential: boolean;keepTemp: boolean;+ /**+ * Which render path to exercise. `in-process` (default) calls+ * `executeRenderJob`; `distributed-simulated` calls+ * `plan() → renderChunk() × N → assemble()` from+ * `@hyperframes/producer/distributed`. See+ * `regression-harness-distributed.ts`.+ */+ mode: HarnessMode;};type TestResult = {suite: TestSuite;passed: boolean;+ /**+ * Set when `--mode=distributed-simulated` skips a fixture that the+ * distributed pipeline can't run (webm, HDR, NTSC fps, fps∉{24,30,60}).+ * `passed` is `true` for skipped fixtures — skipping is a clean outcome,+ * not a failure — but the summary distinguishes them.+ */+ skipped?: { reason: string };compilation?: {passed: boolean;errors: string[];@@ -105,6 +139,7 @@ function parseArgs(argv: string[]): CliOptions {let update = false;let sequential = false;let keepTemp = false;+ let mode: HarnessMode = "in-process";for (let i = 2; i < argv.length; i += 1) {const token = argv[i];@@ -119,12 +154,29 @@ function parseArgs(argv: string[]): CliOptions {i += 1;const tagArg = argv[i];if (tagArg) excludeTags.push(...tagArg.split(","));- } else if (!token.startsWith("--")) {- testNames.push(token);+ } else {+ const parsedMode = parseHarnessModeFlag(token);+ if (parsedMode !== null) {+ mode = parsedMode;+ } else if (!token.startsWith("--")) {+ testNames.push(token);+ }}}- return { testNames, excludeTags, update, sequential, keepTemp };+ if (update && mode === "distributed-simulated") {+ // The in-process renderer is the source of truth for golden baselines —+ // distributed-simulated's job is to verify the contract against the+ // same baseline, not to author its own. Surfacing this at parse time+ // saves a multi-minute render before the user notices.+ throw new Error(+ "regression-harness: --update is incompatible with --mode=distributed-simulated. " ++ "Generate baselines with the in-process renderer (the default mode), then re-run " ++ "without --update to verify both modes match.",+ );+ }++ return { testNames, excludeTags, update, sequential, keepTemp, mode };}function validateMetadata(meta: unknown): TestMetadata {@@ -195,6 +247,20 @@ function validateMetadata(meta: unknown): TestMetadata {) {throw new Error("meta.json: 'renderConfig.variables' must be a JSON object (or omitted)");}+ if (rc.chunkSize !== undefined) {+ if (!Number.isInteger(rc.chunkSize) || (rc.chunkSize as number) < 1) {+ throw new Error(+ "meta.json: 'renderConfig.chunkSize' must be a positive integer (or omitted)",+ );+ }+ }+ if (rc.maxParallelChunks !== undefined) {+ if (!Number.isInteger(rc.maxParallelChunks) || (rc.maxParallelChunks as number) < 1) {+ throw new Error(+ "meta.json: 'renderConfig.maxParallelChunks' must be a positive integer (or omitted)",+ );+ }+ }return m as TestMetadata;}@@ -399,6 +465,7 @@ function saveFailureDetails(result: TestResult,renderedVideoPath: string,snapshotVideoPath: string,+ effectiveMinPsnr: number,compiledHtml?: string,snapshotHtml?: string,): void {@@ -441,12 +508,13 @@ function saveFailureDetails(summary: {totalCheckpoints: result.visual.checkpoints.length,failedCheckpoints: failedCheckpoints.length,- threshold: suite.meta.minPsnr,+ threshold: effectiveMinPsnr,+ fixtureThreshold: suite.meta.minPsnr,},failedFrames: failedCheckpoints.map((c) => ({time: c.time,psnr: c.psnr,- belowThresholdBy: suite.meta.minPsnr - c.psnr,+ belowThresholdBy: effectiveMinPsnr - c.psnr,})),};@@ -522,6 +590,7 @@ async function runTestSuite(options: {update: boolean;keepTemp: boolean;+ mode: HarnessMode;},): Promise<TestResult> {// Use predictable temp location: /tmp/hyperframes-tests/{test-id}/@@ -621,25 +690,68 @@ async function runTestSuite(}// STEP 2: Render video- console.log(JSON.stringify({ event: "rendering_start", suite: suite.id }));- logPretty("Rendering video...", "🎬");+ console.log(JSON.stringify({ event: "rendering_start", suite: suite.id, mode: options.mode }));+ logPretty(`Rendering video (mode=${options.mode})...`, "🎬");const tempSrcDir = join(tempRoot, "src");copyFixtureSupportFiles(suite, tempRoot);cpSync(suite.srcDir, tempSrcDir, { recursive: true });- const job = createRenderJob({- fps: suite.meta.renderConfig.fps,- quality: "high", // Always use max quality for tests- format: outputFormat,- workers: suite.meta.renderConfig.workers,- useGpu: false,- debug: false,- hdrMode: suite.meta.renderConfig.hdr ? "force-hdr" : "force-sdr",- variables: suite.meta.renderConfig.variables,- });+ if (options.mode === "distributed-simulated") {+ const support = checkDistributedSupport(suite.meta.renderConfig);+ if (!support.supported) {+ // Skipping is a clean outcome — the distributed pipeline can't+ // run this fixture, but in-process mode already covers it. Mark+ // passed so the suite summary doesn't trip CI; the `skipped`+ // field is what distinguishes a real pass from a skip.+ console.log(+ JSON.stringify({+ event: "test_skipped",+ suite: suite.id,+ mode: options.mode,+ reason: support.reason,+ }),+ );+ logPretty(`Skipping ${suite.meta.name} (mode=${options.mode}): ${support.reason}`, "⏭️");+ result.passed = true;+ result.skipped = { reason: support.reason };+ return result;+ }+ // The support check narrows `fps.num` to 24|30|60; assert here so+ // TS sees the literal type that `DistributedRenderConfig.fps`+ // requires. The check itself rejected every other value above.+ const fpsNum = suite.meta.renderConfig.fps.num as 24 | 30 | 60;+ const distributedFormat: "mp4" | "mov" | "png-sequence" =+ suite.meta.renderConfig.format === "webm"+ ? // Unreachable — checkDistributedSupport rejected webm above.+ (() => {+ throw new Error("webm reached distributed render path");+ })()+ : (suite.meta.renderConfig.format ?? "mp4");+ await runDistributedSimulatedRender({+ projectDir: tempSrcDir,+ tempRoot,+ renderedOutputPath,+ fps: fpsNum,+ format: distributedFormat,+ chunkSize: suite.meta.renderConfig.chunkSize,+ maxParallelChunks: suite.meta.renderConfig.maxParallelChunks,+ variables: suite.meta.renderConfig.variables,+ });+ } else {+ const job = createRenderJob({+ fps: suite.meta.renderConfig.fps,+ quality: "high", // Always use max quality for tests+ format: outputFormat,+ workers: suite.meta.renderConfig.workers,+ useGpu: false,+ debug: false,+ hdrMode: suite.meta.renderConfig.hdr ? "force-hdr" : "force-sdr",+ variables: suite.meta.renderConfig.variables,+ });- await executeRenderJob(job, tempSrcDir, renderedOutputPath);+ await executeRenderJob(job, tempSrcDir, renderedOutputPath);+ }console.log(JSON.stringify({ event: "rendering_complete", suite: suite.id }));logPretty("Render complete! Starting quality validation...", "✓");@@ -680,6 +792,7 @@ async function runTestSuite(// which causes ffmpeg's PSNR filter to emit no `average:` line.const videoDuration = Math.min(videoMetadata.durationSeconds, snapshotMetadata.durationSeconds);+ const minPsnrForMode = resolveMinPsnrForMode(options.mode, suite.meta.minPsnr);const visualCheckpoints: Array<{ time: number; psnr: number; passed: boolean }> = [];for (let i = 0; i < 100; i++) {const time = (videoDuration * i) / 100;@@ -692,7 +805,7 @@ async function runTestSuite(visualCheckpoints.push({time,psnr,- passed: psnr >= suite.meta.minPsnr,+ passed: psnr >= minPsnrForMode,});// Progress indicator every 20 checkpoints@@ -815,6 +928,7 @@ async function runTestSuite(result,renderedOutputPath,snapshotVideoPath,+ resolveMinPsnrForMode(options.mode, suite.meta.minPsnr),compiledHtml,snapshotHtml,);@@ -857,11 +971,13 @@ async function run(): Promise<void> {event: "test_suite_start",totalSuites: suites.length,parallel: !options.sequential,+ mode: options.mode,}),);logPretty(- `Starting ${suites.length} test suite(s) - ${options.sequential ? "sequential" : "parallel"} mode`,+ `Starting ${suites.length} test suite(s) - ${options.sequential ? "sequential" : "parallel"} mode, ` ++ `harness mode=${options.mode}`,"🚀",);@@ -925,7 +1041,8 @@ async function run(): Promise<void> {);logPretty(`Updated ${results.length} snapshot(s)`, "📸");} else {- const passed = results.filter((r) => r.passed).length;+ const skipped = results.filter((r) => r.skipped).length;+ const passed = results.filter((r) => r.passed && !r.skipped).length;const failed = results.filter((r) => !r.passed).length;const failedAtCompilation = results.filter((r) => r.compilation && !r.compilation.passed,@@ -939,6 +1056,8 @@ async function run(): Promise<void> {total: results.length,passed,failed,+ skipped,+ mode: options.mode,failedAtCompilation,failedAtVisual,failedAtAudio,@@ -946,6 +1065,7 @@ async function run(): Promise<void> {suite: r.suite.id,name: r.suite.meta.name,passed: r.passed,+ skipped: r.skipped?.reason,compilation: r.compilation?.passed,visual: r.visual?.passed,audio: r.audio?.passed,@@ -955,8 +1075,11 @@ async function run(): Promise<void> {// Pretty summarylogPretty("═══════════════════════════════════════", "");- logPretty(`Test Suite Summary`, "📊");- logPretty(`Total: ${results.length} | Passed: ${passed} | Failed: ${failed}`, "");+ logPretty(`Test Suite Summary (mode=${options.mode})`, "📊");+ logPretty(+ `Total: ${results.length} | Passed: ${passed} | Failed: ${failed} | Skipped: ${skipped}`,+ "",+ );if (failed > 0) {logPretty(` Failed at compilation: ${failedAtCompilation}`, "");logPretty(` Failed at visual: ${failedAtVisual}`, "");diff --git a/packages/producer/tests/README.md b/packages/producer/tests/README.mdnew file mode 100644index 0000000000..3f4971ff1d--- /dev/null+++ b/packages/producer/tests/README.md@@ -0,0 +1,151 @@+# Producer regression test fixtures++Each subdirectory under this folder is a **regression fixture** for the+HTML-to-video pipeline. The harness at+`packages/producer/src/regression-harness.ts` walks every subdirectory,+runs the composition, and PSNR-compares the rendered output against a+checked-in golden baseline.++## Fixture layout++```+<fixture-name>/+├── meta.json # name, tags, PSNR threshold, renderConfig+├── src/+│ ├── index.html # composition entry point+│ └── assets/... # any locally-referenced media+└── output/+ ├── compiled.html # golden compiled HTML (validated as a snapshot)+ └── output.mp4 # golden rendered video+```++`meta.json` is validated by `validateMetadata` in+`src/regression-harness.ts`. The required fields are:++- `name` (string), `description` (string), `tags` (string[])+- `minPsnr` (number, dB)+- `maxFrameFailures` (integer)+- `minAudioCorrelation` (0..1), `maxAudioLagWindows` (integer ≥1)+- `renderConfig.fps` (integer like `30` or a rational string like `"30000/1001"`)++Optional `renderConfig` fields:++- `format` — `"mp4"` (default) or `"webm"`+- `workers` — integer ≥ 1+- `hdr` — boolean (default `false`)+- `variables` — JSON object of render-time variable overrides+- `chunkSize` — integer ≥ 1 (used by `--mode=distributed-simulated`)+- `maxParallelChunks` — integer ≥ 1 (used by `--mode=distributed-simulated`)++## Generating / updating a baseline++**Always inside Docker.** Host Chrome / FFmpeg versions drift across+distros, so a baseline captured on the host won't match the bytes CI+renders.++```bash+# From the repo root.+docker build -t hyperframes-producer:test -f Dockerfile.test .++# Generate a baseline (single fixture):+bun run --cwd packages/producer docker:test:update <fixture-name>++# Generate all baselines (rarely needed):+bun run --cwd packages/producer docker:test:update+```++The `--update` flag writes `output/compiled.html` and `output/output.mp4`+from the current render. Without `--update`, the harness compares against+those baselines.++## Running the harness locally++```bash+# Run every fixture (parallel, in-process mode — the default).+bun run --cwd packages/producer docker:test++# Run a single fixture:+bun run --cwd packages/producer docker:test font-variant-numeric++# Run sequentially (lower memory):+bun run --cwd packages/producer docker:test -- --sequential+```++## Harness modes++`--mode=<value>` chooses which render path the harness exercises:++| Mode | What it calls | Use for |+|---|---|---|+| `in-process` (default) | `executeRenderJob` | Day-to-day baselines. This is the same path the `hyperframes render` CLI takes, and it is what produced every existing `output/output.mp4`. |+| `distributed-simulated` | `plan()` → `renderChunk()` × N → `assemble()` from `@hyperframes/producer/distributed` | Validates the distributed pipeline against the in-process baseline. No Temporal or Lambda involvement — the controller and chunk worker are both this process. |++### `--mode=distributed-simulated`++```bash+bun run --cwd packages/producer docker:test -- --mode=distributed-simulated+bun run --cwd packages/producer docker:test font-variant-numeric -- --mode=distributed-simulated+```++The distributed pipeline cannot run every fixture. Fixtures that fail any+of these gates are **skipped** with a clear log line (and counted as+passing in the summary):++- `fps.den !== 1` — distributed mode is integer-fps only (no NTSC).+- `fps.num ∉ {24, 30, 60}` — closed set per `DistributedRenderConfig`.+- `format === "webm"` — `plan()` refuses webm.+- `hdr === true` — distributed mode is SDR-only at v1.++For fixtures that *are* supported, the PSNR threshold tightens to **≥ 50+dB** (the §5.1 determinism contract) or the fixture's own `minPsnr`,+whichever is higher. A failure at this threshold means the distributed+pipeline has drifted from in-process output — file an issue rather than+adjusting the threshold.++`--update` is incompatible with `--mode=distributed-simulated`: the+in-process renderer is the source of truth for baselines, and the+distributed mode's job is to verify the contract against the same+baseline.++### Validating PR 4.1 (the harness mode itself)++The smallest fixtures (`font-variant-numeric`, `many-cuts`) are sufficient+to verify the mode plumbing end to end:++```bash+docker build -t hyperframes-producer:test -f Dockerfile.test .++# In-process: existing behavior, unchanged.+bun run --cwd packages/producer docker:test font-variant-numeric+bun run --cwd packages/producer docker:test many-cuts++# Distributed-simulated: same baselines, distributed pipeline.+bun run --cwd packages/producer docker:test font-variant-numeric -- --mode=distributed-simulated+bun run --cwd packages/producer docker:test many-cuts -- --mode=distributed-simulated+```++Both modes must produce PSNR ≥ 50 dB against the existing baseline. If+`--mode=distributed-simulated` fails on a baseline, the distributed+primitive has a regression — stop, file an issue, do not paper over it+by adjusting the threshold.++## Distributed-only fixtures++Fixtures under `tests/distributed/<name>/` are authored specifically for+the distributed pipeline. They follow the same `meta.json` schema as the+top-level fixtures, but they always set `chunkSize` / `maxParallelChunks`+so a `plan()` over the fixture produces N>1 chunks. Each fixture+exercises one of:++- per-format chunk-boundary correctness (mp4 H.264, mp4 H.265, ProRes, png-sequence)+- per-adapter chunk-seam state preservation (GSAP, Anime.js, Three.js, Lottie, CSS, WAAPI)++See `DISTRIBUTED-RENDERING-PLAN.md` §10.2 for the equivalence axes each+distributed fixture covers.++## Tags++Common `tags` values control which fixtures the default `bun test`+invocation runs. `--exclude-tags transparency` (the default for+`bun test`) skips webm/png-sequence alpha fixtures that need a working+chrome-headless-shell alpha pipeline.