Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(ci): fail prs that drop live storybook baselines (#110205)

Georges-Antoine Assic79de1890d15
diff --git a/.github/scripts/check-snapshot-baseline-removals.mjs b/.github/scripts/check-snapshot-baseline-removals.mjs
new file mode 100644
index 000000000000..f61aa10fa4c2
--- /dev/null
+++ b/.github/scripts/check-snapshot-baseline-removals.mjs
@@ -0,0 +1,135 @@
+import { appendFileSync, readFileSync } from 'node:fs'
+import { posix } from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { parseArgs } from 'node:util'
+
+const BASELINE_PATH = 'frontend/snapshots.yml'
+
+// Returns each snapshot id with its lines as written, so a failure can print them for restoring.
+// The YAML writer emits a key over 128 characters in the explicit `? key` form.
+export function readSnapshotEntries(yamlText) {
+ const entries = new Map()
+ let inSnapshots = false
+ let current = null
+ for (const line of yamlText.split('\n')) {
+ if (/^\s*(#|$)/.test(line)) {
+ continue
+ }
+ if (/^\S/.test(line)) {
+ inSnapshots = /^snapshots:\s*(#.*)?$/.test(line)
+ current = null
+ continue
+ }
+ if (!inSnapshots) {
+ continue
+ }
+ const key = /^ {4}(?:\? +(['"]?)([^\s'":?]+)\1|(['"]?)([^\s'":?]+)\3:)(?:\s+#.*)?\s*$/.exec(line)
+ if (key) {
+ current = [line]
+ entries.set(key[2] ?? key[4], current)
+ } else if (current) {
+ current.push(line)
+ }
+ }
+ return entries
+}
+
+// Storybook sanitizes a story id to exactly one `--` (title--export), and the test runner appends
+// `--<viewport width>`, `--<theme>` and `--<browser>` to it, so the first two segments name the story.
+export function storyIdOf(snapshotId) {
+ return snapshotId.split('--').slice(0, 2).join('--')
+}
+
+export function readSnapshottedStories(indexJsonText, storybookRoot) {
+ const entries = JSON.parse(indexJsonText).entries ?? {}
+ const stories = new Map()
+ for (const entry of Object.values(entries)) {
+ if (entry?.type !== 'story' || (entry.tags ?? []).includes('test-skip')) {
+ continue
+ }
+ stories.set(entry.id, entry.importPath ? posix.normalize(posix.join(storybookRoot, entry.importPath)) : null)
+ }
+ return stories
+}
+
+// A story the PR's Visual Review run renders shows a wrong removal there for review. Only stories
+// that run skips can lose every entry silently.
+export function findLiveRemovals({ baseIds, headIds, stories, renderedFiles }) {
+ const storiesWithHeadEntries = new Set([...headIds].map(storyIdOf))
+ const removals = []
+ for (const id of baseIds) {
+ if (headIds.has(id)) {
+ continue
+ }
+ const storyId = storyIdOf(id)
+ if (!stories.has(storyId) || storiesWithHeadEntries.has(storyId) || renderedFiles.has(stories.get(storyId))) {
+ continue
+ }
+ removals.push(id)
+ }
+ return removals.sort()
+}
+
+export function formatFailure(removals, baseEntries) {
+ const storyCount = new Set(removals.map(storyIdOf)).size
+ const stories = storyCount === 1 ? 'story that still exists' : 'stories that still exist'
+ return [
+ `This PR removes every ${BASELINE_PATH} entry of ${storyCount} ${stories}.`,
+ "This PR's Visual Review run does not render these stories, so it cannot show the removal.",
+ 'The merge queue renders every story and rejects the batch that holds this PR.',
+ '',
+ `To fix it, add these lines back to ${BASELINE_PATH} under snapshots, in alphabetical order:`,
+ '',
+ ...removals.flatMap((id) => baseEntries.get(id)),
+ '',
+ "If a story should no longer take snapshots, tag it 'test-skip' in its story file and this check passes.",
+ ].join('\n')
+}
+
+function main() {
+ const { values } = parseArgs({
+ options: {
+ 'base-snapshots': { type: 'string' },
+ 'head-snapshots': { type: 'string' },
+ 'storybook-index': { type: 'string' },
+ 'storybook-root': { type: 'string', default: 'common/storybook' },
+ 'rendered-files': { type: 'string' },
+ },
+ })
+ for (const required of ['base-snapshots', 'head-snapshots', 'storybook-index', 'rendered-files']) {
+ if (!values[required]) {
+ console.error(`Missing --${required}`)
+ process.exit(2)
+ }
+ }
+
+ const baseEntries = readSnapshotEntries(readFileSync(values['base-snapshots'], 'utf8'))
+ const removals = findLiveRemovals({
+ baseIds: new Set(baseEntries.keys()),
+ headIds: new Set(readSnapshotEntries(readFileSync(values['head-snapshots'], 'utf8')).keys()),
+ stories: readSnapshottedStories(readFileSync(values['storybook-index'], 'utf8'), values['storybook-root']),
+ renderedFiles: new Set(JSON.parse(readFileSync(values['rendered-files'], 'utf8'))),
+ })
+ if (removals.length === 0) {
+ console.log(`No ${BASELINE_PATH} entry was removed for a story that still takes snapshots.`)
+ return
+ }
+
+ const message = formatFailure(removals, baseEntries)
+ console.log(message)
+ if (process.env.GITHUB_STEP_SUMMARY) {
+ appendFileSync(
+ process.env.GITHUB_STEP_SUMMARY,
+ `### Snapshot baselines removed\n\n\`\`\`\n${message}\n\`\`\`\n`
+ )
+ }
+ if (process.env.GITHUB_ACTIONS) {
+ const annotation = message.replaceAll('%', '%25').replaceAll('\r', '%0D').replaceAll('\n', '%0A')
+ console.log(`::error title=Snapshot baselines removed for existing stories::${annotation}`)
+ }
+ process.exit(1)
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main()
+}
diff --git a/.github/scripts/check-snapshot-baseline-removals.test.mjs b/.github/scripts/check-snapshot-baseline-removals.test.mjs
new file mode 100644
index 000000000000..53bb10cce193
--- /dev/null
+++ b/.github/scripts/check-snapshot-baseline-removals.test.mjs
@@ -0,0 +1,130 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+
+import {
+ findLiveRemovals,
+ formatFailure,
+ readSnapshotEntries,
+ readSnapshottedStories,
+} from './check-snapshot-baseline-removals.mjs'
+
+const LONG_KEY_LENGTH = 60
+
+const entryLines = (id) => {
+ const comment = id.endsWith('--light') ? ' # approved' : ''
+ return id.length > LONG_KEY_LENGTH
+ ? [` ? ${id}${comment}`, ` : hash: v1.k1.${id.length}.fake`]
+ : [` ${id}:${comment}`, ` hash: v1.k1.${id.length}.fake`]
+}
+
+const baselineYaml = (ids) =>
+ [
+ 'version: 1',
+ 'config:',
+ ' api: https://us.example.com',
+ " team: '2'",
+ 'snapshots: # approved baselines',
+ ...ids.flatMap(entryLines),
+ '# end of baselines',
+ '',
+ ].join('\n')
+
+const indexJson = (stories) =>
+ JSON.stringify({
+ v: 5,
+ entries: Object.fromEntries([
+ [
+ 'settings-form--docs',
+ { type: 'docs', id: 'settings-form--docs', importPath: '../../frontend/src/SettingsForm.mdx' },
+ ],
+ ...stories.map(({ id, file, tags = ['dev', 'test'] }) => [
+ id,
+ { type: 'story', id, importPath: `../../${file}`, tags },
+ ]),
+ ]),
+ })
+
+const LONG_STORY = 'products-dashboards-widget-types-error-tracking-settings--before-ingestion'
+
+const BASE = [
+ `${LONG_STORY}--dark`,
+ `${LONG_STORY}--light`,
+ 'settings-form--edited--dark',
+ 'settings-form--edited--light',
+ 'settings-form--empty--dark',
+ 'settings-form--empty--light',
+ 'widget-grid--default--narrow--dark',
+ 'widget-grid--default--narrow--light',
+]
+
+const STORIES = [
+ { id: LONG_STORY, file: 'products/dashboards/frontend/ErrorTrackingSettings.stories.tsx' },
+ { id: 'settings-form--edited', file: 'frontend/src/SettingsForm.stories.tsx' },
+ { id: 'settings-form--empty', file: 'frontend/src/SettingsForm.stories.tsx' },
+ { id: 'widget-grid--default', file: 'products/widgets/frontend/WidgetGrid.stories.tsx' },
+]
+
+const cases = [
+ {
+ name: 'flags every entry of an existing story the PR run does not render',
+ head: BASE.filter((id) => !id.startsWith('settings-form--edited')),
+ stories: STORIES,
+ renderedFiles: [],
+ expected: ['settings-form--edited--dark', 'settings-form--edited--light'],
+ },
+ {
+ name: 'flags entries written with explicit keys',
+ head: BASE.filter((id) => !id.startsWith(LONG_STORY)),
+ stories: STORIES,
+ renderedFiles: [],
+ expected: [`${LONG_STORY}--dark`, `${LONG_STORY}--light`],
+ },
+ {
+ name: 'passes when the story was deleted or renamed',
+ head: BASE.filter((id) => !id.startsWith('widget-grid')),
+ stories: STORIES.filter((story) => story.id !== 'widget-grid--default'),
+ renderedFiles: [],
+ expected: [],
+ },
+ {
+ name: 'passes when the story keeps another variant',
+ head: BASE.filter((id) => id !== 'widget-grid--default--narrow--dark'),
+ stories: STORIES,
+ renderedFiles: [],
+ expected: [],
+ },
+ {
+ name: 'passes when the story is tagged test-skip',
+ head: BASE.filter((id) => !id.startsWith('widget-grid')),
+ stories: STORIES.map((story) =>
+ story.id === 'widget-grid--default' ? { ...story, tags: ['dev', 'test', 'test-skip'] } : story
+ ),
+ renderedFiles: [],
+ expected: [],
+ },
+ {
+ name: 'passes when the PR run renders the story',
+ head: BASE.filter((id) => !id.startsWith('widget-grid')),
+ stories: STORIES,
+ renderedFiles: ['products/widgets/frontend/WidgetGrid.stories.tsx'],
+ expected: [],
+ },
+]
+
+for (const { name, head, stories, renderedFiles, expected } of cases) {
+ test(name, () => {
+ const removals = findLiveRemovals({
+ baseIds: new Set(readSnapshotEntries(baselineYaml(BASE)).keys()),
+ headIds: new Set(readSnapshotEntries(baselineYaml(head)).keys()),
+ stories: readSnapshottedStories(indexJson(stories), 'common/storybook'),
+ renderedFiles: new Set(renderedFiles),
+ })
+ assert.deepEqual(removals, expected)
+ })
+}
+
+test('the failure prints the removed entries exactly as the base file wrote them', () => {
+ const removed = [`${LONG_STORY}--dark`, 'settings-form--edited--dark']
+ const message = formatFailure(removed, readSnapshotEntries(baselineYaml(BASE)))
+ assert.ok(message.includes(removed.flatMap(entryLines).join('\n')))
+})
diff --git a/.github/workflows/ci-storybook.yml b/.github/workflows/ci-storybook.yml
index 71f9ee2ecfd0..95f36e6ff456 100644
--- a/.github/workflows/ci-storybook.yml
+++ b/.github/workflows/ci-storybook.yml
@@ -93,6 +93,7 @@ jobs:
&& steps.baseline_push.outputs.result != 'true')
}}
matrix: ${{ steps.matrix.outputs.matrix }}
+ snapshots_baseline: ${{ steps.filter.outputs.snapshots_baseline }}
# Trunk's merge queue opens its PR from trunk-merge/**. Scoped to same-repo
# heads because github.head_ref is author-controlled: without the scope, any
# contributor could opt out of the visual gates below by naming their branch
@@ -149,6 +150,8 @@ jobs:
frontend_generated:
- 'frontend/src/generated/**'
- 'products/**/frontend/generated/**'
+ snapshots_baseline:
+ - 'frontend/snapshots.yml'
- name: Detect Visual Review baseline-only push
id: baseline_push
@@ -340,6 +343,102 @@ jobs:
retention-days: 1
if-no-files-found: warn
+ # Consumed by check-baseline-removals, which needs only the story index.
+ - name: Upload story index artifact
+ uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
+ with:
+ name: storybook-index
+ path: common/storybook/dist/index.json
+ retention-days: 1
+ if-no-files-found: error
+
+ # A narrowed PR run renders only the stories its diff affects, so a PR can drop every baseline
+ # entry of a story outside that set and stay green. The merge queue renders every story and
+ # rejects the batch that holds the PR. This job finds such removals on the PR, from the story
+ # index, without rendering anything. A full PR run renders every story, so Visual Review shows
+ # the removal there and this job skips.
+ check-baseline-removals:
+ name: Check snapshot baseline removals
+ runs-on: ubuntu-24.04
+ timeout-minutes: 5
+ needs: [changes, build-storybook, select-stories]
+ if: >-
+ github.event_name == 'pull_request'
+ && needs.changes.outputs.snapshots_baseline == 'true'
+ && needs.build-storybook.result == 'success'
+ && needs.select-stories.outputs.mode == 'selective'
+ steps:
+ # The checker comes from the base branch, so the PR under test cannot change its verdict.
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.base.ref }}
+ repository: ${{ github.event.pull_request.base.repo.full_name }}
+ path: checker
+ sparse-checkout: |
+ .nvmrc
+ .github/scripts/check-snapshot-baseline-removals.mjs
+ sparse-checkout-cone-mode: false
+
+ - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
+ with:
+ ref: ${{ github.event.pull_request.head.sha }}
+ repository: ${{ github.event.pull_request.head.repo.full_name }}
+ path: head
+ sparse-checkout: frontend/snapshots.yml
+ sparse-checkout-cone-mode: false
+
+ - uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
+ with:
+ node-version-file: checker/.nvmrc
+
+ - name: Download story index artifact
+ uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
+ with:
+ name: storybook-index
+ path: ${{ runner.temp }}/storybook-index
+
+ # Compare against the merge base, not the base tip, so entries the base branch gained after
+ # this PR branched off do not count as removals. A base branch that predates the checker
+ # skips the check. The merge queue also catches these removals, so an API error that
+ # persists after retries skips the check with a warning instead of failing the PR.
+ - name: Check for removed baselines of existing stories
+ env:
+ GH_TOKEN: ${{ github.token }}
+ REPO: ${{ github.repository }}
+ RENDERED_FILES_JSON: ${{ needs.select-stories.outputs.affected_files_json }}
+ BASE_SHA: ${{ github.event.pull_request.base.sha }}
+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}
+ run: |
+ set -euo pipefail
+ checker=checker/.github/scripts/check-snapshot-baseline-removals.mjs
+ if [ ! -f "$checker" ]; then
+ echo "::notice::The base branch has no $checker, so this check is skipped."
+ exit 0
+ fi
+ gh_api_to() {
+ local out=$1
+ shift
+ for attempt in 1 2 3; do
+ if gh api "$@" > "$out"; then
+ return 0
+ fi
+ [ "$attempt" -lt 3 ] && sleep $((attempt * 10))
+ done
+ echo "::warning::The GitHub API call failed 3 times, so this check is skipped. The merge queue still catches removed baselines."
+ exit 0
+ }
+ gh_api_to "$RUNNER_TEMP/merge-base.txt" "repos/$REPO/compare/$BASE_SHA...$HEAD_SHA" --jq '.merge_base_commit.sha'
+ merge_base=$(cat "$RUNNER_TEMP/merge-base.txt")
+ echo "Comparing frontend/snapshots.yml at $HEAD_SHA with merge base $merge_base"
+ gh_api_to "$RUNNER_TEMP/base-snapshots.yml" -H 'Accept: application/vnd.github.raw+json' \
+ "repos/$REPO/contents/frontend/snapshots.yml?ref=$merge_base"
+ printf '%s' "$RENDERED_FILES_JSON" > "$RUNNER_TEMP/rendered-files.json"
+ node "$checker" \
+ --base-snapshots "$RUNNER_TEMP/base-snapshots.yml" \
+ --head-snapshots head/frontend/snapshots.yml \
+ --storybook-index "$RUNNER_TEMP/storybook-index/index.json" \
+ --rendered-files "$RUNNER_TEMP/rendered-files.json"
+
vr-setup:
name: Create Visual Review run
runs-on: ubuntu-24.04
@@ -910,7 +1009,16 @@ jobs:
# Collate matrix + VR completion status for the required check
visual_regression_tests:
- needs: [changes, build-storybook, select-stories, visual-regression, vr-setup, vr-complete]
+ needs:
+ [
+ changes,
+ build-storybook,
+ select-stories,
+ visual-regression,
+ vr-setup,
+ vr-complete,
+ check-baseline-removals,
+ ]
name: Visual regression tests pass
runs-on: ubuntu-24.04
timeout-minutes: 5
@@ -957,6 +1065,11 @@ jobs:
exit 1
fi
+ if [[ "${{ needs.check-baseline-removals.result }}" != "success" && "${{ needs.check-baseline-removals.result }}" != "skipped" ]]; then
+ echo "Check snapshot baseline removals did not pass (result: ${{ needs.check-baseline-removals.result }}). Its log shows why, and lists any removed entries with how to restore them."
+ exit 1
+ fi
+
echo "All jobs passed or were skipped successfully."
vr-complete: