diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index fe853c3195f5..4da8714b1e43 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -313,7 +313,7 @@ jobs: job_size_check: name: Size Check needs: [job_get_metadata, job_get_test_matrix] - timeout-minutes: 15 + timeout-minutes: 25 runs-on: ubuntu-24.04-arm if: github.event_name == 'pull_request' || needs.job_get_metadata.outputs.is_base_branch == 'true' || diff --git a/dev-packages/size-limit-gh-action/index.mjs b/dev-packages/size-limit-gh-action/index.mjs index 8331e61e6b15..37be8cc76d46 100644 --- a/dev-packages/size-limit-gh-action/index.mjs +++ b/dev-packages/size-limit-gh-action/index.mjs @@ -7,7 +7,7 @@ import { getExecOutput } from '@actions/exec'; import { context, getOctokit } from '@actions/github'; import { markdownTable } from 'markdown-table'; import sizeConfig from '../../.size-limit.js'; -import { getArtifactForBranch } from './utils/artifacts.mjs'; +import { getArtifactForBranch, getArtifactForCommit, waitForSizeCheck } from './utils/artifacts.mjs'; import { formatResults, getSizeIncreases, MAX_INCREASE_BYTES, parseResults } from './utils/results.mjs'; const OVERRIDE_LABEL = 'Accept Bundlesize Increase'; @@ -16,6 +16,7 @@ const SIZE_LIMIT_HEADING = '## size-limit report 📦 '; const ARTIFACT_NAME = 'size-limit-action'; const ACTION_DIRECTORY = path.dirname(fileURLToPath(import.meta.url)); const RESULTS_FILE_PATH = path.join(ACTION_DIRECTORY, 'size-limit-results.json'); +const BASE_PR_WAIT_MS = 10 * 60_000; const WORKFLOW_FILE = path.basename(process.env.GITHUB_WORKFLOW_REF.split('@')[0]); const REPO_URL = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}`; @@ -40,20 +41,23 @@ async function run() { const { stdout } = await getExecOutput('pnpm', ['exec', 'size-limit', '--json']); const current = parseResults(stdout); + // PRs store their results too, so PRs stacked on top of them can use them as their baseline + await uploadResults(current, { required: !comparisonBranch }); + if (!comparisonBranch) { - await uploadResults(current); return; } const mergedBaseSha = await getMergedBaseSha(octokit); - const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch }); + const basePr = mergedBaseSha && (await findBasePr(octokit, mergedBaseSha, pr)); + const baseline = await downloadBaseline(octokit, githubToken, { comparisonBranch, basePr }); const hasIncrease = baseline ? getSizeIncreases(baseline.results, current, sizeConfig).length > 0 : false; const bodyParts = [SIZE_LIMIT_HEADING]; let failure; if (baseline) { - bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }))); + bodyParts.push(...(await describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch, basePr }))); } if (pr.head.ref.startsWith(RELEASE_BRANCH_PREFIX)) { @@ -80,9 +84,21 @@ async function run() { } } -async function uploadResults(results) { - await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify(results), 'utf8'); - await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY); +/** + * `sha` is the commit that was measured. On PRs, that is the merge commit GitHub checks out (`refs/pull//merge`), + * not the PR's head commit. Only `required` results fail the run when the upload fails, i.e. on develop where they are + * the baseline for PRs. + */ +async function uploadResults(results, { required }) { + try { + await fs.writeFile(RESULTS_FILE_PATH, JSON.stringify({ sha: context.sha, results }), 'utf8'); + await artifactClient.uploadArtifact(ARTIFACT_NAME, [RESULTS_FILE_PATH], ACTION_DIRECTORY); + } catch (error) { + if (required) { + throw error; + } + core.warning(`Unable to upload size-limit results: ${error.message}`); + } } /** @@ -99,13 +115,65 @@ async function getMergedBaseSha(octokit) { } } -async function downloadBaseline(octokit, githubToken, { comparisonBranch }) { +/** + * Find the open PR this PR is stacked on, and the commit of it that this PR was tested on. With GitHub stacks, a PR is + * tested on top of its base PR's test merge, whose second parent is the base PR's head. With a plain base branch, the + * merge base is the base PR's head itself. Re-runs keep their original test merge, so the base PR may have moved on + * since. Open PRs that contain this PR's head are this PR itself or stacked on top of it. + * + * The baseline is looked up by the returned commit, so a wrong guess between sibling PRs stacked on the same base only + * affects the PR number in the report. Base PRs are usually opened before the PRs stacked on them. + */ +async function findBasePr(octokit, mergedBaseSha, pr) { try { - const found = await getArtifactForBranch(octokit, { - workflow: WORKFLOW_FILE, - branch: comparisonBranch, - artifactName: ARTIFACT_NAME, - }); + const { data } = await octokit.rest.repos.getCommit({ ...context.repo, ref: mergedBaseSha }); + const candidates = [mergedBaseSha, ...data.parents.slice(1).map(({ sha }) => sha)]; + const prsAbove = new Set((await listOpenPrsWithCommit(octokit, pr.head.sha)).map(({ number }) => number)); + + for (const sha of candidates) { + const prs = (await listOpenPrsWithCommit(octokit, sha)).filter(({ number }) => !prsAbove.has(number)); + const basePr = + prs.find(({ head }) => head.sha === sha) ?? + prs + .filter(({ head, base }) => head.ref === pr.base.ref || base.ref === pr.base.ref) + .sort((a, b) => a.number - b.number)[0]; + if (basePr) { + return { number: basePr.number, sha }; + } + } + } catch (error) { + core.warning(`Unable to check whether this PR is stacked: ${error.message}`); + } + + return undefined; +} + +async function listOpenPrsWithCommit(octokit, sha) { + const { data } = await octokit.rest.repos.listPullRequestsAssociatedWithCommit({ ...context.repo, commit_sha: sha }); + return data.filter( + pr => pr.state === 'open' && pr.head.repo?.full_name === `${context.repo.owner}/${context.repo.repo}`, + ); +} + +/** + * A stacked PR compares only against its base PR's results, because the comparison branch would also count the base + * PR's changes. The base PR's Size Check usually runs at the same time as ours, so we wait for it. + */ +async function downloadBaseline(octokit, githubToken, { comparisonBranch, basePr }) { + try { + let found; + if (basePr) { + core.info(`Waiting for the results of base PR #${basePr.number}`); + const { sha } = basePr; + await waitForSizeCheck(octokit, { workflow: WORKFLOW_FILE, sha, timeoutMs: BASE_PR_WAIT_MS }); + found = await getArtifactForCommit(octokit, { workflow: WORKFLOW_FILE, sha, artifactName: ARTIFACT_NAME }); + } else { + found = await getArtifactForBranch(octokit, { + workflow: WORKFLOW_FILE, + branch: comparisonBranch, + artifactName: ARTIFACT_NAME, + }); + } if (!found) { throw new Error('No artifacts found'); @@ -121,9 +189,11 @@ async function downloadBaseline(octokit, githubToken, { comparisonBranch }) { }, }); + const data = JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8')); + // Older artifacts store only the results, measured on the run's head commit return { - results: JSON.parse(await fs.readFile(RESULTS_FILE_PATH, 'utf8')), - sha: found.workflowRun.head_sha, + results: data.results ?? data, + sha: data.sha ?? found.workflowRun.head_sha, workflowRun: found.workflowRun, }; } catch (error) { @@ -135,43 +205,42 @@ async function downloadBaseline(octokit, githubToken, { comparisonBranch }) { /** * Report which commits were compared, and whether the baseline contains exactly what this PR was tested against. */ -async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch }) { +async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBranch, basePr }) { const unverified = '⚠️ Unable to verify whether the baseline matches the PR build.'; if (!mergedBaseSha) { return [unverified]; } const { sha, workflowRun } = baseline; + const base = basePr ? `base PR #${basePr.number}` : comparisonBranch; const parts = [ - `Compared: ${commitLink(context.sha)} (PR test merge using ${comparisonBranch} at ${commitLink(mergedBaseSha)})`, - `Against: ${commitLink(sha)} (${comparisonBranch}) · [base run #${workflowRun.run_number}](${workflowRun.html_url})`, + `Compared: ${commitLink(context.sha)} (PR test merge using ${base} at ${commitLink(mergedBaseSha)})`, + `Against: ${commitLink(sha)} (${base}) · [base run #${workflowRun.run_number}](${workflowRun.html_url})`, ]; - if (sha === mergedBaseSha) { - parts.push("✅ Baseline matches: this diff contains only this PR's changes."); - return parts; - } - try { + if (sha === mergedBaseSha || (await haveSameTree(octokit, sha, mergedBaseSha))) { + parts.push("✅ Baseline matches: this diff contains only this PR's changes."); + return parts; + } + const { data: comparison } = await octokit.rest.repos.compareCommitsWithBasehead({ ...context.repo, basehead: `${sha}...${mergedBaseSha}`, }); const differences = []; if (comparison.ahead_by > 0) { - differences.push( - `${comparison.ahead_by} ${comparisonBranch} commit(s) in the PR build are missing from the baseline`, - ); + differences.push(`${comparison.ahead_by} commit(s) in the PR build are missing from the baseline`); } if (comparison.behind_by > 0) { - differences.push( - `${comparison.behind_by} ${comparisonBranch} commit(s) in the baseline are missing from the PR build`, - ); + differences.push(`${comparison.behind_by} commit(s) in the baseline are missing from the PR build`); } const guidance = comparison.behind_by > 0 - ? `Rebase your PR onto the latest ${comparisonBranch} to compare against an up-to-date baseline.` - : `Re-run once ${comparisonBranch}'s baseline build for ${commitLink(mergedBaseSha)} finishes.`; + ? basePr + ? `Update this PR and ${base} with their base branches to compare against an up-to-date baseline.` + : `Rebase your PR onto the latest ${base} to compare against an up-to-date baseline.` + : `Re-run once the baseline build for ${commitLink(mergedBaseSha)} finishes.`; parts.push( `⚠️ Baseline mismatch: ${differences.join('; ')}. Their size changes also affect this comparison. ` + `[Compare commits](${comparison.html_url}). ${guidance}`, @@ -184,6 +253,18 @@ async function describeBaseline(octokit, { baseline, mergedBaseSha, comparisonBr return parts; } +/** + * A base PR is measured on its own test merge commit. With a plain base branch, that commit differs from the one this + * PR was tested against, but has the same tree when the base branch is up to date with develop. + */ +async function haveSameTree(octokit, shaA, shaB) { + const [{ data: a }, { data: b }] = await Promise.all([ + octokit.rest.repos.getCommit({ ...context.repo, ref: shaA }), + octokit.rest.repos.getCommit({ ...context.repo, ref: shaB }), + ]); + return a.commit.tree.sha === b.commit.tree.sha; +} + async function hasLabel(octokit, pr, label) { const { data } = await octokit.rest.pulls.get({ ...context.repo, pull_number: pr.number }); return data.labels.some(({ name }) => name === label); diff --git a/dev-packages/size-limit-gh-action/utils/artifacts.mjs b/dev-packages/size-limit-gh-action/utils/artifacts.mjs index 0dbe1ee48178..84f857959645 100644 --- a/dev-packages/size-limit-gh-action/utils/artifacts.mjs +++ b/dev-packages/size-limit-gh-action/utils/artifacts.mjs @@ -2,6 +2,8 @@ import * as core from '@actions/core'; import { context } from '@actions/github'; const MAX_COMMITS = 50; +const SIZE_CHECK_JOB_NAME = 'Size Check'; +const POLL_INTERVAL_MS = 30_000; /** * Find the newest `artifactName` artifact on `branch`. This walks the branch's commits, because listing workflow runs by @@ -28,7 +30,7 @@ export async function getArtifactForBranch(octokit, { workflow, branch, artifact return null; } -async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) { +export async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) { for (const workflowRun of await listRunsForCommit(octokit, { workflow, sha })) { const { data } = await octokit.rest.actions.listWorkflowRunArtifacts({ ...context.repo, run_id: workflowRun.id }); const artifact = data.artifacts.find(({ name }) => name === artifactName); @@ -41,6 +43,32 @@ async function getArtifactForCommit(octokit, { workflow, sha, artifactName }) { return null; } +export async function waitForSizeCheck(octokit, { workflow, sha, timeoutMs }) { + const deadline = Date.now() + timeoutMs; + + while (Date.now() < deadline) { + const jobs = []; + for (const { id } of await listRunsForCommit(octokit, { workflow, sha })) { + const { data } = await octokit.rest.actions.listJobsForWorkflowRun({ + ...context.repo, + run_id: id, + filter: 'latest', + per_page: 100, + }); + jobs.push(...data.jobs.filter(({ name }) => name === SIZE_CHECK_JOB_NAME)); + } + + if (jobs.length > 0 && jobs.every(({ status }) => status === 'completed')) { + return; + } + + core.info(`Waiting for the ${SIZE_CHECK_JOB_NAME} job of commit ${sha}...`); + await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS)); + } + + core.warning(`Timed out waiting for the ${SIZE_CHECK_JOB_NAME} job of commit ${sha}.`); +} + /** * Newest first. Runs from forks are never trusted. */