Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(ci): parallelize visual gate planning and comparison (#5831)

Cindy Zhang4a882996ad1b
diff --git a/.github/scripts/visual-gate/README.md b/.github/scripts/visual-gate/README.md
index 3ac48ae4f5..57c1ea2f4e 100644
--- a/.github/scripts/visual-gate/README.md
+++ b/.github/scripts/visual-gate/README.md
@@ -181,10 +181,12 @@ instant lives in `lib/capture.mjs` and is recorded in every manifest. Changing
it changes those shots, so it is a deliberate rebaseline, not a tweak.
Theme and colour mode are switched over Storybook's own channel rather than
-by reloading. Two workers capture independent story groups concurrently, but
-all shots for one story stay together so seeded random state and fast-global
-ordering remain deterministic. `--no-fast-globals` forces a reload per shot if
-a story's state ever turns out to survive the re-render.
+by reloading. Two workers scout and capture independent story groups
+concurrently, but all shots for one story stay together so seeded random state
+and fast-global ordering remain deterministic. After capture closes the browser,
+two CPU workers decode and compare the baseline PNGs. `--no-fast-globals`
+forces a reload per shot if a story's state ever turns out to survive the
+re-render.
## Where the images live
diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjs
index abefb54aff..b61b0e23d0 100644
--- a/.github/scripts/visual-gate/gate.mjs
+++ b/.github/scripts/visual-gate/gate.mjs
@@ -192,6 +192,7 @@ async function plan() {
storybookDir,
theme: config.defaultTheme,
viewport: config.viewport,
+ concurrency: config.scoutConcurrency,
});
if (cachePath) fs.writeFileSync(cachePath, `${JSON.stringify(observations)}\n`);
}
@@ -377,13 +378,14 @@ async function check() {
let comparison;
try {
comparison = await compare({
- baselineDir: path.join(baselineDir, 'shots'),
- currentDir: path.join(outDir, 'shots'),
- baselineManifest,
- currentManifest: manifest,
- diffDir: path.join(reportDir, 'diff'),
- threshold: config.threshold,
- maxDiffPixels: config.maxDiffPixels,
+ baselineDir: path.join(baselineDir, 'shots'),
+ currentDir: path.join(outDir, 'shots'),
+ baselineManifest,
+ currentManifest: manifest,
+ diffDir: path.join(reportDir, 'diff'),
+ threshold: config.threshold,
+ maxDiffPixels: config.maxDiffPixels,
+ concurrency: config.compareConcurrency,
failures,
});
} catch (error) {
@@ -400,6 +402,7 @@ async function check() {
diffDir: path.join(reportDir, 'diff'),
threshold: config.threshold,
maxDiffPixels: config.maxDiffPixels,
+ concurrency: config.compareConcurrency,
});
}
diff --git a/.github/scripts/visual-gate/lib/capture.mjs b/.github/scripts/visual-gate/lib/capture.mjs
index 3764b4e8aa..64dc642461 100644
--- a/.github/scripts/visual-gate/lib/capture.mjs
+++ b/.github/scripts/visual-gate/lib/capture.mjs
@@ -349,6 +349,50 @@ async function settle(page, settleMs) {
}
}
+export function partitionScoutStories(storyIds, concurrency) {
+ if (storyIds.length === 0) return [];
+ const workerCount = Math.max(1, Math.min(Math.floor(concurrency), storyIds.length));
+ const partitions = Array.from({length: workerCount}, () => []);
+ storyIds.forEach((storyId, index) => partitions[index % workerCount].push(storyId));
+ return partitions;
+}
+
+async function scoutPartition({storyIds, browser, origin, theme, viewport, onStory}) {
+ const context = await browser.newContext({
+ viewport,
+ deviceScaleFactor: 1,
+ timezoneId: TIMEZONE_ID,
+ ...CAPTURE_CONTEXT_SECURITY,
+ });
+ await context.clock.setFixedTime(FROZEN_NOW);
+ await context.addInitScript(BACKGROUND_NETWORK_GUARD);
+ await context.addInitScript(SEEDED_RANDOM);
+ await blockExternalNetwork(context, origin);
+ const page = await context.newPage();
+ const observations = {};
+
+ try {
+ for (const storyId of storyIds) {
+ try {
+ await page.goto(
+ `${origin}/iframe.html?id=${encodeURIComponent(storyId)}&viewMode=story&globals=astryxTheme:${theme};colorMode:light`,
+ {waitUntil: 'load', timeout: 30000},
+ );
+ await page.waitForSelector('#storybook-root > *', {timeout: 20000});
+ observations[storyId] = await observeTargets(page);
+ } catch {
+ // A story that will not render is the capture's problem to report, not
+ // the scout's; it simply contributes no observations.
+ observations[storyId] = {};
+ }
+ onStory();
+ }
+ } finally {
+ await context.close();
+ }
+ return observations;
+}
+
/**
* Load stories without photographing them, and report what each one rendered.
*
@@ -363,48 +407,36 @@ async function settle(page, settleMs) {
* @param {string} options.storybookDir
* @param {string} options.theme - any theme; observed targets do not depend on it
* @param {{width: number, height: number}} options.viewport
+ * @param {number} [options.concurrency]
* @param {(progress: {done: number, total: number}) => void} [options.onProgress]
* @returns {Promise<Record<string, Record<string, string[]>>>} story id → observed targets
*/
-export async function scout({storyIds, storybookDir, theme, viewport, onProgress}) {
+export async function scout({storyIds, storybookDir, theme, viewport, concurrency = 1, onProgress}) {
const {chromium} = await import('playwright');
const server = await serveDirectory(storybookDir);
const origin = `http://127.0.0.1:${server.port}`;
- const browser = await chromium.launch();
- const context = await browser.newContext({
- viewport,
- deviceScaleFactor: 1,
- timezoneId: TIMEZONE_ID,
- ...CAPTURE_CONTEXT_SECURITY,
- });
- await context.clock.setFixedTime(FROZEN_NOW);
- await context.addInitScript(BACKGROUND_NETWORK_GUARD);
- await context.addInitScript(SEEDED_RANDOM);
- await blockExternalNetwork(context, origin);
- const page = await context.newPage();
-
- /** @type {Record<string, Record<string, string[]>>} */
- const observations = {};
- let done = 0;
- for (const storyId of storyIds) {
- try {
- await page.goto(
- `${origin}/iframe.html?id=${encodeURIComponent(storyId)}&viewMode=story&globals=astryxTheme:${theme};colorMode:light`,
- {waitUntil: 'load', timeout: 30000},
- );
- await page.waitForSelector('#storybook-root > *', {timeout: 20000});
- observations[storyId] = await observeTargets(page);
- } catch {
- // A story that will not render is the capture's problem to report, not
- // the scout's; it simply contributes no observations.
- observations[storyId] = {};
- }
- onProgress?.({done: ++done, total: storyIds.length});
+ let browser;
+ try {
+ browser = await chromium.launch();
+ let done = 0;
+ const results = await Promise.all(
+ partitionScoutStories(storyIds, concurrency).map(partition =>
+ scoutPartition({
+ storyIds: partition,
+ browser,
+ origin,
+ theme,
+ viewport,
+ onStory: () => onProgress?.({done: ++done, total: storyIds.length}),
+ }),
+ ),
+ );
+ const observed = Object.assign({}, ...results);
+ return Object.fromEntries(storyIds.map(storyId => [storyId, observed[storyId] ?? {}]));
+ } finally {
+ await browser?.close().catch(() => {});
+ await server.close();
}
-
- await browser.close();
- await server.close();
- return observations;
}
async function capturePartition({
diff --git a/.github/scripts/visual-gate/lib/capture.test.mjs b/.github/scripts/visual-gate/lib/capture.test.mjs
index 34a90a1e6b..949d443151 100644
--- a/.github/scripts/visual-gate/lib/capture.test.mjs
+++ b/.github/scripts/visual-gate/lib/capture.test.mjs
@@ -12,6 +12,7 @@ import {
blockExternalNetwork,
isSameOrigin,
partitionCapturePlan,
+ partitionScoutStories,
serveDirectory,
} from './capture.mjs';
@@ -20,6 +21,15 @@ afterEach(() => {
for (const root of roots.splice(0)) fs.rmSync(root, {recursive: true, force: true});
});
+describe('scout partitioning', () => {
+ it('balances the current 388-story scout across two workers', () => {
+ const stories = Array.from({length: 388}, (_, index) => `story-${index}`);
+ const partitions = partitionScoutStories(stories, 2);
+ expect(partitions.map(partition => partition.length)).toEqual([194, 194]);
+ expect(new Set(partitions.flat()).size).toBe(388);
+ });
+});
+
describe('capture plan partitioning', () => {
it('keeps the 3,378-shot release workload below 1,700 shots per worker', () => {
const plan = [];
diff --git a/.github/scripts/visual-gate/lib/compare-worker.mjs b/.github/scripts/visual-gate/lib/compare-worker.mjs
new file mode 100644
index 0000000000..803482c7e8
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/compare-worker.mjs
@@ -0,0 +1,95 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CPU-bound PNG comparison worker for the visual gate.
+ *
+ * @input one partition of baseline/current image pairs
+ * @output unchanged keys or pixel-diff metadata, plus diff PNGs for changes
+ *
+ * PNG inflate, filtering, and pixelmatch are synchronous CPU work. Keeping them
+ * off the gate's main thread lets the pinned two-core runner compare two clean
+ * frame streams at once after browser capture has finished.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {parentPort, workerData} from 'node:worker_threads';
+
+import {PNG} from 'pngjs';
+import pixelmatch from 'pixelmatch';
+
+function pad(png, width, height) {
+ if (png.width === width && png.height === height) return png;
+ const padded = new PNG({width, height});
+ padded.data.fill(0);
+ PNG.bitblt(
+ png,
+ padded,
+ 0,
+ 0,
+ Math.min(png.width, width),
+ Math.min(png.height, height),
+ 0,
+ 0,
+ );
+ return padded;
+}
+
+const results = [];
+for (const key of workerData.keys) {
+ const baselinePng = PNG.sync.read(
+ fs.readFileSync(path.join(workerData.baselineDir, `${key}.png`)),
+ );
+ const currentPng = PNG.sync.read(
+ fs.readFileSync(path.join(workerData.currentDir, `${key}.png`)),
+ );
+ const width = Math.max(baselinePng.width, currentPng.width);
+ const height = Math.max(baselinePng.height, currentPng.height);
+ const sizeChanged =
+ baselinePng.width !== currentPng.width ||
+ baselinePng.height !== currentPng.height;
+ const before = pad(baselinePng, width, height);
+ const after = pad(currentPng, width, height);
+
+ // Promotion canonicalizes accepted PNG encoding. A fresh Playwright PNG can
+ // therefore have different file bytes while decoding to identical pixels.
+ if (!sizeChanged && Buffer.compare(before.data, after.data) === 0) {
+ results.push({key, unchanged: true});
+ continue;
+ }
+
+ const diff = new PNG({width, height});
+ const diffPixels = pixelmatch(
+ before.data,
+ after.data,
+ diff.data,
+ width,
+ height,
+ {
+ threshold: workerData.threshold,
+ includeAA: false,
+ alpha: 0.2,
+ diffMask: false,
+ },
+ );
+ if (diffPixels <= workerData.maxDiffPixels && !sizeChanged) {
+ results.push({key, unchanged: true});
+ continue;
+ }
+
+ fs.writeFileSync(
+ path.join(workerData.diffDir, `${key}.png`),
+ PNG.sync.write(diff),
+ );
+ results.push({
+ key,
+ change: {
+ key,
+ diffPixels,
+ diffRatio: Number((diffPixels / (width * height)).toFixed(6)),
+ sizeChanged,
+ },
+ });
+}
+
+parentPort.postMessage(results);
diff --git a/.github/scripts/visual-gate/lib/compare.mjs b/.github/scripts/visual-gate/lib/compare.mjs
index d2b5473742..d8dd78ca0c 100644
--- a/.github/scripts/visual-gate/lib/compare.mjs
+++ b/.github/scripts/visual-gate/lib/compare.mjs
@@ -21,7 +21,7 @@
import * as crypto from 'node:crypto';
import * as fs from 'node:fs';
-import * as path from 'node:path';
+import {Worker} from 'node:worker_threads';
const RELEASE_LANE = 'stable-release';
@@ -63,20 +63,33 @@ export function validateReleasePlan(plan, currentManifest, failures = []) {
* @property {boolean} sizeChanged
*/
-/**
- * Widen an image to the given canvas, transparent-padded from the top left, so
- * two shots of different heights can still be diffed pixel for pixel.
- * @param {{width: number, height: number, data: Buffer}} png
- * @param {number} width
- * @param {number} height
- * @param {typeof import('pngjs').PNG} PNG
- */
-function pad(png, width, height, PNG) {
- if (png.width === width && png.height === height) return png;
- const padded = new PNG({width, height});
- padded.data.fill(0);
- PNG.bitblt(png, padded, 0, 0, Math.min(png.width, width), Math.min(png.height, height), 0, 0);
- return padded;
+export function partitionComparisonKeys(keys, concurrency) {
+ if (keys.length === 0) return [];
+ const workerCount = Math.max(1, Math.min(Math.floor(concurrency), keys.length));
+ const partitions = Array.from({length: workerCount}, () => []);
+ keys.forEach((key, index) => partitions[index % workerCount].push(key));
+ return partitions;
+}
+
+function comparePartition(workerData) {
+ return new Promise((resolve, reject) => {
+ const worker = new Worker(new URL('./compare-worker.mjs', import.meta.url), {
+ workerData,
+ execArgv: [],
+ });
+ let settled = false;
+ worker.once('message', value => {
+ settled = true;
+ resolve(value);
+ });
+ worker.once('error', error => {
+ settled = true;
+ reject(error);
+ });
+ worker.once('exit', code => {
+ if (!settled) reject(new Error(`Visual comparison worker exited ${code} without a result.`));
+ });
+ });
}
/**
@@ -88,6 +101,7 @@ function pad(png, width, height, PNG) {
* @param {string} options.diffDir - where diff PNGs are written
* @param {number} options.threshold - pixelmatch per-pixel colour threshold
* @param {number} options.maxDiffPixels - pixels allowed to differ before a shot counts as changed
+ * @param {number} [options.concurrency] - bounded CPU workers for PNG decoding and pixel comparison
* @returns {Promise<{changes: Change[], added: string[], removed: string[], unchanged: string[]}>}
*/
export async function compareCaptures({
@@ -98,22 +112,16 @@ export async function compareCaptures({
diffDir,
threshold,
maxDiffPixels,
+ concurrency = 2,
}) {
- const {PNG} = await import('pngjs');
- const pixelmatch = (await import('pixelmatch')).default;
-
const baselineKeys = new Set(Object.keys(baselineManifest.shots ?? {}));
const currentKeys = Object.keys(currentManifest.shots ?? {});
-
- /** @type {Change[]} */
- const changes = [];
- /** @type {string[]} */
+ const positions = new Map(currentKeys.map((key, index) => [key, index]));
const added = [];
- /** @type {string[]} */
const unchanged = [];
+ const pixelKeys = [];
fs.mkdirSync(diffDir, {recursive: true});
-
for (const key of currentKeys) {
if (!baselineKeys.has(key)) {
added.push(key);
@@ -121,42 +129,34 @@ export async function compareCaptures({
}
const current = currentManifest.shots[key];
const baseline = baselineManifest.shots[key];
- // The bytes are the cheapest possible comparison and the common case.
- if (current.sha256 === baseline.sha256) {
- unchanged.push(key);
- continue;
- }
-
- const baselinePng = PNG.sync.read(fs.readFileSync(path.join(baselineDir, `${key}.png`)));
- const currentPng = PNG.sync.read(fs.readFileSync(path.join(currentDir, `${key}.png`)));
- const width = Math.max(baselinePng.width, currentPng.width);
- const height = Math.max(baselinePng.height, currentPng.height);
- const sizeChanged = baselinePng.width !== currentPng.width || baselinePng.height !== currentPng.height;
-
- const a = pad(baselinePng, width, height, PNG);
- const b = pad(currentPng, width, height, PNG);
- const diff = new PNG({width, height});
- const diffPixels = pixelmatch(a.data, b.data, diff.data, width, height, {
- threshold,
- includeAA: false,
- alpha: 0.2,
- diffMask: false,
- });
+ if (current.sha256 === baseline.sha256) unchanged.push(key);
+ else pixelKeys.push(key);
+ }
- if (diffPixels <= maxDiffPixels && !sizeChanged) {
- unchanged.push(key);
- continue;
- }
- fs.writeFileSync(path.join(diffDir, `${key}.png`), PNG.sync.write(diff));
- changes.push({
- key,
- diffPixels,
- diffRatio: Number((diffPixels / (width * height)).toFixed(6)),
- sizeChanged,
- });
+ const workerResults = (
+ await Promise.all(
+ partitionComparisonKeys(pixelKeys, concurrency).map(keys =>
+ comparePartition({
+ keys,
+ baselineDir,
+ currentDir,
+ diffDir,
+ threshold,
+ maxDiffPixels,
+ }),
+ ),
+ )
+ ).flat();
+ const changes = [];
+ for (const result of workerResults) {
+ if (result.unchanged) unchanged.push(result.key);
+ else changes.push(result.change);
}
- changes.sort((a, b) => b.diffPixels - a.diffPixels);
+ unchanged.sort((a, b) => positions.get(a) - positions.get(b));
+ changes.sort(
+ (a, b) => b.diffPixels - a.diffPixels || positions.get(a.key) - positions.get(b.key),
+ );
return {changes, added, removed: [], unchanged};
}
diff --git a/.github/scripts/visual-gate/lib/compare.test.mjs b/.github/scripts/visual-gate/lib/compare.test.mjs
index 620ce6b4f7..032b45ac96 100644
--- a/.github/scripts/visual-gate/lib/compare.test.mjs
+++ b/.github/scripts/visual-gate/lib/compare.test.mjs
@@ -9,7 +9,13 @@ import {fileURLToPath} from 'node:url';
import {afterEach, beforeEach, describe, expect, it} from 'vitest';
import {PNG} from 'pngjs';
-import {analyzeTargeting, buildVerdict, compareCaptures, compareReleaseCaptures} from './compare.mjs';
+import {
+ analyzeTargeting,
+ buildVerdict,
+ compareCaptures,
+ compareReleaseCaptures,
+ partitionComparisonKeys,
+} from './compare.mjs';
import {createReleasePlan} from './plan.mjs';
/** A solid rectangle, so a change is unambiguous. */
@@ -61,6 +67,13 @@ const compare = (baseline, current) =>
});
describe('compareCaptures', () => {
+ it('balances the current 3,378-shot comparison across two CPU workers', () => {
+ const keys = Array.from({length: 3378}, (_, index) => `shot-${index}`);
+ const partitions = partitionComparisonKeys(keys, 2);
+ expect(partitions.map(partition => partition.length)).toEqual([1689, 1689]);
+ expect(new Set(partitions.flat()).size).toBe(3378);
+ });
+
it('calls an identical shot unchanged without decoding it', async () => {
write('baseline', 'a', png(10, 10, [255, 0, 0]));
write('current', 'a', png(10, 10, [255, 0, 0]));
@@ -68,6 +81,21 @@ describe('compareCaptures', () => {
expect(result).toMatchObject({unchanged: ['a'], changes: [], added: [], removed: []});
});
+ it('skips pixelmatch when differently encoded PNGs decode to identical pixels', async () => {
+ const image = png(10, 10, [255, 0, 0]);
+ const decoded = PNG.sync.read(image);
+ write('baseline', 'a', PNG.sync.write(decoded, {deflateLevel: 1, filterType: 0}));
+ write('current', 'a', PNG.sync.write(decoded, {deflateLevel: 9, filterType: -1}));
+
+ const result = await compare(
+ manifest({a: {sha256: 'baseline-encoding'}}),
+ manifest({a: {sha256: 'current-encoding'}}),
+ );
+
+ expect(result).toMatchObject({unchanged: ['a'], changes: []});
+ expect(fs.readdirSync(path.join(root, 'diff'))).toEqual([]);
+ });
+
it('reports a changed shot with its pixel count and writes a diff image', async () => {
write('baseline', 'a', png(10, 10, [255, 0, 0]));
write('current', 'a', png(10, 10, [0, 0, 255]));
@@ -189,6 +217,24 @@ describe('compareCaptures', () => {
).toThrow(/stable release plan is internal/);
});
+ it('keeps current-manifest order when equal diffs cross worker partitions', async () => {
+ const keys = ['a', 'b', 'c', 'd'];
+ for (const key of keys) {
+ write('baseline', key, png(10, 10, [255, 0, 0]));
+ write('current', key, png(10, 10, [0, 0, 255]));
+ }
+ const before = manifest(
+ Object.fromEntries(keys.map(key => [key, {sha256: `before-${key}`}]))
+ );
+ const after = manifest(
+ Object.fromEntries(keys.map(key => [key, {sha256: `after-${key}`}]))
+ );
+
+ const result = await compare(before, after);
+
+ expect(result.changes.map(change => change.key)).toEqual(keys);
+ });
+
it('ranks the biggest change first', async () => {
write('baseline', 'small', png(10, 10, [255, 0, 0]));
write('current', 'small', png(10, 10, [255, 0, 10]));
diff --git a/.github/scripts/visual-gate/lib/sources.mjs b/.github/scripts/visual-gate/lib/sources.mjs
index 2aee4f2d9e..2a23a96573 100644
--- a/.github/scripts/visual-gate/lib/sources.mjs
+++ b/.github/scripts/visual-gate/lib/sources.mjs
@@ -174,14 +174,16 @@ function unreadableTheme(repoRoot, name, built, error, rebuilt) {
/**
* @param {string} repoRoot
- * @returns {{excludeStories: Record<string, string>, viewport: {width: number, height: number}, settleMs: number, captureConcurrency: number, threshold: number, maxDiffPixels: number, defaultTheme: string, probeTheme: string, stableStoryPackages: string[], tiers: string[]}}
+ * @returns {{excludeStories: Record<string, string>, viewport: {width: number, height: number}, settleMs: number, scoutConcurrency: number, captureConcurrency: number, compareConcurrency: number, threshold: number, maxDiffPixels: number, defaultTheme: string, probeTheme: string, stableStoryPackages: string[], tiers: string[]}}
*/
export function loadConfig(repoRoot) {
const defaults = {
excludeStories: {},
viewport: {width: 1024, height: 768},
settleMs: 50,
+ scoutConcurrency: 2,
captureConcurrency: 2,
+ compareConcurrency: 2,
threshold: 0.1,
maxDiffPixels: 0,
defaultTheme: 'neutral',
diff --git a/.github/scripts/visual-gate/visual-gate.config.json b/.github/scripts/visual-gate/visual-gate.config.json
index 62ba98e6e8..440077f6f5 100644
--- a/.github/scripts/visual-gate/visual-gate.config.json
+++ b/.github/scripts/visual-gate/visual-gate.config.json
@@ -8,8 +8,12 @@
"tiers": ["surface", "theme-matrix", "probe"],
"viewport": {"width": 1024, "height": 768},
"settleMs": 50,
+ "$scoutConcurrency": "Scouting is independent by story and uses two bounded browser contexts on the pinned two-core runner.",
+ "scoutConcurrency": 2,
"$captureConcurrency": "Independent stories may capture concurrently, but every shot for one story stays on one worker so seeded state and fast theme switches remain deterministic.",
"captureConcurrency": 2,
+ "$compareConcurrency": "PNG decoding and pixel comparison run on two CPU workers after browser capture closes.",
+ "compareConcurrency": 2,
"threshold": 0.1,
"maxDiffPixels": 0,
"excludeStories": {