Skip to content

Commit 59c2065

Browse files
fix(producer): page timers during a render run on film time (#7362)
* fix(producer): page timers during a render run on film time * test(producer): a regression film whose timer bars must follow film time * test(producer): schedule the timers regression film in CI shards * fix(producer): keep setup timers on the wall clock until the page reports ready * fix(producer): keep the renderer's own waits and deadlines on the wall clock * test(engine): fail CI on a bare timer in code the engine runs in the page * fix(core): type the wall-clock timers like the global timers they replace * chore(engine): drop the comment on the shim's window type
1 parent 9efbbdf commit 59c2065

30 files changed

Lines changed: 559 additions & 71 deletions

‎packages/core/src/runtime/adapters/seek-dispatch.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,34 @@ describe("seek-dispatch", () => {
257257
}
258258
});
259259

260+
it("a seek's deadline still fires while the render shim holds page timers for the next seek", async () => {
261+
const page = window as unknown as Record<string, unknown>;
262+
const realSetTimeout = globalThis.setTimeout;
263+
const realClearTimeout = globalThis.clearTimeout;
264+
const held = ((): number => 0) as unknown as typeof setTimeout;
265+
page.__HF_VIRTUAL_TIME__ = {
266+
originalSetTimeout: realSetTimeout,
267+
originalClearTimeout: realClearTimeout,
268+
};
269+
globalThis.setTimeout = held;
270+
window.setTimeout = held;
271+
try {
272+
registerSeekCompletion(new Promise(() => {}), "vfx");
273+
const outcome = await Promise.race([
274+
waitForSeekCompletion({ timeoutMs: 50 }).then(
275+
() => "resolved",
276+
(err: Error) => err.message,
277+
),
278+
new Promise((resolve) => realSetTimeout(() => resolve("still pending"), 1000)),
279+
]);
280+
expect(outcome).toBe("seek did not settle within 50 ms: still waiting on vfx");
281+
} finally {
282+
globalThis.setTimeout = realSetTimeout;
283+
window.setTimeout = realSetTimeout;
284+
delete page.__HF_VIRTUAL_TIME__;
285+
}
286+
});
287+
260288
it("a seek whose holds settle in time resolves as before", async () => {
261289
registerSeekCompletion(new Promise((resolve) => setTimeout(resolve, 5)), "scene-window");
262290
await expect(waitForSeekCompletion({ timeoutMs: 1000 })).resolves.toBeUndefined();

‎packages/core/src/runtime/adapters/seek-dispatch.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallClearTimeout, wallSetTimeout } from "../wallClock";
12
import { swallow } from "../diagnostics";
23

34
/**
@@ -132,12 +133,12 @@ async function settledBy(
132133
if (deadline === undefined) return Promise.all(pending);
133134
let timer: ReturnType<typeof setTimeout> | undefined;
134135
const late = new Promise<null>((resolve) => {
135-
timer = setTimeout(() => resolve(null), Math.max(0, deadline - Date.now()));
136+
timer = wallSetTimeout(() => resolve(null), Math.max(0, deadline - Date.now()));
136137
});
137138
try {
138139
return await Promise.race([Promise.all(pending), late]);
139140
} finally {
140-
clearTimeout(timer);
141+
wallClearTimeout(timer);
141142
}
142143
}
143144

‎packages/core/src/runtime/adapters/typegpu.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallClearInterval, wallSetInterval } from "../wallClock";
12
import type { RuntimeDeterministicAdapter } from "../types";
23
import {
34
dispatchSeekEvent,
@@ -73,18 +74,18 @@ export const TYPEGPU_PRESENT_HEARTBEAT_MS = 250;
7374
export function createTypegpuAdapter(): RuntimeDeterministicAdapter {
7475
let forcedTime: number | null = null;
7576
let lastForcedTime = 0;
76-
let presentHeartbeat: number | null = null;
77+
let presentHeartbeat: ReturnType<typeof wallSetInterval> | null = null;
7778

7879
const stopPresentHeartbeat = () => {
7980
if (presentHeartbeat === null) return;
80-
window.clearInterval(presentHeartbeat);
81+
wallClearInterval(presentHeartbeat);
8182
presentHeartbeat = null;
8283
};
8384

8485
const startPresentHeartbeat = () => {
8586
if (presentHeartbeat !== null) return;
8687
if (!document.querySelector("[data-composition-id][data-requires-webgpu]")) return;
87-
presentHeartbeat = window.setInterval(() => {
88+
presentHeartbeat = wallSetInterval(() => {
8889
if (forcedTime === null) return;
8990
if (isSeekCompletionBarrierActive()) return;
9091
window.__hfTypegpuTime = forcedTime;

‎packages/core/src/runtime/afterFonts.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
12
import { AFTER_FONTS_CLAIM, DEFERRED_FILE, typeAfterFonts } from "../compiler/scriptRuns";
23
import { postRuntimeMessage } from "./bridge";
34
import { applyTextBindings } from "./applyVariableBindings";
@@ -19,9 +20,11 @@ export async function waitForFonts(): Promise<void> {
1920
let timer: ReturnType<typeof setTimeout> | undefined;
2021
const timedOut = await Promise.race([
2122
fonts.ready.then(() => false),
22-
new Promise<boolean>((resolve) => (timer = setTimeout(resolve, FONT_WAIT_TIMEOUT_MS, true))),
23+
new Promise<boolean>(
24+
(resolve) => (timer = wallSetTimeout(resolve, FONT_WAIT_TIMEOUT_MS, true)),
25+
),
2326
]);
24-
clearTimeout(timer);
27+
wallClearTimeout(timer);
2528
if (!timedOut) return;
2629
const loadingFamilies = [
2730
...new Set(

‎packages/core/src/runtime/bridge.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallSetTimeout } from "./wallClock";
12
import { swallow } from "./diagnostics";
23
import type { HfColorGradingTarget } from "../colorGrading";
34
import type { RuntimeBridgeControlMessage, RuntimeOutboundMessage } from "./types";
@@ -190,7 +191,7 @@ function flashElements(selectors: string[], duration: number): void {
190191
const els = document.querySelectorAll(selector);
191192
els.forEach((el) => {
192193
el.classList.add("__hf-flash");
193-
setTimeout(() => el.classList.remove("__hf-flash"), duration);
194+
wallSetTimeout(() => el.classList.remove("__hf-flash"), duration);
194195
});
195196
} catch (err) {
196197
// Invalid selector — skip

‎packages/core/src/runtime/captureMotionBlur/index.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
* Needs html-in-canvas (`drawElementImage`); without it nothing changes.
1212
*/
1313

14+
import { wallClearTimeout, wallSetTimeout } from "../wallClock";
1415
import {
1516
htmlInCanvasForm,
1617
markCaptureCanvas,
@@ -530,7 +531,7 @@ function createInstance(host: CaptureMotionBlurHost, config: Config, form: HtmlI
530531
const mine = ++seq;
531532
let timer: ReturnType<typeof setTimeout> | undefined;
532533
const startTimer = (): void => {
533-
timer = setTimeout(() => {
534+
timer = wallSetTimeout(() => {
534535
if (pending?.seq === mine) onPaintTimeout(pending);
535536
else resolve();
536537
}, PAINT_TIMEOUT_MS);
@@ -545,7 +546,7 @@ function createInstance(host: CaptureMotionBlurHost, config: Config, form: HtmlI
545546
startTimer,
546547
ms: 0,
547548
settle: () => {
548-
clearTimeout(timer);
549+
wallClearTimeout(timer);
549550
resolve();
550551
},
551552
};

‎packages/core/src/runtime/colorGrading.ts‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
12
import {
23
HF_COLOR_GRADING_ADJUST_KEYS,
34
HF_COLOR_GRADING_ANIMATABLE_PROPERTIES,
@@ -3939,7 +3940,7 @@ export function createColorGradingRuntime(pausedMediaLease?: {
39393940
});
39403941
canvas.addEventListener("webglcontextrestored", () => {
39413942
if (shared?.canvas !== canvas) return;
3942-
clearTimeout(rebuildTimer);
3943+
wallClearTimeout(rebuildTimer);
39433944
for (const entry of trackedEntries()) {
39443945
entry.contextLost = !replaceProgramResources(entry);
39453946
entry.drawError = entry.contextLost ? "WebGL context restore failed" : null;
@@ -3953,8 +3954,8 @@ export function createColorGradingRuntime(pausedMediaLease?: {
39533954
};
39543955

39553956
const watchForRestore = (canvas: HTMLCanvasElement, gl: WebGLRenderingContext): void => {
3956-
clearTimeout(rebuildTimer);
3957-
rebuildTimer = setTimeout(() => rebuildLostContext(canvas, gl), CONTEXT_RESTORE_GRACE_MS);
3957+
wallClearTimeout(rebuildTimer);
3958+
rebuildTimer = wallSetTimeout(() => rebuildLostContext(canvas, gl), CONTEXT_RESTORE_GRACE_MS);
39583959
};
39593960

39603961
const rebuildLostContext = (canvas: HTMLCanvasElement, gl: WebGLRenderingContext): void => {
@@ -4297,7 +4298,7 @@ export function createColorGradingRuntime(pausedMediaLease?: {
42974298
const destroy = (): void => {
42984299
if (destroyed) return;
42994300
destroyed = true;
4300-
clearTimeout(rebuildTimer);
4301+
wallClearTimeout(rebuildTimer);
43014302
observer?.disconnect();
43024303
observer = null;
43034304
for (const element of trackedElements) removeElement(element);

‎packages/core/src/runtime/compositionLoader.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
12
import {
23
SVG_REFERENCE_ALIASES_ATTR,
34
readSvgReferenceAliases,
@@ -195,12 +196,12 @@ const waitForExternalScriptLoad = (
195196
new Promise((resolve) => {
196197
let settled = false;
197198
const startedAt = Date.now();
198-
let timeoutId: number | null = null;
199+
let timeoutId: ReturnType<typeof wallSetTimeout> | null = null;
199200
const settle = (status: "load" | "error" | "timeout") => {
200201
if (settled) return;
201202
settled = true;
202203
if (timeoutId != null) {
203-
window.clearTimeout(timeoutId);
204+
wallClearTimeout(timeoutId);
204205
}
205206
resolve({
206207
status,
@@ -209,7 +210,7 @@ const waitForExternalScriptLoad = (
209210
};
210211
scriptEl.addEventListener("load", () => settle("load"), { once: true });
211212
scriptEl.addEventListener("error", () => settle("error"), { once: true });
212-
timeoutId = window.setTimeout(() => settle("timeout"), EXTERNAL_SCRIPT_LOAD_TIMEOUT_MS);
213+
timeoutId = wallSetTimeout(() => settle("timeout"), EXTERNAL_SCRIPT_LOAD_TIMEOUT_MS);
213214
});
214215

215216
function resetCompositionHost(host: Element) {

‎packages/core/src/runtime/filmBridge.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { wallClearTimeout, wallSetTimeout } from "./wallClock";
12
const PREFIX = "appifact-film:";
23

34
export interface FilmBridge {
@@ -36,15 +37,15 @@ export function createFilmBridge(options: {
3637
} | null = null;
3738
const fail = (error: Error) => {
3839
failure = error;
39-
clearTimeout(startupTimer);
40+
wallClearTimeout(startupTimer);
4041
rejectReady(error);
4142
if (pending) {
42-
clearTimeout(pending.timer);
43+
wallClearTimeout(pending.timer);
4344
pending.reject(error);
4445
pending = null;
4546
}
4647
};
47-
const startupTimer = setTimeout(
48+
const startupTimer = wallSetTimeout(
4849
() => fail(new Error("Film runner did not become ready within 20 s")),
4950
20_000,
5051
);
@@ -58,7 +59,7 @@ export function createFilmBridge(options: {
5859
return;
5960
const request = pending;
6061
pending = null;
61-
clearTimeout(request.timer);
62+
wallClearTimeout(request.timer);
6263
if (data.type === PREFIX + "frame-error") {
6364
request.reject(new Error("message" in data ? String(data.message) : "Film frame failed"));
6465
} else request.resolve();
@@ -81,7 +82,7 @@ export function createFilmBridge(options: {
8182
loaded = true;
8283
send({ ...load, type: PREFIX + "load" });
8384
} else if (data.type === PREFIX + "ready" && loaded) {
84-
clearTimeout(startupTimer);
85+
wallClearTimeout(startupTimer);
8586
resolveReady();
8687
} else if (data.type === PREFIX + "error") {
8788
fail(new Error("message" in data ? String(data.message) : "Film runner failed"));
@@ -106,7 +107,7 @@ export function createFilmBridge(options: {
106107
if (pending) throw new Error("Film seeks must be serialized; use registerFrameSource");
107108
const seq = ++sequence;
108109
return new Promise<void>((resolve, reject) => {
109-
const timer = setTimeout(() => {
110+
const timer = wallSetTimeout(() => {
110111
fail(new Error("Film frame did not arrive within 15 s"));
111112
}, 15_000);
112113
pending = { sequence: seq, resolve, reject, timer };

0 commit comments

Comments
 (0)