Skip to content
1 change: 1 addition & 0 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,7 @@ export {
} from "./services/audioMixer.js";
export { audioFailureDiagnostics } from "./services/audioFailureDiagnostic.js";
export { cloneCaptureWarning, cloneCaptureWarnings } from "./services/captureWarning.js";
export { retainCapturePerf } from "./services/pageTextBounds.js";
export type {
AudioElement,
AudioFailureReason,
Expand Down
108 changes: 108 additions & 0 deletions packages/engine/src/services/frameCapture-subTimelineMemo.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,21 @@ function makeDomPage(timelines: Record<string, unknown>): Page {
} as unknown as Page;
}

// A fake DOM of hosts with these composition ids and the given registered timelines.
function pageWithHosts(ids: string[], timelines: Record<string, unknown>): Page {
const host = (id: string) => ({
hasAttribute: () => false,
getAttribute: (name: string) => (name === "data-composition-id" ? id : null),
});
const document = { querySelectorAll: () => ids.map(host) };
const window = { __timelines: timelines, __hfForceTimelineRebind: vi.fn() };
return {
evaluate: vi.fn(async (expr: string) =>
new Function("document", "window", `return ${expr}`)(document, window),
),
} as unknown as Page;
}

function makeSession(
memo: SubTimelineWaitMemo,
extra: Partial<Pick<CaptureSession, "pageErrors" | "scriptLoadFailures" | "vfxFailure">> = {},
Expand Down Expand Up @@ -87,6 +102,99 @@ describe("sub-composition timeline wait memo", () => {
expect(memo.unregisteredIds).toBeUndefined();
});

// fails at 30537d4e: the page sent every isolated composition it named, at full length, before Node cut it
it("isolates every broken composition in the page but keeps a fixed record of them", async () => {
const root = { parentElement: null };
const host = (id: string, nested = true) => ({
id: "",
hasAttribute: () => false,
getAttribute: (name: string) => (name === "data-composition-id" ? id : null),
parentElement: nested ? { closest: () => root } : null,
});
const broken = Array.from({ length: 1_000 }, (_, n) => `${n}:${"b".repeat(5_000)}`);
const timelines: Record<string, unknown> = { main: {}, live: {} };
const document = {
querySelectorAll: () => [host("main", false), host("live"), ...broken.map((id) => host(id))],
};
const window = {
__timelines: timelines,
__hfForceTimelineRebind: vi.fn(),
gsap: { timeline: () => ({ set: () => undefined }) },
};
const page = {
evaluate: vi.fn(async (expr: string) =>
new Function("document", "window", `return ${expr}`)(document, window),
),
} as unknown as Page;
const session = makeSession({}, { pageErrors: ["runtime-error:TypeError: x is undefined"] });

const wait = track(waitForSubCompositionTimelines(session, page, TIMEOUT_MS));
await vi.advanceTimersByTimeAsync(TIMEOUT_MS * 2);
await wait.promise;

expect(broken.every((id) => timelines[id])).toBe(true);
const answers = await Promise.all(vi.mocked(page.evaluate).mock.results.map((r) => r.value));
const records = answers.filter(
(a): a is { compositionId: string }[] =>
Array.isArray(a) && a[0]?.compositionId !== undefined,
);
expect(records).toHaveLength(1);
expect(records[0]).toHaveLength(50);
expect(Math.max(...records[0]!.map((c) => c.compositionId.length))).toBeLessThanOrEqual(2_000);
expect(session.isolatedCompositions).toHaveLength(50);
const ids = session.isolatedCompositions?.map((c) => c.compositionId) ?? [];
expect(Math.max(...ids.map((id) => id.length))).toBeLessThanOrEqual(2_000);
});

// fails at e2d37846: every unregistered id was sent, kept on the session and in the memo at full length
it("sends, keeps and remembers a fixed number of unregistered ids, remembering only whole ones", async () => {
const ids = Array.from({ length: 5_000 }, (_, n) =>
n % 2 ? `${n}:${"u".repeat(500)}` : `s${n}`,
);
const memo: SubTimelineWaitMemo = {};
const session = makeSession(memo);
const page = pageWithHosts(ids, {});

const wait = track(waitForSubCompositionTimelines(session, page, TIMEOUT_MS));
await vi.advanceTimersByTimeAsync(TIMEOUT_MS * 2);
await wait.promise;

const answers = await Promise.all(vi.mocked(page.evaluate).mock.results.map((r) => r.value));
const sent = answers.filter((a): a is (string | null)[] => Array.isArray(a) && a.length > 0);
expect(sent.length).toBeGreaterThan(0);
for (const list of [...sent, session.pendingTimelineIds ?? []]) {
expect(list).toHaveLength(1_000);
expect(Math.max(...list.map((id) => id?.length ?? 0))).toBeLessThanOrEqual(200);
}
expect(memo.unregisteredIds).toHaveLength(500);
expect(memo.unregisteredIds?.every((id) => ids.includes(id))).toBe(true);
expect(session.subTimelineWaitOutcome).toBe("timeout");
});

// fails at 68aaf33f: the memo held a long id's cut label, and a host whose real id equals it was not waited on
it("waits again for a host whose id equals another host's cut-short id", async () => {
const long = "x".repeat(300);
const memo: SubTimelineWaitMemo = {};
const first = track(
waitForSubCompositionTimelines(makeSession(memo), pageWithHosts([long], {}), TIMEOUT_MS),
);
await vi.advanceTimersByTimeAsync(TIMEOUT_MS * 2);
await first.promise;

const lookalike = `${"x".repeat(199)}…`;
const second = track(
waitForSubCompositionTimelines(
makeSession(memo),
pageWithHosts([long, lookalike], { [long]: {} }),
TIMEOUT_MS,
),
);
await vi.advanceTimersByTimeAsync(0);
expect(second.settled()).toBe(false);
await vi.advanceTimersByTimeAsync(TIMEOUT_MS * 2);
await second.promise;
});

it("does not remember a wait a VFX failure stopped early", async () => {
const memo: SubTimelineWaitMemo = {};
const session = makeSession(memo, { vfxFailure: "chain failed" });
Expand Down
142 changes: 138 additions & 4 deletions packages/engine/src/services/frameCapture.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { describe, it, expect, vi } from "vitest";
import type { Protocol } from "puppeteer-core";
import { COMPOSITION_SOURCE_URL, SCENE_CALLBACK_ERROR_PREFIX } from "@hyperframes/core";
import type { CaptureSession } from "./frameCapture.js";
import type { SubTimelineWaitMemo } from "../types.js";
import type { CapturePerfSummary, CaptureSession } from "./frameCapture.js";
import { retainCapturePerf } from "./pageTextBounds.js";
import type { CaptureWarning, SubTimelineWaitMemo } from "../types.js";
import {
buildZeroDurationDiagnostic,
pollHfReady,
recordBackgroundDecodeTimeouts,
recordSubTimelineWarning,
captureFramesBatchPipelined,
captureFrameToBufferPipelined,
classifyConsoleScriptError,
Expand Down Expand Up @@ -175,7 +178,12 @@ describe("classifyPageError", () => {
(listeners: typeof pageListeners) => (event: string, listener: (event: unknown) => void) =>
listeners.set(event, listener);
const client = { on: listen(runtimeListeners), send };
const page = { on: listen(pageListeners), createCDPSession: async () => client };
const frameUrl = { current: doc };
const page = {
on: listen(pageListeners),
createCDPSession: async () => client,
frames: () => [{ url: () => frameUrl.current }],
};
const session = {
page,
serverUrl: server,
Expand All @@ -186,7 +194,7 @@ describe("classifyPageError", () => {
subTimelineWaitMemo: memo,
} as unknown as CaptureSession;
await initializeSession(session).catch(() => {});
return { session, pageListeners, runtimeListeners };
return { session, pageListeners, runtimeListeners, frameUrl };
}

it("keeps browser diagnostics on stderr and in the session buffer", async () => {
Expand Down Expand Up @@ -353,6 +361,132 @@ describe("classifyPageError", () => {
}
});

// fails without the fix: a warning kept every timeline id and media source the page named, at full length
it("keeps a warning's timeline ids and media sources only up to a fixed count and size", () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const long = (n: number) => `${n}:${"z".repeat(10_000)}`;
const session = {
subTimelineWaitOutcome: "timeout",
pendingTimelineIds: Array.from({ length: 1_000 }, (_, n) => long(n)),
scriptLoadFailures: [],
pageErrors: [],
warnings: [],
browserConsoleBuffer: [],
} as unknown as CaptureSession;
recordSubTimelineWarning(session, 45_000);
recordBackgroundDecodeTimeouts(
session,
Array.from({ length: 1_000 }, (_, n) => `https://cdn.test/${long(n)}.jpg`),
);

const lists = session.warnings.flatMap((w) =>
Object.values(w.details ?? {}).filter((v): v is string[] => Array.isArray(v)),
);
const texts = [...session.warnings.map((w) => w.message), ...lists.flat()];
expect(session.warnings.map((w) => w.code)).toEqual([
"sub_timeline_readiness_timeout",
"media_readiness_timeout",
]);
expect(Math.max(...texts.map((text) => text.length))).toBeLessThanOrEqual(2_000);
expect(Math.max(...lists.map((list) => list.length))).toBeLessThanOrEqual(50);
});

// fails at 5c807e39: long pending ids came first, so the cut message lost the exception and the repair advice
it("keeps the exception and its repair advice in a timeline warning whose pending ids are long", () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const session = {
subTimelineWaitOutcome: "timeout",
pendingTimelineIds: Array.from({ length: 1_000 }, (_, n) => `${n}:${"p".repeat(2_000)}`),
scriptLoadFailures: [],
pageErrors: ["runtime-error:TypeError: boom"],
warnings: [],
browserConsoleBuffer: [],
} as unknown as CaptureSession;
recordSubTimelineWarning(session, 45_000);

const [warning] = session.warnings;
expect(warning?.message.length).toBeLessThanOrEqual(2_000);
expect(warning?.message).toContain("runtime-error:TypeError: boom");
expect(warning?.message).toContain("Fix the error");
expect(warning?.message).toContain("and 997 more");
expect(warning?.details?.pendingCompositionIds).toHaveLength(50);
});

// fails without the fix: every distinct warning was kept, so a page could grow a render's memory without end
it("keeps a fixed total of page text per render, and still each kind of warning", () => {
vi.spyOn(console, "warn").mockImplementation(() => {});
const session = { warnings: [], browserConsoleBuffer: [] } as unknown as CaptureSession;
for (let n = 0; n < 2_000; n++) {
recordBackgroundDecodeTimeouts(session, [`https://cdn.test/${n}-${"q".repeat(1_900)}.jpg`]);
}
session.subTimelineWaitOutcome = "timeout";
Object.assign(session, { scriptLoadFailures: [], pageErrors: [], pendingTimelineIds: ["a"] });
recordSubTimelineWarning(session, 45_000);

expect(JSON.stringify(session.warnings).length).toBeLessThanOrEqual(1_100_000);
expect(new Set(session.warnings.map((w) => w.code))).toEqual(
new Set(["media_readiness_timeout", "sub_timeline_readiness_timeout"]),
);
});

// fails at 50501bcb (late scripts' throws dropped), 5c807e39 (long or moved documents counted) and 2bfcb813
// (a script's throw dropped while a frame showed that URL as its document)
it.each([doc, `${doc}#c`, `${server}/elsewhere/page?q=1`, `${server}/${"d".repeat(3_000)}.html`])(
"records every served script's throw, however many and long, and none from the document at %s",
async (documentUrl) => {
const { session, pageListeners, runtimeListeners, frameUrl } = await listenedSession();
const script = (n: number) => `${server}/s${n}.js`;
const long = `${server}/${"l".repeat(3_000)}.js`;
for (const url of [...Array.from({ length: 2_000 }, (_, n) => script(n)), long]) {
pageListeners.get("response")?.({
status: () => 200,
url: () => url,
request: () => ({ resourceType: () => "script" }),
});
}
const throwFrom = (n: number, url: string) =>
runtimeListeners.get("Runtime.exceptionThrown")?.({
exceptionDetails: thrown(`Error: from ${n}`, url, [url]),
});
throwFrom(0, script(0));
throwFrom(-1, long);
frameUrl.current = documentUrl;
throwFrom(-2, documentUrl);
frameUrl.current = script(1_999);
throwFrom(1_999, script(1_999));
expect(session.pageErrors).toEqual([
"runtime-error:Error: from 0",
"runtime-error:Error: from -1",
"runtime-error:Error: from 1999",
]);
},
);

// fails at 50501bcb: each recycled session kept its own 1M characters, so a render's kept warnings grew per session
it("keeps a fixed total of warning text across a render's sessions, and each kind once more", () => {
const perf = (code: CaptureWarning["code"], n: number) =>
({
warnings: Array.from({ length: 200 }, (_, i) => ({
code,
message: `${n}.${i}:${"w".repeat(1_900)}`,
details: { sources: [`https://cdn.test/${n}.${i}.jpg`] },
})),
}) as unknown as CapturePerfSummary;
const kept: CapturePerfSummary[] = [];
for (let n = 0; n < 20; n++) retainCapturePerf(kept, perf("media_readiness_timeout", n));
retainCapturePerf(kept, perf("sub_timeline_script_failure", 20));

const warnings = kept.flatMap((p) => p.warnings ?? []);
expect(JSON.stringify(warnings).length).toBeLessThanOrEqual(1_100_000);
expect(new Set(warnings.map((w) => w.code))).toEqual(
new Set(["media_readiness_timeout", "sub_timeline_script_failure"]),
);

kept.length = 0;
retainCapturePerf(kept, perf("media_readiness_timeout", 21));
expect(kept[0]?.warnings).toHaveLength(200);
});

it("records the page's uncaught errors from scripts it loaded from the server", async () => {
const { session, pageListeners, runtimeListeners } = await listenedSession();
const loaded = (url: string, resourceType: string) => ({
Expand Down
Loading
Loading