From 590617475f6f2e4c592b1bc6783bb6dc49d5accf Mon Sep 17 00:00:00 2001 From: Vance Ingalls Date: Mon, 23 Nov 2026 10:34:44 -0800 Subject: [PATCH] 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. --- .fallowrc.jsonc | 5 + docs/guides/rendering.mdx | 2 + packages/producer/buildEntries.mjs | 1 + .../producer/scripts/integration-tests.json | 1 + packages/producer/src/buildEntries.test.ts | 8 +- .../__fixtures__/compileWorkerFake.mjs | 21 +++ .../services/__fixtures__/compileWorkerTs.mjs | 6 + .../src/services/compileInWorker.test.ts | 146 ++++++++++++++++ .../producer/src/services/compileInWorker.ts | 164 ++++++++++++++++++ .../producer/src/services/compileWorker.ts | 70 ++++++++ .../services/render/stages/compileStage.ts | 33 ++-- .../src/services/safeRenderErrorCode.ts | 1 + scripts/package-size-budgets.json | 2 +- 13 files changed, 444 insertions(+), 16 deletions(-) create mode 100644 packages/producer/src/services/__fixtures__/compileWorkerFake.mjs create mode 100644 packages/producer/src/services/__fixtures__/compileWorkerTs.mjs create mode 100644 packages/producer/src/services/compileInWorker.test.ts create mode 100644 packages/producer/src/services/compileInWorker.ts create mode 100644 packages/producer/src/services/compileWorker.ts diff --git a/.fallowrc.jsonc b/.fallowrc.jsonc index 284b7d3ec7..a56de95095 100644 --- a/.fallowrc.jsonc +++ b/.fallowrc.jsonc @@ -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. diff --git a/docs/guides/rendering.mdx b/docs/guides/rendering.mdx index 8702937e16..0356f2c2f6 100644 --- a/docs/guides/rendering.mdx +++ b/docs/guides/rendering.mdx @@ -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`. + Always watch the exported file itself. Preview proves that the project can play; the output file proves that the delivery is correct. diff --git a/packages/producer/buildEntries.mjs b/packages/producer/buildEntries.mjs index ff6c205592..8d2d94d9de 100644 --- a/packages/producer/buildEntries.mjs +++ b/packages/producer/buildEntries.mjs @@ -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" }, ]; diff --git a/packages/producer/scripts/integration-tests.json b/packages/producer/scripts/integration-tests.json index 81244f5349..e8cffb173e 100644 --- a/packages/producer/scripts/integration-tests.json +++ b/packages/producer/scripts/integration-tests.json @@ -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", diff --git a/packages/producer/src/buildEntries.test.ts b/packages/producer/src/buildEntries.test.ts index e4b79454cf..97433ddd6a 100644 --- a/packages/producer/src/buildEntries.test.ts +++ b/packages/producer/src/buildEntries.test.ts @@ -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", diff --git a/packages/producer/src/services/__fixtures__/compileWorkerFake.mjs b/packages/producer/src/services/__fixtures__/compileWorkerFake.mjs new file mode 100644 index 0000000000..1a8f87df7c --- /dev/null +++ b/packages/producer/src/services/__fixtures__/compileWorkerFake.mjs @@ -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 }, + }, + }, + }); +} diff --git a/packages/producer/src/services/__fixtures__/compileWorkerTs.mjs b/packages/producer/src/services/__fixtures__/compileWorkerTs.mjs new file mode 100644 index 0000000000..2b9e02111d --- /dev/null +++ b/packages/producer/src/services/__fixtures__/compileWorkerTs.mjs @@ -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"); diff --git a/packages/producer/src/services/compileInWorker.test.ts b/packages/producer/src/services/compileInWorker.test.ts new file mode 100644 index 0000000000..9f4d7e8b40 --- /dev/null +++ b/packages/producer/src/services/compileInWorker.test.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((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"), + `
${"".repeat(100_001)}
`, + ); + 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"), + ` +

x

+`, + ); + 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); +}); diff --git a/packages/producer/src/services/compileInWorker.ts b/packages/producer/src/services/compileInWorker.ts new file mode 100644 index 0000000000..0376f07259 --- /dev/null +++ b/packages/producer/src/services/compileInWorker.ts @@ -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 { + 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((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; + 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`)), + ), + ); + }); +} diff --git a/packages/producer/src/services/compileWorker.ts b/packages/producer/src/services/compileWorker.ts new file mode 100644 index 0000000000..e6af96d623 --- /dev/null +++ b/packages/producer/src/services/compileWorker.ts @@ -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; +}; + +function post(level: string, message: string, meta?: Record): 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 | undefined; + try { + plain = JSON.parse(JSON.stringify(meta)) as Record; + } 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 = {}; + 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 }, + }); +} diff --git a/packages/producer/src/services/render/stages/compileStage.ts b/packages/producer/src/services/render/stages/compileStage.ts index 1366059087..b764ee8965 100644 --- a/packages/producer/src/services/render/stages/compileStage.ts +++ b/packages/producer/src/services/render/stages/compileStage.ts @@ -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([ "VARIABLES_INVALID", "OUTPUT_DIMENSIONS_MISMATCH", "COMPOSITION_TOO_LARGE", + "COMPILE_TIMEOUT", ]); /** diff --git a/scripts/package-size-budgets.json b/scripts/package-size-budgets.json index 260db430e6..7222a8fde9 100644 --- a/scripts/package-size-budgets.json +++ b/scripts/package-size-budgets.json @@ -36,7 +36,7 @@ "unpacked": 590000 }, "@hyperframes/producer": { - "packed": 993551, + "packed": 1065767, "unpacked": 3702639 }, "@hyperframes/sdk": {