diff --git a/.github/workflows/release-manual.yml b/.github/workflows/release-manual.yml index 00da85bf6b..182fd1b852 100644 --- a/.github/workflows/release-manual.yml +++ b/.github/workflows/release-manual.yml @@ -116,14 +116,17 @@ jobs: exit 1 fi - - name: Pre-flight gate - # keep the claude-native live e2e subtests in this pre-publish gate (#1248) - env: - ACP_TEST_CLAUDE_NATIVE: "1" + - name: Pre-flight gate (fast sanity) + # #3539: the full `npm test` used to serialize here (~30-40 min on one + # shared 2-core runner) and then run AGAIN as the sharded CI matrix — + # the same suites twice per release chain. The full suite is now owned + # exclusively by the CI lanes dispatched at the exact publish sha + # below (policy 2026-10-10 unchanged); the Full CI gate blocks publish + # until they are all green, so coverage is identical — only the + # executor moved from this job to the parallel lane matrix. run: | npm ci npm run typecheck - npm test npm run build - name: Commit and push to master @@ -162,10 +165,13 @@ jobs: # npm publish. The direct-push commit lands on master via GITHUB_TOKEN, # which fires no push events — nothing runs CI on it. Dispatch every # missing lane at master (idempotent); the Full CI gate step below - # blocks publish until all lanes are green. + # blocks publish until all lanes are green. The script first refuses + # to dispatch if master's head is no longer the release commit + # (#3539) and cancels stale in-flight runs from this attempt. if: steps.push.outputs.direct == 'true' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_RUN_STARTED_AT: ${{ github.run_started_at }} run: | GITHUB_SHA="$(git rev-parse HEAD)" GITHUB_REF_NAME="master" @@ -175,12 +181,13 @@ jobs: - name: Full CI gate (all lanes green at the release commit) # Hard precondition for publish: every required lane green at the # publish sha. Any red lane or timeout ⇒ release fails, nothing is - # published. NOTE: dispatches above landed at master's head — if - # another push lands first, the runs' head_sha no longer matches this - # commit, the gate times out and publish is blocked (fail-safe). + # published. The dispatch step above already refused to fire when + # master's head was not this commit (#3539); a later push does not + # invalidate runs already landed at it. if: steps.push.outputs.direct == 'true' env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + RELEASE_RUN_STARTED_AT: ${{ github.run_started_at }} CI_GATE_TIMEOUT_MIN: "60" run: | GITHUB_SHA="$(git rev-parse HEAD)" @@ -188,31 +195,31 @@ jobs: export GITHUB_SHA GITHUB_REF_NAME node scripts/release-ci-gate.mjs --wait - - name: Dispatch CI on fallback branch + - name: Dispatch full CI on fallback branch if: steps.push.outputs.needs_pr == 'true' continue-on-error: true env: - GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} PR_BRANCH: ${{ steps.push.outputs.pr_branch }} + RELEASE_RUN_STARTED_AT: ${{ github.run_started_at }} + CI_FULL_DISPATCH: "1" run: | # GITHUB_TOKEN ref updates deliver no push events, so the push # trigger in ci.yml never fires on this branch. An explicit # workflow_dispatch on the same ref produces check runs on the head # sha → required status checks pass → the auto-PR is mergeable # without approving its gated pull_request runs (#772, #1744). - RESP_FILE="$(mktemp)" - HTTP_CODE="$(curl -sS -o "$RESP_FILE" -w '%{http_code}' -X POST \ - -H "Authorization: Bearer $GH_TOKEN" \ - -H "Accept: application/vnd.github+json" \ - -H "Content-Type: application/json" \ - "https://api.github.com/repos/${{ github.repository }}/actions/workflows/ci.yml/dispatches" \ - -d "{\"ref\": \"${PR_BRANCH}\"}")" - echo "POST /dispatches (ci.yml, ref=${PR_BRANCH}) → HTTP ${HTTP_CODE}" - if [ "$HTTP_CODE" != "204" ]; then - echo "::warning::could not dispatch CI on ${PR_BRANCH} (HTTP ${HTTP_CODE}: $(cat "$RESP_FILE")). The fallback PR stays gated until someone approves its workflow runs manually." - else - echo "::notice::CI dispatched on ${PR_BRANCH}; once its check runs are green the fallback PR satisfies required checks and is mergeable." - fi + # #3539: dispatch the COMPLETE lane set (ci.yml FULL matrix + every + # e2e lane) in one pass — previously only ci.yml CORE landed here + # and release.yml re-ran the rest after merge, paying for the same + # suites up to three times per chain. With everything green at the + # PR head, release.yml's gate reuses the runs and publishes without + # extra CI. The script verifies the branch head matches before + # dispatching and cancels stale in-flight runs from this attempt. + GITHUB_SHA="$(git rev-parse HEAD)" + GITHUB_REF_NAME="$PR_BRANCH" + export GITHUB_SHA GITHUB_REF_NAME + node scripts/release-ci-gate.mjs --dispatch - name: Open fallback PR (best effort) if: steps.push.outputs.needs_pr == 'true' @@ -289,6 +296,28 @@ jobs: echo "::warning::Finish the release with one click: ${LINK} (then merge to publish v${VER})" exit 0 + - name: Wait for full CI green on fallback branch (track head) + if: steps.push.outputs.needs_pr == 'true' + continue-on-error: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + PR_BRANCH: ${{ steps.push.outputs.pr_branch }} + RELEASE_RUN_STARTED_AT: ${{ github.run_started_at }} + WAIT_TRACK_HEAD: "1" + CI_GATE_TIMEOUT_MIN: "60" + run: | + # Certifies "fallback PR ready": every required lane green at the + # CURRENT branch head. If master gets merged into the release branch + # mid-wait (the v0.1.198 queue stomp, #3534), the head moves: stale + # in-flight runs at the old head are cancelled and missing lanes are + # re-dispatched at the new head instead of burning runners on a + # superseded sha. On timeout the PR stays open with CI still running + # — watch the PR, nothing is lost. + GITHUB_SHA="$(git rev-parse HEAD)" + GITHUB_REF_NAME="$PR_BRANCH" + export GITHUB_SHA GITHUB_REF_NAME + node scripts/release-ci-gate.mjs --wait + - name: Check if prerelease id: pre if: steps.push.outputs.direct == 'true' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d83b502f5b..c822e9dbe4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -51,6 +51,23 @@ jobs: export GITHUB_SHA EXTRA_MATCH_SHAS node scripts/release-ci-gate.mjs --dispatch + - name: Probe full-suite reuse (#3539) + # One-shot, non-blocking: is the full suite ALREADY proven green at + # the PR head (every required lane has a green run there)? Together + # with "master did not move since", that lets Build-and-test skip its + # local full pass — the one-click fallback chain then pays for the + # full suite exactly once. Any doubt falls back to running it. + if: steps.check.outputs.is_release == 'true' + id: reuse + continue-on-error: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + GITHUB_SHA="$(git rev-parse HEAD)" + EXTRA_MATCH_SHAS="$(git rev-parse HEAD^2 2>/dev/null || true)" + export GITHUB_SHA EXTRA_MATCH_SHAS + node scripts/release-ci-gate.mjs --probe-reuse + - name: Setup if: steps.check.outputs.is_release == 'true' run: npm ci @@ -62,7 +79,18 @@ jobs: ACP_TEST_CLAUDE_NATIVE: "1" run: | npm run typecheck - npm test + # #3539: skip the local full pass only when it is provably redundant — + # every required lane already green at the PR head (reuse probe above) + # AND master did not move since (HEAD^2..HEAD empty), i.e. the PR-head + # tree IS this tree. Human-cut release PRs (core lanes only) never + # skip: their e2e lanes are absent at the PR head, so this runs + # exactly as before. The Full CI gate below still blocks publish. + MASTER_ONLY="$(git rev-list --count HEAD^2..HEAD 2>/dev/null || echo 1)" + if [ "${{ steps.reuse.outputs.allLanesReused }}" = "yes" ] && [ "$MASTER_ONLY" -eq 0 ]; then + echo "full suite already green at the PR head and master did not move since — skipping the local full pass (#3539)" + else + npm test + fi npm run build - name: Read version diff --git a/reference/release.md b/reference/release.md index e8db2f514f..04a3e9a215 100644 --- a/reference/release.md +++ b/reference/release.md @@ -105,11 +105,15 @@ The Agent does steps 1–6, the human does step 7 (merge). - PR title: `release v{VERSION}`; body lists changes since last tag. 7. **Human merges the PR** (Agent MUST NOT merge). 8. **CI publishes automatically** — no manual `npm publish`: - - On merge, `release.yml` detects the `*_release-v*` branch name + - `release v{VERSION}` commit message. - - It runs `npm ci` + `typecheck` + `test` + `build`, then - `npm publish --tag latest` (using the `NPM_TOKEN` repo secret), creates git - tag `v{VERSION}`, and creates a GitHub Release. + - On merge, `release.yml` detects the `*_release-v*` branch name + + `release v{VERSION}` commit message. + - It runs `npm ci` + `typecheck` + `build`, plus the full test suite UNLESS a + reuse probe proves it redundant: every required CI lane already green at the + PR head AND master did not move since the PR head (#3539 — the full suite is + then paid for exactly once per chain; human-cut PRs with core lanes only never + skip). The full-CI gate still blocks publish until every lane is green at the + publish sha (fresh or reused). Then `npm publish --tag latest` (using the + `NPM_TOKEN` repo secret), git tag `v{VERSION}`, GitHub Release. 9. **Verify** the published version is live: ```bash npm view billion-context version @@ -137,8 +141,15 @@ The workflow then: prerequisite above. 2. Bumps ONLY `package.json` + `package-lock.json` and commits `release v{VERSION}` — the same one-version-one-commit discipline as `AGENTS.md` Version Bumps. -3. Runs the full pre-flight gate (`npm ci` + typecheck + test + build). +3. Runs the fast pre-flight gate (`npm ci` + typecheck + build). The FULL test suite + deliberately does NOT run here anymore (#3539): it runs exactly once, as the sharded + CI lanes dispatched at the exact publish sha in the next steps, and the full-CI gate + blocks publish until they are all green — same coverage, parallel shards instead of + ~30-40 min serial on one shared runner. 4. Pushes the release commit directly to `master` (GITHUB_TOKEN, fast-forward only). + On success the run dispatches every missing CI lane at the release commit — refusing + first if master's head has moved past it — and blocks until all lanes are green + before publishing. If branch protection blocks direct pushes, the release lands on a release branch instead and the run tries to open the release PR itself (best-effort — if the account forbids Actions-created PRs the run still finishes green with a one-click "open the @@ -148,15 +159,23 @@ The workflow then: publishes via the standard flow; red is reserved for real failures (guard trips, gate failures, or a failed branch push). GitHub suppresses push-event delivery for ref updates made with GITHUB_TOKEN, so the push trigger never fires on the fallback - branch; instead the run explicitly dispatches `ci.yml` on that branch - (`POST …/actions/workflows/ci.yml/dispatches`, ref = branch; requires the - `workflow_dispatch` trigger that `ci.yml` declares for exactly this purpose). Those - check runs land on the same head sha — once green, required checks pass and the - auto-PR is mergeable without approving its `action_required` pull_request runs - (bot-authored PRs are gated there) (#772, #1744). If the dispatch fails (transient - API error), the fallback PR stays gated until someone approves those runs manually. - (Push-triggered CI on release branches still works for branches pushed with a real - account token — e.g. agent-driven standard-flow release branches.) + branch; instead the run invokes `scripts/release-ci-gate.mjs --dispatch` with + `CI_FULL_DISPATCH=1`, which fires the COMPLETE lane set at the branch head in one + pass — `ci.yml` in FULL matrix scope plus every e2e lane (each requires the + `workflow_dispatch` trigger the workflows declare for exactly this purpose). Those + check runs land on the same head sha — once green, required checks pass and the + auto-PR is mergeable without approving its `action_required` pull_request runs + (bot-authored PRs are gated there) (#772, #1744). Because the full set goes green + at the PR head, `release.yml` reuses every run at merge time instead of re-running + the suites (#3539: one full pass per chain). The dispatch refuses to fire if the + branch head no longer matches the release commit, cancels stale in-flight runs from + the attempt, and a follow-up track-head wait step certifies "PR ready": if master + gets merged into the release branch mid-wait, stale runs at the old head are + cancelled and missing lanes re-dispatched at the new head instead of burning + runners on a superseded sha (the v0.1.198 queue stomp, #3539/#3534). If the dispatch + fails (transient API error), the fallback PR stays gated until someone approves + those runs manually. (Push-triggered CI on release branches still works for branches + pushed with a real account token — e.g. agent-driven standard-flow release branches.) 5. Publishes to npm (`latest`, or `dev` for prerelease), tags `v{VERSION}`, and creates the GitHub Release with notes generated from `git log` since the last tag. diff --git a/scripts/release-ci-gate.mjs b/scripts/release-ci-gate.mjs index 43f2300453..46cfcf1913 100644 --- a/scripts/release-ci-gate.mjs +++ b/scripts/release-ci-gate.mjs @@ -13,11 +13,27 @@ // at any target sha. Idempotent: lanes with an existing run // (any status) are left alone. Call this EARLY in the release // workflow so lanes run in parallel with the local pre-flight. -// --wait Block until every required lane's latest run at the publish +// BEFORE dispatching it verifies the ref's current head equals +// the target sha and refuses otherwise (#3539): dispatching at +// a moved head lands runs on the wrong sha where the gate could +// never see them — previously that burned ~10 runners and then +// timed out 60 min later (the v0.1.198 queue stomp, #3534). +// --wait Block until every required lane's latest run at the target // sha is `success`. Reuses an already-green run at one of the // EXTRA_MATCH_SHAS (e.g. the PR head sha HEAD^2 — exactly how // branch-protection required checks work). Fails fast on any // red lane; fails on timeout. MUST run before the publish step. +// --probe-reuse One-shot, NON-blocking: report whether every required lane +// already has a green run at one of the EXTRA_MATCH_SHAS, +// ignoring runs at the publish sha deliberately (a merge push +// auto-fires ci.yml there and would mask the reuse question). +// Writes allLanesReused=yes|no to $GITHUB_OUTPUT when set. +// Report-only: a normal read exits 0; an upstream API error +// exits non-zero, which the calling step absorbs via +// continue-on-error:true — so the output stays absent or "no" +// and callers treat that as "run the local suite anyway" +// (#3539: release.yml skips its local full pass only when the +// full suite is provably green at the PR head). // // Env: // GITHUB_TOKEN token with actions:read (+ actions:write for --dispatch) @@ -33,6 +49,26 @@ // CI_GATE_TIMEOUT_MIN --wait deadline, default 60 // CI_GATE_POLL_SEC poll interval, default 20 // DRY_RUN=1 print what would be dispatched instead of POSTing +// RELEASE_RUN_STARTED_AT ISO timestamp scoping stale-run cancellation to +// runs created AFTER this release attempt started +// (set from ${{ github.run_started_at }}). Absent => +// cancellation disabled (manual use stays untouched). +// WAIT_TRACK_HEAD=1 --wait mode for branches whose head may move mid-wait +// (one-click fallback release branches receiving late +// master merges): the target sha follows the branch +// head; on movement, stale in-flight runs at the old +// head are cancelled and missing lanes re-dispatched +// at the new head (#3539). +// CI_FULL_DISPATCH=1 dispatch ci.yml with inputs.full=true (full matrix +// instead of core) so the release branch carries the +// COMPLETE lane set in one pass (#3539). +// +// Stale-run cancellation (best-effort hygiene, never blocks the gate): when +// RELEASE_RUN_STARTED_AT is set, in-flight queued/in_progress +// workflow_dispatch runs of the required workflows are cancelled if their +// head_sha differs from the current target AND they were created after the +// release attempt started. Scheduled, push- and PR-triggered runs and runs +// created before this attempt are never touched. // // Default required set = the full every-PR lane set plus the server-lane e2e // workflows (path-filtered on PRs but security-relevant for releases): @@ -44,6 +80,8 @@ // matrix), ci-theorem.yml / ci-image.yml / ci-registry.yml (path-gated aux // lanes). Extend via REQUIRED_CI_WORKFLOWS if policy changes. +import { appendFileSync } from "node:fs"; + const DEFAULT_REQUIRED = [ "ci.yml", "ci-e2e.yml", @@ -65,8 +103,8 @@ const RED_CONCLUSIONS = new Set([ ]); const mode = process.argv[2]; -if (mode !== "--dispatch" && mode !== "--wait") { - console.error("usage: release-ci-gate.mjs --dispatch | --wait"); +if (mode !== "--dispatch" && mode !== "--wait" && mode !== "--probe-reuse") { + console.error("usage: release-ci-gate.mjs --dispatch | --wait | --probe-reuse"); process.exit(2); } @@ -158,12 +196,66 @@ async function latestRunAt(workflow, sha) { return runs[0]; } -async function laneStates() { +// Newest up-to-30 runs of `workflow` regardless of sha (stale-run scan). +async function listRecentRuns(workflow) { + const res = await api(`/repos/${repo}/actions/workflows/${encodeURIComponent(workflow)}/runs?per_page=30`); + if (!res.ok) { + const body = await res.text().catch(() => ""); + throw new Error(`GET runs for ${workflow} (stale scan) → HTTP ${res.status}: ${body.slice(0, 300)}`); + } + const runs = (await res.json()).workflow_runs || []; + runs.sort((a, b) => b.id - a.id); + return runs; +} + +// Current head sha of `ref`, or null (branch absent). +async function branchHead(ref) { + const res = await api(`/repos/${repo}/branches/${encodeURIComponent(ref)}`); + if (!res.ok) { + const body = await res.text().catch(() => ""); + throw new Error(`GET branch ${ref} → HTTP ${res.status}: ${body.slice(0, 300)}`); + } + const j = await res.json(); + return j?.commit?.sha || null; +} + +// #3539: bounded stale-run cleanup. Only in-flight runs of THIS release +// attempt (created after RELEASE_RUN_STARTED_AT, workflow_dispatch event, +// head different from the current target) are cancelled. Best-effort: any +// failure here warns and moves on — the gate itself remains the safety net. +const runStartedAtMs = Date.parse((process.env.RELEASE_RUN_STARTED_AT || "").trim()); + +async function cancelStaleRuns(targetSha) { + if (!Number.isFinite(runStartedAtMs)) return; // no scoping anchor → disabled + for (const wf of required) { + try { + const runs = await listRecentRuns(wf); + for (const r of runs) { + if (r.status !== "queued" && r.status !== "in_progress") continue; + if (r.event !== "workflow_dispatch") continue; + if (r.head_sha === targetSha) continue; + const createdMs = Date.parse(r.created_at || ""); + if (!Number.isFinite(createdMs) || createdMs < runStartedAtMs) continue; + const c = await api(`/repos/${repo}/actions/runs/${r.id}/cancel`, { method: "POST" }); + if (c.ok || c.status === 404) { + console.log(`cancelled stale run ${r.id} (${wf} @ ${String(r.head_sha).slice(0, 8)}, created ${r.created_at})`); + } else { + console.log(`::warning::cancel of stale run ${r.id} (${wf}) returned HTTP ${c.status} — leaving it alone`); + } + } + } catch (err) { + console.log(`::warning::stale-run cleanup failed for ${wf}: ${err.message} — continuing (cleanup is best-effort)`); + } + } +} + +async function laneStates(targetSha) { const states = {}; for (const wf of required) { - const atPublish = await latestRunAt(wf, publishSha); - if (atPublish) { - states[wf] = { run: atPublish, via: `publish sha ${publishSha.slice(0, 8)}` }; + const atTarget = await latestRunAt(wf, targetSha); + if (atTarget) { + const label = targetSha === publishSha ? "publish sha" : "tracked head"; + states[wf] = { run: atTarget, via: `${label} ${targetSha.slice(0, 8)}` }; continue; } let reused = null; @@ -198,7 +290,7 @@ function printStates(states) { } } -async function dispatchMissing(states) { +async function dispatchMissing(states, targetSha) { let fired = 0; for (const wf of required) { if (classify(states[wf]) !== "missing") continue; @@ -207,32 +299,79 @@ async function dispatchMissing(states) { fired += 1; continue; } + // CI_FULL_DISPATCH: ci.yml's plan job defaults to CORE scope for bare + // workflow_dispatch; release branches need the FULL matrix so the whole + // chain pays for the full suite exactly once (#3539). + const payload = wf === "ci.yml" && process.env.CI_FULL_DISPATCH === "1" + ? { ref: refName, inputs: { full: true } } + : { ref: refName }; const res = await api(`/repos/${repo}/actions/workflows/${encodeURIComponent(wf)}/dispatches`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ ref: refName }), + body: JSON.stringify(payload), }); if (res.status !== 204) { const body = await res.text().catch(() => ""); console.error(`::error::dispatch ${wf} at ref ${refName} → HTTP ${res.status}: ${body.slice(0, 300)}`); - console.error(`::error::${wf} has no run at ${publishSha.slice(0, 8)} and cannot be dispatched (missing workflow_dispatch trigger, or file absent from the default branch). Refusing to publish without it.`); + console.error(`::error::${wf} has no run at ${targetSha.slice(0, 8)} and cannot be dispatched (missing workflow_dispatch trigger, or file absent from the default branch). Refusing to publish without it.`); process.exit(1); } - console.log(`dispatched ${wf} at ref ${refName}`); + console.log(`dispatched ${wf} at ref ${refName}${payload.inputs ? " (full scope)" : ""}`); fired += 1; } if (!fired) console.log("no missing lanes — nothing dispatched"); } +function writeOutput(key, value) { + if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`); +} + async function main() { console.log(`release CI gate (${mode.slice(2)}) repo=${repo} publish sha=${publishSha.slice(0, 12)} ref=${refName}`); console.log(`required lanes (${required.length}): ${required.join(", ")}`); if (extraShas.length) console.log(`extra reuse shas: ${extraShas.map((s) => s.slice(0, 8)).join(", ")}`); + if (mode === "--probe-reuse") { + if (!extraShas.length) { + console.log("reuse probe: no extra match shas provided — nothing to reuse"); + writeOutput("allLanesReused", "no"); + return; + } + let all = true; + for (const wf of required) { + let greenAt = null; + for (const sha of extraShas) { + const r = await latestRunAt(wf, sha); // eslint-disable-line no-await-in-loop + if (r && r.conclusion === "success") { + greenAt = sha; + break; + } + } + if (greenAt) { + console.log(` reusable ${wf.padEnd(30)} green at ${greenAt.slice(0, 8)}`); + } else { + console.log(` absent ${wf.padEnd(30)} no green run at any extra sha`); + all = false; + } + } + console.log(`reuse probe: ${all ? "ALL" : "NOT ALL"} ${required.length} lanes reusable from extra shas`); + writeOutput("allLanesReused", all ? "yes" : "no"); + return; + } + if (mode === "--dispatch") { - const states = await laneStates(); + const head = await branchHead(refName); + if (head !== publishSha) { + console.error( + `::error::ref ${refName} head is ${head ? head.slice(0, 12) : "unknown"} but the target sha is ${publishSha.slice(0, 12)} — refusing to dispatch: ` + + `runs would land on the wrong sha where the gate could never see them. Sync the ref to the target sha (or re-cut the release at the current head) and retry.`, + ); + process.exit(1); + } + await cancelStaleRuns(publishSha); + const states = await laneStates(publishSha); printStates(states); - await dispatchMissing(states); + await dispatchMissing(states, publishSha); return; } @@ -240,19 +379,34 @@ async function main() { const timeoutMin = Number(process.env.CI_GATE_TIMEOUT_MIN || 60); const pollSec = Number(process.env.CI_GATE_POLL_SEC || 20); const deadline = Date.now() + timeoutMin * 60_000; + const trackHead = process.env.WAIT_TRACK_HEAD === "1"; + let targetSha = publishSha; + await cancelStaleRuns(targetSha); let attempt = 0; for (;;) { attempt += 1; - const states = await laneStates(); + if (trackHead) { + const head = await branchHead(refName); + if (head && head !== targetSha) { + console.log( + `branch head moved: ${targetSha.slice(0, 8)} → ${head.slice(0, 8)} — re-targeting: cancelling stale runs and re-dispatching missing lanes at the new head`, + ); + targetSha = head; + await cancelStaleRuns(targetSha); + await dispatchMissing(await laneStates(targetSha), targetSha); + } + } + const states = await laneStates(targetSha); + const shaLabel = targetSha === publishSha ? "the publish sha" : `the tracked head ${targetSha.slice(0, 12)}`; const red = required.filter((wf) => classify(states[wf]).startsWith("red")); if (red.length) { printStates(states); - console.error(`::error::CI lane(s) RED at the publish sha: ${red.join(", ")} — refusing to publish. Re-run the lane(s) or fix, then retry the release.`); + console.error(`::error::CI lane(s) RED at ${shaLabel}: ${red.join(", ")} — refusing to publish. Re-run the lane(s) or fix, then retry the release.`); process.exit(1); } if (required.every((wf) => classify(states[wf]) === "green")) { printStates(states); - console.log(`full CI gate PASSED — all ${required.length} lanes green at ${publishSha.slice(0, 12)} (attempt ${attempt})`); + console.log(`full CI gate PASSED — all ${required.length} lanes green at ${targetSha.slice(0, 12)} (attempt ${attempt})`); return; } if (Date.now() > deadline) { diff --git a/tests/release-ci-gate.test.ts b/tests/release-ci-gate.test.ts index 1fbf0d32ec..51ad563318 100644 --- a/tests/release-ci-gate.test.ts +++ b/tests/release-ci-gate.test.ts @@ -5,26 +5,61 @@ // sha before npm publish (follow-up to the v0.1.192 carve-out, #2664). // // Runs the real script as a child process against an inline mock of the -// GitHub Actions API (list-runs + dispatch endpoints) — no network, no token. +// GitHub Actions API (list-runs + dispatch + branches + cancel endpoints) — +// no network, no token. #3539 additions: head-match refusal before dispatch, +// scoped stale-run cancellation, track-head waiting, --probe-reuse, and +// CI_FULL_DISPATCH payloads. import test from "node:test"; import assert from "node:assert/strict"; import http from "node:http"; import { once } from "node:events"; import { spawn } from "node:child_process"; -import { fileURLToPath } from "node:url"; +import { readFileSync, rmSync } from "node:fs"; import path from "node:path"; const SCRIPT = path.resolve(import.meta.dirname, "../scripts/release-ci-gate.mjs"); -type Run = { id: number; head_sha: string; status: string; conclusion: string | null }; -const runs = new Map(); // `${workflow}@${sha}` -> newest run +type Run = { + id: number; + head_sha: string; + status: string; + conclusion: string | null; + event?: string; + created_at?: string; +}; +const runs = new Map(); // `${workflow}@${sha}` -> run const dispatchLog: string[] = []; +const dispatchBodies: unknown[] = []; +const cancelLog: number[] = []; +const branchHeads = new Map(); // ref -> head sha (default "publish") const failDispatch = new Set(); let flakyGetsLeft = 0; // first N runs-listing GETs respond 500 (transient-failure injection) +function resetState() { + runs.clear(); + dispatchLog.length = 0; + dispatchBodies.length = 0; + cancelLog.length = 0; + branchHeads.clear(); +} + const mock = http.createServer((req, res) => { const url = new URL(req.url ?? "/", "http://mock"); + const br = url.pathname.match(/^\/repos\/[^/]+\/[^/]+\/branches\/([^/]+)$/); + if (br) { + const ref = decodeURIComponent(br[1]); + res.writeHead(200, { "Content-Type": "application/json" }).end( + JSON.stringify({ commit: { sha: branchHeads.get(ref) ?? "publish" } }), + ); + return; + } + const cx = url.pathname.match(/^\/repos\/[^/]+\/[^/]+\/actions\/runs\/(\d+)\/cancel$/); + if (cx) { + cancelLog.push(Number(cx[1])); + res.writeHead(204).end(); + return; + } const m = url.pathname.match(/^\/repos\/([^/]+\/[^/]+)\/actions\/workflows\/([^/]+)\/(runs|dispatches)$/); if (!m) { res.writeHead(404).end("{}"); @@ -39,7 +74,9 @@ const mock = http.createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { - dispatchLog.push(`${wf}@${JSON.parse(body).ref}`); + const parsed = JSON.parse(body); + dispatchLog.push(`${wf}@${parsed.ref}`); + dispatchBodies.push(parsed); res.writeHead(204).end(); }); return; @@ -49,8 +86,13 @@ const mock = http.createServer((req, res) => { res.writeHead(500, { "Content-Type": "application/json" }).end(JSON.stringify({ message: "internal error" })); return; } - const run = runs.get(`${wf}@${url.searchParams.get("head_sha")}`); - res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ workflow_runs: run ? [run] : [] })); + // With a head_sha filter: only that sha's runs; without: every run of the + // workflow (the stale-run scan shape). + const headSha = url.searchParams.get("head_sha"); + const list = [...runs.entries()] + .filter(([k, r]) => k.startsWith(`${wf}@`) && (!headSha || r.head_sha === headSha)) + .map(([, r]) => r); + res.writeHead(200, { "Content-Type": "application/json" }).end(JSON.stringify({ workflow_runs: list })); }); function gate(args: string[], env: Record): Promise<{ code: number | null; out: string }> { @@ -63,6 +105,7 @@ function gate(args: string[], env: Record): Promise<{ code: numb GITHUB_SHA: "publish", GITHUB_REF_NAME: "master", API_BASE: `http://127.0.0.1:${port}`, + GITHUB_OUTPUT: "", ...env, }, }); @@ -75,6 +118,7 @@ function gate(args: string[], env: Record): Promise<{ code: numb test("release-ci-gate dispatch: dry-run reports missing lanes only", async (t) => { await t.diagnostic("seed: ci.yml completed/green at publish, ci-e2e-fake in_progress, ci-e2e-dsh absent"); + resetState(); runs.set("ci.yml@publish", { id: 1, head_sha: "publish", status: "completed", conclusion: "success" }); runs.set("ci-e2e-fake.yml@publish", { id: 2, head_sha: "publish", status: "in_progress", conclusion: null }); const r = await gate(["--dispatch"], { @@ -89,7 +133,7 @@ test("release-ci-gate dispatch: dry-run reports missing lanes only", async (t) = }); test("release-ci-gate dispatch: fires missing lanes, idempotent on rerun", async () => { - runs.clear(); + resetState(); runs.set("ci.yml@publish", { id: 1, head_sha: "publish", status: "completed", conclusion: "success" }); const env = { REQUIRED_CI_WORKFLOWS: "ci.yml,ci-e2e.yml" }; const r1 = await gate(["--dispatch"], env); @@ -105,16 +149,17 @@ test("release-ci-gate dispatch: fires missing lanes, idempotent on rerun", async }); test("release-ci-gate dispatch: un-dispatchable missing lane is a hard failure", async () => { - runs.clear(); + resetState(); failDispatch.add("ci-e2e.yml"); const r = await gate(["--dispatch"], { REQUIRED_CI_WORKFLOWS: "ci-e2e.yml" }); assert.equal(r.code, 1, r.out); assert.match(r.out, /HTTP 422/); assert.match(r.out, /Refusing to publish/); + failDispatch.delete("ci-e2e.yml"); }); test("release-ci-gate wait: passes once every lane is green at the publish sha", async () => { - runs.clear(); + resetState(); runs.set("ci.yml@publish", { id: 1, head_sha: "publish", status: "completed", conclusion: "success" }); runs.set("ci-e2e-fake.yml@publish", { id: 2, head_sha: "publish", status: "in_progress", conclusion: null }); setTimeout(() => runs.set("ci-e2e-fake.yml@publish", { id: 2, head_sha: "publish", status: "completed", conclusion: "success" }), 1500); @@ -128,7 +173,7 @@ test("release-ci-gate wait: passes once every lane is green at the publish sha", }); test("release-ci-gate wait: red lane fails fast and blocks publish", async () => { - runs.clear(); + resetState(); runs.set("ci.yml@publish", { id: 1, head_sha: "publish", status: "completed", conclusion: "success" }); runs.set("ci-e2e-fake.yml@publish", { id: 2, head_sha: "publish", status: "completed", conclusion: "failure" }); const r = await gate(["--wait"], { @@ -142,7 +187,7 @@ test("release-ci-gate wait: red lane fails fast and blocks publish", async () => }); test("release-ci-gate wait: red at publish sha is never overridden by a green extra (PR-head) sha", async () => { - runs.clear(); + resetState(); runs.set("ci.yml@publish", { id: 1, head_sha: "publish", status: "completed", conclusion: "failure" }); runs.set("ci.yml@prhead", { id: 2, head_sha: "prhead", status: "completed", conclusion: "success" }); const r = await gate(["--wait"], { REQUIRED_CI_WORKFLOWS: "ci.yml", EXTRA_MATCH_SHAS: "prhead" }); @@ -151,7 +196,7 @@ test("release-ci-gate wait: red at publish sha is never overridden by a green ex }); test("release-ci-gate: green run at extra sha counts as satisfied (PR-head reuse, no extra CI)", async () => { - runs.clear(); + resetState(); runs.set("ci.yml@prhead", { id: 2, head_sha: "prhead", status: "completed", conclusion: "success" }); const r = await gate(["--dispatch"], { REQUIRED_CI_WORKFLOWS: "ci.yml", @@ -164,7 +209,7 @@ test("release-ci-gate: green run at extra sha counts as satisfied (PR-head reuse }); test("release-ci-gate wait: timeout with a lane still missing blocks publish", async () => { - runs.clear(); + resetState(); const r = await gate(["--wait"], { REQUIRED_CI_WORKFLOWS: "ci-e2e.yml", CI_GATE_POLL_SEC: "1", @@ -176,7 +221,7 @@ test("release-ci-gate wait: timeout with a lane still missing blocks publish", a }); test("release-ci-gate dispatch: transient API errors on read-only calls are retried, not fatal", async () => { - runs.clear(); + resetState(); runs.set("ci.yml@prhead", { id: 2, head_sha: "prhead", status: "completed", conclusion: "success" }); // First two runs-listing GETs get HTTP 500; the retried third succeeds. flakyGetsLeft = 2; @@ -189,6 +234,136 @@ test("release-ci-gate dispatch: transient API errors on read-only calls are retr assert.match(r.out, /reused green run at prhead/); }); +test("release-ci-gate dispatch: refuses when ref head != target sha (nothing dispatched)", async () => { + resetState(); + branchHeads.set("master", "moved-head"); + const r = await gate(["--dispatch"], { REQUIRED_CI_WORKFLOWS: "ci-e2e.yml" }); + assert.equal(r.code, 1, r.out); + assert.match(r.out, /ref master head is moved-head/); + assert.match(r.out, /refusing to dispatch/); + assert.deepEqual(dispatchLog, []); // the whole point: no runners burned on the wrong sha +}); + +test("release-ci-gate dispatch: cancels only stale in-flight runs from this attempt", async () => { + resetState(); + const t0 = Date.now(); + const nowIso = new Date(t0).toISOString(); + const soonIso = new Date(t0 + 60_000).toISOString(); + const oldIso = new Date(t0 - 3_600_000).toISOString(); + runs.set("ci-e2e.yml@stale-dispatch", { id: 101, head_sha: "stale-dispatch", status: "in_progress", conclusion: null, event: "workflow_dispatch", created_at: soonIso }); + runs.set("ci-e2e.yml@push-triggered", { id: 102, head_sha: "push-triggered", status: "in_progress", conclusion: null, event: "push", created_at: soonIso }); + runs.set("ci-e2e.yml@publish", { id: 103, head_sha: "publish", status: "in_progress", conclusion: null, event: "workflow_dispatch", created_at: soonIso }); + runs.set("ci-e2e.yml@pre-attempt", { id: 104, head_sha: "pre-attempt", status: "in_progress", conclusion: null, event: "workflow_dispatch", created_at: oldIso }); + const r = await gate(["--dispatch"], { + REQUIRED_CI_WORKFLOWS: "ci-e2e.yml", + RELEASE_RUN_STARTED_AT: nowIso, + }); + assert.equal(r.code, 0, r.out); + // 101 alone: 102 is push-triggered, 103 sits at the target sha, 104 predates the attempt. + assert.deepEqual(cancelLog, [101], r.out); + assert.match(r.out, /cancelled stale run 101/); + assert.match(r.out, /no missing lanes/); +}); + +test("release-ci-gate dispatch: stale cancellation disabled without RELEASE_RUN_STARTED_AT", async () => { + resetState(); + runs.set("ci-e2e.yml@stale-dispatch", { id: 101, head_sha: "stale-dispatch", status: "in_progress", conclusion: null, event: "workflow_dispatch", created_at: new Date().toISOString() }); + runs.set("ci-e2e.yml@publish", { id: 103, head_sha: "publish", status: "completed", conclusion: "success" }); + const r = await gate(["--dispatch"], { REQUIRED_CI_WORKFLOWS: "ci-e2e.yml" }); + assert.equal(r.code, 0, r.out); + assert.deepEqual(cancelLog, []); +}); + +test("release-ci-gate wait: track-head follows branch movement, cancels stale, re-targets to green", async () => { + resetState(); + const t0 = Date.now(); + const startIso = new Date(t0).toISOString(); + const mk = (sha: string, status: string, conclusion: string | null, id: number): Run => ({ + id, + head_sha: sha, + status, + conclusion, + event: "workflow_dispatch", + created_at: new Date().toISOString(), + }); + branchHeads.set("master", "h1"); + runs.set("ci.yml@h1", mk("h1", "completed", "success", 200)); + runs.set("ci-e2e.yml@h1", mk("h1", "in_progress", null, 201)); + // The v0.1.198 queue stomp (#3534): master merged into the release branch + // mid-release moves the head; the old-head run KEEPS RUNNING (GitHub does + // not delete superseded runs) until something cancels it. + setTimeout(() => { + branchHeads.set("master", "h2"); + runs.set("ci.yml@h2", mk("h2", "completed", "success", 202)); + runs.set("ci-e2e.yml@h2", mk("h2", "in_progress", null, 203)); + }, 2500); + setTimeout(() => runs.set("ci-e2e.yml@h2", mk("h2", "completed", "success", 203)), 5000); + const r = await gate(["--wait"], { + REQUIRED_CI_WORKFLOWS: "ci.yml,ci-e2e.yml", + GITHUB_SHA: "h1", + WAIT_TRACK_HEAD: "1", + RELEASE_RUN_STARTED_AT: startIso, + CI_GATE_POLL_SEC: "1", + CI_GATE_TIMEOUT_MIN: "2", + }); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /branch head moved: h1 → h2/); + assert.deepEqual(cancelLog, [201], r.out); + assert.match(r.out, /full CI gate PASSED — all 2 lanes green/); +}); + +test("release-ci-gate probe-reuse: all lanes green at extra sha → allLanesReused=yes", async () => { + resetState(); + runs.set("ci.yml@prhead", { id: 1, head_sha: "prhead", status: "completed", conclusion: "success" }); + runs.set("ci-e2e-fake.yml@prhead", { id: 2, head_sha: "prhead", status: "completed", conclusion: "success" }); + // A red run at the publish sha must NOT mask reuse (the merge push auto-fires ci.yml there). + runs.set("ci.yml@publish", { id: 3, head_sha: "publish", status: "completed", conclusion: "failure" }); + const outFile = path.join(import.meta.dirname, "probe-output.txt"); + try { + const r = await gate(["--probe-reuse"], { + REQUIRED_CI_WORKFLOWS: "ci.yml,ci-e2e-fake.yml", + EXTRA_MATCH_SHAS: "prhead", + GITHUB_OUTPUT: outFile, + }); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /reuse probe: ALL 2 lanes reusable/); + assert.ok(readFileSync(outFile, "utf8").includes("allLanesReused=yes")); + } finally { + rmSync(outFile, { force: true }); + } +}); + +test("release-ci-gate probe-reuse: a lane without a green extra-sha run → allLanesReused=no", async () => { + resetState(); + runs.set("ci.yml@prhead", { id: 1, head_sha: "prhead", status: "completed", conclusion: "success" }); + runs.set("ci-e2e-fake.yml@prhead", { id: 2, head_sha: "prhead", status: "completed", conclusion: "failure" }); + const outFile = path.join(import.meta.dirname, "probe-output.txt"); + try { + const r = await gate(["--probe-reuse"], { + REQUIRED_CI_WORKFLOWS: "ci.yml,ci-e2e-fake.yml", + EXTRA_MATCH_SHAS: "prhead", + GITHUB_OUTPUT: outFile, + }); + assert.equal(r.code, 0, r.out); + assert.match(r.out, /reuse probe: NOT ALL 2 lanes reusable/); + assert.ok(readFileSync(outFile, "utf8").includes("allLanesReused=no")); + } finally { + rmSync(outFile, { force: true }); + } +}); + +test("release-ci-gate dispatch: CI_FULL_DISPATCH sends inputs.full for ci.yml only", async () => { + resetState(); + runs.set("ci-e2e.yml@publish", { id: 1, head_sha: "publish", status: "completed", conclusion: "success" }); + const r = await gate(["--dispatch"], { + REQUIRED_CI_WORKFLOWS: "ci.yml,ci-e2e.yml", + CI_FULL_DISPATCH: "1", + }); + assert.equal(r.code, 0, r.out); + assert.deepEqual(dispatchBodies, [{ ref: "master", inputs: { full: true } }]); + assert.match(r.out, /dispatched ci\.yml at ref master \(full scope\)/); +}); + let port = 0; test.before(async () => { mock.listen(0, "127.0.0.1");