From 6d3b70776806ccf3f5e651f348f0213721e83be0 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:27:28 -0500 Subject: [PATCH] perf(ci): add 4th server test shard and skip duplicate push CI after merge queue After PR #1078 rebalanced shards and skipped unnecessary apt installs, Server Test (5.5 to 6.2 min) remained the only job above 4.3 minutes, and every merged PR still ran full CI a third time on push to main (wasting ~35 runner-minutes per merge and allowing post-merge flakes to block nightlies). Added a 4th server_test shard (and updated DEFAULT_REQUIRED_CHECKS in scripts/verify-release-ci.ts), added a push-only precheck job that skips duplicate main runs when a green main merge_group run already verified all required checks on the exact SHA (while warming the main pnpm cache if pnpm-lock.yaml changed and failing open to full CI on errors or direct pushes), updated verify-release-ci.ts to query filter=all and treat skipped runs as non-verdicts while ordering queued runs properly, and updated update-test-shard-weights.ts to sample landed merge_group runs. --- .github/workflows/ci.yml | 132 +++++++++++++++++++++++++-- scripts/update-test-shard-weights.ts | 95 +++++++++++++++---- scripts/verify-release-ci.test.ts | 68 ++++++++++++++ scripts/verify-release-ci.ts | 54 ++++++++--- 4 files changed, 308 insertions(+), 41 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c194ef65f..3ccc40a7f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -17,6 +17,7 @@ on: type: boolean permissions: + checks: read contents: read concurrency: @@ -24,9 +25,110 @@ concurrency: cancel-in-progress: true jobs: + # On pushes to main, check whether a green merge_group run of this workflow + # targeting main already verified every required job on this exact commit. + # Skipped immediately on pull_request, merge_group, and workflow_dispatch with + # no runner startup cost. Fails open: if precheck errors or skips, full CI + # still runs. Keep the required job list in step with DEFAULT_REQUIRED_CHECKS + # in scripts/verify-release-ci.ts. + precheck: + name: Check if commit already passed CI + if: github.event_name == 'push' + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + skip_ci: ${{ steps.check.outputs.skip_ci }} + warm_cache: ${{ steps.check.outputs.warm_cache }} + steps: + - id: check + name: Check prior merge_group verdict on this commit + env: + GH_TOKEN: ${{ github.token }} + BEFORE: ${{ github.event.before }} + run: | + set -euo pipefail + required_json='[ + "Checks and Build", + "Unit Test", + "Server Test (1/4)", + "Server Test (2/4)", + "Server Test (3/4)", + "Server Test (4/4)", + "Browser Test (1/2)", + "Browser Test (2/2)", + "Release Smoke" + ]' + + # Find the newest successful merge_group run of ci.yml for main on this exact SHA. + merge_run_id="$( + gh api "repos/${GITHUB_REPOSITORY}/actions/workflows/ci.yml/runs?event=merge_group&head_sha=${GITHUB_SHA}&status=success&per_page=20" \ + --jq '[.workflow_runs[] | select(.conclusion == "success" and (.head_branch | startswith("gh-readonly-queue/main/")))] | sort_by(.run_started_at // .created_at) | last | .id // empty' + )" + + already_passed="false" + if [[ -n "$merge_run_id" ]]; then + already_passed="$( + gh api --paginate "repos/${GITHUB_REPOSITORY}/actions/runs/${merge_run_id}/jobs?per_page=100" --jq '.jobs[]' \ + | jq -s --argjson required "$required_json" ' + . as $jobs | + $required | all(. as $name | + any($jobs[]; .name == $name and .status == "completed" and .conclusion == "success") + ) + ' + )" + fi + + if [[ "$already_passed" != "true" ]]; then + echo "Commit ${GITHUB_SHA} has no passing main merge_group CI run covering all required checks; running full CI." + echo "skip_ci=false" >> "$GITHUB_OUTPUT" + echo "warm_cache=false" >> "$GITHUB_OUTPUT" + exit 0 + fi + + echo "merge_group run ${merge_run_id} already passed every required check on ${GITHUB_SHA}; skipping duplicate push CI." + echo "skip_ci=true" >> "$GITHUB_OUTPUT" + + # Keep the main-scoped pnpm store cache warm when pnpm-lock.yaml changed + # (caches saved on merge_group branches are not visible to future PRs). + # Compare the lockfile blob SHA directly so large diffs (>300 files) never + # miss a lockfile change, and warm conservatively if the lookup fails. + warm_cache="true" + if [[ -n "$BEFORE" && "$BEFORE" != "0000000000000000000000000000000000000000" ]]; then + before_blob="$(gh api "repos/${GITHUB_REPOSITORY}/contents/pnpm-lock.yaml?ref=${BEFORE}" --jq '.sha' 2>/dev/null || true)" + after_blob="$(gh api "repos/${GITHUB_REPOSITORY}/contents/pnpm-lock.yaml?ref=${GITHUB_SHA}" --jq '.sha' 2>/dev/null || true)" + if [[ -n "$before_blob" && -n "$after_blob" && "$before_blob" == "$after_blob" ]]; then + warm_cache="false" + fi + fi + echo "warm_cache=${warm_cache}" >> "$GITHUB_OUTPUT" + + warm_cache: + name: Warm main dependency cache + needs: [precheck] + if: ${{ github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true' && needs.precheck.outputs.warm_cache == 'true' }} + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Setup Vite+ + uses: voidzero-dev/setup-vp@cab1ab9eaff52d4857875f4f2c016e36af8f2c76 # v1.22.0 + with: + node-version: "24" + cache: true + run-install: false + + - name: Install dependencies + env: + ELECTRON_SKIP_BINARY_DOWNLOAD: "1" + run: vp install --frozen-lockfile + # scripts/verify-release-ci.ts requires this job by name. quality: name: Checks and Build + needs: [precheck] + if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} runs-on: ubuntu-latest # 20 minutes starves dependency-bump branches: a lockfile change cold-starts # every cache and slow runners then hit the cap mid-pipeline. @@ -84,6 +186,8 @@ jobs: # scripts/verify-release-ci.ts requires this job by name. unit_test: name: Unit Test + needs: [precheck] + if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} runs-on: ubuntu-latest timeout-minutes: 20 steps: @@ -116,13 +220,15 @@ jobs: # update DEFAULT_REQUIRED_CHECKS in scripts/verify-release-ci.ts. server_test: name: Server Test (${{ matrix.shard }}/${{ strategy.job-total }}) + needs: [precheck] + if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} runs-on: ubuntu-latest timeout-minutes: 20 strategy: # One failing shard still lets the others report their own failures. fail-fast: false matrix: - shard: [1, 2, 3] + shard: [1, 2, 3, 4] steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -161,8 +267,8 @@ jobs: # verification (scripts/verify-release-ci.ts) checks the jobs themselves. quality_gate: name: Format, Lint, Typecheck, Test, Build - if: ${{ always() }} - needs: [quality, unit_test, server_test] + if: ${{ always() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} + needs: [precheck, quality, unit_test, server_test] runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -170,8 +276,8 @@ jobs: env: RESULTS: ${{ toJSON(needs) }} run: | - echo "$RESULTS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"' - echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' > /dev/null + echo "$RESULTS" | jq -r 'del(.precheck) | to_entries[] | "\(.key): \(.value.result)"' + echo "$RESULTS" | jq -e 'del(.precheck) | all(.[]; .result == "success")' > /dev/null # The browser suite is CPU-bound (every spec renders the whole app), so one # 4-core runner tops out at about two tabs' worth of work. Two shards on two @@ -180,6 +286,8 @@ jobs: # updates DEFAULT_REQUIRED_CHECKS in scripts/verify-release-ci.ts too. browser: name: Browser Test (${{ matrix.shard }}/${{ strategy.job-total }}) + needs: [precheck] + if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} runs-on: ubuntu-latest timeout-minutes: 30 strategy: @@ -265,8 +373,8 @@ jobs: # name: it passes only when every browser shard passed. browser_gate: name: Browser Test - if: ${{ always() }} - needs: [browser] + if: ${{ always() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} + needs: [precheck, browser] runs-on: ubuntu-latest timeout-minutes: 5 steps: @@ -274,11 +382,13 @@ jobs: env: RESULTS: ${{ toJSON(needs) }} run: | - echo "$RESULTS" | jq -r 'to_entries[] | "\(.key): \(.value.result)"' - echo "$RESULTS" | jq -e 'all(.[]; .result == "success")' > /dev/null + echo "$RESULTS" | jq -r 'del(.precheck) | to_entries[] | "\(.key): \(.value.result)"' + echo "$RESULTS" | jq -e 'del(.precheck) | all(.[]; .result == "success")' > /dev/null release_smoke: name: Release Smoke + needs: [precheck] + if: ${{ !cancelled() && !(github.event_name == 'push' && needs.precheck.result == 'success' && needs.precheck.outputs.skip_ci == 'true') }} runs-on: ubuntu-latest # A lockfile change cold-starts the Vite+ cache: setup alone took ~8 minutes # on #950 and the old 10-minute cap cut the job off while saving the cache. @@ -306,6 +416,8 @@ jobs: - quality_gate - browser_gate - release_smoke - if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.deploy == true + # Explicit status checks are required because `precheck` is a skipped + # transitive ancestor on workflow_dispatch (implicit success() would skip). + if: ${{ !cancelled() && needs.quality_gate.result == 'success' && needs.browser_gate.result == 'success' && needs.release_smoke.result == 'success' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.deploy == true }} uses: ./.github/workflows/deploy-web.yml secrets: inherit diff --git a/scripts/update-test-shard-weights.ts b/scripts/update-test-shard-weights.ts index 242f67be6..e696a9222 100644 --- a/scripts/update-test-shard-weights.ts +++ b/scripts/update-test-shard-weights.ts @@ -38,25 +38,61 @@ const repoRoot = NodeURL.fileURLToPath(new URL("..", import.meta.url)); const gh = (args: ReadonlyArray): string => NodeChildProcess.execFileSync("gh", args, { cwd: repoRoot, encoding: "utf8" }).trim(); +const CANDIDATE_RUNS_PER_EVENT = 15; + +type ListedRun = { + readonly databaseId: number; + readonly createdAt: string; + readonly headSha: string; + readonly headBranch: string; +}; + +const isOnOriginMain = (sha: string): boolean => { + const result = NodeChildProcess.spawnSync( + "git", + ["merge-base", "--is-ancestor", sha, "origin/main"], + { + cwd: repoRoot, + stdio: "ignore", + }, + ); + return result.status === 0; +}; + const givenRunIds = process.argv.slice(3); -const runIds = - givenRunIds.length > 0 - ? givenRunIds - : gh([ +let candidates: ReadonlyArray<{ readonly runId: string; readonly headSha?: string }>; +if (givenRunIds.length > 0) { + candidates = givenRunIds.map((runId) => ({ runId })); +} else { + // Fetch origin/main so we only sample merge_group runs whose commit actually + // landed on main (ignoring green queue runs that were later dequeued). + NodeChildProcess.execFileSync("git", ["fetch", "--quiet", "origin", "main"], { cwd: repoRoot }); + + const listRuns = (extraArgs: ReadonlyArray): ReadonlyArray => + JSON.parse( + gh([ "run", "list", "--workflow=ci.yml", - "--branch=main", - "--event=push", "--status=success", - `--limit=${RUNS_TO_READ}`, - "--json=databaseId", - "--jq=.[].databaseId", - ]) - .split("\n") - .filter(Boolean); -if (runIds.length === 0) { - throw new Error("Found no green CI run on main to read test timings from."); + `--limit=${CANDIDATE_RUNS_PER_EVENT}`, + "--json=databaseId,createdAt,headSha,headBranch", + ...extraArgs, + ]), + ) as ReadonlyArray; + + // Query merge_group and main push separately so PR runs never crowd them out. + candidates = [ + ...listRuns(["--event=merge_group"]).filter( + (run) => run.headBranch.startsWith("gh-readonly-queue/main/") && isOnOriginMain(run.headSha), + ), + ...listRuns(["--branch=main", "--event=push"]), + ] + .toSorted((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt)) + .map((run) => ({ runId: String(run.databaseId), headSha: run.headSha })); +} +if (candidates.length === 0) { + throw new Error("Found no green CI run on main or landed merge_group to read test timings from."); } const downloadDir = NodeFS.mkdtempSync( @@ -64,15 +100,34 @@ const downloadDir = NodeFS.mkdtempSync( ); // One map of file -> seconds per run, newest run first. const runs: Array> = []; +const sampledShas = new Set(); try { - for (const runId of runIds) { + for (const { runId, headSha } of candidates) { + if (givenRunIds.length === 0 && runs.length >= RUNS_TO_READ) { + break; + } + if (headSha && sampledShas.has(headSha)) { + continue; + } const runDir = NodePath.join(downloadDir, runId); - gh(["run", "download", runId, `--pattern=${suite.artifacts}`, `--dir=${runDir}`]); + try { + gh(["run", "download", runId, `--pattern=${suite.artifacts}`, `--dir=${runDir}`]); + } catch (error) { + // Skipped push runs on main upload no timings artifacts; keep scanning + // unless the caller explicitly asked for this run id. + if (givenRunIds.length > 0) { + throw error; + } + continue; + } const reports = NodeFS.readdirSync(runDir, { recursive: true, encoding: "utf8" }).filter( (entry) => NodePath.basename(entry) === TIMINGS_FILE, ); if (reports.length === 0) { - throw new Error(`CI run ${runId} has no ${suiteName} test timings.`); + if (givenRunIds.length > 0) { + throw new Error(`CI run ${runId} has no ${suiteName} test timings.`); + } + continue; } const timings = new Map(); for (const entry of reports) { @@ -82,11 +137,17 @@ try { for (const [file, seconds] of Object.entries(report)) timings.set(file, seconds); } runs.push(timings); + if (headSha) { + sampledShas.add(headSha); + } console.log(`Read ${reports.length} shard reports from CI run ${runId}.`); } } finally { NodeFS.rmSync(downloadDir, { recursive: true, force: true }); } +if (runs.length === 0) { + throw new Error(`Found no green CI run with ${suiteName} test timings.`); +} const median = (values: ReadonlyArray): number => { const ordered = values.toSorted((a, b) => a - b); diff --git a/scripts/verify-release-ci.test.ts b/scripts/verify-release-ci.test.ts index a72d8dcd7..1d666b986 100644 --- a/scripts/verify-release-ci.test.ts +++ b/scripts/verify-release-ci.test.ts @@ -72,3 +72,71 @@ it("a check whose only run was cancelled still fails the gate", () => { assert.equal(evaluation.failures.length, 1); assert.deepEqual(evaluation.pending, []); }); + +it("a skipped newer run yields to an older passing run of the same check", () => { + const evaluation = evaluateRequiredChecks( + [CHECK], + [ + { + name: CHECK, + status: "completed", + conclusion: "success", + completed_at: "2026-09-06T09:11:40Z", + html_url: "https://example.test/merge-queue", + }, + { + name: CHECK, + status: "completed", + conclusion: "skipped", + completed_at: "2026-09-06T09:14:50Z", + html_url: "https://example.test/main-push", + }, + ], + ); + + assert.deepEqual(evaluation.failures, []); + assert.deepEqual(evaluation.pending, []); + assert.equal(evaluation.checksByName.get(CHECK)?.html_url, "https://example.test/merge-queue"); +}); + +it("a check whose only run was skipped still fails the gate", () => { + const evaluation = evaluateRequiredChecks( + [CHECK], + [ + { + name: CHECK, + status: "completed", + conclusion: "skipped", + completed_at: "2026-09-06T09:14:50Z", + }, + ], + ); + + assert.equal(evaluation.failures.length, 1); + assert.deepEqual(evaluation.pending, []); +}); + +it("a newer queued run with null timestamps is waited on even when an older run passed", () => { + const evaluation = evaluateRequiredChecks( + [CHECK], + [ + { + id: 100, + name: CHECK, + status: "completed", + conclusion: "success", + completed_at: "2026-09-06T09:11:40Z", + }, + { + id: 200, + name: CHECK, + status: "queued", + started_at: null, + completed_at: null, + }, + ], + ); + + assert.deepEqual(evaluation.failures, []); + assert.equal(evaluation.pending.length, 1); +}); diff --git a/scripts/verify-release-ci.ts b/scripts/verify-release-ci.ts index a49f31734..1c24f1103 100644 --- a/scripts/verify-release-ci.ts +++ b/scripts/verify-release-ci.ts @@ -6,6 +6,7 @@ type GitHubApp = { }; type CheckRun = { + id?: number; app?: GitHubApp; completed_at?: string | null; conclusion?: string | null; @@ -35,9 +36,10 @@ type CheckRunEvaluation = { const DEFAULT_REQUIRED_CHECKS = [ "Checks and Build", "Unit Test", - "Server Test (1/3)", - "Server Test (2/3)", - "Server Test (3/3)", + "Server Test (1/4)", + "Server Test (2/4)", + "Server Test (3/4)", + "Server Test (4/4)", "Browser Test (1/2)", "Browser Test (2/2)", "Release Smoke", @@ -80,9 +82,30 @@ function readNonNegativeNumberEnv(name: string, fallback: number): number { } function compareCheckRuns(a: CheckRun, b: CheckRun): number { - const aTime = Date.parse(a.completed_at ?? a.started_at ?? "1970-01-01T00:00:00Z"); - const bTime = Date.parse(b.completed_at ?? b.started_at ?? "1970-01-01T00:00:00Z"); - return bTime - aTime; + const aTimestamp = a.completed_at ?? a.started_at; + const bTimestamp = b.completed_at ?? b.started_at; + + // A queued check run has neither started_at nor completed_at yet. Order it + // by monotonically increasing GitHub check-run id when available, and treat + // an unstarted non-completed run without an id as newer than a finished one + // so polling never misses a freshly queued rerun. + if (!aTimestamp || !bTimestamp) { + if (a.id !== undefined && b.id !== undefined && a.id !== b.id) { + return b.id - a.id; + } + const aPending = a.status !== "completed" ? 1 : 0; + const bPending = b.status !== "completed" ? 1 : 0; + if (aPending !== bPending) { + return bPending - aPending; + } + } + + const aTime = Date.parse(aTimestamp ?? "1970-01-01T00:00:00Z"); + const bTime = Date.parse(bTimestamp ?? "1970-01-01T00:00:00Z"); + if (bTime !== aTime) { + return bTime - aTime; + } + return (b.id ?? 0) - (a.id ?? 0); } function getNextUrl(linkHeader: string | null): string | null { @@ -130,7 +153,7 @@ async function fetchJson( async function fetchCheckRuns(repository: string, ref: string, token: string): Promise { const encodedRef = encodeURIComponent(ref); let nextUrl: string | null = - `https://api.github.com/repos/${repository}/commits/${encodedRef}/check-runs?filter=latest&per_page=100`; + `https://api.github.com/repos/${repository}/commits/${encodedRef}/check-runs?filter=all&per_page=100`; const checkRuns: CheckRun[] = []; while (nextUrl) { @@ -165,15 +188,18 @@ function formatCheckRunStatus(checkName: string, checkRun: CheckRun | undefined) return `${checkName}: status=${checkRun.status ?? "unknown"}, conclusion=${checkRun.conclusion ?? "unknown"} (${checkRun.html_url ?? checkRun.details_url ?? "no URL"})`; } -function isCancelled(checkRun: CheckRun): boolean { - return checkRun.status === "completed" && checkRun.conclusion === "cancelled"; +function isNonVerdict(checkRun: CheckRun): boolean { + return ( + checkRun.status === "completed" && + (checkRun.conclusion === "cancelled" || checkRun.conclusion === "skipped") + ); } /** - * Picks the newest run of each required check and grades it. A cancelled run - * is not a verdict on the commit, so it yields to the newest run that has one: - * a merge landing on main cancels the previous main CI run, but the merge - * queue already ran the same checks on that exact commit. + * Picks the newest run of each required check and grades it. A cancelled or + * skipped run is not a verdict on the commit, so it yields to the newest run + * that has one: a merge landing on main cancels or skips the duplicate push CI + * run, while the merge queue already ran the same checks on that exact commit. */ export function evaluateRequiredChecks( requiredChecks: ReadonlyArray, @@ -185,7 +211,7 @@ export function evaluateRequiredChecks( continue; } const current = checksByName.get(checkRun.name); - if (!current || (isCancelled(current) && !isCancelled(checkRun))) { + if (!current || (isNonVerdict(current) && !isNonVerdict(checkRun))) { checksByName.set(checkRun.name, checkRun); } }