Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/how-it-works.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <step> on <side>`.
- **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
Expand Down
1 change: 1 addition & 0 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Page, { open: Set<Request>; last: number; failed: Set<string> }>();
/** The step each page's capture is on, for the shot deadline to name. */
export const step = new WeakMap<Page, string>();

/** Never finish, so they would hold network idle open until its timeout. */
const STREAMS = new Set(["eventsource", "websocket", "ping"]);
Expand Down Expand Up @@ -159,6 +161,7 @@ export async function capture(
cfg: ResolvedConfig,
now: number,
): Promise<Shot> {
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);
Expand All @@ -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) {
Expand All @@ -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);
Expand Down Expand Up @@ -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}`);
Expand Down
46 changes: 31 additions & 15 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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 }),
]),
Expand All @@ -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 }),
),
Expand Down Expand Up @@ -602,20 +603,35 @@ 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",
width: number,
cfg: ResolvedConfig,
now: number,
): Promise<Shot> {
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();
}
}

Expand Down
2 changes: 1 addition & 1 deletion tests/fixtures/pages/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
26 changes: 26 additions & 0 deletions tests/fixtures/pages/hang/left.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Layout parity</title>
<link rel="stylesheet" href="/shared/base.css">
<style>
/* GUARD RAIL for the shot deadline. The page wedges its renderer on the first stylesheet
renderdiff injects, so the capture never returns and must error at the deadline. */
</style>
</head>
<body>
<div class="page">
<h1>Hung page guard rail</h1>
<p class="lede">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.</p>

<section class="notes">
<h2>Notes</h2>
<p>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.</p>
</section>
</div>
<script>
new MutationObserver(() => { for (;;); }).observe(document.head, { childList: true });
</script>
</body>
</html>
26 changes: 26 additions & 0 deletions tests/fixtures/pages/hang/right.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Layout parity</title>
<link rel="stylesheet" href="/shared/base.css">
<style>
/* GUARD RAIL for the shot deadline. The page wedges its renderer on the first stylesheet
renderdiff injects, so the capture never returns and must error at the deadline. */
</style>
</head>
<body>
<div class="page">
<h1>Hung page guard rail</h1>
<p class="lede">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.</p>

<section class="notes">
<h2>Notes</h2>
<p>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.</p>
</section>
</div>
<script>
new MutationObserver(() => { for (;;); }).observe(document.head, { childList: true });
</script>
</body>
</html>
1 change: 1 addition & 0 deletions tests/helpers/corpus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const GUARDRAILS = [
"media",
"long",
"video",
"hang",
] as const;

export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS];
Expand Down
41 changes: 41 additions & 0 deletions tests/visual/guardrails.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`);
});
});
Loading