Skip to content

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

TypeScript

ci(visual): scout the full visual plan in three parallel shards (#7414)

Cindy Zhang526363d5c48a
diff --git a/.github/scripts/release-check-workflow.test.mjs b/.github/scripts/release-check-workflow.test.mjs
index 01f57172ee..25da934aab 100644
--- a/.github/scripts/release-check-workflow.test.mjs
+++ b/.github/scripts/release-check-workflow.test.mjs
@@ -24,6 +24,7 @@ const releaseJobs = [
'check-components',
'build-storybook',
'typecheck',
+ 'visual-scout',
'pr-visual',
'pr-a11y-shard',
'pr-a11y-audit',
@@ -227,6 +228,7 @@ describe('explicit release routing', () => {
'pr-a11y-shard',
'pr-a11y',
'a11y-contracts',
+ 'visual-scout',
'pr-visual',
'pr-rtl-shard',
])('blocks %s when its build fails', name => {
diff --git a/.github/scripts/visual-gate/gate.mjs b/.github/scripts/visual-gate/gate.mjs
index 55b963727f..aaa336b82d 100644
--- a/.github/scripts/visual-gate/gate.mjs
+++ b/.github/scripts/visual-gate/gate.mjs
@@ -12,6 +12,7 @@
* plan what would be captured, and why
* capture take the shots
* check capture, compare against the baseline, write verdict + report
+ * scout observe one shard of the release plan's theming-target scout
* accept record that the after is the correct picture, for named shots
*
* Exit codes are the contract for automation: 0 clean, 1 crashed, 2 changed.
@@ -28,6 +29,13 @@ import * as path from 'node:path';
import {fileURLToPath} from 'node:url';
import {capture, scout} from './lib/capture.mjs';
+import {
+ mergeScoutShards,
+ parseShard,
+ readShardFiles,
+ shardFile,
+ shardStoryIds,
+} from './lib/scout-shards.mjs';
import {
analyzeTargeting,
buildVerdict,
@@ -77,11 +85,14 @@ const captureIdentity = () => ({
const config = loadConfig(REPO_ROOT);
const releaseMode = command === 'release';
+// `scout` observes a shard of exactly the release plan's scout, so it plans
+// with the same inputs and accepts no flag that could change that list.
+const releasePlanInputs = releaseMode || command === 'scout';
const themeCatalog = readThemeCatalog(REPO_ROOT, config.baselineThemes);
const storybookDir = path.resolve(flag('storybook-dir') ?? 'apps/storybook/dist');
const baselineDir = path.resolve(flag('baseline') ?? '.visual-baseline');
let outDir = path.resolve(flag('out') ?? '.visual-run');
-const tiers = releaseMode
+const tiers = releasePlanInputs
? RELEASE_TIERS
: (flag('tiers') ?? config.tiers.join(',')).split(',').filter(Boolean);
const sample = flag('sample') ? Number(flag('sample')) : null;
@@ -111,7 +122,7 @@ const storyPackages = (flag('story-packages') ?? config.stableStoryPackages.join
/** A trusted, exact shot list used only to recapture an accepted merged result. */
const planFile = flag('plan-file');
if (
- releaseMode &&
+ releasePlanInputs &&
(flag('tiers') ||
flag('story-packages') ||
flag('observations') ||
@@ -171,7 +182,17 @@ function storiesToScout(stories, targets, themeOverrides) {
}
/** @returns {Promise<{shots: import('./lib/plan.mjs').Shot[], stories: ReturnType<typeof readStoryIndex>}>} */
-async function plan() {
+/** The Storybook build a run reads, as stamped by the build job (or null). */
+function storybookBuildSha() {
+ const stamp = path.join(storybookDir, 'astryx-build-sha.txt');
+ return fs.existsSync(stamp) ? fs.readFileSync(stamp, 'utf8').trim() || null : null;
+}
+
+/**
+ * @param {{scoutOnly?: boolean}} [options] `scoutOnly` returns the scout's
+ * story list instead of a plan; `null` when this plan scouts nothing.
+ */
+async function plan({scoutOnly = false} = {}) {
if (planFile) {
return {
shots: withThemeMetadata(readExactPlan(planFile), themeCatalog),
@@ -182,7 +203,7 @@ async function plan() {
loadThemingTargets(REPO_ROOT),
loadThemeOverrides(REPO_ROOT, config.probeTheme),
]);
- const themeOverrides = releaseMode
+ const themeOverrides = releasePlanInputs
? Object.fromEntries(
Object.entries(allThemeOverrides).filter(
([theme]) => themeCatalog[theme]?.stableVisual === true,
@@ -208,18 +229,30 @@ async function plan() {
const themeStories = baselineVisualStories(stories, baselineManifest);
let observations;
- if (
+ const scouts =
!has('no-scout') &&
(tiers.includes('probe') ||
- (tiers.includes('theme-matrix') && matrixThemes.length === 0))
- ) {
+ (tiers.includes('theme-matrix') && matrixThemes.length === 0));
+ const storyIds = scouts
+ ? tiers.includes('probe')
+ ? stories.map(story => story.id)
+ : storiesToScout(stories, targets, themeOverrides)
+ : null;
+ if (scoutOnly) return {scoutStoryIds: storyIds};
+ if (scouts) {
const cachePath = flag('observations');
- if (cachePath && fs.existsSync(cachePath)) {
+ const shardDir = flag('observation-shards');
+ if (shardDir) {
+ // Shards scouted this same list on this same build in parallel jobs;
+ // the merge refuses anything less than the complete set.
+ observations = mergeScoutShards(readShardFiles(shardDir), {
+ storyIds,
+ storybookSha: storybookBuildSha(),
+ });
+ process.stderr.write(`Read ${storyIds.length} scouted stories from ${shardDir}\n`);
+ } else if (cachePath && fs.existsSync(cachePath)) {
observations = JSON.parse(fs.readFileSync(cachePath, 'utf8'));
} else {
- const storyIds = tiers.includes('probe')
- ? stories.map(story => story.id)
- : storiesToScout(stories, targets, themeOverrides);
process.stderr.write(`Scouting ${storyIds.length} stories for theming targets…\n`);
observations = await scout({
storyIds,
@@ -615,6 +648,37 @@ function summarize(verdict, baselineExists) {
async function main() {
switch (command) {
+ case 'scout': {
+ const shard = parseShard(flag('shard'));
+ const out = flag('observations-out');
+ if (!out) throw new Error('scout needs --observations-out <file>.');
+ const {scoutStoryIds} = await plan({scoutOnly: true});
+ if (!scoutStoryIds) throw new Error('The release plan scouts nothing.');
+ const mine = shardStoryIds(scoutStoryIds, shard);
+ process.stderr.write(
+ `Scouting shard ${shard.index}/${shard.count}: ${mine.length} of ${scoutStoryIds.length} stories…\n`,
+ );
+ const observations = await scout({
+ storyIds: mine,
+ storybookDir,
+ theme: config.defaultTheme,
+ viewport: config.viewport,
+ concurrency: config.scoutConcurrency,
+ });
+ fs.mkdirSync(path.dirname(path.resolve(out)), {recursive: true});
+ fs.writeFileSync(
+ out,
+ `${JSON.stringify(
+ shardFile({
+ storyIds: scoutStoryIds,
+ shard,
+ storybookSha: storybookBuildSha(),
+ observations,
+ }),
+ )}\n`,
+ );
+ return EXIT.clean;
+ }
case 'plan': {
const {shots} = await plan();
if (has('json')) {
@@ -748,7 +812,7 @@ async function main() {
}
default:
process.stderr.write(
- 'Usage: gate.mjs <flaky|plan|capture|check|release|accept> [--storybook-dir dir] [--baseline dir] [--out dir] [--tiers a,b] [--sample n]\n',
+ 'Usage: gate.mjs <flaky|plan|scout|capture|check|release|accept> [--storybook-dir dir] [--baseline dir] [--out dir] [--tiers a,b] [--sample n]\n',
);
return EXIT.crashed;
}
diff --git a/.github/scripts/visual-gate/lib/scout-shards.mjs b/.github/scripts/visual-gate/lib/scout-shards.mjs
new file mode 100644
index 0000000000..a70fe87cdf
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/scout-shards.mjs
@@ -0,0 +1,151 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Split the theming-target scout across jobs and join the parts.
+ *
+ * @input the plan's ordered scout story list, one shard's observations
+ * @output a shard file per job, and — only when every shard of the same list
+ * and the same Storybook build is present — the full observations
+ * object, in the plan's story order
+ * @position Used by `gate.mjs scout` (write) and by the plan when it is given
+ * `--observation-shards` (read). The plan cannot tell a missing
+ * observation from a story that renders nothing, so a partial or
+ * mismatched set is refused rather than merged.
+ */
+
+import {createHash} from 'node:crypto';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+
+export const SHARD_FILE_VERSION = 1;
+
+/** @param {string | null | undefined} value e.g. `2/3` */
+export function parseShard(value) {
+ const match = /^(\d+)\/(\d+)$/.exec(value ?? '');
+ const index = match ? Number(match[1]) : NaN;
+ const count = match ? Number(match[2]) : NaN;
+ if (
+ !Number.isInteger(index) ||
+ !Number.isInteger(count) ||
+ count < 1 ||
+ index < 1 ||
+ index > count
+ ) {
+ throw new Error(
+ `--shard must be <index>/<count> with 1 <= index <= count, got ${value ?? 'nothing'}.`,
+ );
+ }
+ return {index, count};
+}
+
+/**
+ * The stories one shard scouts: every count-th story, starting at its index,
+ * so each shard gets a spread of the index rather than one slow corner of it.
+ * @param {string[]} storyIds
+ * @param {{index: number, count: number}} shard
+ */
+export function shardStoryIds(storyIds, {index, count}) {
+ return storyIds.filter((_, position) => position % count === index - 1);
+}
+
+/** @param {string[]} storyIds */
+export function storyListDigest(storyIds) {
+ return createHash('sha256').update(JSON.stringify(storyIds)).digest('hex');
+}
+
+/**
+ * @param {object} options
+ * @param {string[]} options.storyIds the plan's full scout list
+ * @param {{index: number, count: number}} options.shard
+ * @param {string | null} options.storybookSha
+ * @param {Record<string, Record<string, string[]>>} options.observations this shard's stories only
+ */
+export function shardFile({storyIds, shard, storybookSha, observations}) {
+ return {
+ version: SHARD_FILE_VERSION,
+ shard,
+ storybookSha,
+ storyListDigest: storyListDigest(storyIds),
+ storyCount: storyIds.length,
+ observations,
+ };
+}
+
+/** @param {string} dir */
+export function readShardFiles(dir) {
+ if (!fs.existsSync(dir)) return [];
+ return fs
+ .readdirSync(dir)
+ .filter(name => name.endsWith('.json'))
+ .sort()
+ .map(name => {
+ const file = path.join(dir, name);
+ return {file, content: JSON.parse(fs.readFileSync(file, 'utf8'))};
+ });
+}
+
+/**
+ * Join shard files into the observations a single scout of `storyIds` would
+ * have produced. Throws unless every shard of this exact list and build is
+ * present once and together they cover every story exactly once.
+ * @param {{file: string, content: any}[]} files
+ * @param {{storyIds: string[], storybookSha: string | null}} expected
+ * @returns {Record<string, Record<string, string[]>>}
+ */
+export function mergeScoutShards(files, {storyIds, storybookSha}) {
+ if (files.length === 0) throw new Error('No scout shard files to merge.');
+ const digest = storyListDigest(storyIds);
+ const count = files[0].content?.shard?.count;
+ const seen = new Set();
+ /** @type {Record<string, Record<string, string[]>>} */
+ const merged = {};
+ for (const {file, content} of files) {
+ const where = path.basename(file);
+ if (content?.version !== SHARD_FILE_VERSION) {
+ throw new Error(
+ `${where}: unsupported scout shard version ${content?.version}.`,
+ );
+ }
+ if (content.shard?.count !== count) {
+ throw new Error(
+ `${where}: shard count ${content.shard?.count} does not match ${count}.`,
+ );
+ }
+ if (seen.has(content.shard.index)) {
+ throw new Error(
+ `${where}: shard ${content.shard.index}/${count} appears twice.`,
+ );
+ }
+ seen.add(content.shard.index);
+ if (
+ content.storyListDigest !== digest ||
+ content.storyCount !== storyIds.length
+ ) {
+ throw new Error(
+ `${where}: scouted a different story list than this plan.`,
+ );
+ }
+ if ((content.storybookSha ?? null) !== (storybookSha ?? null)) {
+ throw new Error(
+ `${where}: scouted Storybook ${content.storybookSha ?? 'unstamped'}, this plan reads ${storybookSha ?? 'unstamped'}.`,
+ );
+ }
+ const expectedIds = new Set(shardStoryIds(storyIds, content.shard));
+ const ids = Object.keys(content.observations ?? {});
+ if (
+ ids.length !== expectedIds.size ||
+ ids.some(id => !expectedIds.has(id))
+ ) {
+ throw new Error(
+ `${where}: does not hold exactly the stories of shard ${content.shard.index}/${count}.`,
+ );
+ }
+ Object.assign(merged, content.observations);
+ }
+ if (seen.size !== count) {
+ throw new Error(
+ `Scout shards ${[...seen].sort((a, b) => a - b).join(', ')} of ${count} — the set is incomplete.`,
+ );
+ }
+ return Object.fromEntries(storyIds.map(id => [id, merged[id]]));
+}
diff --git a/.github/scripts/visual-gate/lib/scout-shards.test.mjs b/.github/scripts/visual-gate/lib/scout-shards.test.mjs
new file mode 100644
index 0000000000..2c1a5b2a7b
--- /dev/null
+++ b/.github/scripts/visual-gate/lib/scout-shards.test.mjs
@@ -0,0 +1,110 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+
+import {
+ mergeScoutShards,
+ parseShard,
+ shardFile,
+ shardStoryIds,
+} from './scout-shards.mjs';
+
+const storyIds = [
+ 'a--one',
+ 'a--two',
+ 'b--one',
+ 'c--one',
+ 'c--two',
+ 'd--one',
+ 'e--one',
+];
+const observe = id => ({[`target-${id}`]: [id]});
+
+function shards(count, {storybookSha = 'abc', ids = storyIds} = {}) {
+ return Array.from({length: count}, (_, offset) => {
+ const shard = {index: offset + 1, count};
+ const mine = shardStoryIds(ids, shard);
+ return {
+ file: `observations-${shard.index}.json`,
+ content: shardFile({
+ storyIds: ids,
+ shard,
+ storybookSha,
+ observations: Object.fromEntries(mine.map(id => [id, observe(id)])),
+ }),
+ };
+ });
+}
+
+describe('scout shards', () => {
+ it('parses index/count and refuses anything else', () => {
+ expect(parseShard('2/3')).toEqual({index: 2, count: 3});
+ for (const bad of [null, '', '0/3', '4/3', '1/0', 'x/3', '1']) {
+ expect(() => parseShard(bad), String(bad)).toThrow(/--shard/);
+ }
+ });
+
+ it('gives every story to exactly one shard', () => {
+ const parts = [1, 2, 3].map(index =>
+ shardStoryIds(storyIds, {index, count: 3}),
+ );
+ expect(parts.flat().sort()).toEqual([...storyIds].sort());
+ expect(new Set(parts.flat()).size).toBe(storyIds.length);
+ });
+
+ it('joins a complete set into the single-scout result, in plan order', () => {
+ const merged = mergeScoutShards(shards(3).reverse(), {
+ storyIds,
+ storybookSha: 'abc',
+ });
+ expect(Object.keys(merged)).toEqual(storyIds);
+ expect(merged).toEqual(
+ Object.fromEntries(storyIds.map(id => [id, observe(id)])),
+ );
+ });
+
+ it('refuses a missing shard', () => {
+ expect(() =>
+ mergeScoutShards(shards(3).slice(1), {storyIds, storybookSha: 'abc'}),
+ ).toThrow(/incomplete/);
+ });
+
+ it('refuses a duplicated shard', () => {
+ const set = shards(3);
+ expect(() =>
+ mergeScoutShards([set[0], set[0], set[1]], {
+ storyIds,
+ storybookSha: 'abc',
+ }),
+ ).toThrow(/twice/);
+ });
+
+ it('refuses shards of another story list or another build', () => {
+ expect(() =>
+ mergeScoutShards(shards(2, {ids: storyIds.slice(1)}), {
+ storyIds,
+ storybookSha: 'abc',
+ }),
+ ).toThrow(/different story list/);
+ expect(() =>
+ mergeScoutShards(shards(2, {storybookSha: 'other'}), {
+ storyIds,
+ storybookSha: 'abc',
+ }),
+ ).toThrow(/Storybook/);
+ });
+
+ it('refuses a shard holding the wrong stories', () => {
+ const set = shards(2);
+ delete set[1].content.observations[storyIds[1]];
+ expect(() =>
+ mergeScoutShards(set, {storyIds, storybookSha: 'abc'}),
+ ).toThrow(/exactly the stories of shard 2\/2/);
+ });
+
+ it('refuses an empty set', () => {
+ expect(() => mergeScoutShards([], {storyIds, storybookSha: 'abc'})).toThrow(
+ /No scout shard/,
+ );
+ });
+});
diff --git a/.github/scripts/visual-gate/workflow-concurrency.test.mjs b/.github/scripts/visual-gate/workflow-concurrency.test.mjs
index a65c9bff12..29b0e49867 100644
--- a/.github/scripts/visual-gate/workflow-concurrency.test.mjs
+++ b/.github/scripts/visual-gate/workflow-concurrency.test.mjs
@@ -140,7 +140,7 @@ describe('PR report and deployment workflow contracts', () => {
value.indexOf(' pr-rtl-shard:'),
);
expect(visual).toContain(
- 'needs: [build-storybook, check-components, maintenance-request]',
+ '[build-storybook, check-components, maintenance-request, visual-scout]',
);
expect(visual).toContain(
'name: storybook-${{ needs.build-storybook.outputs.short_hash }}',
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 5a50d78709..12fdc4b560 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -2045,6 +2045,74 @@ jobs:
- name: Verify guest fixture contrast
run: pnpm -F @astryxdesign/vibe-tests fixtures:contrast
+ # The full visual plan first loads every Core story to learn which theming
+ # targets it renders, and that scout is most of the job's time. It runs here
+ # as parallel shards over exactly the release plan's story list; pr-visual
+ # joins them only when every shard succeeded, and otherwise scouts inline.
+ visual-scout:
+ name: Stable visual scout (${{ matrix.shard }}/${{ strategy.job-total }})
+ needs: [build-storybook, check-components]
+ if: >-
+ !cancelled() &&
+ needs.build-storybook.result == 'success' &&
+ needs.check-components.result == 'success' &&
+ ((github.event_name == 'pull_request' &&
+ needs.check-components.outputs.has_stable_visual == 'true' &&
+ needs.check-components.outputs.broad_stable_visual == 'true') ||
+ (github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check'))
+ strategy:
+ fail-fast: false
+ matrix:
+ shard: [1, 2, 3]
+ runs-on: 2-core-ubuntu-arm
+ permissions:
+ contents: read
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v7
+
+ - name: Setup Node and pnpm
+ uses: ./.github/actions/setup
+ with:
+ install: 'false'
+
+ - name: Download Storybook artifact
+ uses: actions/download-artifact@v8
+ with:
+ name: storybook-${{ needs.build-storybook.outputs.short_hash }}
+ path: apps/storybook/dist
+
+ # If the optional theme artifact is missing, the gate builds the themes.
+ - name: Download built themes and core
+ continue-on-error: true
+ uses: actions/download-artifact@v8
+ with:
+ name: dists-${{ needs.build-storybook.outputs.short_hash }}
+ path: packages
+
+ - name: Install Playwright
+ run: pnpm install --frozen-lockfile && npx playwright install chromium
+
+ # Downloaded theme builds import Core's consumer-facing dist files.
+ - name: Build Core dependency for theme inspection
+ run: pnpm -F @astryxdesign/core build
+
+ - name: Scout this shard of the release plan
+ run: |
+ node .github/scripts/visual-gate/gate.mjs scout \
+ --storybook-dir apps/storybook/dist \
+ --baseline .github/visual-baseline \
+ --shard "${{ matrix.shard }}/${{ strategy.job-total }}" \
+ --observations-out ".visual-scout/observations-${{ matrix.shard }}.json"
+
+ - name: Upload scout shard
+ uses: actions/upload-artifact@v7
+ with:
+ name: visual-scout-${{ needs.build-storybook.outputs.short_hash }}-${{ matrix.shard }}
+ path: .visual-scout/observations-${{ matrix.shard }}.json
+ retention-days: 1
+ if-no-files-found: error
+
# Stable-package visual regression and explicit baseline capture share this
# owner. Focused PRs compare the checked-in baseline; broad PRs use the full
# canonical plan. Maintenance captures candidates on the same runner, and a
@@ -2052,7 +2120,8 @@ jobs:
# Audit and interaction fixtures stay with their existing browser checks.
pr-visual:
name: Stable visual regression
- needs: [build-storybook, check-components, maintenance-request]
+ needs:
+ [build-storybook, check-components, maintenance-request, visual-scout]
if: >-
!cancelled() &&
((github.event_name == 'pull_request' &&
@@ -2098,6 +2167,16 @@ jobs:
name: dists-${{ needs.build-storybook.outputs.short_hash }}
path: packages
+ # Only a complete set: the gate refuses a partial or mismatched one, and
+ # without any it scouts inline as before.
+ - name: Download scout shards
+ if: (github.event_name == 'pull_request' || inputs.operation == 'release-check') && needs.visual-scout.result == 'success'
+ uses: actions/download-artifact@v8
+ with:
+ pattern: visual-scout-${{ needs.build-storybook.outputs.short_hash }}-*
+ path: .visual-scout
+ merge-multiple: true
+
- name: Install Playwright
run: pnpm install --frozen-lockfile && npx playwright install chromium
@@ -2144,12 +2223,15 @@ jobs:
echo "Stable Core components: ${COMPONENTS:-none}"
echo "Stable themes: ${THEMES:-none}"
+ OBS_ARGS=()
+ if [ -d .visual-scout ]; then OBS_ARGS=(--observation-shards .visual-scout); fi
set +e
node .github/scripts/visual-gate/gate.mjs "$COMMAND" \
--storybook-dir apps/storybook/dist \
--baseline .github/visual-baseline \
--out .visual-run \
"${SCOPE_ARGS[@]}" \
+ "${OBS_ARGS[@]}" \
--summary-output visual-summary.md
code=$?
set -e
@@ -2165,6 +2247,7 @@ jobs:
--storybook-dir apps/storybook/dist \
--baseline .github/visual-baseline \
--out .visual-run \
+ "${OBS_ARGS[@]}" \
--summary-output visual-summary.md
code=$?
set -e
@@ -2194,11 +2277,14 @@ jobs:
if: github.event_name == 'workflow_dispatch' && inputs.operation == 'release-check'
run: |
set -eu
+ OBS_ARGS=()
+ if [ -d .visual-scout ]; then OBS_ARGS=(--observation-shards .visual-scout); fi
set +e
node .github/scripts/visual-gate/gate.mjs release \
--storybook-dir apps/storybook/dist \
--baseline .github/visual-baseline \
--out .visual-run \
+ "${OBS_ARGS[@]}" \
--summary-output visual-summary.md
code=$?
set -e