: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(ci): select affected Storybook shards (#69932)
Marius Andrafd4ff8bc66ce
diff --git a/.github/workflows/ci-storybook.yml b/.github/workflows/ci-storybook.ymlindex 264bc8d74948..f2c18fa095bb 100644--- a/.github/workflows/ci-storybook.yml+++ b/.github/workflows/ci-storybook.yml@@ -1,10 +1,10 @@name: Storybookon:pull_request:- # Draft PRs run a narrowed visual-regression matrix (affected stories only);- # ready PRs run the full chromium matrix (the merge gate). ready_for_review- # re-triggers the full run on the current head when a PR leaves draft. To- # force the full matrix on a draft, add the `run-ci-frontend` label —+ # Draft PRs run a narrowed visual-regression matrix when the Storybook module+ # graph can safely identify affected stories. Ready PRs run the full chromium+ # matrix as the merge gate. To force the full matrix on a draft, add the+ # `run-ci-frontend` label —# labeled/unlabeled re-trigger the run so it starts without needing a push.types: [opened, synchronize, reopened, ready_for_review, labeled, unlabeled]merge_group:@@ -338,10 +338,9 @@ jobs:fail-fast: false# Shard counts and worker config (maxWorkers in common/storybook/package.json)# are tuned for runner CPU — consult #team-devex before changing.- # On draft PRs, select-stories may narrow the matrix to a single chromium- # shard running just the affected story files. On ready PRs and master push- # it's skipped, so we fall back to changes.outputs.matrix (ready PRs:- # full chromium; master push: chromium + webkit).+ # Draft PRs may use chromium shards running only affected story files.+ # Ready PRs fall back to changes.outputs.matrix (full chromium), while+ # master pushes run chromium + webkit.# Storybook CI is skipped entirely on merge_group (changes.if).matrix: ${{ fromJson(needs.select-stories.outputs.matrix || needs.changes.outputs.matrix) }}env:@@ -454,13 +453,13 @@ jobs:HOME: /rootSTORYBOOK_SKIP_TAGS: 'test-skip,test-skip-${{ matrix.browser }}'MODE: ${{ needs.select-stories.outputs.mode }}- AFFECTED_FILES: ${{ needs.select-stories.outputs.affected_files }}+ AFFECTED_FILES_JSON: ${{ needs.select-stories.outputs.affected_files_json }}run: |if [ "$MODE" = "selective" ]; then# test-storybook is jest-based; positional path args filter the run to- # only those story files. Single shard, so --shard 1/1 is a no-op.- # shellcheck disable=SC2086- pnpm --filter=@posthog/storybook test:visual:ci:update --browsers ${{ matrix.browser }} --shard ${{ matrix.shard }}/${{ matrix.shard_count }} -- $AFFECTED_FILES+ # only those story files before Jest distributes them across shards.+ mapfile -d '' -t AFFECTED_FILES < <(jq -j '.[] | ., "\u0000"' <<< "$AFFECTED_FILES_JSON")+ pnpm --filter=@posthog/storybook test:visual:ci:update --browsers ${{ matrix.browser }} --shard ${{ matrix.shard }}/${{ matrix.shard_count }} -- "${AFFECTED_FILES[@]}"elsepnpm --filter=@posthog/storybook test:visual:ci:update --browsers ${{ matrix.browser }} --shard ${{ matrix.shard }}/${{ matrix.shard_count }}fi@@ -728,15 +727,11 @@ jobs:github-token: ${{ steps.telemetry-app-token.outputs.token }}status-job: 'Visual regression tests pass'- # Shadow measurement: reports which stories could have rendered differently- # Pick the visual-regression matrix on draft PRs based on which stories the- # webpack module graph (emitted by ModuleGraphPlugin) says are affected- # by the diff. On ready PRs and master push this job is skipped and- # visual-regression falls back to needs.changes.outputs.matrix (the full- # suite). The ready-for-review full run is the merge gate — storybook- # already skips merge_group entirely (changes.if). The run-ci-frontend- # label forces the full matrix on a draft. When selection can't be trusted- # on a draft, visual-regression is skipped and deferred to the ready run.+ # Pick a narrowed visual-regression matrix for draft PRs based on which stories+ # the Vite module graph says are affected by the diff. Ready PRs and drafts with+ # the run-ci-frontend label skip this job and use the full chromium matrix.+ # Selector uncertainty skips draft visual regression because the ready run is+ # still the merge gate.select-stories:name: Story selectionruns-on: ubuntu-latest@@ -751,7 +746,7 @@ jobs:mode: ${{ steps.classify.outputs.mode }}matrix: ${{ steps.classify.outputs.matrix }}should_run: ${{ steps.classify.outputs.should_run }}- affected_files: ${{ steps.classify.outputs.affected_files }}+ affected_files_json: ${{ steps.classify.outputs.affected_files_json }}steps:- uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2with:@@ -802,50 +797,46 @@ jobs:run: |set -euo pipefail- # Untrusted selection on a draft skips visual-regression entirely- # (should_run=false gates vr-setup and the test matrix off); the- # ready-for-review full run is the gate. A skipped draft can't- # trade green-by-default for green-by-skipping: drafts can't- # merge, and ready re-runs the full suite. The run-ci-frontend- # label forces the full matrix on a draft.fall_back_to_skip() {echo "mode=skip" >> "$GITHUB_OUTPUT"echo 'matrix={"include":[]}' >> "$GITHUB_OUTPUT"echo "should_run=false" >> "$GITHUB_OUTPUT"- echo "affected_files=" >> "$GITHUB_OUTPUT"+ echo "affected_files_json=[]" >> "$GITHUB_OUTPUT"}if [[ "$SELECT_OUTCOME" != "success" ]] || [[ ! -s /tmp/selection-result.json ]]; then- echo "::warning::story selector did not produce output; draft skips visual-regression (full run happens on ready for review)"+ echo "::warning::story selector did not produce output; skipping draft visual regression"fall_back_to_skipexit 0fiMODE=$(jq -r '.mode' /tmp/selection-result.json)if [[ "$MODE" != "selective" ]]; then- echo "Selector declined to narrow (mode=$MODE); draft skips visual-regression (full run happens on ready for review)"+ echo "Selector declined to narrow (mode=$MODE); skipping draft visual regression"fall_back_to_skipexit 0fiCOUNT=$(jq -r '.affected_story_count' /tmp/selection-result.json)if [[ "$COUNT" -eq 0 ]]; then- # Selective mode found zero affected stories — skip visual-regression entirely.echo "mode=selective" >> "$GITHUB_OUTPUT"echo 'matrix={"include":[]}' >> "$GITHUB_OUTPUT"echo "should_run=false" >> "$GITHUB_OUTPUT"- echo "affected_files=" >> "$GITHUB_OUTPUT"- echo "Selective mode: 0 affected stories, skipping visual-regression"+ echo "affected_files_json=[]" >> "$GITHUB_OUTPUT"+ echo "Selective mode: 0 affected stories, skipping draft visual regression"exit 0fi- # Selective with affected stories: collapse to one chromium shard.- AFFECTED_FILES=$(jq -r '.affected_stories | join(" ")' /tmp/selection-result.json)+ # Size the narrowed matrix from the estimated affected workload.+ AFFECTED_FILES_JSON=$(jq -c '.affected_stories' /tmp/selection-result.json)+ SHARDS=$(jq -r '[.suggested_shards, 16] | min' /tmp/selection-result.json)+ MATRIX=$(jq -cn --argjson count "$SHARDS" \+ '{include: [range(1; $count + 1) | {browser: "chromium", shard_count: $count, shard: .}]}')echo "mode=selective" >> "$GITHUB_OUTPUT"- echo 'matrix={"include":[{"browser":"chromium","shard":1,"shard_count":1}]}' >> "$GITHUB_OUTPUT"+ echo "matrix=$MATRIX" >> "$GITHUB_OUTPUT"echo "should_run=true" >> "$GITHUB_OUTPUT"- echo "affected_files=$AFFECTED_FILES" >> "$GITHUB_OUTPUT"- echo "Selective mode: $COUNT affected story files"+ echo "affected_files_json=$AFFECTED_FILES_JSON" >> "$GITHUB_OUTPUT"+ echo "Selective mode: $COUNT affected story files across $SHARDS shard(s)"- name: Write summaryif: steps.selection.outcome == 'success'@@ -861,8 +852,7 @@ jobs:COUNT=$(echo "$RESULT" | jq -r '.affected_story_count')AFFECTED_DUR=$(echo "$RESULT" | jq -r '.affected_duration_seconds')TOTAL_DUR=$(echo "$RESULT" | jq -r '.total_duration_seconds')- # Selected mode collapses to a single chromium shard (see classify step).- SHARDS=1+ SHARDS=$(echo "$RESULT" | jq -r '[.suggested_shards, 16] | min')SAVED_STORIES=$((TOTAL - COUNT))SAVED_SHARDS=$((CURRENT_SHARDS - SHARDS))@@ -880,7 +870,7 @@ jobs:| Est. CI minutes | ~${FULL_MINUTES} | ~${SELECTIVE_MINUTES} | **~${SAVED_MINUTES}** || Est. render time | ${TOTAL_DUR}s | ${AFFECTED_DUR}s | **$((TOTAL_DUR - AFFECTED_DUR))s** |- > Predictor: webpack module graph from build-storybook. Master push runs the full suite.+ > Predictor: Vite module graph from build-storybook. Shared code and uncertain changes run the full suite.EOFecho "SELECTION_METRICS: $(echo "$RESULT" | jq -c '{mode, affected: .affected_story_count, total: .total_story_count, current_shards: '$CURRENT_SHARDS', affected_dur: .affected_duration_seconds, total_dur: .total_duration_seconds}')"elsediff --git a/bin/find-affected-stories b/bin/find-affected-storiesindex 8b30dc266efd..9dd1ac56a67b 100755--- a/bin/find-affected-stories+++ b/bin/find-affected-stories@@ -2,10 +2,10 @@/*** Compute the set of stories affected by a set of changed files using the* module-graph.json emitted by the Storybook build (see the ModuleGraphPlugin- * in `common/storybook/.storybook/plugins/module-graph-plugin.ts`).+ * in `common/storybook/.storybook/plugins/vite-module-graph-plugin.ts`).*- * Called from `.github/workflows/ci-storybook.yml`'s shadow-story-selection- * job. Shadow-only today — does not change what visual-regression runs.+ * Called from `.github/workflows/ci-storybook.yml`'s story-selection job to+ * narrow visual-regression runs to stories affected by a pull request.** Usage:* bin/find-affected-stories \@@ -27,9 +27,10 @@import { execFileSync } from 'child_process'import * as fs from 'fs'+import { pathToFileURL } from 'url'// ------------------------------------------------------------------------------// Invalidators webpack can't see+// Invalidators the module graph can't see// -----------------------------------------------------------------------------// Changes to any file matching these substrings force a full-run: the effect@@ -38,8 +39,8 @@ import * as fs from 'fs'const FULL_RUN_PATTERNS = ['.storybook/','common/storybook/tailwind.config.js',- 'common/storybook/webpack.config.js','common/storybook/package.json',+ 'frontend/src/lib/','frontend/src/styles/','frontend/src/mocks/','common/tailwind/',@@ -57,9 +58,14 @@ const FULL_RUN_PATTERNS = ['.nvmrc',]+const STORYBOOK_RELEVANT_FILE_RE =+ /^(frontend\/|products\/.*\/(frontend|mcp\/apps)\/|common\/(esbuilder|mosaic|storybook|tailwind)\/|packages\/quill\/|ee\/frontend\/|services\/mcp\/src\/ui-apps\/)/+const NON_RUNTIME_FILE_RE =+ /(^|\/)(__tests__|tests?)\/|\.(test|spec)\.[cm]?[jt]sx?$|(^|\/)README\.md$|^(frontend|playwright)\/snapshots\.yml$/+const MAX_CHANGED_FILES = 100// Rough per-story render cost (see ci-storybook.yml matrix); used only for-// the savings-estimate row in the shadow job summary.+// the savings-estimate row in the job summary.const AVG_STORY_DURATION_SECONDS = 6const TARGET_SHARD_SECONDS = 10 * 60const STORY_RE = /\.stories\.(tsx?|mdx|jsx?)$/@@ -109,7 +115,7 @@ function emitFull(reason, totalStories) {function emitSelective(affected, totalStories, unresolved) {const affectedDuration = affected.length * AVG_STORY_DURATION_SECONDSconst totalDuration = totalStories * AVG_STORY_DURATION_SECONDS- // 2x safety factor, matching the backend shadow convention.+ // 2x safety factor keeps selective shards below the target under variance.const suggestedShards = Math.max(1, Math.floor((affectedDuration * 2) / TARGET_SHARD_SECONDS) + 1)process.stdout.write(JSON.stringify({@@ -129,7 +135,7 @@ function emitSelective(affected, totalStories, unresolved) {// Core logic// ------------------------------------------------------------------------------function requiresFullRun(changedFile) {+export function requiresFullRun(changedFile) {for (const pattern of FULL_RUN_PATTERNS) {if (changedFile.includes(pattern)) {return `changed file matches full-run pattern '${pattern}': ${changedFile}`@@ -138,10 +144,10 @@ function requiresFullRun(changedFile) {return null}-function normalize(p) {+export function normalize(p) {if (!p) return p// Strip any leading ./ or / so equality works against module names from the- // ModuleGraphPlugin (which emits repo-relative names).+ // module graph plugin (which emits repo-relative names).return p.replace(/^\.\//, '').replace(/^\/+/, '')}@@ -165,7 +171,7 @@ function countStories(modules) {return n}-function affectedStoriesFor(changedFiles, graph) {+export function affectedStoriesFor(changedFiles, graph) {const { byName } = graphconst unresolved = []const start = new Set()@@ -200,11 +206,17 @@ function affectedStoriesFor(changedFiles, graph) {return { affected: [...stories].sort(), unresolved }}+export function unresolvedRuntimeFiles(unresolvedFiles) {+ return unresolvedFiles.filter(+ (file) => STORYBOOK_RELEVANT_FILE_RE.test(normalize(file)) && !NON_RUNTIME_FILE_RE.test(normalize(file))+ )+}+// -----------------------------------------------------------------------------// Entrypoint// ------------------------------------------------------------------------------function main() {+export function main() {const args = parseArgs(process.argv.slice(2))if (!args.graph) {process.stderr.write('Error: --graph is required\n')@@ -254,8 +266,15 @@ function main() {}const { affected, unresolved } = affectedStoriesFor(changed, graph)+ const unresolvedRuntime = unresolvedRuntimeFiles(unresolved)+ if (unresolvedRuntime.length > 0) {+ emitFull(`changed frontend file missing from module graph: ${unresolvedRuntime[0]}`, totalStories)+ return+ }process.stderr.write(`Affected stories: ${affected.length} / ${totalStories} (unresolved: ${unresolved.length})\n`)emitSelective(affected, totalStories, unresolved)}-main()+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {+ main()+}diff --git a/bin/find-affected-stories.test.mjs b/bin/find-affected-stories.test.mjsnew file mode 100644index 000000000000..226fc7372979--- /dev/null+++ b/bin/find-affected-stories.test.mjs@@ -0,0 +1,64 @@+import assert from 'node:assert/strict'+import { describe, test } from 'node:test'++import {+ affectedStoriesFor,+ requiresFullRun,+ unresolvedRuntimeFiles,+} from './find-affected-stories'++describe('find-affected-stories', () => {+ const graph = {+ byName: new Map([+ [+ 'frontend/src/scenes/experiments/experimentLogic.ts',+ {+ name: 'frontend/src/scenes/experiments/experimentLogic.ts',+ reasons: ['frontend/src/scenes/experiments/Experiment.tsx'],+ },+ ],+ [+ 'frontend/src/scenes/experiments/Experiment.tsx',+ {+ name: 'frontend/src/scenes/experiments/Experiment.tsx',+ reasons: ['frontend/src/scenes/experiments/stories/Experiments.stories.tsx'],+ },+ ],+ [+ 'frontend/src/scenes/experiments/stories/Experiments.stories.tsx',+ { name: 'frontend/src/scenes/experiments/stories/Experiments.stories.tsx', reasons: [] },+ ],+ [+ 'frontend/src/scenes/data-warehouse/editor/SqlEditor.stories.tsx',+ { name: 'frontend/src/scenes/data-warehouse/editor/SqlEditor.stories.tsx', reasons: [] },+ ],+ ]),+ }++ test('selects only stories that transitively import a feature-local change', () => {+ const result = affectedStoriesFor(['frontend/src/scenes/experiments/experimentLogic.ts'], graph)++ assert.deepEqual(result.affected, ['frontend/src/scenes/experiments/stories/Experiments.stories.tsx'])+ })++ test('requires a full run for shared frontend library changes', () => {+ assert.match(requiresFullRun('frontend/src/lib/lemon-ui/LemonButton.tsx'), /frontend\/src\/lib\//)+ })++ test('treats unresolved runtime frontend files as unsafe to skip', () => {+ assert.deepEqual(unresolvedRuntimeFiles(['frontend/src/scenes/experiments/newLogic.ts']), [+ 'frontend/src/scenes/experiments/newLogic.ts',+ ])+ })++ test('ignores unresolved backend, test, and README files', () => {+ assert.deepEqual(+ unresolvedRuntimeFiles([+ 'products/experiments/backend/api.py',+ 'frontend/src/scenes/experiments/experimentLogic.test.ts',+ 'frontend/src/scenes/experiments/README.md',+ ]),+ []+ )+ })+})