fix(producer): a render's compile runs on its own thread and stops at a deadline (#8611)

A compile that ran long held the render server's main thread, so the
render's cancel, its maxRenderMs guard, a client disconnect and /health
could not act until it finished. The compile now runs on a worker
thread. The render's abort signal stops it, and a 10-minute cap ends it
with COMPILE_TIMEOUT, a non-retryable user error. Production compiles
over 7 days peaked at 154 s (p99.9 18 s). HYPERFRAMES_COMPILE_TIMEOUT_MS
overrides the cap.

Bundles that inline the producer name the worker with
HF_COMPILE_WORKER_ENTRY, or compile in-process as before. The producer's
packed-size budget grows for the worker bundle.
This commit is contained in:
Vance Ingalls
2026-11-23 10:34:44 -08:00
committed by GitHub
parent 4f863db6d7
commit 590617475f
13 changed files with 444 additions and 16 deletions
+5
View File
@@ -61,6 +61,8 @@
"packages/producer/src/services/healthWorkerThread.ts",
// Worker thread of runHyperframeLint, spawned by path from hyperframeLint.ts.
"packages/producer/src/services/hyperframeLintWorker.ts",
// Render compile worker, spawned by path from compileInWorker.ts.
"packages/producer/src/services/compileWorker.ts",
// Render-setup worker, spawned by path from cancellableProcess.ts.
"packages/cli/src/renderSetupWorker.ts",
// Sub-composition build worker, started by path from subCompositionBuild.ts (.dev.mjs from source under Node).
@@ -81,6 +83,9 @@
"packages/producer/src/services/__fixtures__/crashOnMessageWorker.mjs",
// Test fixture worker for runHyperframeLint, passed by path as its workerEntry option.
"packages/producer/src/services/__fixtures__/lintWorkerStuck.mjs",
// Test fixture workers for compileForRenderInWorker, passed by path as its entry option.
"packages/producer/src/services/__fixtures__/compileWorkerFake.mjs",
"packages/producer/src/services/__fixtures__/compileWorkerTs.mjs",
"scripts/**/*.{ts,mjs,js}",
"scripts/*/run.mjs",
// Keyframe UI components — wired dynamically via EaseCurveSection/MotionPanel.
+2
View File
@@ -420,6 +420,8 @@ The same error refuses a render whose sub-composition mounts add up to more than
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.
The render server compiles each composition on its own thread and stops a compile that runs past 10 minutes, with the error code `COMPILE_TIMEOUT`. Retrying the same composition fails the same way. Real compositions compile in seconds, so this usually means a very large page or one with very many style rules or media tags. Operators can change the limit with `HYPERFRAMES_COMPILE_TIMEOUT_MS`.
<Tip>
Always watch the exported file itself. Preview proves that the project can play; the output file
proves that the delivery is correct.
+1
View File
@@ -9,4 +9,5 @@ export const WORKERS = [
{ entry: "src/services/shaderTransitionWorker.ts", outfile: "dist/shaderTransitionWorker.js" },
{ entry: "src/services/healthWorkerThread.ts", outfile: "dist/healthWorkerThread.js" },
{ entry: "src/services/hyperframeLintWorker.ts", outfile: "dist/hyperframeLintWorker.js" },
{ entry: "src/services/compileWorker.ts", outfile: "dist/compileWorker.js" },
];
@@ -30,6 +30,7 @@
"src/services/fileServer.host.test.ts",
"src/services/fileServer.listenError.test.ts",
"src/services/outsideProjectAssets.test.ts",
"src/services/compileInWorker.test.ts",
"src/services/healthWorker.test.ts",
"src/services/hyperframeLint.worker.test.ts",
"src/server.lintWorker.test.ts",
+7 -1
View File
@@ -6,8 +6,14 @@ describe("published build layout", () => {
it("emits each worker beside the bundles whose worker lookup probes their own directory", () => {
const bundleDirs = new Set(BUNDLES.map(({ outfile }) => dirname(outfile)));
expect([...bundleDirs]).toEqual(["dist"]);
expect(WORKERS.map(({ outfile }) => dirname(outfile))).toEqual(["dist", "dist", "dist"]);
expect(WORKERS.map(({ outfile }) => dirname(outfile))).toEqual([
"dist",
"dist",
"dist",
"dist",
]);
expect(WORKERS.map(({ outfile }) => basename(outfile)).sort()).toEqual([
"compileWorker.js",
"healthWorkerThread.js",
"hyperframeLintWorker.js",
"shaderTransitionWorker.js",
@@ -0,0 +1,21 @@
// Stands in for compileWorker.ts. workerData.projectDir picks the behaviour: "hang" spins in one
// synchronous pass and never answers, "typed" fails with a typed producer error.
import { parentPort, workerData } from "node:worker_threads";
if (workerData.projectDir === "hang") {
for (;;);
} else if (workerData.projectDir === "typed") {
parentPort.postMessage({
type: "error",
error: {
name: "CompositionTooLargeError",
message: "too large",
props: {
code: "COMPOSITION_TOO_LARGE",
owner: "user",
retryable: false,
publicMetadata: { bytes: 2, limitBytes: 1 },
},
},
});
}
@@ -0,0 +1,6 @@
// Loads the real compileWorker.ts under tsx for tests: a worker's own entry loads before --import hooks
// can map its ".js" imports to ".ts" sources, so the hooks are registered first and the entry imported after.
import { register } from "tsx/esm/api";
register();
await import("../compileWorker.ts");
@@ -0,0 +1,146 @@
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { Worker } from "node:worker_threads";
import { afterEach, describe, expect, it, vi } from "vitest";
import { compileForRenderInWorker } from "./compileInWorker.js";
import { compileForRender } from "./htmlCompiler.js";
import { extractSafeRenderErrorMetadata } from "../server.js";
const FAKE = resolve(import.meta.dirname, "__fixtures__/compileWorkerFake.mjs");
const REAL = resolve(import.meta.dirname, "__fixtures__/compileWorkerTs.mjs");
const cleanups: Array<() => void> = [];
afterEach(() => {
for (const cleanup of cleanups.splice(0)) cleanup();
});
describe("compileForRenderInWorker", () => {
it("ends a compile stuck in a synchronous pass at its deadline, with a typed non-retryable error", async () => {
const terminate = vi.spyOn(Worker.prototype, "terminate");
cleanups.push(() => terminate.mockRestore());
const began = performance.now();
const error = await compileForRenderInWorker(
"hang",
"x.html",
"d",
{},
{
entry: FAKE,
timeoutMs: 300,
},
).catch((e: unknown) => e);
expect(performance.now() - began).toBeLessThan(3_000);
expect(extractSafeRenderErrorMetadata(error)).toEqual({
errorCode: "COMPILE_TIMEOUT",
errorOwner: "user",
retryable: false,
errorMetadata: { timeoutMs: 300 },
});
// The stuck thread itself ends, not only the promise.
await vi.waitFor(() => expect(terminate).toHaveBeenCalled(), { timeout: 5_000 });
await expect(terminate.mock.results[0]?.value).resolves.toBeTypeOf("number");
});
it("keeps the main thread answering /health while the compile is stuck", async () => {
const server: Server = createServer((_req, res) => res.end("ok"));
await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));
cleanups.push(() => server.close());
const { port } = server.address() as AddressInfo;
let settled = false;
const compile = compileForRenderInWorker(
"hang",
"x.html",
"d",
{},
{
entry: FAKE,
timeoutMs: 1_500,
},
).catch(() => {});
void compile.then(() => (settled = true));
const health = await fetch(`http://127.0.0.1:${port}/health`).then((r) => r.text());
expect(health).toBe("ok");
expect(settled).toBe(false);
await compile;
});
it("ends the compile with the render's abort reason when the render is cancelled", async () => {
const controller = new AbortController();
const reason = new Error("render cancelled");
setTimeout(() => controller.abort(reason), 100);
const began = performance.now();
const error = await compileForRenderInWorker(
"hang",
"x.html",
"d",
{ abortSignal: controller.signal },
{ entry: FAKE, timeoutMs: 10_000 },
).catch((e: unknown) => e);
expect(error).toBe(reason);
expect(performance.now() - began).toBeLessThan(3_000);
});
it("keeps a typed compile error's code, owner, retryability and metadata across the thread", async () => {
const error = await compileForRenderInWorker("typed", "x.html", "d", {}, { entry: FAKE }).catch(
(e: unknown) => e,
);
expect(extractSafeRenderErrorMetadata(error)).toEqual({
errorCode: "COMPOSITION_TOO_LARGE",
errorOwner: "user",
retryable: false,
errorMetadata: { bytes: 2, limitBytes: 1 },
});
});
it("brings a real compile's typed refusal back with its wire fields", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-compile-worker-"));
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
writeFileSync(
join(dir, "index.html"),
`<!doctype html><html><head></head><body><main data-composition-id="main" data-start="0" data-width="320" data-height="180" data-duration="1">${"<i></i>".repeat(100_001)}</main></body></html>`,
);
const error = await compileForRenderInWorker(
dir,
join(dir, "index.html"),
dir,
{},
{
entry: REAL,
},
).catch((e: unknown) => e);
expect(extractSafeRenderErrorMetadata(error)).toMatchObject({
errorCode: "COMPOSITION_TOO_LARGE",
errorOwner: "user",
retryable: false,
errorMetadata: { exceeded: "elements" },
});
}, 60_000);
it("compiles a project on the real worker exactly as in-process", async () => {
const dir = mkdtempSync(join(tmpdir(), "hf-compile-worker-"));
cleanups.push(() => rmSync(dir, { recursive: true, force: true }));
mkdirSync(join(dir, "downloads"));
writeFileSync(
join(dir, "index.html"),
`<!doctype html><html><head></head><body>
<main data-composition-id="main" data-start="0" data-width="320" data-height="180" data-duration="1"><p>x</p></main>
</body></html>`,
);
const html = join(dir, "index.html");
const downloads = join(dir, "downloads");
const logged: string[] = [];
const log = {
error: (m: string) => logged.push(m),
warn: (m: string) => logged.push(m),
info: (m: string) => logged.push(m),
debug: (m: string) => logged.push(m),
};
const inProcess = await compileForRender(dir, html, downloads, { log });
const onWorker = await compileForRenderInWorker(dir, html, downloads, { log }, { entry: REAL });
expect(onWorker).toEqual(inProcess);
}, 60_000);
});
@@ -0,0 +1,164 @@
import { existsSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { Worker } from "node:worker_threads";
import {
compileForRender,
type CompiledComposition,
type CompileForRenderOptions,
} from "./htmlCompiler.js";
/**
* Production compiles over 7 days (1.3M renders) took 18 s at p99.9 and 154 s at most, so ten
* minutes ends only a compile that has stopped making progress. `HYPERFRAMES_COMPILE_TIMEOUT_MS`
* overrides it.
*/
const DEFAULT_COMPILE_TIMEOUT_MS = 10 * 60 * 1000;
const TERMINATE_GRACE_MS = 2_000;
// Video advisories keep running after the compile returns; they get this long, then the thread ends.
const ADVISORY_GRACE_MS = 30_000;
// setTimeout runs a longer delay after 1 ms, which would end every compile at once.
const MAX_TIMER_MS = 2 ** 31 - 1;
class CompileTimeoutError extends Error {
readonly code = "COMPILE_TIMEOUT" as const;
readonly owner = "user" as const;
readonly retryable = false as const;
readonly publicMetadata: Readonly<{ timeoutMs: number }>;
constructor(timeoutMs: number) {
super(
`Compiling the composition took longer than ${Math.round(timeoutMs / 1000)} s, so it was stopped. ` +
"Very large pages, or pages with very many style rules or media tags, are the usual cause.",
);
this.name = "CompileTimeoutError";
this.publicMetadata = { timeoutMs };
}
}
function compileTimeoutMs(): number {
const fromEnv = Number(process.env.HYPERFRAMES_COMPILE_TIMEOUT_MS);
return Number.isInteger(fromEnv) && fromEnv > 0
? Math.min(fromEnv, MAX_TIMER_MS)
: DEFAULT_COMPILE_TIMEOUT_MS;
}
let warnedMissingEntry = false;
/**
* The published build emits the compile worker beside this module. Bundles that inline the producer
* (the CLI, Lambda, other servers built on it) don't, so they name it with `HF_COMPILE_WORKER_ENTRY`
* or compile in-process as before.
*/
function resolveCompileWorkerEntry(
explicit: string | undefined,
log: CompileForRenderOptions["log"],
): string | undefined {
if (explicit) return explicit;
const fromEnv = process.env.HF_COMPILE_WORKER_ENTRY;
if (fromEnv) {
if (existsSync(fromEnv)) return fromEnv;
if (!warnedMissingEntry) {
warnedMissingEntry = true;
log?.warn(
"[Compiler] HF_COMPILE_WORKER_ENTRY names a missing file, so compiles run on the main thread with no deadline",
{ entry: fromEnv },
);
}
return undefined;
}
const sibling = join(dirname(fileURLToPath(import.meta.url)), "compileWorker.js");
return existsSync(sibling) ? sibling : undefined;
}
type SerializedError = { name: string; message: string; stack?: string; props: object };
function rebuildError({ name, message, stack, props }: SerializedError): Error {
const error = Object.assign(new Error(message), props);
error.name = name;
if (stack) error.stack = stack;
return error;
}
/**
* {@link compileForRender} on a worker thread. A compile that runs past its deadline ends with a
* {@link CompileTimeoutError}, and `options.abortSignal` ends it with the signal's reason. Either
* way the thread is stopped, even inside a synchronous pass, and this thread stays free meanwhile.
*/
export async function compileForRenderInWorker(
projectDir: string,
htmlPath: string,
downloadDir: string,
options: CompileForRenderOptions = {},
worker: { entry?: string; timeoutMs?: number } = {},
): Promise<CompiledComposition> {
const { log, abortSignal, ...cloneable } = options;
const entry = resolveCompileWorkerEntry(worker.entry, log);
if (!entry) return compileForRender(projectDir, htmlPath, downloadDir, options);
abortSignal?.throwIfAborted();
const timeoutMs = worker.timeoutMs ?? compileTimeoutMs();
return new Promise<CompiledComposition>((resolve, reject) => {
const thread = new Worker(entry, {
workerData: { projectDir, htmlPath, downloadDir, options: cloneable },
});
let settled = false;
const settle = (finish: () => void) => {
if (settled) return;
settled = true;
clearTimeout(timer);
abortSignal?.removeEventListener("abort", onAbort);
finish();
};
const stop = () => {
thread.postMessage({ type: "abort" });
setTimeout(() => void thread.terminate(), TERMINATE_GRACE_MS).unref();
};
const timer = setTimeout(() => {
stop();
settle(() => reject(new CompileTimeoutError(timeoutMs)));
}, timeoutMs);
const onAbort = () => {
stop();
settle(() => reject(abortSignal?.reason ?? new Error("Compile aborted")));
};
abortSignal?.addEventListener("abort", onAbort, { once: true });
// Once answered, the thread may still hold downloads or probes; it never keeps the process open
// and ends after the grace.
const retire = (graceMs: number) => {
thread.unref();
setTimeout(() => void thread.terminate(), graceMs).unref();
};
thread.on(
"message",
(message: {
type: string;
level?: "error" | "warn" | "info" | "debug";
message?: string;
meta?: Record<string, unknown>;
compiled?: CompiledComposition;
error?: SerializedError;
}) => {
if (message.type === "log" && message.level) {
log?.[message.level](message.message ?? "", message.meta);
} else if (message.type === "result" && message.compiled) {
const { compiled } = message;
settle(() => resolve(compiled));
retire(ADVISORY_GRACE_MS);
} else if (message.type === "error" && message.error) {
const { error } = message;
settle(() => reject(rebuildError(error)));
thread.postMessage({ type: "abort" });
retire(TERMINATE_GRACE_MS);
}
},
);
thread.on("error", (error) => settle(() => reject(error)));
thread.on("exit", (code) =>
settle(() =>
reject(new Error(`The compile worker exited with code ${code} before answering`)),
),
);
});
}
@@ -0,0 +1,70 @@
// Compiles workerData's project on its own thread, so a page that makes the compile run long holds up
// this thread only: the parent keeps answering /health and other requests, and can end it at a deadline.
import { parentPort, workerData } from "node:worker_threads";
import { compileForRender, type CompileForRenderOptions } from "./htmlCompiler.js";
import type { ProducerLogger } from "../logger.js";
const { projectDir, htmlPath, downloadDir, options } = workerData as {
projectDir: string;
htmlPath: string;
downloadDir: string;
options: Omit<CompileForRenderOptions, "log" | "abortSignal">;
};
function post(level: string, message: string, meta?: Record<string, unknown>): void {
try {
parentPort?.postMessage({ type: "log", level, message, meta });
} catch {
// A meta that structured clone refuses (a function, say) must not fail the compile.
let plain: Record<string, unknown> | undefined;
try {
plain = JSON.parse(JSON.stringify(meta)) as Record<string, unknown>;
} catch {
plain = undefined;
}
parentPort?.postMessage({ type: "log", level, message, meta: plain });
}
}
const log: ProducerLogger = {
error: (message, meta) => post("error", message, meta),
warn: (message, meta) => post("warn", message, meta),
info: (message, meta) => post("info", message, meta),
debug: (message, meta) => post("debug", message, meta),
};
// The parent asks first, so downloads and transcodes stop through the compile's own cancel paths;
// it terminates the thread if the compile is too busy to hear it.
const controller = new AbortController();
parentPort?.on("message", (message: { type?: string }) => {
if (message?.type === "abort") controller.abort(new Error("compile stopped"));
});
// Fire-and-forget advisories may outlive the compile; they must not keep the parent's port open.
parentPort?.unref();
try {
const compiled = await compileForRender(projectDir, htmlPath, downloadDir, {
...options,
log,
abortSignal: controller.signal,
});
parentPort?.postMessage({ type: "result", compiled });
} catch (error) {
const props: Record<string, unknown> = {};
if (error instanceof Error) {
for (const [key, value] of Object.entries(error)) {
try {
props[key] = structuredClone(value);
} catch {
// Not cloneable: the wire envelope reads only plain fields.
}
}
}
parentPort?.postMessage({
type: "error",
error:
error instanceof Error
? { name: error.name, message: error.message, stack: error.stack, props }
: { name: "Error", message: String(error), props },
});
}
@@ -45,7 +45,7 @@ import { extractStandaloneEntryFromIndex, isTemplateEntry } from "@hyperframes/c
import { readTextFile } from "@hyperframes/parsers/asset-resolution";
import { assertCompositionFileSize } from "@hyperframes/core/compiler";
import type { CompiledComposition } from "../../htmlCompiler.js";
import { compileForRender } from "../../htmlCompiler.js";
import { compileForRenderInWorker } from "../../compileInWorker.js";
import type { ProducerLogger } from "../../../logger.js";
import {
applyRenderModeHints,
@@ -253,19 +253,24 @@ export async function runCompileStage(input: CompileStageInput): Promise<Compile
const assetRoot = job.config.allowOutsideProjectAssets ? undefined : projectDir;
const htmlPath = resolveEntryHtmlPath({ projectDir, workDir, entryFile, log, assetRoot });
const compileStart = Date.now();
const compiled = await compileForRender(projectDir, htmlPath, join(workDir, "downloads"), {
log,
failClosedFontFetch: failClosedFontFetch === true,
allowSystemFontCapture,
abortSignal,
variables: input.variables,
urlByAbsentLocalPath: input.urlByAbsentLocalPath,
pageMotionBlur: input.pageMotionBlur,
animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
includeOutsideScripts: job.config.includeOutsideScripts,
});
const compiled = await compileForRenderInWorker(
projectDir,
htmlPath,
join(workDir, "downloads"),
{
log,
failClosedFontFetch: failClosedFontFetch === true,
allowSystemFontCapture,
abortSignal,
variables: input.variables,
urlByAbsentLocalPath: input.urlByAbsentLocalPath,
pageMotionBlur: input.pageMotionBlur,
animatedGifCacheDir: animatedGifCacheDir(cfg.extractCacheDir),
ffmpegProcessTimeout: cfg.ffmpegProcessTimeout,
allowOutsideProjectAssets: job.config.allowOutsideProjectAssets,
includeOutsideScripts: job.config.includeOutsideScripts,
},
);
assertNotAborted();
const compileOnlyMs = Date.now() - compileStart;
// Fold three signals into a single capture-mode decision: caller's
@@ -13,6 +13,7 @@ const SAFE_RENDER_ERROR_CODES = new Set<string>([
"VARIABLES_INVALID",
"OUTPUT_DIMENSIONS_MISMATCH",
"COMPOSITION_TOO_LARGE",
"COMPILE_TIMEOUT",
]);
/**
+1 -1
View File
@@ -36,7 +36,7 @@
"unpacked": 590000
},
"@hyperframes/producer": {
"packed": 993551,
"packed": 1065767,
"unpacked": 3702639
},
"@hyperframes/sdk": {