feat(producer): enforce expected output dimensions before capture (#7871)

This commit is contained in:
terencecho
2026-11-17 05:37:05 +00:00
committed by GitHub
parent 5f6007ffc4
commit 8a13b2cafa
14 changed files with 243 additions and 3 deletions
+12
View File
@@ -106,6 +106,18 @@ segment starts on a keyframe. HLS is SDR only (`hdrMode: "force-hdr"` is
rejected), refuses GPU encoding (GPU encoders ignore the keyframe lock), and is
not available in distributed rendering, Lambda, or Cloud Run.
## Require specific output dimensions
Services can set `expectedOutputDimensions: { width: 1280, height: 720 }` in the render
config or HTTP request. The producer checks the compiled composition and any output
resolution scaling before opening the capture browser. A mismatch fails with
`OUTPUT_DIMENSIONS_MISMATCH`; this option does not resize the composition.
Successful jobs and HTTP completion responses include `outputDimensionsChecked: true`
when this check ran. Distributed planning accepts the same option and reports the
confirmation through `onPlanned`. A caller that requires this contract must reject
an absent confirmation, including responses from older producer versions.
## Inspect output validation
A matching output duration does not prove that every expected frame is present.
@@ -83,6 +83,29 @@ describe("RenderRequest", () => {
parseRenderRequest({ ...value, options: { ...value.options, strictVariables: "yes" } }),
).toThrow(/strictVariables must be a boolean/);
});
it("carries expectedOutputDimensions through the in-process and distributed adapters, and refuses invalid dimensions", () => {
const value = request();
value.options.expectedOutputDimensions = { width: 1280, height: 720 };
expect(renderConfigFromRequest(value).expectedOutputDimensions).toEqual({
width: 1280,
height: 720,
});
const config = distributedConfigFromRequest(value);
expect(config.expectedOutputDimensions).toEqual({ width: 1280, height: 720 });
expect(
renderRequestFromDistributedConfig({
projectDir: value.projectDir,
outputPath: value.outputPath,
config,
}).options.expectedOutputDimensions,
).toEqual({ width: 1280, height: 720 });
expect(() =>
parseRenderRequest({
...value,
options: { ...value.options, expectedOutputDimensions: "yes" },
}),
).toThrow(/expectedOutputDimensions/);
});
it("carries the delivery encoder options through every adapter", () => {
const value = request();
+15
View File
@@ -1,3 +1,7 @@
import {
isExpectedOutputDimensions,
type ExpectedOutputDimensions,
} from "./services/render/outputDimensions.js";
import {
PRORES_PROFILE_NAMES,
isVideoFrameFormat,
@@ -69,6 +73,7 @@ export interface RenderRequestOptions {
pageMotionBlur?: RenderConfig["pageMotionBlur"];
variables?: Record<string, unknown>;
strictVariables?: boolean;
expectedOutputDimensions?: ExpectedOutputDimensions;
outputResolution?: CanvasResolution;
outputResolutionAspectAgnostic?: boolean;
engineConfig: EngineConfig;
@@ -214,6 +219,14 @@ function assertRequestOptionScalars(options: Record<string, unknown>): void {
function assertRequestOptionObjects(options: Record<string, unknown>): void {
validateEngineConfigSnapshot(options.engineConfig);
if (
options.expectedOutputDimensions !== undefined &&
!isExpectedOutputDimensions(options.expectedOutputDimensions)
) {
throw new Error(
"Render request expectedOutputDimensions must contain positive integer width and height",
);
}
if (options.variables !== undefined && !isPlainObject(options.variables)) {
throw new Error("Render request variables must be a JSON object");
}
@@ -361,6 +374,7 @@ export function distributedConfigFromRequest(
planDirSizeLimitBytes: distributed.planDirSizeLimitBytes,
variables: options.variables,
strictVariables: options.strictVariables,
expectedOutputDimensions: options.expectedOutputDimensions,
};
}
@@ -412,6 +426,7 @@ export function renderRequestFromDistributedConfig(input: {
...optionalProperty("entryFile", config.entryFile),
...optionalProperty("variables", config.variables),
...optionalProperty("strictVariables", config.strictVariables),
...optionalProperty("expectedOutputDimensions", config.expectedOutputDimensions),
} satisfies CreateRenderRequestInput["options"];
return createRenderRequest({
projectDir: input.projectDir,
@@ -5,7 +5,11 @@ import { Hono } from "hono";
import { afterAll, describe, expect, it, vi } from "vitest";
import { referenceBackgroundResult, type ReferenceBackground } from "@hyperframes/engine";
const state = vi.hoisted(() => ({ background: undefined as unknown }));
const state = vi.hoisted(() => ({
background: undefined as unknown,
dimensionsChecked: undefined as boolean | undefined,
config: {} as Record<string, unknown>,
}));
vi.mock("./services/renderOrchestrator.js", () => ({
RenderCancelledError: class extends Error {},
createRenderJob: (config: Record<string, unknown>) => ({ config, progress: 0, warnings: [] }),
@@ -15,6 +19,8 @@ vi.mock("./services/renderOrchestrator.js", () => ({
outputPath: string,
) => {
job.reference_background = state.background;
job.outputDimensionsChecked = state.dimensionsChecked;
state.config = job.config as Record<string, unknown>;
job.outcome = "completed";
writeFileSync(outputPath, "fixture");
},
@@ -83,3 +89,54 @@ describe("completed render reference background", () => {
expect(terminal.producerVersion).toBe(pkg.version);
});
});
describe("output dimension confirmation", () => {
it.each([true, undefined])(
"transports the renderer confirmation %s without inventing it",
async (checked) => {
state.dimensionsChecked = checked;
const handlers = createRenderHandlers({ rendersDir: dir });
const app = new Hono();
app.post("/render", handlers.render);
app.post("/stream", handlers.renderStream);
for (const path of ["/render", "/stream"]) {
const response = await app.request(path, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
html: "<html/>",
expectedOutputDimensions: { width: 1280, height: 720 },
}),
});
expect(response.status).toBe(200);
const result =
path === "/render"
? await response.json()
: (await response.text())
.split("\n")
.filter((line) => line.startsWith("data:"))
.map((line) => JSON.parse(line.slice(5)))
.find((event) => event.type === "complete");
expect(state.config.expectedOutputDimensions).toEqual({ width: 1280, height: 720 });
expect(result.outputDimensionsChecked).toBe(checked);
}
},
);
it.each([
null,
{},
{ width: 0, height: 720 },
{ width: 1280.5, height: 720 },
{ width: "1280", height: 720 },
])("rejects invalid dimension constraints %j before rendering", async (dimensions) => {
const app = new Hono();
app.post("/render", createRenderHandlers({ rendersDir: dir }).render);
const response = await app.request("/render", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ html: "<html/>", expectedOutputDimensions: dimensions }),
});
expect(response.status).toBe(400);
expect(await response.json()).toMatchObject({ success: false });
});
});
+22
View File
@@ -1,4 +1,5 @@
#!/usr/bin/env node
/**
* @hyperframes/producer — Public Server
*
@@ -13,6 +14,10 @@
* GET /outputs/:token — download rendered MP4
*/
import {
isExpectedOutputDimensions,
type ExpectedOutputDimensions,
} from "./services/render/outputDimensions.js";
import {
existsSync,
mkdirSync,
@@ -131,6 +136,7 @@ interface RenderInput {
variables?: Record<string, unknown>;
/** Fails with `VARIABLES_INVALID` before any frame if `variables` mismatch the page's declarations. Default off. */
strictVariables?: boolean;
expectedOutputDimensions?: ExpectedOutputDimensions;
/**
* Output resolution preset (e.g. `landscape-4k`). Drives the same
* `resolveDeviceScaleFactor` supersampling path the local CLI uses — Chrome
@@ -293,6 +299,9 @@ export function parseRenderOptions(body: Record<string, unknown>): Omit<RenderIn
outputDynamicRange,
variables,
strictVariables,
expectedOutputDimensions: isExpectedOutputDimensions(body.expectedOutputDimensions)
? body.expectedOutputDimensions
: undefined,
outputResolution,
outputResolutionAspectAgnostic,
videoFrameFormat,
@@ -361,6 +370,7 @@ function buildRenderJobConfig(input: RenderInput, outputPath: string, log: Produ
entryFile: input.entryFile,
variables: input.variables,
strictVariables: input.strictVariables,
expectedOutputDimensions: input.expectedOutputDimensions,
outputResolution: input.outputResolution,
outputResolutionAspectAgnostic: input.outputResolutionAspectAgnostic,
videoFrameFormat: input.videoFrameFormat,
@@ -448,6 +458,12 @@ function validateRenderOverrides(body: Record<string, unknown>): string | undefi
if (body.variables !== undefined && !isPlainObject(body.variables)) {
return 'variables must be a JSON object keyed by variable id (e.g. {"title":"Hello"})';
}
if (
body.expectedOutputDimensions !== undefined &&
!isExpectedOutputDimensions(body.expectedOutputDimensions)
) {
return "expectedOutputDimensions must contain positive integer width and height";
}
if (body.strictVariables !== undefined && typeof body.strictVariables !== "boolean") {
return "strictVariables must be a boolean";
}
@@ -941,6 +957,9 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
warnings: job.warnings,
perf: policy ? publicPerfSummary(job) : (job.perfSummary ?? null),
...strictVariablesResult(job),
...(job.outputDimensionsChecked === undefined
? {}
: { outputDimensionsChecked: job.outputDimensionsChecked }),
});
} catch (error) {
const durationMs = Date.now() - t0;
@@ -1045,6 +1064,9 @@ export function createRenderHandlers(options: HandlerOptions = {}): RenderHandle
perf: policy ? publicPerfSummary(job) : (job.perfSummary ?? null),
producerVersion: readProducerVersion(),
...strictVariablesResult(job),
...(job.outputDimensionsChecked === undefined
? {}
: { outputDimensionsChecked: job.outputDimensionsChecked }),
}),
});
} catch (error) {
@@ -1,3 +1,4 @@
import type { ExpectedOutputDimensions } from "../render/outputDimensions.js";
import {
REFERENCE_BACKGROUND_FIELD,
referenceBackgroundResult,
@@ -313,6 +314,7 @@ export interface DistributedRenderConfig extends Pick<RenderRequestOptions, "pag
variables?: Record<string, unknown>;
/** Fails with `VARIABLES_INVALID` before any frame if `variables` mismatch the page's declarations. Default off. */
strictVariables?: boolean;
expectedOutputDimensions?: ExpectedOutputDimensions;
}
/** Shared local representation consumed by both distributed plan transports. */
@@ -329,6 +331,7 @@ export interface LocalExecutionPlan extends Partial<ReferenceBackgroundResult> {
producerVersion: string;
/** Present when `strictVariables` was asked; true only if this producer honoured it. */
strictVariablesChecked?: boolean;
outputDimensionsChecked?: boolean;
}
export interface BuildLocalExecutionPlanOptions {
@@ -396,6 +399,7 @@ export interface PlanResult extends Partial<ReferenceBackgroundResult> {
producerVersion: string;
/** Present when `strictVariables` was asked; true only if this producer honoured it. */
strictVariablesChecked?: boolean;
outputDimensionsChecked?: boolean;
}
/** Applies the same audio correctness policy used by the in-process renderer. */
@@ -1252,6 +1256,7 @@ async function compilePlanComposition(
producerConfig: cfg,
variables: config.variables,
strictVariables: config.strictVariables,
expectedOutputDimensions: config.expectedOutputDimensions,
pageMotionBlur: config.pageMotionBlur,
allowOutsideProjectAssets: options.allowOutsideProjectAssets === true,
includeOutsideScripts: options.includeOutsideScripts === true,
@@ -1866,6 +1871,9 @@ export async function buildLocalExecutionPlan(
format: config.format,
ffmpegVersion,
producerVersion,
...(job.outputDimensionsChecked === undefined
? {}
: { outputDimensionsChecked: job.outputDimensionsChecked }),
...(job.strictVariablesChecked === undefined
? {}
: { strictVariablesChecked: job.strictVariablesChecked }),
@@ -1939,6 +1947,9 @@ export async function plan(
format: executionPlan.format,
ffmpegVersion: executionPlan.ffmpegVersion,
producerVersion: executionPlan.producerVersion,
...(executionPlan.outputDimensionsChecked === undefined
? {}
: { outputDimensionsChecked: executionPlan.outputDimensionsChecked }),
...(executionPlan.strictVariablesChecked === undefined
? {}
: { strictVariablesChecked: executionPlan.strictVariablesChecked }),
@@ -160,7 +160,10 @@ export interface PlanV2WithPublisherOptions {
readonly remoteFiles?: BuildLocalExecutionPlanOptions["remoteFiles"];
readonly chunksCarryAudio?: boolean;
readonly deferAudio?: boolean;
readonly onPlanned?: (summary: { readonly strictVariablesChecked?: boolean }) => void;
readonly onPlanned?: (summary: {
readonly strictVariablesChecked?: boolean;
readonly outputDimensionsChecked?: boolean;
}) => void;
}
export interface PlanV2MaterializationResult {
@@ -790,7 +793,10 @@ export async function planV2WithPublisher(
sliceChunkAudio: true,
deferAudio: options.deferAudio,
});
options.onPlanned?.({ strictVariablesChecked: planned.strictVariablesChecked });
options.onPlanned?.({
strictVariablesChecked: planned.strictVariablesChecked,
outputDimensionsChecked: planned.outputDimensionsChecked,
});
return await publishExecutionPlan(stagingRoot, publisher, { digests, log: config.logger });
} catch (error) {
try {
@@ -1,3 +1,4 @@
import { isExpectedOutputDimensions } from "../render/outputDimensions.js";
/**
* Cloud-agnostic validation of a serializable `DistributedRenderConfig`.
*
@@ -90,6 +91,15 @@ export function validateDistributedRenderConfig(
);
}
if (
config.expectedOutputDimensions !== undefined &&
!isExpectedOutputDimensions(config.expectedOutputDimensions)
) {
throw new InvalidConfigError(
"config.expectedOutputDimensions",
"must contain positive integer width and height",
);
}
validateIntDimension("config.width", config.width);
validateIntDimension("config.height", config.height);
@@ -445,6 +445,7 @@ export interface SyntheticRenderJobInput {
/** Render-time overrides consumed by the plan browser probe. */
variables?: RenderConfig["variables"];
strictVariables?: RenderConfig["strictVariables"];
expectedOutputDimensions?: RenderConfig["expectedOutputDimensions"];
pageMotionBlur?: RenderConfig["pageMotionBlur"];
allowOutsideProjectAssets?: boolean;
includeOutsideScripts?: boolean;
@@ -476,6 +477,7 @@ export function buildSyntheticRenderJob(input: SyntheticRenderJobInput): RenderJ
producerConfig: input.producerConfig,
variables: input.variables,
strictVariables: input.strictVariables,
expectedOutputDimensions: input.expectedOutputDimensions,
pageMotionBlur: input.pageMotionBlur,
allowOutsideProjectAssets: input.allowOutsideProjectAssets,
includeOutsideScripts: input.includeOutsideScripts,
@@ -0,0 +1,42 @@
export interface ExpectedOutputDimensions {
width: number;
height: number;
}
export function isExpectedOutputDimensions(value: unknown): value is ExpectedOutputDimensions {
return (
typeof value === "object" &&
value !== null &&
"width" in value &&
"height" in value &&
typeof value.width === "number" &&
typeof value.height === "number" &&
Number.isSafeInteger(value.width) &&
Number.isSafeInteger(value.height) &&
value.width > 0 &&
value.height > 0
);
}
class OutputDimensionsMismatchError extends Error {
readonly code = "OUTPUT_DIMENSIONS_MISMATCH";
constructor() {
super("Compiled output dimensions do not match the requested render dimensions.");
}
}
export function requireOutputDimensions(
expected: ExpectedOutputDimensions | undefined,
width: number,
height: number,
): void {
if (
expected !== undefined &&
(!isExpectedOutputDimensions(expected) ||
expected.width !== width ||
expected.height !== height)
) {
throw new OutputDimensionsMismatchError();
}
}
@@ -659,3 +659,36 @@ describe("runCompileStage — chromaSubsampling 444 drawElement gate", () => {
}
});
});
describe("compiled output dimension contract", () => {
it.each([
[1920, 1080, true],
[1280, 720, false],
[8000, 8000, false],
])("checks actual HTML size %i by %i before capture", async (width, height, accepted) => {
const fixture = setupFixture(orientedHtml(width, height));
const job = createJob();
job.config.expectedOutputDimensions = { width: 1920, height: 1080 };
try {
const result = runCompileStage({
projectDir: join(fixture.workDir, "project"),
workDir: fixture.workDir,
entryFile: "index.html",
job,
cfg: createCfg(),
needsAlpha: false,
log: noopLog,
assertNotAborted: () => {},
});
if (accepted) {
await expect(result).resolves.toMatchObject({ outputWidth: 1920, outputHeight: 1080 });
expect(job.outputDimensionsChecked).toBe(true);
} else {
await expect(result).rejects.toMatchObject({ code: "OUTPUT_DIMENSIONS_MISMATCH" });
expect(job.outputDimensionsChecked).toBeUndefined();
}
} finally {
fixture.cleanup();
}
});
});
@@ -35,6 +35,7 @@
* same behavior as before this PR.
*/
import { requireOutputDimensions } from "../outputDimensions.js";
import { existsSync, writeFileSync } from "node:fs";
import { join, relative } from "node:path";
import { escapesAssetRoot } from "../../../utils/paths.js";
@@ -418,6 +419,8 @@ export async function runCompileStage(input: CompileStageInput): Promise<Compile
});
const outputWidth = Math.round(width * deviceScaleFactor);
const outputHeight = Math.round(height * deviceScaleFactor);
requireOutputDimensions(job.config.expectedOutputDimensions, outputWidth, outputHeight);
if (job.config.expectedOutputDimensions !== undefined) job.outputDimensionsChecked = true;
if (deviceScaleFactor !== 1) {
log.info("Scaling composition via deviceScaleFactor", {
compositionWidth: width,
@@ -1,3 +1,4 @@
import type { ExpectedOutputDimensions } from "./render/outputDimensions.js";
import { audioFailureDiagnostics } from "@hyperframes/engine";
// fallow-ignore-file unused-type circular-dependency code-duplication complexity
/**
@@ -496,6 +497,7 @@ export interface RenderConfig {
*/
variables?: Record<string, unknown>;
strictVariables?: boolean;
expectedOutputDimensions?: ExpectedOutputDimensions;
/**
* Override the output resolution via Chrome `deviceScaleFactor` (DPR).
* The composition's authored dimensions are unchanged. See
@@ -807,6 +809,7 @@ export interface RenderStageProgress {
export interface RenderJob extends Partial<ReferenceBackgroundResult> {
id: string;
strictVariablesChecked?: boolean;
outputDimensionsChecked?: boolean;
config: RenderConfig;
status: RenderStatus;
progress: number;
@@ -11,6 +11,7 @@ const SAFE_RENDER_ERROR_CODES = new Set<string>([
"RENDER_STAGE_STALLED",
"PAGE_NEVER_READY",
"VARIABLES_INVALID",
"OUTPUT_DIMENSIONS_MISMATCH",
"COMPOSITION_TOO_LARGE",
]);