An open source design system that's fully customizable and agent ready
TypeScript
fix(ci): PR Comment stands down instead of failing when its source run moved on (#7791)
Cindy Zhang141085399a14
diff --git a/.github/scripts/lib/pr-preview.mjs b/.github/scripts/lib/pr-preview.mjsindex b4dbc5416d..1af647a221 100644--- a/.github/scripts/lib/pr-preview.mjs+++ b/.github/scripts/lib/pr-preview.mjs@@ -30,6 +30,37 @@ function refuse(message) {throw new Error(`PR preview refused: ${message}`);}+/**+ * The pull request moved on from the source run: it closed, merged, or got a+ * newer head. That is ordinary churn, not a forged identity. Nothing is+ * published for the old run and the job stays green; the newer head's own run+ * reports.+ */+export class PullRequestMovedOn extends Error {+ constructor(message) {+ super(`PR preview stood down: ${message}`);+ this.name = 'PullRequestMovedOn';+ }+}++function standDown(message) {+ throw new PullRequestMovedOn(message);+}++/**+ * An artifact can come from an earlier attempt of the same run: rerunning only+ * the failed jobs keeps the artifacts of the jobs that passed. A later attempt+ * than the reported one cannot have produced it.+ */+export function attemptBelongsToRun(artifactAttempt, reportedAttempt) {+ const artifact = Number(artifactAttempt);+ return (+ Number.isSafeInteger(artifact) &&+ artifact > 0 &&+ artifact <= Number(reportedAttempt)+ );+}+function positiveInteger(value, name) {const number = Number(value);if (!Number.isSafeInteger(number) || number <= 0) {@@ -83,9 +114,9 @@ function identityFromPullAndRun({pull, run, baseRepository}) {const headRepository = runRepository(run);const headRepositoryId = runRepositoryId(run);- if (pull?.state !== 'open') refuse('pull request is not open');+ if (pull?.state !== 'open') standDown('pull request is not open');if (pull?.head?.sha !== headSha)- refuse('pull request head does not match source run');+ standDown('pull request head does not match source run');if (pull?.head?.ref !== headRef)refuse('pull request branch does not match source run');if (pull?.head?.repo?.full_name !== headRepository) {@@ -98,21 +129,12 @@ function identityFromPullAndRun({pull, run, baseRepository}) {refuse('pull request targets another repository');}- const sourcePull = run.pull_requests?.find(- candidate =>- Number(candidate.number) === Number(pull.number) &&- candidate.head?.sha === headSha,- );- // The source run records the tested base. Live main may have advanced by the- // time its report is published; that is not a new CI attempt. Fork runs may- // omit this association, so absence is explicit rather than replaced by main.- const testedBaseSha = sourcePull?.base?.sha- ? fullSha(sourcePull.base.sha, 'source pull request base')- : null;-+ // The run's `pull_requests` association is not a record of the tested base:+ // GitHub reports the pull request's live base and head there, so it moves+ // with main. No trusted field records the tested base; the visual report+ // carries the base its own CI run tested.return {prNumber: positiveInteger(pull.number, 'pull request number'),- testedBaseSha,headSha,headRef,headRepository,@@ -126,18 +148,24 @@ function identityFromPullAndRun({pull, run, baseRepository}) {};}-function sameIdentity(actual, expected) {- for (const key of [- 'prNumber',- 'headSha',- 'headRef',- 'headRepository',- 'headRepositoryId',- 'baseRepository',- 'sourceRunId',- 'sourceRunAttempt',- 'sourceConclusion',- ]) {+const RUN_IDENTITY_KEYS = [+ 'headSha',+ 'headRef',+ 'headRepository',+ 'headRepositoryId',+ 'sourceRunId',+ 'sourceRunAttempt',+ 'sourceConclusion',+];++const SOURCE_IDENTITY_KEYS = [+ 'prNumber',+ 'baseRepository',+ ...RUN_IDENTITY_KEYS,+];++function sameIdentity(actual, expected, keys = SOURCE_IDENTITY_KEYS) {+ for (const key of keys) {if (String(actual[key]) !== String(expected[key])) {refuse(`${key} does not match the trusted source identity`);}@@ -251,6 +279,22 @@ export async function confirmSourceRunIdentity({readRun,github.rest.pulls.get({owner, repo, pull_number: prNumber}),]);+ // Compare the run with the trusted event before looking at the pull request.+ // A run's own identity never changes, so a mismatch there refuses even when+ // the pull request has also moved on.+ sameIdentity(+ {+ headSha: run?.head_sha,+ headRef: run?.head_branch,+ headRepository: run?.head_repository?.full_name,+ headRepositoryId: run?.head_repository?.id,+ sourceRunId: run?.id,+ sourceRunAttempt: run?.run_attempt,+ sourceConclusion: run?.conclusion ?? '',+ },+ expected,+ RUN_IDENTITY_KEYS,+ );const actual = identityFromPullAndRun({pull,run,@@ -260,6 +304,26 @@ export async function confirmSourceRunIdentity({return actual;}+/**+ * The confirmed identity, or null when the pull request moved on from the+ * source run. Any other mismatch still refuses.+ */+export async function confirmOrStandDown({+ github,+ owner,+ repo,+ expected,+ core,+}) {+ try {+ return await confirmSourceRunIdentity({github, owner, repo, expected});+ } catch (error) {+ if (!(error instanceof PullRequestMovedOn)) throw error;+ core.info(`${error.message}; nothing to publish for this run.`);+ return null;+ }+}+/*** The run's latest attempt number, or null when the client cannot say. A* report for an earlier attempt must not replace the latest attempt's: that@@ -319,7 +383,7 @@ export function validateAnalysisMetadata(metadata, identity) {}if (metadata?.runAttempt !== undefined &&- String(metadata.runAttempt) !== String(identity.sourceRunAttempt)+ !attemptBelongsToRun(metadata.runAttempt, identity.sourceRunAttempt)) {refuse('analysis source run attempt does not match');}@@ -409,12 +473,16 @@ export async function reconcilePrComment({execute = execFileSync,}) {const {owner, repo} = context.repo;- const identity = await confirmSourceRunIdentity({+ const identity = await confirmOrStandDown({github,owner,repo,expected: expectedIdentity,+ core,});+ if (identity === null) {+ return {action: 'none', body: null, identity: null};+ }if (await supersededByNewerAttempt({github, owner, repo, identity, core})) {return {action: 'none', body: null, identity};}@@ -522,12 +590,17 @@ export async function reconcilePrComment({// the reported attempt's identity again, and stand down if a newer attempt// of the run has started since: an earlier attempt's report must not replace// the latest attempt's.- await confirmSourceRunIdentity({- github,- owner,- repo,- expected: expectedIdentity,- });+ if (+ (await confirmOrStandDown({+ github,+ owner,+ repo,+ expected: expectedIdentity,+ core,+ })) === null+ ) {+ return {action: 'none', body: null, identity};+ }if (await supersededByNewerAttempt({github, owner, repo, identity, core})) {return {action: 'none', body: null, identity};}diff --git a/.github/scripts/lib/pr-preview.test.mjs b/.github/scripts/lib/pr-preview.test.mjsindex dc6100023f..994777a2c2 100644--- a/.github/scripts/lib/pr-preview.test.mjs+++ b/.github/scripts/lib/pr-preview.test.mjs@@ -9,6 +9,7 @@ import {afterEach, describe, expect, it, vi} from 'vitest';import yaml from 'yaml';import {+ confirmOrStandDown,confirmSourceRunIdentity,PR_ANALYSIS_MARKER,reconcileEarlyPreviewComment,@@ -33,6 +34,13 @@ const EXECUTABLE_RESOLVE_SCRIPT = RESOLVE_SCRIPT.replace(/const \{pathToFileURL\} = require\('node:url'\);\nconst \{resolveWorkflowRunPullRequest\} = await import\([\s\S]*?\n\);/,'const resolveWorkflowRunPullRequest = injectedResolve;',);+const RECONFIRM_SCRIPT = PR_COMMENT_WORKFLOW.jobs.comment.steps.find(+ step => step.name === 'Reconfirm trusted PR identity',+).with.script;+const EXECUTABLE_RECONFIRM_SCRIPT = RECONFIRM_SCRIPT.replace(+ /const \{pathToFileURL\} = require\('node:url'\);\nconst \{confirmOrStandDown\} = await import\([\s\S]*?\n\);/,+ 'const confirmOrStandDown = injectedConfirm;',+);const roots = [];function identity(overrides = {}) {@@ -44,7 +52,6 @@ function identity(overrides = {}) {headRepositoryId: '321',baseRepository: 'facebook/astryx',baseSha: BASE,- testedBaseSha: null,sourceRunId: 33321033727,sourceRunAttempt: 1,sourceConclusion: 'success',@@ -236,13 +243,20 @@ afterEach(() => {});describe('trusted PR preview identity', () => {- it('keeps the source-run base when main advances before publication', async () => {- const current = identity({baseSha: 'f'.repeat(40)});+ it('does not treat the live pull-request base on the run as the tested base', async () => {+ // GitHub reports the pull request's live base on `run.pull_requests`, so+ // after main advances it names a base the run never tested. Checking the+ // visual report against it rejected correct reports.+ const current = identity();const {github} = githubFixture({value: current});const run = {...sourceRun(current),pull_requests: [- {number: current.prNumber, head: {sha: HEAD}, base: {sha: BASE}},+ {+ number: current.prNumber,+ head: {sha: HEAD},+ base: {sha: 'c'.repeat(40)},+ },],};const resolved = await resolveWorkflowRunPullRequest({@@ -251,25 +265,12 @@ describe('trusted PR preview identity', () => {repo: 'astryx',run,});- expect(resolved.testedBaseSha).toBe(BASE);- expect(resolved.baseSha).toBe(current.baseSha);+ expect(resolved).not.toHaveProperty('testedBaseSha');const prepare = PR_COMMENT_WORKFLOW.jobs.comment.steps.find(step => step.name === 'Prepare canonical visual report',);- expect(prepare.env.BASE_SHA).toBe(- '${{ steps.identity.outputs.tested_base_sha }}',- );- });-- it('does not substitute live main when a fork run omits the base association', async () => {- const {github} = githubFixture();- const resolved = await resolveWorkflowRunPullRequest({- github,- owner: 'facebook',- repo: 'astryx',- run: sourceRun(),- });- expect(resolved.testedBaseSha).toBeNull();+ expect(prepare.env).not.toHaveProperty('BASE_SHA');+ expect(prepare.run).not.toContain('--base-sha');});it('resolves a fork run through the trusted owner and branch fallback', async () => {@@ -376,6 +377,96 @@ describe('trusted PR preview identity', () => {expect(github.paginate).not.toHaveBeenCalled();});+ it.each([+ ['closed', {state: 'closed'}],+ ['pushed to a newer head', {head: {sha: 'e'.repeat(40)}}],+ ])(+ 'skips the comment job without failing when the pull request is %s before it runs',+ async (_label, change) => {+ const value = identity();+ const {github} = githubFixture({value});+ const moved = pull(value);+ Object.assign(moved, change, {+ head: {...moved.head, ...change.head},+ });+ github.rest.pulls.get.mockResolvedValue({data: moved});+ const core = {info: vi.fn(), setOutput: vi.fn()};+ const previousEnv = {...process.env};+ Object.assign(process.env, {+ GITHUB_WORKSPACE: ROOT,+ PR_NUMBER: String(value.prNumber),+ HEAD_SHA: value.headSha,+ HEAD_REPOSITORY: value.headRepository,+ HEAD_REPOSITORY_ID: value.headRepositoryId,+ HEAD_REF: value.headRef,+ BASE_REPOSITORY: value.baseRepository,+ SOURCE_RUN_ID: String(value.sourceRunId),+ SOURCE_RUN_ATTEMPT: String(value.sourceRunAttempt),+ SOURCE_CONCLUSION: value.sourceConclusion,+ });++ try {+ await new ASYNC_FUNCTION(+ 'require',+ 'context',+ 'github',+ 'core',+ 'injectedConfirm',+ EXECUTABLE_RECONFIRM_SCRIPT,+ )(+ REQUIRE,+ {repo: {owner: 'facebook', repo: 'astryx'}},+ github,+ core,+ confirmOrStandDown,+ );+ } finally {+ process.env = previousEnv;+ }++ expect(EXECUTABLE_RECONFIRM_SCRIPT).not.toBe(RECONFIRM_SCRIPT);+ expect(core.setOutput).toHaveBeenCalledWith('valid', 'false');+ expect(core.setOutput).not.toHaveBeenCalledWith('valid', 'true');+ expect(core.info).toHaveBeenCalledWith(+ expect.stringContaining('nothing to publish'),+ );+ },+ );++ it('still fails the comment job when the run itself no longer matches', async () => {+ // A run's head never changes. A mismatch there is not churn.+ await expect(+ confirmOrStandDown({+ github: githubFixture({value: identity({headSha: 'f'.repeat(40)})})+ .github,+ core: {info: vi.fn()},+ owner: 'facebook',+ repo: 'astryx',+ expected: identity(),+ }),+ ).rejects.toThrow(/headSha does not match/);+ });++ it('fails rather than stands down when the run differs and the pull request also moved', async () => {+ const value = identity();+ const {github} = githubFixture({value});+ github.rest.actions.getWorkflowRun.mockResolvedValue({+ data: sourceRun(identity({headSha: 'f'.repeat(40)})),+ });+ github.rest.pulls.get.mockResolvedValue({+ data: pull(identity({headSha: 'e'.repeat(40)})),+ });+ await expect(+ confirmOrStandDown({+ github,+ core: {info: vi.fn()},+ owner: 'facebook',+ repo: 'astryx',+ expected: value,+ }),+ ).rejects.toThrow(/headSha does not match/);+ });+it('keeps every write-capable job behind the valid identity output', () => {const writeCapableJobs = Object.entries(PR_COMMENT_WORKFLOW.jobs).filter(([, job]) =>@@ -552,6 +643,28 @@ describe('analysis metadata compatibility', () => {).toThrow(error);});+ it('accepts analysis from an earlier attempt of the same run, never a later one', () => {+ // Rerunning only the failed jobs keeps the passing build job's artifact,+ // so attempt 3 reports with analysis written by attempt 1.+ const value = identity({sourceRunAttempt: 3});+ const metadata = runAttempt => ({+ prNumber: value.prNumber,+ shortHash: value.headSha.slice(0, 7),+ headSha: value.headSha,+ headRepository: value.headRepository,+ baseRepository: value.baseRepository,+ runId: value.sourceRunId,+ runAttempt,+ });+ expect(validateAnalysisMetadata(metadata('1'), value)).toBeDefined();+ expect(validateAnalysisMetadata(metadata('3'), value)).toBeDefined();+ for (const attempt of ['4', '0', 'x']) {+ expect(() => validateAnalysisMetadata(metadata(attempt), value)).toThrow(+ /attempt does not match/,+ );+ }+ });+it('does not ignore mismatched exact identity fields when they are present', () => {const value = identity();expect(() =>@@ -799,31 +912,34 @@ describe('PR comment preview reconciliation', () => {expect(state.listedIssues).toHaveLength(0);});- it('refuses a head push that happens during Vercel readiness before writing a comment', async () => {+ it('stands down without writing when the head moves during Vercel readiness', async () => {const expected = identity();const current = identity({headSha: 'f'.repeat(40)});const paths = fixture(expected);const {github, state} = githubFixture({value: expected});- await expect(- reconcilePrComment({- github,- core: {info: vi.fn(), warning: vi.fn()},- context: {- repo: {owner: 'facebook', repo: 'astryx'},- serverUrl: 'https://github.com',- },- expectedIdentity: expected,- analysisPath: paths.analysis,- metadataPath: paths.metadata,- a11yPath: paths.a11y,- visualPath: paths.visual,- lookupPreview: async () => {- github.rest.pulls.get.mockResolvedValue({data: pull(current)});- return VERCEL_ORIGIN;- },- probePreview: async () => true,- }),- ).rejects.toThrow(/head does not match source run/);+ const core = {info: vi.fn(), warning: vi.fn()};+ const result = await reconcilePrComment({+ github,+ core,+ context: {+ repo: {owner: 'facebook', repo: 'astryx'},+ serverUrl: 'https://github.com',+ },+ expectedIdentity: expected,+ analysisPath: paths.analysis,+ metadataPath: paths.metadata,+ a11yPath: paths.a11y,+ visualPath: paths.visual,+ lookupPreview: async () => {+ github.rest.pulls.get.mockResolvedValue({data: pull(current)});+ return VERCEL_ORIGIN;+ },+ probePreview: async () => true,+ });+ expect(result.action).toBe('none');+ expect(core.info).toHaveBeenCalledWith(+ expect.stringContaining('head does not match source run'),+ );expect(state.created).toHaveLength(0);expect(state.updated).toHaveLength(0);});diff --git a/.github/scripts/visual-gate/README.md b/.github/scripts/visual-gate/README.mdindex 50e65367e9..899daa51bd 100644--- a/.github/scripts/visual-gate/README.md+++ b/.github/scripts/visual-gate/README.md@@ -71,7 +71,9 @@ keys requires explicit full-plan baseline maintenance.- `skipped`: no comparison was performed; the reason is explicit. It does notimply a separate workflow covered the change.-The `visual-pr-report` artifact belongs to the exact CI run and attempt.+The `visual-pr-report` artifact belongs to the exact CI run. A rerun of only+the failed jobs keeps the artifacts of the jobs that passed, so the report can+come from an earlier attempt of that run, never a later one.`pr-comment.yml` only publishes its report: it checks identity, bounds JSON andimage sizes, re-encodes PNGs, and renders escaped HTML from default-branch code.It does not execute artifact HTML, run a browser, compare pixels again, changediff --git a/.github/scripts/visual-gate/publish-pr-report.mjs b/.github/scripts/visual-gate/publish-pr-report.mjsindex cf74c547c2..ec2676a4d9 100644--- a/.github/scripts/visual-gate/publish-pr-report.mjs+++ b/.github/scripts/visual-gate/publish-pr-report.mjs@@ -23,6 +23,18 @@ function refuse(message) {throw new Error(`visual report rejected: ${message}`);}+// Rerunning only the failed jobs keeps the artifacts of the jobs that passed,+// so the report can come from an earlier attempt of the same run, never a+// later one.+function attemptBelongsToRun(artifactAttempt, reportedAttempt) {+ const artifact = Number(artifactAttempt);+ return (+ Number.isSafeInteger(artifact) &&+ artifact > 0 &&+ artifact <= Number(reportedAttempt)+ );+}+function text(value = '') {if (typeof value !== 'string' || value.length > 4000)refuse('invalid report text');@@ -126,7 +138,7 @@ export function publishPrReport({!SHA.test(raw.context?.baseSha) ||(baseSha && raw.context.baseSha !== baseSha) ||String(raw.context?.runId) !== String(runId) ||- String(raw.context?.runAttempt) !== String(runAttempt) ||+ !attemptBelongsToRun(raw.context?.runAttempt, runAttempt) ||!SHA.test(raw.context?.sha)) {refuse('artifact does not match the exact CI head/base/run/attempt');@@ -158,11 +170,13 @@ export function publishPrReport({context: {sha: raw.context.sha,headSha,- // Fork runs can omit GitHub's PR/base association. That base remains- // report data, never acceptance or baseline-write authority.+ // Without a caller-supplied base, this is the base the CI run recorded.+ // It is report data, never acceptance or baseline-write authority.baseSha: baseSha || raw.context.baseSha,runId: String(runId),- runAttempt: String(runAttempt),+ // The attempt that produced this evidence, which can precede the+ // reported attempt after a rerun of only the failed jobs.+ runAttempt: String(raw.context.runAttempt),},baseline: {sha: text(raw.baseline?.sha ?? '')},counts,@@ -221,7 +235,10 @@ export function publishPrReport({if (process.argv[1] === fileURLToPath(import.meta.url)) {const args = process.argv.slice(2);- const flag = name => args[args.indexOf(`--${name}`) + 1];+ const flag = name => {+ const index = args.indexOf(`--${name}`);+ return index === -1 ? undefined : args[index + 1];+ };publishPrReport({input: path.resolve(flag('input')),output: path.resolve(flag('output')),diff --git a/.github/scripts/visual-gate/publish-pr-report.test.mjs b/.github/scripts/visual-gate/publish-pr-report.test.mjsindex 8a2ab525a0..74389791af 100644--- a/.github/scripts/visual-gate/publish-pr-report.test.mjs+++ b/.github/scripts/visual-gate/publish-pr-report.test.mjs@@ -132,6 +132,16 @@ describe('canonical visual report publication', () => {]);});+ it('accepts a report from an earlier attempt of the same run, never a later one', () => {+ // Rerunning only the failed jobs keeps the passing visual job's artifact.+ verdict.context.runAttempt = '1';+ json();+ expect(run({runAttempt: '2'}).context.runAttempt).toBe('1');+ verdict.context.runAttempt = '3';+ json();+ expect(() => run({runAttempt: '2'})).toThrow('exact CI');+ });+it.each(['headSha', 'baseSha', 'runId', 'runAttempt'])('refuses stale or forged %s',field => {diff --git a/.github/scripts/visual-gate/workflow-concurrency.test.mjs b/.github/scripts/visual-gate/workflow-concurrency.test.mjsindex 29b0e49867..ee654b4d78 100644--- a/.github/scripts/visual-gate/workflow-concurrency.test.mjs+++ b/.github/scripts/visual-gate/workflow-concurrency.test.mjs@@ -33,7 +33,7 @@ describe('PR report and deployment workflow contracts', () => {expect(value).toContain('name: visual-pr-report');expect(value).toContain('run-id: ${{ steps.identity.outputs.run_id }}');expect(value).toContain('--head-sha "$HEAD_SHA"');- expect(value).toContain('--base-sha "$BASE_SHA"');+ expect(value).not.toContain('--base-sha');expect(value).toContain('--run-attempt "$RUN_ATTEMPT"');expect(value).toContain('publish-pr-report.mjs');expect(value).toContain('types: [completed]');diff --git a/.github/workflows/pr-comment.yml b/.github/workflows/pr-comment.ymlindex 53cc63803a..7a74d44955 100644--- a/.github/workflows/pr-comment.yml+++ b/.github/workflows/pr-comment.yml@@ -97,7 +97,6 @@ jobs:core.setOutput('head_repo_id', identity.headRepositoryId);core.setOutput('head_ref', identity.headRef);core.setOutput('base_repo', identity.baseRepository);- core.setOutput('tested_base_sha', identity.testedBaseSha ?? '');core.setOutput('base_sha', identity.baseSha);core.setOutput('run_id', String(identity.sourceRunId));core.setOutput('run_attempt', String(identity.sourceRunAttempt));@@ -315,11 +314,12 @@ jobs:retries: 3script: |const {pathToFileURL} = require('node:url');- const {confirmSourceRunIdentity} = await import(+ const {confirmOrStandDown} = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/.github/scripts/lib/pr-preview.mjs`).href);- const identity = await confirmSourceRunIdentity({+ const identity = await confirmOrStandDown({github,+ core,...context.repo,expected: {prNumber: Number(process.env.PR_NUMBER),@@ -333,6 +333,10 @@ jobs:sourceConclusion: process.env.SOURCE_CONCLUSION,},});+ if (identity === null) {+ core.setOutput('valid', 'false');+ return;+ }core.setOutput('valid', 'true');core.setOutput('pr_number', String(identity.prNumber));core.setOutput('head_sha', identity.headSha);@@ -340,7 +344,6 @@ jobs:core.setOutput('head_repo_id', identity.headRepositoryId);core.setOutput('head_ref', identity.headRef);core.setOutput('base_repo', identity.baseRepository);- core.setOutput('tested_base_sha', identity.testedBaseSha ?? '');core.setOutput('base_sha', identity.baseSha);core.setOutput('run_id', String(identity.sourceRunId));core.setOutput('run_attempt', String(identity.sourceRunAttempt));@@ -407,7 +410,6 @@ jobs:if: steps.identity.outputs.valid == 'true' && steps.visual-download.outcome == 'success'env:HEAD_SHA: ${{ steps.identity.outputs.head_sha }}- BASE_SHA: ${{ steps.identity.outputs.tested_base_sha }}RUN_ID: ${{ steps.identity.outputs.run_id }}RUN_ATTEMPT: ${{ steps.identity.outputs.run_attempt }}run: |@@ -415,7 +417,6 @@ jobs:--input visual-pr-report \--output trusted-visual \--head-sha "$HEAD_SHA" \- --base-sha "$BASE_SHA" \--run-id "$RUN_ID" \--run-attempt "$RUN_ATTEMPT"