diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 04d3782..c28633f 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -41,7 +41,7 @@ honestly. This is what renderdiff does to make sure of that. - **Isolates state** — one browser context per origin, so cookies and localStorage never cross (a storage state file seeds each context on its own). Both sides of a route load at the same time. -- **Retries once** per shot; a live site can time out on a cold edge. +- **Retries once** per shot; a live site can time out on a cold edge. Each attempt has a 120s deadline (`RENDERDIFF_SHOT_TIMEOUT`, in seconds); on expiry the page is replaced and the shot errors as `timeout after 120s at on `. - **Replays, never reuses, a cached reference.** With `--cache-right`, the right side's network traffic comes from a HAR recorded by an earlier run, but the page is still loaded, settled and shot under this run's clock. Element attribution needs the live document anyway, so nothing diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 75de8a0..fd83b0c 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -112,6 +112,7 @@ Report (`--open`, for a human): green from 99.5%, amber to 97%, red below. | `selector "…" matched N elements on left (/a), expected 1` | Make it unique (an id, `data-test`, `>> nth=0`), or list the route once per element. | | `selector "…" has no box on …` / `is off the page on …` | Matched an element not rendered (`display: none`, zero size) or outside the page. | | `before hook failed on left: …` | The hook threw. Never retried. | +| `timeout after 120s at settle on left` | That side never finished the step (`load`, `before hook`, `settle`, `screenshot`): a hung script, a dead renderer, a hook that never resolves. Retried once in a fresh page, except a hung hook. For a page that is just very slow, raise `RENDERDIFF_SHOT_TIMEOUT` (seconds). | A failed `--computed` snapshot (`snapshot failed on /a@1440 (…)` on the `computed:` line) is not a route error: the pixel result stands. diff --git a/src/capture.ts b/src/capture.ts index 0d57408..b8ebb9e 100644 --- a/src/capture.ts +++ b/src/capture.ts @@ -69,6 +69,8 @@ const MAX_PAGE_AREA = 1440 * 40_000; /** Requests still open per page, when the last one opened or closed, and stylesheets that failed. */ const network = new WeakMap; last: number; failed: Set }>(); +/** The step each page's capture is on, for the shot deadline to name. */ +export const step = new WeakMap(); /** Never finish, so they would hold network idle open until its timeout. */ const STREAMS = new Set(["eventsource", "websocket", "ping"]); @@ -159,6 +161,7 @@ export async function capture( cfg: ResolvedConfig, now: number, ): Promise { + step.set(page, "load"); await page.setViewportSize({ width, height: 900 }); const maxHeight = Math.max(40_000, Math.floor(MAX_PAGE_AREA / width)); await page.clock.setSystemTime(now); @@ -172,6 +175,7 @@ export async function capture( throw new Error(`HTTP ${res.status()} at ${url}`); } if (route.before) { + step.set(page, "before hook"); try { await route.before(page, { side, route: label(route), width }); } catch (e) { @@ -180,6 +184,7 @@ export async function capture( ); } } + step.set(page, "settle"); await page.addStyleTag({ content: cfg.neutralizeCss }); // Before the scroll too, so autoplay never starts and page state driven by playback stays put. if (cfg.freezeVideo) await page.evaluate(freezeVideo); @@ -282,6 +287,7 @@ export async function capture( ); } + step.set(page, "screenshot"); const measure = async (l: Locator) => { const b = await l.boundingBox(); if (!b?.width || !b.height) throw new Error(`selector "${selector}" has no box ${where}`); diff --git a/src/run.ts b/src/run.ts index 4ce4f06..feb7350 100644 --- a/src/run.ts +++ b/src/run.ts @@ -6,7 +6,7 @@ import { setTimeout as sleep } from "node:timers/promises"; import { chromium, errors, type Browser, type Page } from "playwright"; import { applyAccepted, readAccepted, unacceptable, updateAccepted } from "./accept.ts"; import { CACHE_DIR, cacheFile, replayable, REPLAY_TTL, saveRecording, shotId } from "./cache.ts"; -import { cancelUnstable, capture, HookError, prepare, type Shot } from "./capture.ts"; +import { cancelUnstable, capture, HookError, prepare, step, type Shot } from "./capture.ts"; import { compare, crops, type Band, type Region } from "./compare.ts"; import { diffSnapshots, fmtComputed, pageError } from "./computed.ts"; import { locate, snapshot, type ElementDiff } from "./locate.ts"; @@ -36,6 +36,8 @@ import { const LOCATE_TIMEOUT = 5_000; /** A full-page walk reads every element's style; past this, report the snapshot as failed. */ const COMPUTED_TIMEOUT = 15_000; +/** Bounds one capture: a renderer that dies or never returns from an evaluate would hang the run. */ +const SHOT_TIMEOUT = (Math.max(0, Number(process.env.RENDERDIFF_SHOT_TIMEOUT)) || 120) * 1000; /** Past this share of a page unstable, too little was measured for a score to mean anything. */ const MAX_UNSTABLE_SHARE = 0.25; @@ -283,10 +285,9 @@ export async function run({ : { update: true, updateContent: "embed", updateMode: "minimal" }, ); } - const leftPage = await leftCtx.newPage(); - const rightPage = await rightCtx.newPage(); - await prepare(leftPage, cfg, now); - await prepare(rightPage, cfg, now); + const pages = { left: await leftCtx.newPage(), right: await rightCtx.newPage() }; + await prepare(pages.left, cfg, now); + await prepare(pages.right, cfg, now); for (let job = queue.shift(); job; job = queue.shift()) { const { route, width } = job; @@ -300,8 +301,8 @@ export async function run({ missed = 0; // allSettled, not all: a page must not start the next job while still loading this one. const settled = await Promise.allSettled([ - shoot(leftPage, cfg.left + route.left, route, "left", width, cfg, now), - shoot(rightPage, cfg.right + route.right, route, "right", width, cfg, now), + shoot(pages, cfg.left + route.left, route, "left", width, cfg, now), + shoot(pages, cfg.right + route.right, route, "right", width, cfg, now), ]); const failed = settled.find((r) => r.status === "rejected"); if (failed) throw failed.reason; @@ -338,9 +339,9 @@ export async function run({ const [made, named] = await Promise.all([ crops(leftShot.png, rightShot.png, spots), Promise.race([ - locate([leftPage, rightPage], [leftShot, rightShot], spots, [ - masksFor(cfg, leftPage, route), - masksFor(cfg, rightPage, route), + locate([pages.left, pages.right], [leftShot, rightShot], spots, [ + masksFor(cfg, pages.left, route), + masksFor(cfg, pages.right, route), ]).catch(() => null), sleep(LOCATE_TIMEOUT, null, { ref: false }), ]), @@ -357,7 +358,7 @@ export async function run({ }); const computed = cfg.computed ? await Promise.race([ - Promise.all([snap(leftPage, "left"), snap(rightPage, "right")]).then( + Promise.all([snap(pages.left, "left"), snap(pages.right, "right")]).then( ([l, r]) => ({ computed: diffSnapshots(l, r) }), (e: Error) => ({ computed: null, computedError: e.message }), ), @@ -602,7 +603,7 @@ const transient = (e: unknown) => /** One retry for a transient failure: a live site can time out once on a cold edge. */ async function shoot( - page: Page, + pages: Record<"left" | "right", Page>, url: string, route: Route, side: "left" | "right", @@ -610,12 +611,27 @@ async function shoot( cfg: ResolvedConfig, now: number, ): Promise { + const once = async () => { + const page = pages[side]; + const shot = await Promise.race([ + capture(page, url, route, side, width, cfg, now), + sleep(SHOT_TIMEOUT, null, { ref: false }), + ]); + if (shot) return shot; + const at = step.get(page); + // Awaited: page.clock is the context's, so prepare() and the next capture would reach a closing page. + await page.close(); + pages[side] = await page.context().newPage(); + await prepare(pages[side], cfg, now); + const E = at === "before hook" ? HookError : errors.TimeoutError; + throw new E(`timeout after ${SHOT_TIMEOUT / 1000}s at ${at} on ${side}`); + }; try { - return await capture(page, url, route, side, width, cfg, now); + return await once(); } catch (e) { if (!transient(e)) throw e; - await page.waitForTimeout(1000); - return await capture(page, url, route, side, width, cfg, now); + await pages[side].waitForTimeout(1000); + return await once(); } } diff --git a/tests/fixtures/pages/README.md b/tests/fixtures/pages/README.md index 37108ef..1cf2ff6 100644 --- a/tests/fixtures/pages/README.md +++ b/tests/fixtures/pages/README.md @@ -19,7 +19,7 @@ Three groups: elements each change names (`margin`, `color`, `nav`), and a lost `::before` line and a re-parented pairing (`divider`). - **Guard rails** — `blank`, `tall`, `animated`, `lazy`, `lazy-deep`, `lazy-js`, `lazy-grow`, `consent`, - `drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`. + `drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `hang`. One per defence in `src/capture.ts` / `src/config.ts`. ## Authoring rules diff --git a/tests/fixtures/pages/hang/left.html b/tests/fixtures/pages/hang/left.html new file mode 100644 index 0000000..65b7c52 --- /dev/null +++ b/tests/fixtures/pages/hang/left.html @@ -0,0 +1,26 @@ + + + + +Layout parity + + + + +
+

Hung page guard rail

+

The page loads normally, then spins forever as soon as a style element is added to its head. Nothing after that point can run, so the shot has to be abandoned rather than waited on.

+ +
+

Notes

+

A renderer that never answers would otherwise hold the run open with no output. Each shot has a deadline, and on expiry the page is replaced so the next route still compares.

+
+
+ + + diff --git a/tests/fixtures/pages/hang/right.html b/tests/fixtures/pages/hang/right.html new file mode 100644 index 0000000..65b7c52 --- /dev/null +++ b/tests/fixtures/pages/hang/right.html @@ -0,0 +1,26 @@ + + + + +Layout parity + + + + +
+

Hung page guard rail

+

The page loads normally, then spins forever as soon as a style element is added to its head. Nothing after that point can run, so the shot has to be abandoned rather than waited on.

+ +
+

Notes

+

A renderer that never answers would otherwise hold the run open with no output. Each shot has a deadline, and on expiry the page is replaced so the next route still compares.

+
+
+ + + diff --git a/tests/helpers/corpus.ts b/tests/helpers/corpus.ts index e4d3201..2160961 100644 --- a/tests/helpers/corpus.ts +++ b/tests/helpers/corpus.ts @@ -53,6 +53,7 @@ export const GUARDRAILS = [ "media", "long", "video", + "hang", ] as const; export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS]; diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index 8d58194..9066614 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -1159,3 +1159,44 @@ describe("retries", () => { assert.equal(site.hits("/no-such-route") - before, 2, context(run)); }); }); + +describe("shot deadline", () => { + test("a page that never returns errors at the deadline, and the worker carries on", async () => { + const run = await runCli( + renderdiffArgs({ + left: site.left, + right: site.right, + routes: ["/hang", "/home"], + widths: [1440], + concurrency: 1, + }), + { env: { RENDERDIFF_SHOT_TIMEOUT: "5" }, timeoutMs: 60_000 }, + ); + assert.equal(run.code, 3, context(run)); + const report = parseReport(run.report()!); + assert.equal(report.errors.length, 1, context(run)); + assert.match(report.errors[0]!.message, /^timeout after 5s at settle on left$/); + // Same worker, replaced page: the next route still compares. + assert.equal(cardFor(run, "/home").diffPixels, 0, context(run)); + }); + + test("a hook that never resolves errors at the deadline, and is not retried", async () => { + const file = path.join(tempDir(), "hook.mjs"); + fs.writeFileSync(file, "export default { before: () => new Promise(() => {}) };\n"); + const before = site.hits("/menu"); + const run = await runCli( + renderdiffArgs({ + left: site.left, + right: site.right, + routes: ["/menu"], + widths: [1440], + config: file, + }), + { env: { RENDERDIFF_SHOT_TIMEOUT: "2" }, timeoutMs: 60_000 }, + ); + assert.equal(run.code, 3, context(run)); + const [r] = results(run.outDir).results; + assert.equal(r?.status === "error" && r.error, "timeout after 2s at before hook on left"); + assert.equal(site.hits("/menu") - before, 2, `the hook was retried${context(run)}`); + }); +});