From acdf9e59b2cde84ab11476f6b56db5cb3a5c53b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sat, 21 Nov 2026 01:00:38 +0000 Subject: [PATCH] fix(producer): count composition ids once for nested hosts, and charge the entry page's elements (#8335) * test(producer): a nested host's id search and the entry page's elements stay bounded * fix(producer): count composition ids once for nested hosts, and charge the entry page's elements --- .../core/src/compiler/compositionSizeLimit.ts | 5 +- packages/core/src/compiler/index.ts | 1 + .../services/htmlCompiler.lateHostIds.test.ts | 74 +++++++++++++++++++ .../services/htmlCompiler.sizeLimit.test.ts | 9 ++- .../producer/src/services/htmlCompiler.ts | 34 +++++++-- 5 files changed, 110 insertions(+), 13 deletions(-) create mode 100644 packages/producer/src/services/htmlCompiler.lateHostIds.test.ts diff --git a/packages/core/src/compiler/compositionSizeLimit.ts b/packages/core/src/compiler/compositionSizeLimit.ts index bcd13fd2f6..940889cddc 100644 --- a/packages/core/src/compiler/compositionSizeLimit.ts +++ b/packages/core/src/compiler/compositionSizeLimit.ts @@ -59,6 +59,7 @@ const limitText = `One render generates at most ${megabytes(MAX_EXPANDED_COMPOSI export const REMOTE_SCRIPTS = "remote scripts"; export const REMOTE_STYLESHEETS = "remote stylesheets"; +export const ENTRY_PAGE = "the entry page"; function generatedTooLarge(file: string, bytes: number): string { if (file === "composition variables") { @@ -98,7 +99,9 @@ export class CompositionExpansionBudget { this.elements += count; if (this.elements <= MAX_EXPANDED_ELEMENTS) return; throw new CompositionTooLargeError( - `Sub-composition mounts, ending at "${file}", add up to ${this.elements} elements. ` + + (file === ENTRY_PAGE + ? `The entry page holds ${this.elements} elements. ` + : `Sub-composition mounts, ending at "${file}", add up to ${this.elements} elements. `) + `One render inlines at most ${MAX_EXPANDED_ELEMENTS} elements. Mount large or repeated scenes fewer times.`, { bytes: this.bytes, diff --git a/packages/core/src/compiler/index.ts b/packages/core/src/compiler/index.ts index a0b7cdd915..6c38f4e045 100644 --- a/packages/core/src/compiler/index.ts +++ b/packages/core/src/compiler/index.ts @@ -101,6 +101,7 @@ export { export { assertCompositionFileSize, CompositionExpansionBudget, + ENTRY_PAGE, isCompositionTooLargeError, MAX_COMPOSITION_HTML_BYTES, MAX_EXPANDED_COMPOSITION_BYTES, diff --git a/packages/producer/src/services/htmlCompiler.lateHostIds.test.ts b/packages/producer/src/services/htmlCompiler.lateHostIds.test.ts new file mode 100644 index 0000000000..76e58684ee --- /dev/null +++ b/packages/producer/src/services/htmlCompiler.lateHostIds.test.ts @@ -0,0 +1,74 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { parseHTML } from "linkedom"; +import { afterEach, expect, it, vi } from "vitest"; +import { MAX_EXPANDED_ELEMENTS } from "@hyperframes/core/compiler"; +import { compileForRender } from "./htmlCompiler.js"; +import { extractSafeRenderErrorCode } from "./safeRenderErrorCode.js"; + +const dirs: string[] = []; +afterEach(() => { + vi.restoreAllMocks(); + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +const root = (body: string) => + `
${body}
`; +const mount = (id: string, src: string) => + `
`; + +function compile(files: Record) { + const dir = mkdtempSync(join(tmpdir(), "hf-late-host-ids-")); + dirs.push(dir); + for (const [name, html] of Object.entries(files)) writeFileSync(join(dir, name), html); + return compileForRender(dir, join(dir, "index.html"), join(dir, "out"), { + allowSystemFontCapture: false, + }); +} + +// fails without the fix: each candidate id of a nested host rescanned the whole page. +it("finds a nested host's id in reads proportional to the page, whatever ids it already holds", async () => { + const taken = 2000; + const element = Object.getPrototypeOf(parseHTML("

").document.querySelector("p")); + const owner = (function find(proto) { + return Object.prototype.hasOwnProperty.call(proto, "getAttribute") + ? proto + : find(Object.getPrototypeOf(proto)); + })(element); + const read = owner.getAttribute; + let idReads = 0; + vi.spyOn(owner, "getAttribute").mockImplementation(function (this: Element, name: string) { + if (name === "data-composition-id") idReads += 1; + return read.call(this, name); + }); + const held = Array.from( + { length: taken }, + (_, i) => ``, + ); + + const { html } = await compile({ + "index.html": root(held.join("") + mount("outer", "outer.html")), + "outer.html": ``, + "card.html": ``, + }); + + expect(idReads).toBeLessThan(taken * 50); + const assigned = `card__hf${taken + 1}`; + expect(html.split(`data-composition-id="${assigned}"`).length - 1).toBe(1); +}, 60_000); + +// fails without the fix: only elements copied by mounts were counted, so the entry page's own were never bounded. +it("counts the entry page's own elements against the element cap", async () => { + const error = await compile({ + "index.html": root("".repeat(MAX_EXPANDED_ELEMENTS)), + }).then( + () => undefined, + (thrown: unknown) => thrown, + ); + + expect(extractSafeRenderErrorCode(error)).toBe("COMPOSITION_TOO_LARGE"); + expect(error).toMatchObject({ + publicMetadata: { limitElements: MAX_EXPANDED_ELEMENTS, exceeded: "elements" }, + }); +}, 60_000); diff --git a/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts b/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts index 706b3afdc5..d4bca9950b 100644 --- a/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts +++ b/packages/producer/src/services/htmlCompiler.sizeLimit.test.ts @@ -147,13 +147,14 @@ describe("composition expansion budget", () => { const perScene = 1000; const scene = ``; const mounts = Math.floor(MAX_EXPANDED_ELEMENTS / perScene) + 1; - const error = await compileError( - project({ "index.html": rootMounting("scene.html", mounts), "scene.html": scene }), - ); + const entry = rootMounting("scene.html", mounts); + const entryElements = parseHTML(entry).document.querySelectorAll("*").length; + const copied = Math.floor((MAX_EXPANDED_ELEMENTS - entryElements) / perScene) + 1; + const error = await compileError(project({ "index.html": entry, "scene.html": scene })); expect(extractSafeRenderErrorCode(error)).toBe("COMPOSITION_TOO_LARGE"); expect(error).toMatchObject({ publicMetadata: { - elements: mounts * perScene, + elements: entryElements + copied * perScene, limitElements: MAX_EXPANDED_ELEMENTS, exceeded: "elements", }, diff --git a/packages/producer/src/services/htmlCompiler.ts b/packages/producer/src/services/htmlCompiler.ts index f1ef397805..86caffceb5 100644 --- a/packages/producer/src/services/htmlCompiler.ts +++ b/packages/producer/src/services/htmlCompiler.ts @@ -107,6 +107,7 @@ import { extractMediaMetadata, extractAudioMetadata } from "../utils/ffprobe.js" import { assertCompositionFileSize, CompositionExpansionBudget, + ENTRY_PAGE, REMOTE_SCRIPTS, REMOTE_STYLESHEETS, } from "@hyperframes/core/compiler"; @@ -1139,15 +1140,32 @@ function promoteCssImportsToLinkTags(html: string): string { } class ProducerHostIdentityMap extends Map { - readonly #document: Document; readonly #lateInstanceByCompositionId = new Map(); + /** How many elements carry each composition id: the page once, then each mount's copy once. */ + readonly #idCounts = new Map(); + /** Hosts whose copied content has not been counted yet; the inliner fills a host after asking for it. */ + #uncounted: ParentNode[]; constructor(document: Document, initialHosts: Element[]) { super(assignBundledRuntimeCompositionIds(initialHosts)); - this.#document = document; + this.#uncounted = [document]; + } + + #countUncopied(): void { + for (const root of this.#uncounted.splice(0)) { + for (const element of Array.from(root.querySelectorAll("[data-composition-id]"))) { + this.#adjust(element.getAttribute("data-composition-id"), 1); + } + } + } + + #adjust(id: string | null, by: number): void { + if (id) this.#idCounts.set(id, (this.#idCounts.get(id) ?? 0) + by); } override get(host: Element): BundledHostCompositionIdentity | undefined { + this.#countUncopied(); + this.#uncounted.push(host); const existing = super.get(host); if (existing) return existing; @@ -1166,21 +1184,20 @@ class ProducerHostIdentityMap extends Map (this.#idCounts.get(id) ?? 0) - (id === ownId ? 1 : 0) > 0; let instanceIndex = this.#lateInstanceByCompositionId.get(authoredCompositionId) || 0; let runtimeCompositionId: string; do { instanceIndex += 1; runtimeCompositionId = `${authoredCompositionId}__hf${instanceIndex}`; - } while ( - Array.from(this.#document.querySelectorAll("[data-composition-id]")).some( - (element) => - element !== host && element.getAttribute("data-composition-id") === runtimeCompositionId, - ) - ); + } while (heldByOthers(runtimeCompositionId)); this.#lateInstanceByCompositionId.set(authoredCompositionId, instanceIndex); host.setAttribute("data-hf-original-composition-id", authoredCompositionId); host.setAttribute("data-composition-id", runtimeCompositionId); + this.#adjust(ownId, -1); + this.#adjust(runtimeCompositionId, 1); const identity = { authoredCompositionId, runtimeCompositionId }; this.set(host, identity); return identity; @@ -1275,6 +1292,7 @@ function inlineSubCompositions( budget: CompositionExpansionBudget, ): { html: string; variablesByComp: Record> } { const { document } = parseHTML(html); + budget.chargeElements(ENTRY_PAGE, document.querySelectorAll("*").length); const head = document.querySelector("head"); const body = document.querySelector("body"); const hosts = Array.from(document.querySelectorAll("[data-composition-src]"));