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 @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/output.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
4 changes: 2 additions & 2 deletions skills/renderdiff/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. `<shot>.<side>.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. |
Expand Down Expand Up @@ -307,7 +307,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`,
Expand Down
13 changes: 12 additions & 1 deletion src/capture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
/**
Expand Down Expand Up @@ -367,7 +369,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;
}
}
Expand Down
2 changes: 2 additions & 0 deletions src/report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
47 changes: 41 additions & 6 deletions src/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ const MAX_UNSTABLE_SHARE = 0.25;
interface Job {
route: Route;
width: number;
retried?: boolean;
}

interface RunOpts {
Expand Down Expand Up @@ -98,13 +99,26 @@ function slugs(routes: Route[]): Map<string, string> {
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;
Expand All @@ -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 {
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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`];
(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))}`];
}),
);
throw new Error(
`page did not settle: ${unstablePixels}px unstable at ${key}, again on retry; ${where.flat().join("; ")}`,
);
}
let varies: Region[] = [];
let variesPixels = 0;
Expand Down Expand Up @@ -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),
Expand Down Expand Up @@ -496,6 +530,7 @@ export async function run({
...entry,
status: "error",
error: e instanceof Error ? e.message : String(e),
...(frames && { frames }),
});
++done;
if (progress) {
Expand Down
6 changes: 3 additions & 3 deletions 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`, `video-seek`, `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`, `video-seek`, `hang`, `origin`, `cooperate`.
One per defence in `src/capture.ts` / `src/config.ts`.

## Authoring rules
Expand Down Expand Up @@ -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

Expand Down
42 changes: 42 additions & 0 deletions tests/fixtures/pages/unsettled-once/page.ts
Original file line number Diff line number Diff line change
@@ -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 = `<script>
let n = 0;
setInterval(() => {
n++;
document.body.style.background = "rgb(" + ((n * 53) % 256) + ", " + ((n * 97) % 256) + ", " + ((n * 29) % 256) + ")";
}, 10);
</script>`;

const page = () => `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Layout parity</title>
<link rel="stylesheet" href="/shared/base.css">
</head>
<body>
<div class="page">
<h1>Unsettled once guard rail</h1>
<p class="lede">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.</p>

<section class="notes">
<h2>Notes</h2>
<p>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.</p>
</section>
</div>
${++renders === 1 ? RECOLOUR : ""}
</body>
</html>
`;

export const left = page;
export const right = page;
3 changes: 2 additions & 1 deletion tests/helpers/corpus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export const GUARDRAILS = [
"clock",
"ticker",
"unsettled",
"unsettled-once",
"sprite",
"short",
"tall-region",
Expand All @@ -62,7 +63,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"];
Expand Down
28 changes: 27 additions & 1 deletion tests/visual/guardrails.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down Expand Up @@ -1163,9 +1184,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",
);
});
});

Expand Down
Loading