From 71e11cdbfd03f14debd0b93532e7158c007dc709 Mon Sep 17 00:00:00 2001 From: Timur Mashara <62305878+tmashara@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:53:46 +0100 Subject: [PATCH 1/2] Retry a page that did not settle once, then save its differing frames The settle check requeues the job once. If it fails again, each unsettled side's last two frames are written as ..unsettled-a/-b.png, listed as frames on the error result, and the message gives the box they differ in. Fixes #77 Co-Authored-By: Claude Opus 5.5 --- docs/how-it-works.md | 2 +- docs/output.md | 3 +- skills/renderdiff/reference.md | 4 +- src/capture.ts | 13 +++++- src/report.ts | 2 + src/run.ts | 47 ++++++++++++++++++--- tests/fixtures/pages/README.md | 6 +-- tests/fixtures/pages/unsettled-once/page.ts | 42 ++++++++++++++++++ tests/helpers/corpus.ts | 3 +- tests/visual/guardrails.test.ts | 28 +++++++++++- 10 files changed, 134 insertions(+), 16 deletions(-) create mode 100644 tests/fixtures/pages/unsettled-once/page.ts diff --git a/docs/how-it-works.md b/docs/how-it-works.md index 4dd69d4..55bc68e 100644 --- a/docs/how-it-works.md +++ b/docs/how-it-works.md @@ -33,7 +33,7 @@ honestly. This is what renderdiff does to make sure of that. for tiled pages). Pixels still changing between the last two shots of the same load are noise from that origin: they're painted magenta on both sides, reported per comparison as `unstable`, and excluded from the measurement — the score is over the remaining - pixels. A route more than 25% unstable errors as `page did not settle`. + pixels. A route more than 25% unstable errors as `page did not settle` after one retry. - **Rechecks a differing shot** — reloads the right side once in a fresh context. The elements that differ between the two loads are `varies`: painted out on both sides like a mask, excluded from the score, and listed with the mask that would cover them. Off with diff --git a/docs/output.md b/docs/output.md index baab7af..f873c80 100644 --- a/docs/output.md +++ b/docs/output.md @@ -244,7 +244,8 @@ sides differed at capture time, even when its pixels were painted out as unstabl Pixels that changed between two shots of the *same* page load, so they're noise from that origin (a ticker, a carousel). They're painted magenta on both sides and excluded from the score, and a route with any is never on the `clean:` line. More than 25% unstable is an -error, `page did not settle`. +error, `page did not settle`, after one retry, with the two frames saved as +`{slug}.{width}.{side}.unsettled-a.png`/`-b.png`. ## Crops diff --git a/skills/renderdiff/reference.md b/skills/renderdiff/reference.md index 801bfee..f30c454 100644 --- a/skills/renderdiff/reference.md +++ b/skills/renderdiff/reference.md @@ -119,7 +119,7 @@ Report (`--open`, for a human): green from 99.5%, amber to 97%, red below. | `HTTP 404 at …` (any ≥ 400) | That side answered an error: a route missing on one origin, or a server not ready. | | `not an HTML page: server sent … at …` | The route is a file (PDF, image, JSON, download), not a page. Drop it from the routes. Never retried. | | `page did not render on either side (…)` | Both sides under 200 chars of text and no visible image, SVG, canvas, video, iframe or form control. Usually a failed asset or an app that never mounted. One blank side isn't refused; it scores low. | -| `page did not settle: Npx unstable at …` | Over 25% of the page kept changing. Mask or stop the moving part. | +| `page did not settle: Npx unstable at …` | Over 25% of the page kept changing, on two loads. `..unsettled-a/-b.png` are the two differing frames, and the message gives the box they differ in. Mask or stop the moving part. | | `page is Npx tall at Wpx wide, past the …px sanity ceiling …` | Taller than 57,600,000px ÷ width (never under 40,000px): a runaway layout, not a page. | | `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. | @@ -306,7 +306,7 @@ For scripts and drilling into one route; the loop doesn't need it. One result pe `grep '"url":"/about"'` pulls a route. Paths are relative to the out dir. - **Each result:** `url`, `left`, `right`, `selector` (`{ left, right }` or null), `hook`, - `width`, `status` (`compared` or `error` with `error`); `score`, `alignedScore`, + `width`, `status` (`compared`, or `error` with `error`, and `frames` when it did not settle); `score`, `alignedScore`, `diffPixels`, `totalPixels`, `unstablePixels`, `varies` and `variesPixels` (absent unless a recheck found some; regions with `elements`), `heightDelta`, `widthDelta`; `regions` (`x,y,w,h,pixels`, left-page px, `line` `{ y, h, side }`, `accepted` reason); `bands` (`side`, diff --git a/src/capture.ts b/src/capture.ts index acf1026..38453db 100644 --- a/src/capture.ts +++ b/src/capture.ts @@ -9,6 +9,8 @@ export interface Shot { png: Buffer; /** One byte per pixel of `png`, set where the last two shots of this load disagreed. */ unstable: Uint8Array | null; + /** The frame before `png`, set only when the two differed. */ + prev?: Buffer; /** Why this side looks blank, or null. Only an error when both sides do. */ blank: string | null; /** @@ -362,7 +364,16 @@ export async function capture( const png = await shoot(); if (png.equals(prev)) return { png, unstable: null, blank, text, origin, failed, marked }; if (n === tries) - return { png, unstable: await differing(prev, png), blank, text, origin, failed, marked }; + return { + png, + prev, + unstable: await differing(prev, png), + blank, + text, + origin, + failed, + marked, + }; prev = png; } } diff --git a/src/report.ts b/src/report.ts index 816a772..a7dbfb4 100644 --- a/src/report.ts +++ b/src/report.ts @@ -97,6 +97,8 @@ export interface CropResult { export interface ErrorResult extends BaseResult { status: "error"; error: string; + /** The two differing frames per unsettled side, out-dir relative. */ + frames?: string[]; } export type RouteResult = ComparedResult | ErrorResult; diff --git a/src/run.ts b/src/run.ts index 8eda881..6165e61 100644 --- a/src/run.ts +++ b/src/run.ts @@ -47,6 +47,7 @@ const MAX_UNSTABLE_SHARE = 0.25; interface Job { route: Route; width: number; + retried?: boolean; } interface RunOpts { @@ -98,13 +99,26 @@ function slugs(routes: Route[]): Map { return out; } +/** The smallest box holding every set pixel of a row-major `width`-wide mask. */ +function bbox(mask: Uint8Array, width: number) { + let [x0, y0, x1, y1] = [width, Infinity, -1, -1]; + for (let i = 0; i < mask.length; i++) { + if (!mask[i]) continue; + const x = i % width, + y = Math.floor(i / width); + [x0, x1, y1] = [Math.min(x0, x), Math.max(x1, x), y]; + if (y0 === Infinity) y0 = y; + } + return { x: x0, y: y0, w: x1 - x0 + 1, h: y1 - y0 + 1 }; +} + /** Only a directory holding nothing but files renderdiff writes is safe to wipe. */ const ours = (f: string) => f === "report.html" || f === "evidence.html" || f === "results.json" || f === CACHE_DIR || - /^[a-z0-9_~@-]+\.[\d.]+\.(left|right|diff|c\d+)\.png$/.test(f); + /^[a-z0-9_~@-]+\.[\d.]+\.((left|right)(\.unsettled-[ab])?|diff|c\d+)\.png$/.test(f); function wipeable(dir: string): boolean { if (!fs.existsSync(dir)) return true; @@ -119,7 +133,9 @@ export const reusable = (r: RouteResult) => ((r.diffPixels === 0 && r.unstablePixels === 0 && !broken(r)) || r.accepted); const files = (r: RouteResult) => - r.status === "compared" ? [...Object.values(r.images), ...r.crops.map((c) => c.path)] : []; + r.status === "compared" + ? [...Object.values(r.images), ...r.crops.map((c) => c.path)] + : (r.frames ?? []); /** Everything that decides how a shot is taken, hook and `locate` sources included. */ function configHash(cfg: ResolvedConfig, routes: Route[]): string { @@ -302,6 +318,10 @@ export async function run({ const tag = `${label(route)} @${width}`; // Its own line: parse.ts reads the route on the row as one \S+ token. const sel = route.selector ? `selector ${selectorText(route.selector)}` : ""; + const base = `${stems.get(key)}.${width}`; + const write = (name: string, buf: Buffer) => + fs.promises.writeFile(path.join(cfg.outDir, name), buf); + let frames: string[] | undefined; try { missed = 0; // allSettled, not all: a page must not start the next job while still loading this one. @@ -329,7 +349,24 @@ export async function run({ let { diffPng, spots, ...metrics } = await compare(leftShot, rightShot); if (unstablePixels > MAX_UNSTABLE_SHARE * metrics.totalPixels) { - throw new Error(`page did not settle: ${unstablePixels}px unstable at ${key}`); + if (!job.retried) { + queue.push({ ...job, retried: true }); + continue; + } + const where = await Promise.all( + (["left", "right"] as const).map(async (side, s) => { + const shot = s ? rightShot : leftShot; + if (!shot.prev || !shot.unstable) return []; + const [a, b] = [`${base}.${side}.unsettled-a.png`, `${base}.${side}.unsettled-b.png`]; + await Promise.all([write(a, shot.prev), write(b, raw[s]!)]); + (frames ??= []).push(a, b); + const { width: w } = await sharp(raw[s]!).metadata(); + return [`${side}: ${a} vs -b differ within ${fmtRegion(bbox(shot.unstable, w))}`]; + }), + ); + throw new Error( + `page did not settle: ${unstablePixels}px unstable at ${key}, again on retry; ${where.flat().join("; ")}`, + ); } let varies: Region[] = []; let variesPixels = 0; @@ -392,14 +429,11 @@ export async function run({ } const measured = metrics.totalPixels - unstablePixels - variesPixels; metrics.score = measured > 0 ? 1 - metrics.diffPixels / measured : 0; - const base = `${stems.get(key)}.${width}`; const images = { left: `${base}.left.png`, right: `${base}.right.png`, diff: `${base}.diff.png`, }; - const write = (name: string, buf: Buffer) => - fs.promises.writeFile(path.join(cfg.outDir, name), buf); // Both pages still hold this job's document: the next load waits for the loop. const [made, named] = await Promise.all([ crops(leftShot.png, rightShot.png, spots), @@ -496,6 +530,7 @@ export async function run({ ...entry, status: "error", error: e instanceof Error ? e.message : String(e), + ...(frames && { frames }), }); ++done; if (progress) { diff --git a/tests/fixtures/pages/README.md b/tests/fixtures/pages/README.md index 804d90a..1c16d66 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`, `hang`, `origin`, `cooperate`. + `drifting`, `tracker`, `clock`, `ticker`, `unsettled`, `unsettled-once`, `sprite`, `short`, `tall-region`, `reorder`, `stripe`, `frameset`, `menu`, `signed-in`, `fixed`, `inserted`, `labelled`, `broken-asset`, `media`, `long`, `video`, `hang`, `origin`, `cooperate`. One per defence in `src/capture.ts` / `src/config.ts`. ## Authoring rules @@ -59,8 +59,8 @@ Breaking any of these produces a flaky suite, and the flake looks like a renderd than 900px from fixed heights alone, as `inserted` does. 9. **No animation** except in `animated`, which exists to prove `STILL_CSS` and the image-animation launch flag kill it, `ticker`, whose timer exists to be caught by the - stability check, and `unsettled`, which recolours the whole page to trip the - unstable-pixel cap. + stability check, `unsettled`, which recolours the whole page to trip the + unstable-pixel cap, and `unsettled-once`, which does so on its first render only. ## Adding a route diff --git a/tests/fixtures/pages/unsettled-once/page.ts b/tests/fixtures/pages/unsettled-once/page.ts new file mode 100644 index 0000000..0f07d4a --- /dev/null +++ b/tests/fixtures/pages/unsettled-once/page.ts @@ -0,0 +1,42 @@ +/** + * GUARD RAIL for the settle retry. + * + * `unsettled`'s page, except that only the first render, on whichever side loads first, + * recolours. The first attempt trips the unstable-pixel cap; the retry renders two static + * pages and must compare clean. Generated because the counter has to live on the server. + */ + +let renders = 0; + +const RECOLOUR = ``; + +const page = () => ` + + + +Layout parity + + + +
+

Unsettled once guard rail

+

On its first load the page background changes colour every ten milliseconds. Every later load is still, so a second attempt has a page to measure.

+ +
+

Notes

+

A page that did not settle may only have been slow once. The pair is shot again before it is refused, and a still second attempt scores like any other page.

+
+
+${++renders === 1 ? RECOLOUR : ""} + + +`; + +export const left = page; +export const right = page; diff --git a/tests/helpers/corpus.ts b/tests/helpers/corpus.ts index ff9818a..1881dc2 100644 --- a/tests/helpers/corpus.ts +++ b/tests/helpers/corpus.ts @@ -38,6 +38,7 @@ export const GUARDRAILS = [ "clock", "ticker", "unsettled", + "unsettled-once", "sprite", "short", "tall-region", @@ -61,7 +62,7 @@ export const GUARDRAILS = [ export const ALL: string[] = [...EQUIVALENCE, ...CONTROLS, ...GUARDRAILS]; /** Routes whose markup comes from a `page.ts` generator instead of static files. */ -export const GENERATED = ["tall", "drifting"]; +export const GENERATED = ["tall", "drifting", "unsettled-once"]; /** Routes that deliberately do not link `shared/base.css`. */ export const SELF_CONTAINED = ["blank", "sprite", "tall", "frameset"]; diff --git a/tests/visual/guardrails.test.ts b/tests/visual/guardrails.test.ts index d20fa60..75e1cb6 100644 --- a/tests/visual/guardrails.test.ts +++ b/tests/visual/guardrails.test.ts @@ -207,11 +207,32 @@ describe("the stability check", () => { }); test("a page that is mostly unstable is an error, not a score", async () => { + const before = site.hits("/unsettled"); const run = await capture(["/unsettled"]); assert.equal(run.code, 3, context(run)); + assert.equal(site.hits("/unsettled") - before, 4, "each side is loaded twice"); const report = parseReport(run.report()!); assert.equal(report.errors.length, 1, context(run)); - assert.match(report.errors[0]!.message, /page did not settle: \d+px unstable at \/unsettled/); + const { message } = report.errors[0]!; + assert.match(message, /page did not settle: \d+px unstable at \/unsettled, again on retry/); + assert.match(message, /differ within \d+×\d+ at \(\d+,\d+\)/); + const r = results(run.outDir).results[0]!; + const frames = r.status === "error" ? (r.frames ?? []) : []; + assert.ok(frames.length === 2 || frames.length === 4, `frames: ${frames}`); + for (const f of frames) { + assert.ok(message.includes(f.replace(/-b\.png$/, "-a.png")), `${f} is not named`); + assert.ok((await sharp(run.file(f)).metadata()).width, `${f} is not an image`); + } + }); + + test("a page that settles on the retry is compared as usual", async () => { + const before = site.hits("/unsettled-once"); + const run = await capture(["/unsettled-once"]); + assert.equal(run.code, 0, context(run)); + assert.equal(site.hits("/unsettled-once") - before, 4, "each side is loaded twice"); + const r = result(results(run.outDir), "/unsettled-once", 1440); + assert.equal(r.diffPixels, 0, context(run)); + assert.equal(r.unstablePixels, 0, context(run)); }); test("a static page reports nothing unstable", async () => { @@ -1156,9 +1177,14 @@ describe("the output directory", () => { test("an interrupted run's directory, with images but no report, is reused", async () => { const dir = tempDir(); fs.writeFileSync(path.join(dir, "x.1440.left.png"), ""); + fs.writeFileSync(path.join(dir, "x.1440.left.unsettled-a.png"), ""); const run = await into(dir); assert.equal(run.code, 0, context(run)); assert.ok(!fs.existsSync(path.join(dir, "x.1440.left.png")), "the old run was not wiped"); + assert.ok( + !fs.existsSync(path.join(dir, "x.1440.left.unsettled-a.png")), + "the old frames were not wiped", + ); }); }); From b8d4f2d19024a700fc50bbe8aceaa307d3710c1b Mon Sep 17 00:00:00 2001 From: Timur Mashara <62305878+tmashara@users.noreply.github.com> Date: Thu, 29 Oct 2026 18:59:45 +0100 Subject: [PATCH 2/2] Keep an unsettled error's frames in left, right order Co-Authored-By: Claude Opus 5.5 --- src/run.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/run.ts b/src/run.ts index 6165e61..f57d247 100644 --- a/src/run.ts +++ b/src/run.ts @@ -358,8 +358,8 @@ export async function run({ const shot = s ? rightShot : leftShot; if (!shot.prev || !shot.unstable) return []; const [a, b] = [`${base}.${side}.unsettled-a.png`, `${base}.${side}.unsettled-b.png`]; - await Promise.all([write(a, shot.prev), write(b, raw[s]!)]); (frames ??= []).push(a, b); + await Promise.all([write(a, shot.prev), write(b, raw[s]!)]); const { width: w } = await sharp(raw[s]!).metadata(); return [`${side}: ${a} vs -b differ within ${fmtRegion(bbox(shot.unstable, w))}`]; }),