fix(core): give the preview bundler the render's expansion budget (#8306)

* fix(core): give the preview bundler the render's expansion budget

The preview bundler inlined every sub-composition mount with only a depth
limit, so a few small files that mount each other many times assembled a
page without bound. The producer's expansion budget now lives in core, and
the bundler charges every mount and the scripts and styles generated for
it to that budget, and checks each file's size before reading it. Studio
preview shows the refusal instead of falling back to the raw page, whose
mounts the browser would expand the same way.

* refactor: drop comments the names already carry

* test(core): give the preview fan-out budget test a 30 s timeout

The flake gate saw it pass 9 of 10 runs under CPU contention, timing out
at the default 5 s. The neighbouring scoper bound tests use 30 s too.
This commit is contained in:
Michael Wang
2026-11-20 21:22:17 +00:00
committed by GitHub
parent 5f024e34e2
commit 19253b3c86
14 changed files with 268 additions and 7 deletions
+2
View File
@@ -418,6 +418,8 @@ A render refuses any composition HTML file, the entry or a sub-composition, that
The same error refuses a render whose sub-composition mounts add up to more than 64 MB of composition HTML, to more than 10,000 mounts, or to more than 100,000 elements copied by those mounts. Every mount counts, including each repeat of the same file and each mount nested inside another. The scripts and scoped styles generated for those mounts have their own 64 MB limit. Every inline script in a mounted file is wrapped in a few kilobytes of scoping code, and every style rule is prefixed with its host's `data-composition-id`. Many tiny inline scripts, or a long composition id over many style rules, can reach this limit. Merge small scripts and rules, or keep ids short.
Studio preview and the CLI commands that assemble a project, such as `validate` and `compare`, apply the same limits with the same error. Studio shows the error in place of the preview.
<Tip>
Always watch the exported file itself. Preview proves that the project can play; the output file
proves that the delivery is correct.
@@ -0,0 +1,51 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import * as fs from "node:fs";
import * as path from "node:path";
import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark";
import { createStudioServer, type StudioServer } from "./studioServer.js";
import { cleanupStudioServerRoot, makeStudioServerRoot } from "./studioServerTestFixture.js";
const mounts = (src: string, count: number) =>
`<div data-composition-id="scene" data-composition-src="${src}" data-start="0" data-duration="1"></div>`.repeat(
count,
);
let root: string;
let projectDir: string;
let server: StudioServer;
beforeEach(() => {
({ root, projectDir } = makeStudioServerRoot("hf-preview-too-large-"));
// Four levels of ten: 11,110 mounts from five small files.
fs.writeFileSync(
path.join(projectDir, "index.html"),
`<!doctype html><html><body><div data-composition-id="main" data-width="320" data-height="180">${mounts("level-0.html", 10)}</div></body></html>`,
);
for (let level = 0; level < 3; level += 1) {
fs.writeFileSync(
path.join(projectDir, `level-${level}.html`),
`<template><div data-composition-id="scene">${mounts(`level-${level + 1}.html`, 10)}</div></template>`,
);
}
fs.writeFileSync(
path.join(projectDir, "level-3.html"),
`<template><div data-composition-id="scene"><h1>Leaf</h1></div></template>`,
);
server = createStudioServer({ projectDir, projectName: "film" });
});
afterEach(() => {
cleanupStudioServerRoot(server, root);
});
describe("studio preview of a project over the mount limit", () => {
it("serves the refusal, not the raw page that would expand the mounts in the browser", async () => {
const response = await server.app.request("/api/projects/film/preview");
const html = await response.text();
expect(html).toContain(`window.${STUDIO_PREVIEW_ERRORS}=[`);
expect(html).toContain("Mount large or repeated scenes fewer times");
expect(html).not.toContain("<h1>Leaf</h1>");
expect(html).not.toContain('data-composition-src="level-0.html"');
});
});
+2
View File
@@ -613,6 +613,8 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {
);
return html;
} catch (err) {
const { isCompositionTooLargeError } = await import("@hyperframes/core/compiler");
if (isCompositionTooLargeError(err)) throw err;
console.error("[studio] Bundle failed:", err);
return null;
}
@@ -42,6 +42,10 @@ class CompositionTooLargeError extends Error {
}
}
export function isCompositionTooLargeError(error: unknown): error is Error {
return error instanceof Error && "code" in error && error.code === COMPOSITION_TOO_LARGE;
}
const fileTooLarge = (file: string, bytes: number) =>
new CompositionTooLargeError(
`Composition file "${file}" is ${megabytes(bytes)}, over the ` +
@@ -0,0 +1,115 @@
// @vitest-environment node
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, describe, expect, it } from "vitest";
import { MAX_COMPOSITION_HTML_BYTES, MAX_EXPANDED_COMPOSITION_BYTES } from "./compositionSizeLimit";
import { bundleToSingleHtml } from "./htmlBundler";
const dirs: string[] = [];
afterAll(() => {
for (const dir of dirs) rmSync(dir, { recursive: true, force: true });
});
function project(files: Record<string, string>): string {
const dir = mkdtempSync(join(tmpdir(), "hf-bundle-budget-"));
dirs.push(dir);
for (const [name, text] of Object.entries(files)) writeFileSync(join(dir, name), text);
return dir;
}
const mounts = (src: string, count: number) =>
`<div data-composition-id="scene" data-composition-src="${src}" data-start="0" data-duration="2"></div>`.repeat(
count,
);
const root = (body: string) => `<!doctype html><html><body>
<div data-composition-id="main" data-width="320" data-height="180" data-start="0" data-duration="2">
${body}
</div>
<script>window.__timelines = {};</script>
</body></html>`;
const scene = (body: string) =>
`<template><div data-composition-id="scene" data-width="320" data-height="180">${body}</div></template>`;
const bundleError = (dir: string, onRead?: (path: string) => void) =>
bundleToSingleHtml(dir, { inlineAssets: false, onRead }).then(
() => undefined,
(error: unknown) => error,
);
describe("preview bundle expansion budget", () => {
it("refuses small files that mount each other past the mount limit, reading each file once", async () => {
// Four levels of ten: 11,110 mounts from five small files.
const files: Record<string, string> = { "index.html": root(mounts("level-0.html", 10)) };
for (let level = 0; level < 3; level += 1) {
files[`level-${level}.html`] = scene(mounts(`level-${level + 1}.html`, 10));
}
files["level-3.html"] = scene("<h1>Leaf</h1>");
const dir = project(files);
const reads: string[] = [];
const error = await bundleError(dir, (path) => reads.push(path));
expect(error).toMatchObject({
code: "COMPOSITION_TOO_LARGE",
publicMetadata: { exceeded: "mounts" },
});
expect(String(error)).toContain("Mount large or repeated scenes fewer times");
expect(reads.filter((path) => path.endsWith(".html")).length).toBe(5);
}, 30_000);
it("refuses one large file mounted past the byte limit", async () => {
const big = scene(`<p>${"x".repeat(Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 5))}</p>`);
const dir = project({ "index.html": root(mounts("big.html", 6)), "big.html": big });
const error = await bundleError(dir);
expect(error).toMatchObject({
code: "COMPOSITION_TOO_LARGE",
publicMetadata: { exceeded: "bytes" },
});
});
it("refuses scripts and styles generated for mounts past the limit", async () => {
const scripts = `<script>window.n = (window.n || 0) + 1;</script>`.repeat(
Math.ceil(MAX_EXPANDED_COMPOSITION_BYTES / 10_000),
);
const dir = project({
"index.html": root(mounts("scene.html", 1)),
"scene.html": scene(scripts),
});
const error = await bundleError(dir);
expect(error).toMatchObject({
code: "COMPOSITION_TOO_LARGE",
publicMetadata: { exceeded: "generated" },
});
});
it("refuses a sub-composition file over the per-file limit before reading it", async () => {
const dir = project({
"index.html": root(mounts("huge.html", 1)),
"huge.html": "x".repeat(MAX_COMPOSITION_HTML_BYTES + 1),
});
const error = await bundleError(dir);
expect(error).toMatchObject({ code: "COMPOSITION_TOO_LARGE" });
expect(String(error)).toContain('Composition file "huge.html"');
});
it("still bundles a scene mounted a few times, once per mount", async () => {
const dir = project({
"index.html": root(mounts("wrapper.html", 3)),
"wrapper.html": scene(mounts("scene.html", 2)),
"scene.html": scene("<h1>Scene</h1>"),
});
const html = await bundleToSingleHtml(dir, { inlineAssets: false });
expect(html.split("<h1>Scene</h1>").length - 1).toBe(6);
});
});
@@ -71,6 +71,7 @@ import {
import { validateHyperframeHtmlContract } from "./staticGuard";
import { getHyperframeRuntimeScript } from "../generated/runtime-inline";
import { readDeclaredDefaults } from "../runtime/getVariables";
import { assertCompositionFileSize, CompositionExpansionBudget } from "./compositionSizeLimit";
import {
ensureExternalLinkTag,
inlineSubCompositions,
@@ -1110,6 +1111,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
throw new Error(`${entryFile} not found in project directory`);
}
noteRead(indexPath);
assertCompositionFileSize(indexPath, entryFile);
const entryHtml = readTextFile(indexPath);
const mountedShell = readMountedSceneShell(projectDir, entryFile, entryHtml);
const sourceDir = mountedShell ? projectDir : dirname(indexPath);
@@ -1205,6 +1207,7 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
host.hasAttribute("data-composition-src"),
);
const sceneSources = new Map<string, string | null>();
const budget = new CompositionExpansionBudget();
const subCompResult = inlineSubCompositions(document, subCompositionHosts, {
resolveHtml: (srcPath: string) => {
if (!isRelativeUrl(srcPath)) return null;
@@ -1212,14 +1215,17 @@ async function bundleProject(projectDir: string, options?: BundleOptions): Promi
if (!compPath) return null;
let source = sceneSources.get(compPath);
if (source === undefined) {
if (readAllowed(compPath)) assertCompositionFileSize(compPath, srcPath);
const html = safeReadFile(compPath);
source = html === null ? null : readSource(html);
sceneSources.set(compPath, source);
} else {
noteRead(compPath);
}
if (source !== null) budget.charge(srcPath, Buffer.byteLength(source));
return source;
},
chargeEmitted: (srcPath: string, bytes: number) => budget.chargeGenerated(srcPath, bytes),
parseHtml: parseHTMLContent,
hostIdentityMap: hostIdentityByElement,
rewriteInlineStyles: true,
+12
View File
@@ -97,6 +97,18 @@ export {
wrapScopedCompositionScript,
} from "./compositionScoping";
// Size limits on one compile's expansion (shared between bundler and producer)
export {
assertCompositionFileSize,
CompositionExpansionBudget,
isCompositionTooLargeError,
MAX_COMPOSITION_HTML_BYTES,
MAX_EXPANDED_COMPOSITION_BYTES,
MAX_EXPANDED_ELEMENTS,
REMOTE_SCRIPTS,
REMOTE_STYLESHEETS,
} from "./compositionSizeLimit";
// Sub-composition inlining (shared between bundler and producer)
export {
ensureExternalLinkTag,
@@ -10,7 +10,7 @@ import {
MAX_COMPOSITION_HTML_BYTES,
MAX_EXPANDED_COMPOSITION_BYTES,
MAX_EXPANDED_ELEMENTS,
} from "./compositionSizeLimit.js";
} from "@hyperframes/core/compiler";
import {
compileForRender,
inlineExternalScripts,
@@ -109,7 +109,7 @@ import {
CompositionExpansionBudget,
REMOTE_SCRIPTS,
REMOTE_STYLESHEETS,
} from "./compositionSizeLimit.js";
} from "@hyperframes/core/compiler";
import {
escapesAssetRoot,
isPathInside,
@@ -30,7 +30,7 @@ import {
type CompileStageResult,
} from "./compileStage.js";
import type { RenderJob } from "../../renderOrchestrator.js";
import { MAX_COMPOSITION_HTML_BYTES } from "../../compositionSizeLimit.js";
import { MAX_COMPOSITION_HTML_BYTES } from "@hyperframes/core/compiler";
const noopLog = {
error: () => {},
@@ -43,7 +43,7 @@ import { privateCacheRoot, type ChromaSubsampling, type EngineConfig } from "@hy
import { suggestMatchingPreset, type CanvasResolution } from "@hyperframes/core";
import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/core/compiler";
import { readTextFile } from "@hyperframes/parsers/asset-resolution";
import { assertCompositionFileSize } from "../../compositionSizeLimit.js";
import { assertCompositionFileSize } from "@hyperframes/core/compiler";
import type { CompiledComposition } from "../../htmlCompiler.js";
import { compileForRender } from "../../htmlCompiler.js";
import type { ProducerLogger } from "../../../logger.js";
@@ -3,7 +3,14 @@ import {
STUDIO_PREVIEW_ERRORS,
} from "@hyperframes/core/studio-preview-mark";
const htmlText = (text: string) =>
text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
export function previewRefusalPage(message: string): string {
const script = JSON.stringify(message).replace(/</g, "\\u003c");
return `<!doctype html><meta charset="utf-8"><script>window.${STUDIO_PREVIEW_ERRORS}=[${script}]</script><p>${htmlText(message)}</p>`;
}
export function previewErrorPage(status: number): string {
const message = refusedPreviewMessage(status);
return `<!doctype html><meta charset="utf-8"><script>window.${STUDIO_PREVIEW_ERRORS}=[${JSON.stringify(message)}]</script><p>${message}</p>`;
return previewRefusalPage(refusedPreviewMessage(status));
}
@@ -0,0 +1,56 @@
// @vitest-environment node
import { afterEach, describe, expect, it } from "vitest";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { STUDIO_PREVIEW_ERRORS } from "@hyperframes/core/studio-preview-mark";
import { createStudioApi } from "../createStudioApi";
import type { StudioApiAdapter } from "../types";
const dirs: string[] = [];
afterEach(() => {
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const RAW_ENTRY = `<html><head></head><body><div data-composition-src="scene.html"></div></body></html>`;
function api(bundle: StudioApiAdapter["bundle"]) {
const project = mkdtempSync(join(tmpdir(), "hf-preview-too-large-"));
dirs.push(project);
writeFileSync(join(project, "index.html"), RAW_ENTRY);
return createStudioApi({
listProjects: () => [],
resolveProject: async (id) => ({ id, dir: project }),
bundle,
lint: async () => ({ findings: [] }),
runtimeUrl: "/api/runtime.js",
rendersDir: () => join(project, "renders"),
startRender: () => ({ id: "job", status: "rendering", progress: 0, outputPath: "out.mp4" }),
});
}
const tooLarge = (message: string) =>
Object.assign(new Error(message), { code: "COMPOSITION_TOO_LARGE" as const });
describe("a preview over a size limit", () => {
it("shows the refusal instead of the raw page, whose mounts the browser would expand", async () => {
const message = 'Sub-composition mounts, ending at "<b>scene</b>.html", add up to 64.1 MB.';
const res = await api(async () => {
throw tooLarge(message);
}).request("http://localhost/projects/demo/preview");
const page = await res.text();
expect(page).toContain(`window.${STUDIO_PREVIEW_ERRORS}=[`);
expect(page).toContain("&lt;b&gt;scene&lt;/b&gt;.html");
expect(page).not.toContain("<b>scene</b>");
expect(page).not.toContain('data-composition-src="scene.html"');
});
it("still falls back to the raw page for any other bundle failure", async () => {
const res = await api(async () => {
throw new Error("esbuild failed");
}).request("http://localhost/projects/demo/preview");
expect(await res.text()).toContain('data-composition-src="scene.html"');
});
});
+7 -1
View File
@@ -110,6 +110,7 @@ import {
type PreviewApiAdapter,
} from "../helpers/mediaProxyPreview.js";
import { requestSubPath } from "../helpers/requestSubPath.js";
import { previewRefusalPage } from "../helpers/previewErrorPage.js";
import { lazyPreviewImages } from "../helpers/lazyPreviewImages.js";
import { corsProjectVideos } from "../helpers/captureVideos.js";
import { createJobSlots, JobAbandonedError, JobQueueFullError } from "../helpers/jobSlots.js";
@@ -165,6 +166,10 @@ function parseStudioMotionManifestContent(content: string): {
}
/** Preview hooks must install before authored head scripts register media consumers. */
function isCompositionTooLarge(error: unknown): error is Error {
return error instanceof Error && "code" in error && error.code === "COMPOSITION_TOO_LARGE";
}
export function withPreviewRuntime(html: string, runtimeUrl: string): string {
const tag = `<script ${RUNTIME_BOOTSTRAP_ATTR}="1" src="${runtimeUrl}"></script>`;
return insertRuntimeTag(stripEmbeddedRuntimeScripts(html), tag, true);
@@ -584,7 +589,8 @@ export function registerPreviewRoutes(
if (!capture) adapter.previewDocuments?.write(builtKey, bundled);
}
return bundled;
} catch {
} catch (error) {
if (isCompositionTooLarge(error)) return previewRefusalPage(error.message);
// Re-read disk on bundle failure so we serve the latest file content,
// not the pre-request snapshot that may have been saved over.
const fallback = resolveProjectMainHtml(project.dir, project.id);