From e6ce1d796dbbdb08b07b3cc2c3ea648431f5e670 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 3 Dec 2026 15:35:18 -0800 Subject: [PATCH] Publishing a release runs again only what no passing CI run checked The release gate now looks for a commit whose CI passed and whose tree differs from the release commit's only in the release files and tests: the release commit itself, its first parents, or main's. The same tree runs nothing again; release files alone run their checks; changed tests run on their own, in each engine CI runs them in; anything else, or anything unreadable, runs the full suite. A revert back to a tree that passed is that tree, and a final reuses its candidate's publish checks. v1.2.10's last release PR changed one test on top of a revert, and each of its publishes ran the whole suite while a flaky WebKit crash failed it. --- .github/workflows/ci.yml | 8 +- .github/workflows/publish-release.yml | 105 +++- docs/releasing.md | 81 ++- scripts/ci-changes.ts | 61 +- scripts/release-ci-gate-script.test.ts | 121 ++++ scripts/release-ci-gate.fixture.ts | 297 ++++++++++ scripts/release-ci-gate.test.ts | 755 +++++++++++++++---------- scripts/release-ci-gate.ts | 717 +++++++++++++++++++---- scripts/release-publish-order.test.ts | 108 +++- 9 files changed, 1749 insertions(+), 504 deletions(-) create mode 100644 scripts/release-ci-gate-script.test.ts create mode 100644 scripts/release-ci-gate.fixture.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a96c710ffe..5bfd3caf10 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,10 +19,10 @@ permissions: contents: read # The newest push on a pull request wins. Every commit on main keeps its own run, for the badge and -# for the release: publishing a release relies on main's CI having passed on the commit the release -# PR merged onto (scripts/release-ci-gate.ts). In one group, a push landing while another commit's -# run was in progress replaced the pending run of the commit before it, and that commit never got a -# result. +# for the release: publishing a release relies on main's CI having passed on a commit whose tree +# differs from the release's only in what it runs again (scripts/release-ci-gate.ts). In one group, +# a push landing while another commit's run was in progress replaced the pending run of the commit +# before it, and that commit never got a result. # # `github.workflow` keeps the release's own call of these checks out of main's group. A called # workflow sees its caller's context, so without it Publish release's checks shared diff --git a/.github/workflows/publish-release.yml b/.github/workflows/publish-release.yml index bd00b9ed4d..db61e6d1d6 100644 --- a/.github/workflows/publish-release.yml +++ b/.github/workflows/publish-release.yml @@ -253,40 +253,53 @@ jobs: echo "becomes_latest=$becomes_latest" >> "$GITHUB_OUTPUT" echo "$VERSION becomes the latest release: $becomes_latest." - # Whether the full CI suite runs again on the release commit (scripts/release-ci-gate.ts). A release - # PR that changes only the release files (the versions, CHANGELOG.md and release-policy.json), - # merged onto a commit main's CI passed, has a tree that has already been through every check, so - # `checks` below is skipped and that run stands in for it. Anything else in the diff, or a parent - # whose CI did not pass, runs the full suite as before. When the suite is skipped, the checks CI - # makes that read the release files run here instead, so a changelog or policy edited in the - # release PR is still held to them. + # What runs on the release commit (scripts/release-ci-gate.ts): no test runs again on a tree that + # already passed it. The gate looks for a commit whose CI passed (the release commit itself, its + # first parents, or main's) and whose tree differs from the release commit's in nothing a run + # would check differently, and runs only the difference: + # + # - `reuse`, the same tree, a revert back to a tree that passed included: nothing runs again, but + # the support window, which counts from the day of the release. + # - `release-files`, only the versions, CHANGELOG.md and release-policy.json differ: the checks + # that read them run here. + # - `tests`, only those and the suite's test files differ: the release-file checks and types run + # here, and the changed tests, in each engine they run in, in `release tests`. + # - `full`, anything else, or anything it cannot read: `checks` below runs the full suite. gate: name: checks needed needs: [metadata, verify] if: needs.metadata.outputs.is_release == 'true' runs-on: ubuntu-latest - # The decision waits up to 10 minutes for main's CI on the parent while it is still running + # The decision waits up to 10 minutes for CI still running on a commit that would stand in # (MAX_WAIT_SECONDS in the script), then the release-file checks below run. timeout-minutes: 20 permissions: contents: read - # To read main's CI runs. + # To read the CI runs that stand in. actions: read outputs: full_checks: ${{ steps.decide.outputs.full_checks }} + mode: ${{ steps.decide.outputs.mode }} + tests: ${{ steps.decide.outputs.tests }} + browser_tests: ${{ steps.decide.outputs.browser_tests }} + webkit_tests: ${{ steps.decide.outputs.webkit_tests }} + desktop_browser_tests: ${{ steps.decide.outputs.desktop_browser_tests }} steps: - # The release commit and its parent, which the decision compares. + # The release commit and the history it is compared with: its own first parents, and main's + # for a release branch. Without file contents, which the decision fetches for the few files it + # reads; the release commit's own tree is checked out whole. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: ${{ github.sha }} - fetch-depth: 2 + fetch-depth: 0 + filter: blob:none persist-credentials: false - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 with: bun-version: 1.4.3 no-cache: true - id: decide - name: Decide whether the full checks run again + name: Decide what runs again env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} run: bun scripts/release-ci-gate.ts "$GITHUB_SHA" @@ -295,18 +308,22 @@ jobs: # CI's `format, lint, types` job formats and lints package.json and the policy, and checks the # versions the release moved still agree with each other. - name: Format and lint - if: steps.decide.outputs.full_checks == 'false' + if: steps.decide.outputs.mode == 'release-files' || steps.decide.outputs.mode == 'tests' run: | set -euo pipefail bun run format:check bun run lint + # The changed tests are type checked, as CI's `format, lint, types` would. + - name: Types + if: steps.decide.outputs.mode == 'tests' + run: bun run typecheck - name: Desktop version tracks the release version - if: steps.decide.outputs.full_checks == 'false' + if: steps.decide.outputs.mode == 'release-files' || steps.decide.outputs.mode == 'tests' run: bun desktop/scripts/desktop-version.ts check # Every test that reads the changelog or the policy, found by name so a new one is included # without anybody adding it here. - name: The tests that read CHANGELOG.md and release-policy.json - if: steps.decide.outputs.full_checks == 'false' + if: steps.decide.outputs.mode == 'release-files' || steps.decide.outputs.mode == 'tests' run: | set -euo pipefail tests=() @@ -329,9 +346,50 @@ jobs: if: steps.decide.outputs.full_checks == 'false' run: bun scripts/support-window.ts check --releases "$RUNNER_TEMP/releases.json" - # The same checks CI runs, against the commit being published, unless `gate` found the release - # commit is the release files on a commit main's CI passed. This or that run is the gate: nothing is - # built or tagged unless one of them passed on this tree. + # The test files the release commit changed from the tree whose CI passed, with every test that + # names one, when `gate` found nothing else changed: each in the engines CI runs it in, as CI's + # `tests (changed files)` runs them (scripts/ci-run-tests.ts). A browser test runs in Chromium, and + # in WebKit too when it asks for it; the desktop setup window's from desktop/. + release-tests: + name: release tests + needs: [metadata, verify, gate] + if: needs.metadata.outputs.is_release == 'true' && needs.gate.outputs.mode == 'tests' + runs-on: ubuntu-latest + timeout-minutes: 25 # installs the browsers it needs, then runs a few files + permissions: + contents: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.4.3 + no-cache: true + # The same installs as CI's, since a changed file can be anywhere the suite looks. + - run: bun install --frozen-lockfile + - run: bun install --frozen-lockfile + working-directory: agent-mastra + - run: bun install --frozen-lockfile + working-directory: desktop + - name: Install Chromium + if: needs.gate.outputs.browser_tests != '[]' || needs.gate.outputs.desktop_browser_tests != '[]' + run: bunx playwright-core install --with-deps --no-shell chromium + - name: Install WebKit + if: needs.gate.outputs.webkit_tests != '[]' + run: bunx playwright-core install --with-deps webkit + - name: Run the changed tests + env: + TESTS: ${{ needs.gate.outputs.tests }} + BROWSER_TESTS: ${{ needs.gate.outputs.browser_tests }} + WEBKIT_TESTS: ${{ needs.gate.outputs.webkit_tests }} + DESKTOP_BROWSER_TESTS: ${{ needs.gate.outputs.desktop_browser_tests }} + run: bun scripts/ci-run-tests.ts + + # The same checks CI runs, against the commit being published, unless `gate` found a tree whose CI + # passed that differs from this one only in the release files and tests. This or that run is the + # gate: nothing is built or tagged unless one of them passed on this tree. checks: needs: [metadata, verify, gate] if: needs.metadata.outputs.is_release == 'true' && needs.gate.outputs.full_checks == 'true' @@ -354,15 +412,18 @@ jobs: # decision made in `verify`, the same one that marks the GitHub release Latest: whoever pulls # `latest` gets the newest stable release, never a candidate, a beta or an older patch. # - # After `checks` passed, or after `gate` passed having decided `checks` need not run. Nothing else: - # a `checks` skipped for any other reason, or a `gate` that failed, publishes nothing. + # After `checks` passed, or after `gate` passed having decided `checks` need not run, and the + # changed tests passed when it decided they run. Nothing else: a `checks` or `release tests` + # skipped for any other reason, or a `gate` that failed, publishes nothing. images: - needs: [metadata, verify, gate, checks] + needs: [metadata, verify, gate, release-tests, checks] if: >- !cancelled() && needs.metadata.outputs.is_release == 'true' && needs.verify.result == 'success' && needs.gate.result == 'success' && (needs.checks.result == 'success' || - (needs.checks.result == 'skipped' && needs.gate.outputs.full_checks == 'false')) + (needs.checks.result == 'skipped' && needs.gate.outputs.full_checks == 'false' && + (needs.release-tests.result == 'success' || + (needs.release-tests.result == 'skipped' && needs.gate.outputs.mode != 'tests')))) uses: $/.github/workflows/images.yml with: ref: ${{ github.sha }} diff --git a/docs/releasing.md b/docs/releasing.md index 564250c729..1d0d65a2d9 100644 --- a/docs/releasing.md +++ b/docs/releasing.md @@ -1026,8 +1026,9 @@ Then, in order: - the version in the tree is checked against the branch that is publishing it, and the changelog is checked for a section with that number - the commit is checked, as described under [What has to be green](#what-has-to-be-green): the full - CI suite, or, when the release PR changed only the release files on a commit main's CI passed, - that run and the checks that read the release files + CI suite, or, when a commit CI passed has a tree that differs from the release commit's only in + the release files and tests, that run and only what differs: nothing for the same tree, the checks + that read the release files, and the changed tests - the OpenBot images, `ghcr.io/copilotkit/openbot` (the server and every Bot's computer) and `openbot-supervisor`, are taken at the tag `backend-images.env` names, the release's version, and pinned by digest in `container-images.json`, where `openbot`, `server` and `agent-computer` @@ -1140,29 +1141,59 @@ and refuses to publish without (see [What merging does](#what-merging-does)). These checks gate the publish rather than the proposal, which is why the release PR arriving without its own checks does not matter: a pull request opened by a workflow does not trigger them. When the release PR merges, the publish workflow's `checks needed` job -([`scripts/release-ci-gate.ts`](../scripts/release-ci-gate.ts)) decides whether they run again on the -release commit: - -- When the release commit changes nothing but the release files from the commit it merged onto - (its first parent), and main's CI passed on that commit, they do not. That commit's tree has been - through all of them already. The release files are `CHANGELOG.md` and `release-policy.json`, which - may change freely, and the `version` in `package.json`, the `OPENBOT_BACKEND_TAG` line in - `backend-images.env` and the `openbot-desktop` version line in - `desktop/src-tauri/Cargo.toml` and `Cargo.lock`, which may change nothing else. Only a run of `ci.yml` for a push to this repository's `main`, at - exactly that commit, counts; a pull request's run tests a merge of the PR, not the commit, and - skips the component dockerfile checks unless it was labelled `full-ci`. A run still in progress is waited for, up to 10 minutes; past that the full checks run. In - their place the job re-runs the checks that read the files the release did change: formatting and - lint, the desktop version against `package.json`, and every test that names - `CHANGELOG.md` or `release-policy.json`. -- Otherwise they all run again, as before: when any other path is added, removed, renamed or - changed, when a version file changes more than its version, or when main's CI on that commit - failed, was cancelled, never ran, could not be read, or was still running after the wait. - -The diff is read with renames turned off, so a source file moved onto a release file's name is still -seen as the source file it removed. Every commit on `main` keeps its own CI run for this (the -`concurrency` group in `ci.yml` is per commit on `main`), so a commit pushed while another's run was -in progress still gets a result. A final's parent is its candidate on `release/X.Y`, which main's CI -never ran on, so a final always runs the full suite. +([`scripts/release-ci-gate.ts`](../scripts/release-ci-gate.ts)) decides what runs again on the +release commit. A test is never run again on code that already passed it: the job looks for a +commit whose CI passed and whose tree differs from the release commit's in nothing a run would check +differently, and runs only the difference. + +The commits it looks at are the release commit itself, its first parents (along `main`, or along the +`release/X.Y` branch it publishes on) and `main`'s first parents, 50 of each. It compares trees, not +history, so a revert back to a tree that passed is that tree, and a candidate that carries main's tree +at a commit is that commit's tree. Of the commits that qualify, it uses the one that leaves the least +to run, then the nearest: + +- **Same tree.** CI already passed on exactly this tree, on the release commit itself (a second + attempt at the publish, once main's run of it passed, or the merge queue's run) or on any commit + with the same tree, such as the commit before a change that was then reverted. Nothing runs again + but the 12-month support window, which counts from the day of the release. +- **Release files only.** The trees differ only in the release files: `CHANGELOG.md` and + `release-policy.json`, which may change freely, and the `version` in `package.json`, the + `OPENBOT_BACKEND_TAG` line in `backend-images.env` and the `openbot-desktop` version line in + `desktop/src-tauri/Cargo.toml` and `Cargo.lock`, which may change nothing else. The job runs the + checks that read them: formatting and lint, the desktop version against `package.json`, every + test that names `CHANGELOG.md` or `release-policy.json`, and the support window. +- **Release files and tests.** The trees differ only in those and in the suite's test files, each + added or changed, none deleted. The job runs the release-file checks and type checks the tree, and + `release tests` runs the changed test files, with every test that names one, in each engine CI + runs them in: `bun test`, a real Chromium for a browser test, WebKit as well for one on the + WebKit job's list in `ci.yml` or that asks for it, and the desktop setup window's browser for one + under `desktop/` ([`scripts/ci-run-tests.ts`](../scripts/ci-run-tests.ts)). +- **Anything else: the full suite.** Any other path added, removed, renamed or changed (the app, + `shared/`, `desktop/src-tauri`, the server-facing code, a workflow, a fixture, a Python harness's + or the TypeScript engine's test, the docs), a deleted test, a version file that changes more than + its version, a diff or a list of engines that could not be read, or no such commit whose CI passed. + +A commit's CI passed when one run that tested it finished with every job succeeded or skipped: a run +of `ci.yml` for a push to this repository's `main` or main's merge queue at exactly that commit, or a +Publish release run at that commit whose own `checks` ran and passed (`checks / verify`). A pull +request's run tests a merge of the PR, not the commit, so it never counts, and neither does the +publish deciding. A run still in progress on an older commit is waited for, up to 10 minutes, unless +another commit that qualifies has already passed; past that the full suite runs. main's push run of the release +commit itself is not waited for: it is the full suite on this tree, just started, and waiting would +only start the same suite later. CI that cannot be read means the full suite. + +On v1.2.10 this would have run one changed test and the one test that names it. Its last release PR +sat on a revert of a change taken back out of the release, and changed one browser test, so its tree +differs from the last commit CI passed before that change only in the release files and that test. +Each of its publishes ran the whole suite instead, and the same flaky WebKit crash failed each one. + +The diff is read with renames turned off, so a source file moved onto a release file's or a test's +name is still seen as the source file it removed. Every commit on `main` keeps its own CI run for +this (the `concurrency` group in `ci.yml` is per commit on `main`), so a commit pushed while another's +run was in progress still gets a result. A final's parent is its candidate on `release/X.Y`, which +main's CI never ran on; the candidate's own publish ran every check on it, so a final that changes +only the release files runs only their checks, and the full suite when the candidate's publish relied +on another run instead. The release PR's own CI run is as small, for the same reason ([`scripts/ci-changes.ts`](../scripts/ci-changes.ts)). A PR labelled `release`, from this repository's diff --git a/scripts/ci-changes.ts b/scripts/ci-changes.ts index 9939166665..df092cf1b5 100644 --- a/scripts/ci-changes.ts +++ b/scripts/ci-changes.ts @@ -671,18 +671,7 @@ function decideSuite( ); } - for (const file of [...candidates].sort()) { - if (!isBrowserTest(file, deps)) { - decision.tests.push(file); - } else if (file.startsWith("desktop/")) { - decision.desktopBrowserTests.push(file); - } else { - decision.browserTests.push(file); - if (deps.read(file)?.includes("OPENBOT_APP_ENGINES")) { - decision.webkitTests.push(file); - } - } - } + Object.assign(decision, byEngine([...candidates], deps.read)); run.partial = decision.tests.length + decision.browserTests.length + @@ -707,6 +696,43 @@ function isBrowserTest(file: string, deps: Pick): boolean { ); } +/** The suite's test files to run on their own, sorted by the engines each runs in. */ +export type TestsByEngine = Pick< + Decision, + "tests" | "browserTests" | "webkitTests" | "desktopBrowserTests" +>; + +/** + * Sorts test files by where each runs, as the jobs that run the whole suite run them: `bun test`; + * a real browser, Chromium, for one that drives it, and WebKit as well for one that asks for it + * (OPENBOT_APP_ENGINES), as `app (real browser)` and its WebKit job do; and the desktop setup + * window's browser, from desktop/. + */ +export function byEngine( + files: string[], + read: (path: string) => string | undefined, +): TestsByEngine { + const sorted: TestsByEngine = { + tests: [], + browserTests: [], + webkitTests: [], + desktopBrowserTests: [], + }; + for (const file of [...new Set(files)].sort()) { + if (!isBrowserTest(file, { read })) { + sorted.tests.push(file); + } else if (file.startsWith("desktop/")) { + sorted.desktopBrowserTests.push(file); + } else { + sorted.browserTests.push(file); + if (read(file)?.includes("OPENBOT_APP_ENGINES")) { + sorted.webkitTests.push(file); + } + } + } + return sorted; +} + function releaseDecision( workflow: Workflow, rules: Rule[], @@ -932,16 +958,7 @@ export function decideMergeGroup( .mentions(changed.filter((path) => !isIgnored(path))) .filter(isBunTest) .sort(); - for (const file of named) { - if (!isBrowserTest(file, deps)) decision.tests.push(file); - else if (file.startsWith("desktop/")) - decision.desktopBrowserTests.push(file); - else { - decision.browserTests.push(file); - if (deps.read(file)?.includes("OPENBOT_APP_ENGINES")) - decision.webkitTests.push(file); - } - } + Object.assign(decision, byEngine(named, deps.read)); run.partial = named.length > 0; decision.reasons.push( run.partial diff --git a/scripts/release-ci-gate-script.test.ts b/scripts/release-ci-gate-script.test.ts new file mode 100644 index 0000000000..c5dbf27c70 --- /dev/null +++ b/scripts/release-ci-gate-script.test.ts @@ -0,0 +1,121 @@ +/** + * scripts/release-ci-gate.ts as publish-release.yml's `checks needed` runs it: on a real history, + * with `gh` answering from the CI runs as the Actions API does, read back from $GITHUB_OUTPUT. + */ +import { afterEach, expect, test } from "bun:test"; +import { + ciRun, + cleanUp, + commit, + fakeGh, + GREEN_CI, + git, + mainAt, + publishRun, + queueRun, + release, + runGate, + write, +} from "./release-ci-gate.fixture"; + +afterEach(cleanUp); + +// v1.2.10's release, as it happened: a change merged after the last green commit, a release PR on +// it whose publish failed, a release PR taking the change back out, and a last release PR that also +// made one browser test survive a WebKit renderer crash. Every publish ran the whole suite again, +// and the same flaky crash failed each one. The tree differs from the last green commit only in the +// release files and that test, so only that test runs, in Chromium and in WebKit, with the test that +// names it. Before this change, the full suite. +test("regression: v1.2.10's last release PR runs only its changed test, not the whole suite", () => { + const { repo, parent: green } = mainAt(); + write(repo, { "server/src/index.ts": "export const answer = 'cedar';\n" }); + const cedar = commit(repo, "Boundaries on Cedar (#2880)"); + const firstRelease = release(repo); + write(repo, { "server/src/index.ts": "export const answer = 42;\n" }); + const revert = commit( + repo, + "Take Cedar boundaries (#2880) back out of 1.2.10 (#2903)", + ); + write(repo, { + "app/tests/sidebar-current-row.test.tsx": + 'const asked = process.env.OPENBOT_APP_BROWSER === "1";\ntest("survives a WebKit renderer crash", () => {});\n', + }); + const sha = commit( + repo, + "Release v1.2.10: the sidebar test survives a WebKit renderer crash (#2905)", + ); + const bin = fakeGh( + [ + ciRun({ id: 47207322412, head_sha: green }), + queueRun({ id: 47204828592, head_sha: green }), + ciRun({ id: 47210000001, head_sha: cedar, conclusion: "failure" }), + publishRun({ + id: 47216728264, + head_sha: firstRelease, + conclusion: "failure", + }), + ciRun({ id: 47217642701, head_sha: revert, conclusion: "failure" }), + // main's push run of the release commit, started with the publish. + ciRun({ + id: 47223608122, + head_sha: sha, + status: "in_progress", + conclusion: null, + }), + // The publish deciding. + publishRun({ + id: 1, + head_sha: sha, + status: "in_progress", + conclusion: null, + }), + ], + { 47207322412: GREEN_CI, 47204828592: GREEN_CI }, + ); + const { exitCode, stdout, outputs } = runGate(repo, bin, sha); + expect(exitCode).toBe(0); + expect(outputs.full_checks).toBe("false"); + expect(outputs.mode).toBe("tests"); + expect(outputs.baseline).toBe(green); + expect(JSON.parse(outputs.tests ?? "")).toEqual([ + "app/tests/no-fixed-settle-waits.test.ts", + ]); + expect(JSON.parse(outputs.browser_tests ?? "")).toEqual([ + "app/tests/sidebar-current-row.test.tsx", + ]); + expect(JSON.parse(outputs.webkit_tests ?? "")).toEqual([ + "app/tests/sidebar-current-row.test.tsx", + ]); + expect(stdout).toContain( + "https://github.com/CopilotKit/OpenBot/actions/runs/47207322412", + ); +}); + +// A second attempt at the same publish, once main's run of the release commit has passed. +test("the release commit's own run that passed means nothing runs again", () => { + const { repo, parent } = mainAt(); + const sha = release(repo, { "server/src/index.ts": "export const x = 1;\n" }); + const bin = fakeGh( + [ + ciRun({ head_sha: parent, conclusion: "failure" }), + ciRun({ id: 47223608122, head_sha: sha }), + ], + { 47223608122: GREEN_CI }, + ); + const { exitCode, outputs } = runGate(repo, bin, sha); + expect(exitCode).toBe(0); + expect(outputs.full_checks).toBe("false"); + expect(outputs.mode).toBe("reuse"); + expect(outputs.baseline).toBe(sha); + expect(git(repo, "rev-parse", "HEAD")).toBe(sha); +}); + +test("the full suite runs when no run the API answers with can stand in", () => { + const { repo, parent } = mainAt(); + const sha = release(repo); + const bin = fakeGh([ciRun({ head_sha: parent, conclusion: "failure" })], {}); + const { exitCode, outputs } = runGate(repo, bin, sha); + expect(exitCode).toBe(0); + expect(outputs.full_checks).toBe("true"); + expect(outputs.mode).toBe("full"); +}); diff --git a/scripts/release-ci-gate.fixture.ts b/scripts/release-ci-gate.fixture.ts new file mode 100644 index 0000000000..e467d58e4b --- /dev/null +++ b/scripts/release-ci-gate.fixture.ts @@ -0,0 +1,297 @@ +/** + * The histories and CI runs the release gate's tests decide on (release-ci-gate.test.ts and + * release-ci-gate-script.test.ts): real git repositories in a temporary directory, the Actions API's + * shapes for runs and jobs, and a `gh` that answers `gh api` from them as the Actions API does. + * + * Nothing here imports the gate, so the script's own test runs against any version of it. + */ +import { expect } from "bun:test"; +import { + chmodSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; + +export const REPOSITORY = "CopilotKit/OpenBot"; +export const CI_PATH = ".github/workflows/ci.yml"; +export const PUBLISH_PATH = ".github/workflows/publish-release.yml"; + +/** A workflow run's fields as the Actions API returns them. */ +export type Run = { + id: number; + html_url: string; + path: string; + event: string; + head_branch: string | null; + head_sha: string; + status: string; + conclusion: string | null; + head_repository?: { full_name?: string } | null; +}; + +/** A job's fields as the Actions API returns them. */ +export type Job = { name: string; conclusion: string | null }; + +const made: string[] = []; + +/** Removes every directory made since the last call. For afterEach. */ +export function cleanUp() { + for (const dir of made.splice(0)) + rmSync(dir, { recursive: true, force: true }); +} + +function tempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + made.push(dir); + return dir; +} + +export function git(repo: string, ...args: string[]): string { + const result = Bun.spawnSync(["git", "-C", repo, ...args]); + if (result.exitCode !== 0) { + throw new Error(`${args.join(" ")}: ${result.stderr.toString()}`); + } + return result.stdout.toString().trim(); +} + +export function write(repo: string, files: Record) { + for (const [path, text] of Object.entries(files)) { + mkdirSync(dirname(join(repo, path)), { recursive: true }); + writeFileSync(join(repo, path), text); + } +} + +export function commit(repo: string, message: string): string { + git(repo, "add", "-A"); + git( + repo, + "-c", + "user.name=Test", + "-c", + "user.email=test@example.com", + "commit", + "-q", + "--allow-empty", + "-m", + message, + ); + return git(repo, "rev-parse", "HEAD"); +} + +export const pkg = (version: string, extra: Record = {}) => + `${JSON.stringify({ name: "openbot", version, ...extra }, null, 2)}\n`; +export const lock = (desktop: string, serde = "1.0.0") => + `[[package]]\nname = "openbot-desktop"\nversion = "${desktop}"\n\n[[package]]\nname = "serde"\nversion = "${serde}"\n`; +export const cargo = (version: string) => + `[package]\nname = "openbot-desktop"\nversion = "${version}"\nedition = "2021"\n`; +export const images = (tag: string, comment = "# The OpenBot images.") => + `${comment}\nOPENBOT_BACKEND_TAG=${tag}\n`; +export const policy = (version: string, from: string[]) => + `${JSON.stringify({ version, upgrade: { fromVersions: from } }, null, 2)}\n`; + +/** ci.yml's WebKit job, naming its list one file a line as the real one does. */ +export const CI_YML = `name: CI +jobs: + app-browser-webkit: + steps: + - run: | + files=( + app/tests/sidebar-current-row.test.tsx + ) + bun test "\${files[@]}" +`; + +/** The tests main carries: a browser test on the WebKit list, two plain ones, one naming another. */ +export const TESTS = { + "app/tests/sidebar-current-row.test.tsx": + 'const asked = process.env.OPENBOT_APP_BROWSER === "1";\ntest("the current row", () => {});\n', + "app/tests/composer.test.tsx": 'test("the composer", () => {});\n', + "scripts/release-version.test.ts": 'test("the version", () => {});\n', + "app/tests/no-fixed-settle-waits.test.ts": + "// Holds app/tests/sidebar-current-row.test.tsx to waiting on what it waits for.\n", +}; + +/** main at 0.3.1, as a release PR is cut from it. */ +export function mainAt(): { repo: string; parent: string } { + const repo = tempDir("openbot-ci-gate-"); + git(repo, "init", "-q", "-b", "main"); + write(repo, { + "package.json": pkg("0.3.1"), + "desktop/src-tauri/Cargo.toml": cargo("0.3.1"), + "desktop/src-tauri/Cargo.lock": lock("0.3.1"), + "backend-images.env": images("main"), + "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- A fix.\n\n## 0.3.1\n", + "release-policy.json": policy("v0.3.1", ["v0.3.0"]), + "server/src/index.ts": "export const answer = 42;\n", + "app/src/home.tsx": "export const Home = () => null;\n", + [CI_PATH]: CI_YML, + ...TESTS, + }); + return { repo, parent: commit(repo, "main") }; +} + +/** What Create release PR writes for 0.3.2, plus whatever else the PR carries. */ +export function release( + repo: string, + extra: Record = {}, +): string { + write(repo, { + "package.json": pkg("0.3.2"), + "desktop/src-tauri/Cargo.toml": cargo("0.3.2"), + "desktop/src-tauri/Cargo.lock": lock("0.3.2"), + "backend-images.env": images("v0.3.2"), + "CHANGELOG.md": + "# Changelog\n\n## Unreleased\n\n## 0.3.2\n\n- A fix.\n\n## 0.3.1\n", + "release-policy.json": policy("v0.3.2", ["v0.3.1", "v0.3.0"]), + ...extra, + }); + return commit(repo, "Release v0.3.2"); +} + +let ids = 100; + +/** main's CI on a push, finished and passed unless told otherwise. */ +export function ciRun(overrides: Partial & { head_sha: string }): Run { + const id = overrides.id ?? ids++; + return { + id, + html_url: `https://github.com/CopilotKit/OpenBot/actions/runs/${id}`, + path: CI_PATH, + event: "push", + head_branch: "main", + status: "completed", + conclusion: "success", + head_repository: { full_name: REPOSITORY }, + ...overrides, + }; +} + +/** CI's run in main's merge queue on the commit it merged: what a queue merge leaves at the commit. */ +export function queueRun(overrides: Partial & { head_sha: string }): Run { + return ciRun({ + event: "merge_group", + head_branch: + "gh-readonly-queue/main/pr-2581-bff854d1ab9cc25580bd3efa3308a7f954069c5c", + ...overrides, + }); +} + +/** A Publish release run on a release commit, as it shows on the commit's push. */ +export function publishRun( + overrides: Partial & { head_sha: string }, +): Run { + return ciRun({ path: PUBLISH_PATH, ...overrides }); +} + +/** A passing run's jobs as the API lists them: some run, some skipped as nothing they read changed. */ +export const GREEN_CI: Job[] = [ + { name: "changes", conclusion: "success" }, + { name: "format, lint, types", conclusion: "success" }, + { name: "tests (shard 1 of 5)", conclusion: "success" }, + { name: "tests (changed files)", conclusion: "skipped" }, + { name: "verify", conclusion: "success" }, +]; + +/** A passing publish whose own `checks` ran, as v1.2.10's second attempt's jobs read. */ +export const GREEN_PUBLISH: Job[] = [ + { name: "classify", conclusion: "success" }, + { name: "checks needed", conclusion: "success" }, + { name: "checks / tests (shard 1 of 5)", conclusion: "success" }, + { name: "checks / tests (changed files)", conclusion: "skipped" }, + { name: "checks / verify", conclusion: "success" }, + { name: "images", conclusion: "success" }, +]; + +/** + * A `gh` that answers `gh api` from `runs` and `jobs` as the Actions API does: the runs at a commit + * (all workflows, or one), a run's jobs, a page at a time, and 404 for anything else. Returns the + * directory to put first on PATH. + */ +export function fakeGh(runs: Run[], jobs: Record): string { + const dir = tempDir("openbot-ci-gate-gh-"); + const state = join(dir, "api.json"); + writeFileSync(state, JSON.stringify({ runs, jobs })); + const bin = join(dir, "bin"); + mkdirSync(bin, { recursive: true }); + writeFileSync( + join(bin, "gh"), + `#!${process.execPath} +const { runs, jobs } = JSON.parse(require("node:fs").readFileSync(${JSON.stringify(state)}, "utf8")); +const [command, path] = process.argv.slice(2); +const url = new URL(path ?? "", "https://api.github.com/"); +const page = Number(url.searchParams.get("page") ?? 1); +const per = Number(url.searchParams.get("per_page") ?? 30); +const slice = (list) => list.slice((page - 1) * per, page * per); +let match; +if (command !== "api") { + console.error("unknown command"); + process.exit(1); +} else if ((match = /^\\/repos\\/[^/]+\\/[^/]+\\/actions\\/(?:workflows\\/([^/]+)\\/)?runs$/.exec(url.pathname))) { + const all = runs.filter((run) => run.head_sha === url.searchParams.get("head_sha") && + (!match[1] || run.path === ".github/workflows/" + match[1])); + console.log(JSON.stringify({ total_count: all.length, workflow_runs: slice(all) })); +} else if ((match = /^\\/repos\\/[^/]+\\/[^/]+\\/actions\\/runs\\/(\\d+)\\/jobs$/.exec(url.pathname)) && jobs[match[1]]) { + const all = jobs[match[1]]; + console.log(JSON.stringify({ total_count: all.length, jobs: slice(all) })); +} else { + console.error("gh: Not Found (HTTP 404)"); + process.exit(1); +} +`, + ); + chmodSync(join(bin, "gh"), 0o755); + return bin; +} + +/** + * Runs scripts/release-ci-gate.ts in `repo` on `sha`, as publish-release.yml's `checks needed` runs + * it, with the `gh` in `bin`, and reads back what it wrote to $GITHUB_OUTPUT. + */ +export function runGate(repo: string, bin: string, sha: string) { + const output = join(dirname(bin), "output"); + writeFileSync(output, ""); + const PATH = `${bin}:${process.env.PATH}`; + // The fake is the `gh` the script finds, so no real API is reached. + expect(Bun.which("gh", { PATH })).toBe(join(bin, "gh")); + const result = Bun.spawnSync( + [process.execPath, join(import.meta.dir, "release-ci-gate.ts"), sha], + { + cwd: repo, + env: { + ...process.env, + PATH, + GITHUB_REPOSITORY: REPOSITORY, + GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: "", + GITHUB_RUN_ID: "1", + CI_WAIT_SECONDS: "0", + }, + }, + ); + // Both forms Actions reads: name=value, and name< = {}; + const lines = readFileSync(output, "utf8").split("\n"); + for (let index = 0; index < lines.length; index++) { + const line = lines[index] ?? ""; + const heredoc = /^([\w-]+)<<(.+)$/.exec(line); + if (heredoc?.[1] && heredoc[2]) { + const end = lines.indexOf(heredoc[2], index + 1); + outputs[heredoc[1]] = lines.slice(index + 1, end).join("\n"); + index = end; + } else if (line.includes("=")) { + outputs[line.slice(0, line.indexOf("="))] = line.slice( + line.indexOf("=") + 1, + ); + } + } + return { + exitCode: result.exitCode, + stdout: result.stdout.toString(), + outputs, + }; +} diff --git a/scripts/release-ci-gate.test.ts b/scripts/release-ci-gate.test.ts index 10c536cd85..616add0b1d 100644 --- a/scripts/release-ci-gate.test.ts +++ b/scripts/release-ci-gate.test.ts @@ -1,212 +1,320 @@ /** - * When publishing a release may rely on main's CI instead of running the whole suite again on the - * release commit, and when it may not. The diff is read from a real repository, as the publish - * workflow reads it; main's CI runs are the Actions API's shape, standing in for the API. + * What publishing a release runs on the release commit: nothing again on a tree CI already passed, + * the release-file checks when only the release files differ from one, only the changed tests when + * tests differ too, and the full suite for anything else. The histories are real repositories + * (release-ci-gate.fixture.ts), read the way the publish workflow reads them (localDeps); the CI + * runs and jobs are the Actions API's shapes. release-ci-gate-script.test.ts runs the script itself. */ import { afterEach, expect, test } from "bun:test"; -import { - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - writeFileSync, -} from "node:fs"; -import { tmpdir } from "node:os"; -import { dirname, join } from "node:path"; +import { readFileSync, rmSync } from "node:fs"; +import { join } from "node:path"; import { allowedDiff, changedFiles } from "./release-candidate-check"; import { CI_WORKFLOW, + type CiJob, type CiRun, - ciOnParent, + ciAt, + compareTrees, decide, type GateDeps, + localDeps, + MAIN_REF, MAX_WAIT_SECONDS, + PUBLISH_WORKFLOW, releaseFileViolations, + webkitList, } from "./release-ci-gate"; - -const REPOSITORY = "CopilotKit/OpenBot"; -const repos: string[] = []; -afterEach(() => { - for (const repo of repos.splice(0)) - rmSync(repo, { recursive: true, force: true }); -}); - -function run(repo: string, ...args: string[]): string { - const result = Bun.spawnSync(["git", "-C", repo, ...args]); - if (result.exitCode !== 0) { - throw new Error(`${args.join(" ")}: ${result.stderr.toString()}`); - } - return result.stdout.toString().trim(); -} - -function write(repo: string, files: Record) { - for (const [path, text] of Object.entries(files)) { - mkdirSync(dirname(join(repo, path)), { recursive: true }); - writeFileSync(join(repo, path), text); - } -} - -function commit(repo: string, message: string): string { - run(repo, "add", "-A"); - run( - repo, - "-c", - "user.name=Test", - "-c", - "user.email=test@example.com", - "commit", - "-q", - "-m", - message, - ); - return run(repo, "rev-parse", "HEAD"); -} - -const pkg = (version: string, extra: Record = {}) => - `${JSON.stringify({ name: "openbot", version, ...extra }, null, 2)}\n`; -const lock = (desktop: string, serde = "1.0.0") => - `[[package]]\nname = "openbot-desktop"\nversion = "${desktop}"\n\n[[package]]\nname = "serde"\nversion = "${serde}"\n`; -const cargo = (version: string) => - `[package]\nname = "openbot-desktop"\nversion = "${version}"\nedition = "2021"\n`; -const images = (tag: string, comment = "# The OpenBot images.") => - `${comment}\nOPENBOT_BACKEND_TAG=${tag}\n`; -const policy = (version: string, from: string[]) => - `${JSON.stringify({ version, upgrade: { fromVersions: from } }, null, 2)}\n`; - -/** main at 0.3.1, as a release PR is cut from it. */ -function mainAt(): { repo: string; parent: string } { - const repo = mkdtempSync(join(tmpdir(), "openbot-ci-gate-")); - repos.push(repo); - run(repo, "init", "-q", "-b", "main"); - write(repo, { - "package.json": pkg("0.3.1"), - "desktop/src-tauri/Cargo.toml": cargo("0.3.1"), - "desktop/src-tauri/Cargo.lock": lock("0.3.1"), - "backend-images.env": images("main"), - "CHANGELOG.md": "# Changelog\n\n## Unreleased\n\n- A fix.\n\n## 0.3.1\n", - "release-policy.json": policy("v0.3.1", ["v0.3.0"]), - "server/src/index.ts": "export const answer = 42;\n", - }); - return { repo, parent: commit(repo, "main") }; -} - -/** What Create release PR writes for 0.3.2, plus whatever else the PR carries. */ -function release(repo: string, extra: Record = {}): string { - write(repo, { - "package.json": pkg("0.3.2"), - "desktop/src-tauri/Cargo.toml": cargo("0.3.2"), - "desktop/src-tauri/Cargo.lock": lock("0.3.2"), - "backend-images.env": images("v0.3.2"), - "CHANGELOG.md": - "# Changelog\n\n## Unreleased\n\n## 0.3.2\n\n- A fix.\n\n## 0.3.1\n", - "release-policy.json": policy("v0.3.2", ["v0.3.1", "v0.3.0"]), - ...extra, - }); - return commit(repo, "Release v0.3.2"); -} - -/** The changes, read from the repository as the script reads them. */ -function changesIn(repo: string) { - return (before: string, after: string) => changedFiles(before, after, repo); -} - -function ciRun(overrides: Partial & { head_sha: string }): CiRun { - return { - id: 1, - html_url: "https://github.com/CopilotKit/OpenBot/actions/runs/1", - path: CI_WORKFLOW, - event: "push", - head_branch: "main", - status: "completed", - conclusion: "success", - head_repository: { full_name: REPOSITORY }, - ...overrides, - }; -} - -/** The decision for the release commit at HEAD, with main's CI answering `answers` in turn. */ -function gate(repo: string, answers: CiRun[][], waitSeconds = 600) { +import { + CI_YML, + cargo, + ciRun, + cleanUp, + commit, + GREEN_CI, + GREEN_PUBLISH, + images, + lock, + mainAt, + pkg, + policy, + publishRun, + queueRun, + REPOSITORY, + release, + git as run, + write, +} from "./release-ci-gate.fixture"; + +afterEach(cleanUp); + +type Answers = Record | ((sha: string) => CiRun[]); + +/** The decision for the release commit at HEAD, with CI answering from `answers`. */ +function gate( + repo: string, + answers: Answers, + { + jobs = {}, + waitSeconds = 600, + currentRun, + overrides = {}, + }: { + jobs?: Record; + waitSeconds?: number; + currentRun?: number; + overrides?: Partial; + } = {}, +) { let clock = 0; - let asked = 0; + const asked: string[] = []; const slept: number[] = []; const deps: GateDeps = { - parent: (sha) => run(repo, "rev-parse", `${sha}^1`), - changes: changesIn(repo), - runs: () => answers[Math.min(asked++, answers.length - 1)] ?? [], + ...localDeps(repo), + runs: (sha) => { + asked.push(sha); + return typeof answers === "function" + ? answers(sha) + : (answers[sha] ?? []); + }, + jobs: (ciRun) => + jobs[ciRun.id] ?? + (ciRun.path === PUBLISH_WORKFLOW ? GREEN_PUBLISH : GREEN_CI), + currentRun, sleep: (seconds) => { slept.push(seconds); clock += seconds * 1000; }, now: () => clock, log: () => {}, + ...overrides, }; const sha = run(repo, "rev-parse", "HEAD"); return { + sha, decision: decide(sha, REPOSITORY, deps, { waitSeconds, pollSeconds: 30 }), - asked: () => asked, + asked, slept, }; } -test("a release PR as Create release PR writes it, onto a commit main's CI passed, skips the full checks", () => { +// Release-files-only: the small path. +test("a release PR of only the release files, onto a commit CI passed, runs only the release-file checks", () => { const { repo, parent } = mainAt(); release(repo); - const { decision } = gate(repo, [[ciRun({ head_sha: parent })]]); + const { decision } = gate(repo, { [parent]: [ciRun({ head_sha: parent })] }); + expect(decision.mode).toBe("release-files"); expect(decision.fullChecks).toBe(false); + expect(decision.baseline).toBe(parent); expect(decision.parent).toBe(parent); - expect(decision.reason).toContain("changes only release files"); + expect(decision.tests).toEqual([]); + expect(decision.browserTests).toEqual([]); + expect(decision.reason).toContain("only in the release files"); }); -// The point of the guard: a code change riding in the release PR is never published on the -// strength of a run that did not test it. -test("a code change sneaking into the release PR runs the full checks", () => { +// Test-only: just those files, in each engine they run in. +test("a release PR that changes tests runs only those tests, in every engine CI runs them in, and the tests that name them", () => { const { repo, parent } = mainAt(); - release(repo, { "server/src/index.ts": "export const answer = 43;\n" }); - const { decision, asked } = gate(repo, [[ciRun({ head_sha: parent })]]); - expect(decision.fullChecks).toBe(true); - expect(decision.reason).toContain( - "server/src/index.ts is not a release file", - ); - expect(asked()).toBe(0); + release(repo, { + "app/tests/sidebar-current-row.test.tsx": + 'const asked = process.env.OPENBOT_APP_BROWSER === "1";\ntest("the current row, once more after a crash", () => {});\n', + "scripts/release-version.test.ts": + 'test("the version, again", () => {});\n', + "desktop/tests/setup-window.test.ts": + 'const asked = process.env.OPENBOT_APP_BROWSER === "1";\n', + }); + const { decision } = gate(repo, { [parent]: [ciRun({ head_sha: parent })] }); + expect(decision.mode).toBe("tests"); + expect(decision.fullChecks).toBe(false); + expect(decision.baseline).toBe(parent); + // The plain test, and the one that names the browser test. + expect(decision.tests).toEqual([ + "app/tests/no-fixed-settle-waits.test.ts", + "scripts/release-version.test.ts", + ]); + // In Chromium, and in WebKit because ci.yml's WebKit job lists it. + expect(decision.browserTests).toEqual([ + "app/tests/sidebar-current-row.test.tsx", + ]); + expect(decision.webkitTests).toEqual([ + "app/tests/sidebar-current-row.test.tsx", + ]); + expect(decision.desktopBrowserTests).toEqual([ + "desktop/tests/setup-window.test.ts", + ]); + // Never a test nothing changed. + expect(decision.tests).not.toContain("app/tests/composer.test.tsx"); }); -test("a test, a workflow or a new file in the release PR runs the full checks", () => { - for (const extra of [ - { "tests/release-policy.test.ts": "test.todo('x');\n" }, - { ".github/workflows/ci.yml": "name: CI\n" }, - { "server/src/new.ts": "export {};\n" }, - { "desktop/intelligence-cli.json": '{"cli":"latest"}\n' }, - ]) { +test("a test that asks for WebKit itself runs there, list or not", () => { + const { repo, parent } = mainAt(); + release(repo, { + "app/tests/composer.test.tsx": + 'process.env.OPENBOT_APP_BROWSER;\nprocess.env.OPENBOT_APP_ENGINES;\ntest("the composer", () => {});\n', + }); + const { decision } = gate(repo, { [parent]: [ciRun({ head_sha: parent })] }); + expect(decision.mode).toBe("tests"); + expect(decision.webkitTests).toEqual(["app/tests/composer.test.tsx"]); +}); + +// Product code: everything. +test("a change to product code runs the full suite", () => { + const changes: [string, string][] = [ + ["server/src/index.ts", "export const answer = 43;\n"], + ["app/src/home.tsx", "export const Home = () => 1;\n"], + ["shared/harnesses.json", "[]\n"], + ["desktop/src-tauri/src/main.rs", "fn main() {}\n"], + [".github/workflows/ci.yml", `${CI_YML}# changed\n`], + ["server/src/new.ts", "export {};\n"], + ]; + for (const [path, text] of changes) { const { repo, parent } = mainAt(); - release(repo, extra); - const { decision } = gate(repo, [[ciRun({ head_sha: parent })]]); + release(repo, { [path]: text }); + const { decision, sha } = gate(repo, { + [parent]: [ciRun({ head_sha: parent })], + }); + expect(decision.mode).toBe("full"); expect(decision.fullChecks).toBe(true); expect(decision.reason).toContain( - `${Object.keys(extra)[0]} is not a release file`, + `${path} is not a release file or a test`, ); + // The release commit itself was asked about, and nothing that differs from it in code. + expect(decision.reason).toContain(`CI never ran on ${sha}`); } }); -test("a deleted source file runs the full checks", () => { +// Rule 3: a revert back to a tree that was green. +test("a revert back to a tree CI passed reruns nothing", () => { + const { repo } = mainAt(); + const released = release(repo); + // Something merged after the release that broke CI, then taken back out in a release PR. + write(repo, { "server/src/index.ts": "export const answer = 0;\n" }); + const broke = commit(repo, "A change that broke CI"); + write(repo, { "server/src/index.ts": "export const answer = 42;\n" }); + commit(repo, "Take the change back out"); + const { decision } = gate(repo, { + [released]: [queueRun({ head_sha: released })], + [broke]: [ciRun({ head_sha: broke, conclusion: "failure" })], + }); + expect(decision.mode).toBe("reuse"); + expect(decision.fullChecks).toBe(false); + expect(decision.baseline).toBe(released); + expect(decision.tests).toEqual([]); + expect(decision.reason).toContain("Nothing runs again"); +}); + +test("the release commit's own passing run means nothing runs again", () => { const { repo, parent } = mainAt(); - rmSync(join(repo, "server/src/index.ts")); + const sha = release(repo, { "server/src/index.ts": "export const x = 1;\n" }); + const { decision } = gate(repo, { + [parent]: [ciRun({ head_sha: parent })], + [sha]: [queueRun({ head_sha: sha })], + }); + expect(decision.mode).toBe("reuse"); + expect(decision.baseline).toBe(sha); +}); + +// Unknown: everything. +test("a diff the gate does not know runs the full suite", () => { + const changes: [string, string][] = [ + ["desktop/intelligence-cli.json", '{"cli":"latest"}\n'], + ["scripts/ci-watch.fixtures/run.json", "{}\n"], + ["agent-crewai/tests/test_tools.py", "def test_x(): pass\n"], + ["agent-langgraph-ts/src/x.test.ts", "test('x', () => {});\n"], + ["docs/releasing.md", "# Releasing\n"], + ["app/workbench/x.tsx", "export {};\n"], + ]; + for (const [path, text] of changes) { + const { repo, parent } = mainAt(); + release(repo, { [path]: text }); + const { decision } = gate(repo, { + [parent]: [ciRun({ head_sha: parent })], + }); + expect(decision.mode).toBe("full"); + expect(decision.reason).toContain(path); + } +}); + +test("a deleted test, a deleted source file or a test turned into a link runs the full suite", () => { + const deleted: [string, string][] = [ + ["scripts/release-version.test.ts", "was deleted"], + ["server/src/index.ts", "is not a release file or a test"], + ]; + for (const [path, why] of deleted) { + const { repo, parent } = mainAt(); + rmSync(join(repo, path)); + release(repo); + const { decision } = gate(repo, { + [parent]: [ciRun({ head_sha: parent })], + }); + expect(decision.mode).toBe("full"); + expect(decision.reason).toContain(`${path} ${why}`); + } + const { repo, parent } = mainAt(); + rmSync(join(repo, "scripts/release-version.test.ts")); + Bun.spawnSync([ + "ln", + "-s", + "../server/src/index.ts", + join(repo, "scripts/release-version.test.ts"), + ]); release(repo); - const { decision } = gate(repo, [[ciRun({ head_sha: parent })]]); - expect(decision.fullChecks).toBe(true); - expect(decision.reason).toContain("server/src/index.ts"); + const { decision } = gate(repo, { [parent]: [ciRun({ head_sha: parent })] }); + expect(decision.mode).toBe("full"); + expect(decision.reason).toContain("scripts/release-version.test.ts"); }); -/** main without `name`, so a file moved there is a rename git can detect. */ -function mainWithout(name: string): { repo: string; parent: string } { - const { repo } = mainAt(); - rmSync(join(repo, name)); - return { repo, parent: commit(repo, `main without ${name}`) }; -} +test("a diff that cannot be read, or a path with control characters, runs the full suite", () => { + const { repo, parent } = mainAt(); + const sha = release(repo); + const deps = localDeps(repo); + expect( + compareTrees(parent, sha, { + ...deps, + diff: () => { + throw new Error("fatal: bad object"); + }, + }), + ).toEqual({ reason: "the diff could not be read: fatal: bad object" }); + expect( + compareTrees(parent, sha, { + ...deps, + diff: () => [{ path: "scripts/a\n.test.ts", status: "M" }], + }), + ).toEqual({ reason: "a changed path has control characters" }); + expect(compareTrees("0".repeat(40), sha, deps)).toHaveProperty("reason"); +}); + +test("a test whose engines cannot be read runs the full suite, not a guess", () => { + const { repo, parent } = mainAt(); + release(repo, { + "scripts/release-version.test.ts": 'test("again", () => {});\n', + }); + const local = localDeps(repo); + for (const ci of [undefined, "name: CI\njobs: {}\n"]) { + const { decision } = gate( + repo, + { [parent]: [ciRun({ head_sha: parent })] }, + { + overrides: { + read: (path) => (path === CI_WORKFLOW ? ci : local.read(path)), + }, + }, + ); + expect(decision.mode).toBe("full"); + expect(decision.reason).toContain( + "which engines they run in could not be read", + ); + } + expect(() => webkitList("name: CI\njobs: {}\n")).toThrow("names no test"); + expect(() => webkitList(undefined)).toThrow("missing"); +}); -// With git's rename detection, `server/src/index.ts` moved to a new `release-policy.json` is listed -// as release-policy.json alone, and the removed source file would never be looked at. -test("a source file renamed onto a release file's name runs the full checks", () => { - const { repo, parent } = mainWithout("release-policy.json"); +// The point of the guard: a code change riding in the release PR is never published on the +// strength of a run that did not test it. +test("a source file renamed onto a release file's name runs the full suite", () => { + const { repo } = mainAt(); + rmSync(join(repo, "release-policy.json")); + const parent = commit(repo, "main without release-policy.json"); run(repo, "mv", "server/src/index.ts", "release-policy.json"); write(repo, { "package.json": pkg("0.3.2"), @@ -215,25 +323,27 @@ test("a source file renamed onto a release file's name runs the full checks", () "backend-images.env": images("v0.3.2"), }); commit(repo, "Release v0.3.2"); - const { decision } = gate(repo, [[ciRun({ head_sha: parent })]]); - expect(decision.fullChecks).toBe(true); + const { decision } = gate(repo, { [parent]: [ciRun({ head_sha: parent })] }); + expect(decision.mode).toBe("full"); expect(decision.reason).toContain( - "server/src/index.ts is not a release file", + "server/src/index.ts is not a release file or a test", ); }); // The same hole in the final-against-candidate check, which reads the diff the same way. test("a final that renames a source file onto CHANGELOG.md is refused", () => { - const { repo, parent } = mainWithout("CHANGELOG.md"); + const { repo } = mainAt(); + rmSync(join(repo, "CHANGELOG.md")); + const parent = commit(repo, "main without CHANGELOG.md"); run(repo, "mv", "server/src/index.ts", "CHANGELOG.md"); const sha = commit(repo, "final"); - const violations = allowedDiff(changesIn(repo)(parent, sha)); + const violations = allowedDiff(changedFiles(parent, sha, repo)); expect(violations).toContain( "server/src/index.ts: may not change between a candidate and its final release", ); }); -test("a version file that changes more than its version runs the full checks", () => { +test("a version file that changes more than its version runs the full suite", () => { for (const [path, text] of [ ["package.json", pkg("0.3.2", { dependencies: { left: "1.0.0" } })], ["desktop/src-tauri/Cargo.lock", lock("0.3.2", "1.0.1")], @@ -243,8 +353,10 @@ test("a version file that changes more than its version runs the full checks", ( ] as const) { const { repo, parent } = mainAt(); release(repo, { [path]: text }); - const { decision } = gate(repo, [[ciRun({ head_sha: parent })]]); - expect(decision.fullChecks).toBe(true); + const { decision } = gate(repo, { + [parent]: [ciRun({ head_sha: parent })], + }); + expect(decision.mode).toBe("full"); expect(decision.reason).toContain(`${path} changed beyond its version`); } }); @@ -271,7 +383,7 @@ test("a version file added or removed is not a version change", () => { ).toEqual(["backend-images.env was added"]); }); -test("without a passing run of main's CI on the parent, the full checks run", () => { +test("without a passing run on a commit that would stand in, the full suite runs", () => { const cases: [string, CiRun[]][] = [ ["never ran", []], ["did not pass (failure)", [{ conclusion: "failure" } as CiRun]], @@ -283,35 +395,69 @@ test("without a passing run of main's CI on the parent, the full checks run", () const answer = runs.map((partial) => ciRun({ ...partial, head_sha: parent }), ); - const { decision } = gate(repo, [answer]); + const { decision } = gate(repo, { [parent]: answer }); expect(decision.fullChecks).toBe(true); expect(decision.reason).toContain(why); } }); -// Only a push to this repository's main (or main's merge queue, below) at exactly the parent counts. -// A pull request's run tests a merge of the PR, not the commit, and skips the image builds unless it -// was labelled. -test("a run that is not main's CI at the parent does not count", () => { +// Only a run that finished with every job succeeded or skipped stands in. +test("a run marked success with a job that did not pass does not stand in", () => { + const { repo, parent } = mainAt(); + release(repo); + const green = ciRun({ head_sha: parent }); + for (const conclusion of ["failure", "cancelled", "timed_out", null]) { + const { decision } = gate( + repo, + { [parent]: [green] }, + { + jobs: { + [green.id]: [ + ...GREEN_CI, + { name: "tests (shard 2 of 5)", conclusion }, + ], + }, + }, + ); + expect(decision.mode).toBe("full"); + expect(decision.reason).toContain("a job did not pass"); + } + const none = gate(repo, { [parent]: [green] }, { jobs: { [green.id]: [] } }); + expect(none.decision.mode).toBe("full"); +}); + +// A pull request's run tests a merge of the PR, not the commit; another workflow tests something else. +test("a run that is not main's CI, main's queue or a publish's checks at the commit does not count", () => { const parent = "p".repeat(40); + const jobsOf = () => GREEN_CI; for (const other of [ { event: "pull_request" }, { head_branch: "david/branch" }, { head_sha: "q".repeat(40) }, { path: ".github/workflows/desktop.yml" }, { head_repository: { full_name: "someone/OpenBot" } }, + { + head_branch: "gh-readonly-queue/release/1.2/pr-7-abc", + event: "merge_group", + }, ]) { expect( - ciOnParent([ciRun({ head_sha: parent, ...other })], parent, REPOSITORY) + ciAt([ciRun({ head_sha: parent, ...other })], parent, REPOSITORY, jobsOf) .state, ).toBe("none"); } expect( - ciOnParent([ciRun({ head_sha: parent })], parent, REPOSITORY).state, + ciAt([ciRun({ head_sha: parent })], parent, REPOSITORY, jobsOf).state, ).toBe("passed"); + expect( + ciAt([queueRun({ head_sha: parent })], parent, REPOSITORY, jobsOf).state, + ).toBe("passed"); + // The run deciding never stands in for itself. + const own = ciRun({ head_sha: parent }); + expect(ciAt([own], parent, REPOSITORY, jobsOf, own.id).state).toBe("none"); }); -test("a run in progress on the parent is waited for, and its result decides", () => { +test("a run in progress on an older commit is waited for, and its result decides", () => { const { repo, parent } = mainAt(); release(repo); const running = ciRun({ @@ -319,22 +465,29 @@ test("a run in progress on the parent is waited for, and its result decides", () status: "in_progress", conclusion: null, }); - const passed = gate(repo, [ - [running], - [running], - [ciRun({ head_sha: parent })], - ]); - expect(passed.decision.fullChecks).toBe(false); + let asked = 0; + const passed = gate(repo, (sha) => + sha !== parent + ? [] + : asked++ < 2 + ? [running] + : [ciRun({ head_sha: parent })], + ); + expect(passed.decision.mode).toBe("release-files"); expect(passed.slept).toEqual([30, 30]); - const failed = gate(repo, [ - [running], - [ciRun({ head_sha: parent, conclusion: "failure" })], - ]); - expect(failed.decision.fullChecks).toBe(true); + let again = 0; + const failed = gate(repo, (sha) => + sha !== parent + ? [] + : again++ < 1 + ? [running] + : [ciRun({ head_sha: parent, conclusion: "failure" })], + ); + expect(failed.decision.mode).toBe("full"); }); -test("a run still in progress when the wait runs out means the full checks", () => { +test("a run still in progress when the wait runs out means the full suite", () => { const { repo, parent } = mainAt(); release(repo); const running = ciRun({ @@ -342,146 +495,147 @@ test("a run still in progress when the wait runs out means the full checks", () status: "queued", conclusion: null, }); - const { decision, slept } = gate(repo, [[running]], 90); - expect(decision.fullChecks).toBe(true); + const { decision, slept } = gate( + repo, + { [parent]: [running] }, + { waitSeconds: 90 }, + ); + expect(decision.mode).toBe("full"); expect(decision.reason).toContain("still running after 90 seconds"); expect(slept).toEqual([30, 30, 30]); }); -test("main's CI that cannot be read means the full checks, not a pass", () => { +// main's push run of the release commit is the full suite, just started. Waiting for it would only +// start the same suite later. +test("the release commit's own push run in progress is not waited for", () => { const { repo } = mainAt(); - release(repo); - const sha = run(repo, "rev-parse", "HEAD"); - const decision = decide(sha, REPOSITORY, { - parent: (commit) => run(repo, "rev-parse", `${commit}^1`), - changes: changesIn(repo), - runs: () => { - throw new Error("gh: Server Error (HTTP 502)"); - }, - sleep: () => {}, - now: () => 0, - log: () => {}, + const sha = release(repo, { "server/src/index.ts": "export const x = 1;\n" }); + const { decision, slept } = gate(repo, { + [sha]: [ciRun({ head_sha: sha, status: "in_progress", conclusion: null })], }); - expect(decision.fullChecks).toBe(true); - expect(decision.reason).toContain("could not be read: gh: Server Error"); + expect(decision.mode).toBe("full"); + expect(slept).toEqual([]); }); -test("the decision is made against the first parent, main as the release PR merged onto it", () => { +test("CI that cannot be read means the full suite, not a pass", () => { const { repo } = mainAt(); - write(repo, { "server/src/index.ts": "export const answer = 7;\n" }); - const later = commit(repo, "another PR merged before the release PR"); release(repo); - const { decision } = gate(repo, [[ciRun({ head_sha: later })]]); - expect(decision.parent).toBe(later); - expect(decision.fullChecks).toBe(false); + const { decision } = gate(repo, () => { + throw new Error("gh: Server Error (HTTP 502)"); + }); + expect(decision.mode).toBe("full"); + expect(decision.reason).toContain("could not be read: gh: Server Error"); }); -/** CI's run in main's merge queue on the commit it merged: what a queue merge leaves at the parent. */ -function queueRun(overrides: Partial & { head_sha: string }): CiRun { - return ciRun({ - id: 2, - html_url: "https://github.com/CopilotKit/OpenBot/actions/runs/2", - event: "merge_group", - head_branch: - "gh-readonly-queue/main/pr-2581-bff854d1ab9cc25580bd3efa3308a7f954069c5c", - ...overrides, +test("of the trees that would stand in, the one leaving least to run is used", () => { + const { repo, parent: green } = mainAt(); + // A test changed after `green` passed, and its own CI passed too. + write(repo, { + "scripts/release-version.test.ts": 'test("changed", () => {});\n', }); -} - -// main's own run of a commit the merge queue merged skips the checks the queue already ran on that -// same commit, so the queue's run is what says the parent passed. -test("a release onto a commit only the merge queue tested skips the full checks", () => { - const { repo, parent } = mainAt(); + const testChanged = commit(repo, "a test changed"); release(repo); - const { decision } = gate(repo, [[queueRun({ head_sha: parent })]]); - expect(decision.fullChecks).toBe(false); - expect(decision.run?.event).toBe("merge_group"); - expect(decision.reason).toContain( - "https://github.com/CopilotKit/OpenBot/actions/runs/2", - ); + const both = { + [green]: [ciRun({ head_sha: green })], + [testChanged]: [ciRun({ head_sha: testChanged })], + }; + expect(gate(repo, both).decision).toMatchObject({ + mode: "release-files", + baseline: testChanged, + }); + // With that one red, the older green tree stands in, and the changed test runs. + const older = gate(repo, { + ...both, + [testChanged]: [ciRun({ head_sha: testChanged, conclusion: "failure" })], + }); + expect(older.decision).toMatchObject({ + mode: "tests", + baseline: green, + tests: ["scripts/release-version.test.ts"], + }); }); -test("a merge-queue run on the parent that did not pass, or none at all, means the full checks", () => { - const cases: [string, Partial[]][] = [ - ["never ran", []], - ["did not pass (failure)", [{ conclusion: "failure" }]], - ["did not pass (cancelled)", [{ conclusion: "cancelled" }]], - ]; - for (const [why, runs] of cases) { - const { repo, parent } = mainAt(); - release(repo); - const { decision } = gate(repo, [ - runs.map((partial) => queueRun({ ...partial, head_sha: parent })), - ]); - expect(decision.fullChecks).toBe(true); - expect(decision.reason).toContain(why); - } +// A final's parent is its candidate on release/X.Y, which main's CI never ran on; the candidate's +// own publish ran every check on it. +test("a final onto a candidate whose publish ran and passed every check runs only the release-file checks", () => { + const { repo } = mainAt(); + run(repo, "checkout", "-q", "-b", "release/0.3"); + const candidate = release(repo); + write(repo, { "package.json": pkg("0.3.2-final") }); + commit(repo, "Release v0.3.2"); + const passed = gate(repo, { + [candidate]: [ + publishRun({ head_sha: candidate, head_branch: "release/0.3" }), + ], + }); + expect(passed.decision).toMatchObject({ + mode: "release-files", + baseline: candidate, + }); + // A publish that skipped its own checks, relying on another run, proves nothing new. + const skipped = publishRun({ + head_sha: candidate, + head_branch: "release/0.3", + }); + const relied = gate( + repo, + { [candidate]: [skipped] }, + { + jobs: { + [skipped.id]: GREEN_PUBLISH.map((job) => + job.name.startsWith("checks /") + ? { ...job, conclusion: "skipped" } + : job, + ), + }, + }, + ); + expect(relied.decision.mode).toBe("full"); + expect(relied.decision.reason).toContain( + "a publish whose checks did not run", + ); + // A release PR's own branch is never a release. + const branch = gate(repo, { + [candidate]: [ + publishRun({ + head_sha: candidate, + head_branch: "release/publish/v0.3.2", + }), + ], + }); + expect(branch.decision.mode).toBe("full"); }); -test("a merge-queue run counts only for main's queue, at the parent, in this repository", () => { - const parent = "p".repeat(40); - for (const other of [ - { head_branch: "gh-readonly-queue/release/1.2/pr-7-abc" }, - { head_branch: "main" }, - { head_sha: "q".repeat(40) }, - { path: ".github/workflows/desktop.yml" }, - { head_repository: { full_name: "someone/OpenBot" } }, - ]) { - expect( - ciOnParent([queueRun({ head_sha: parent, ...other })], parent, REPOSITORY) - .state, - ).toBe("none"); - } - expect( - ciOnParent([queueRun({ head_sha: parent })], parent, REPOSITORY).state, - ).toBe("passed"); - // A push run still counts, beside a failed queue run or on its own. - expect( - ciOnParent( - [ - queueRun({ head_sha: parent, conclusion: "failure" }), - ciRun({ head_sha: parent }), - ], - parent, - REPOSITORY, - ).state, - ).toBe("passed"); +// A candidate on a release branch that carries main's tree at a commit is what main's CI tested. +test("a release branch carrying main's tree is compared with main's commits by tree", () => { + const { repo, parent: onMain } = mainAt(); + run(repo, "update-ref", MAIN_REF, onMain); + run(repo, "checkout", "-q", "--orphan", "release/0.3"); + commit(repo, "main's tree, carried onto release/0.3"); + release(repo); + const { decision } = gate(repo, { [onMain]: [ciRun({ head_sha: onMain })] }); + expect(decision).toMatchObject({ mode: "release-files", baseline: onMain }); }); // A hotfix release used to sit up to 40 minutes polling for main's CI. Past ten minutes the full // suite runs instead, whatever CI_WAIT_SECONDS asks for. -test("the wait for main's CI on the parent is capped at ten minutes, by default and when asked for more", () => { +test("the wait is capped at ten minutes, by default and when asked for more", () => { expect(MAX_WAIT_SECONDS).toBe(600); const { repo, parent } = mainAt(); release(repo); - const sha = run(repo, "rev-parse", "HEAD"); const running = ciRun({ head_sha: parent, status: "in_progress", conclusion: null, }); - for (const options of [undefined, { waitSeconds: 2400 }]) { - let clock = 0; - const slept: number[] = []; - const decision = decide( - sha, - REPOSITORY, - { - parent: (commit) => run(repo, "rev-parse", `${commit}^1`), - changes: changesIn(repo), - runs: () => [running], - sleep: (seconds) => { - slept.push(seconds); - clock += seconds * 1000; - }, - now: () => clock, - log: () => {}, - }, - options, + for (const waitSeconds of [undefined, 2400]) { + const { decision, slept } = gate( + repo, + { [parent]: [running] }, + waitSeconds === undefined ? {} : { waitSeconds }, ); - expect(decision.fullChecks).toBe(true); + expect(decision.mode).toBe("full"); expect(decision.reason).toContain("still running after 600 seconds"); - expect(clock).toBe(600_000); expect(slept.length).toBe(20); } }); @@ -497,3 +651,12 @@ test("publish-release's gate job stops soon after the capped wait", () => { expect(limit * 60).toBeGreaterThan(MAX_WAIT_SECONDS); expect(limit).toBeLessThanOrEqual(20); }); + +test("the WebKit list is read from the real ci.yml", () => { + const list = webkitList( + readFileSync(join(import.meta.dir, "..", CI_WORKFLOW), "utf8"), + ); + expect(list.has("app/tests/sidebar-current-row.test.tsx")).toBe(true); + expect(list.has("app/tests/connect-your-ai.test.tsx")).toBe(true); + expect(list.size).toBeGreaterThan(50); +}); diff --git a/scripts/release-ci-gate.ts b/scripts/release-ci-gate.ts index bdcce83ca2..78441ef80d 100644 --- a/scripts/release-ci-gate.ts +++ b/scripts/release-ci-gate.ts @@ -1,34 +1,68 @@ /** - * Whether publishing a release runs the whole CI suite on the release commit again. + * What publishing a release runs on the release commit: the whole CI suite again, or only what no + * passing run has already checked. * - * A release PR, as Create release PR writes it, moves the version and promotes the notes: the - * `version` in package.json, the desktop crate's version line in Cargo.toml and Cargo.lock, the - * chart's `appVersion`, CHANGELOG.md, and the release policy a person writes for the release. When - * that is all the release commit changes from the commit it sits on, and main's CI passed on that - * commit, its tree has already been through every check: running them again costs a quarter of an - * hour and proves nothing new. So publish-release.yml relies on that run instead, and re-runs only - * the checks that read the files the release did change (the `checks needed` job). + * The rule is that a test is not run again on code that already passed it. So the gate looks for a + * commit whose CI passed and whose tree differs from the release commit's in nothing a run would + * check differently, and runs only the difference: * - * Anything else in the diff, an added, removed or renamed file included, or a version file that - * changed more than its version, means the full suite, as does a commit whose parent main's CI did - * not pass: none, failed, cancelled, or still running after the wait. The decision is made against - * the release commit's first parent, which is main as it was when the release PR merged, whichever - * commit the PR was cut from. + * - `reuse`: the same tree. Nothing runs again (publish-release.yml still checks the support window, + * which counts from the day of the release, not from the tree). + * - `release-files`: only the release files differ: CHANGELOG.md and release-policy.json, which may + * change freely, and the `version` in package.json, the `OPENBOT_BACKEND_TAG` line in + * backend-images.env and the `openbot-desktop` version line in desktop/src-tauri/Cargo.toml and + * Cargo.lock, which may change nothing else. The checks that read the release files run. + * - `tests`: only the release files and the suite's test files differ, each test added or changed + * (not deleted). Those test files run, in each engine they run in, with every test that names one, + * plus format, lint and types and the release-file checks. + * - `full`: anything else. Any other path (the app, shared/, desktop/src-tauri, the server-facing + * code, a workflow, a fixture, a Python harness's test), a deleted test, a version file that + * changed beyond its version, a diff that could not be read, or no such commit whose CI passed. * - * Usage, from the repository root of a checkout that has the commit and its parent: + * The commits looked at are the release commit itself, its first parents (main, or the release + * branch it publishes on), and main's first parents, MAX_CANDIDATES of each. They are compared by + * tree, not by history: a revert back to a tree that passed is that tree, and a release branch that + * carries main's tree at a commit is that commit's tree. + * + * A commit's CI passed when one run that tested it finished with every job succeeded or skipped: + * ci.yml for a push to this repository's main or main's merge queue at exactly that commit, or a + * Publish release run at that commit whose own `checks` ran and passed. A pull request's run tests a + * merge of the PR rather than the commit, so it never counts, and neither does the current run. A run + * still in progress on an older commit is waited for, up to MAX_WAIT_SECONDS; the release commit's + * own push run is not, since waiting for it only starts the same suite later. + * + * Fail closed: anything this cannot read or is not sure of runs the full suite. + * + * Usage, from the repository root of a checkout with the history (fetch-depth 0): * * bun scripts/release-ci-gate.ts * - * Env: GITHUB_REPOSITORY and GH_TOKEN, for `gh`; CI_WAIT_SECONDS (default and most MAX_WAIT_SECONDS), - * how long to wait for a run still in progress on the parent; CI_POLL_SECONDS (default 30). Writes `full_checks` - * (`true` or `false`) and `parent` to $GITHUB_OUTPUT, and why to $GITHUB_STEP_SUMMARY, when set. + * Env: GITHUB_REPOSITORY and GH_TOKEN, for `gh`; GITHUB_RUN_ID, the current run, left out; + * CI_WAIT_SECONDS (default and most MAX_WAIT_SECONDS), how long to wait for a run still in progress; + * CI_POLL_SECONDS (default 30). Writes `mode`, `full_checks` (`true` only for `full`), `parent`, + * `baseline` and the test files to run as JSON arrays (`tests`, `browser_tests`, `webkit_tests`, + * `desktop_browser_tests`) to $GITHUB_OUTPUT, and why to $GITHUB_STEP_SUMMARY, when set. */ -import { appendFileSync } from "node:fs"; -import { changedFiles, VERSION_ONLY_RULES } from "./release-candidate-check"; +import { randomBytes } from "node:crypto"; +import { appendFileSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + byEngine, + isBunTest, + type TestsByEngine, + unusualPath, +} from "./ci-changes"; +import { VERSION_ONLY_RULES } from "./release-candidate-check"; -/** The workflow whose run on the parent stands in for the release commit's own checks. */ +/** The workflow whose runs stand in for the release commit's own checks. */ export const CI_WORKFLOW = ".github/workflows/ci.yml"; +/** This workflow, whose `checks` call of ci.yml on an earlier release commit also counts. */ +export const PUBLISH_WORKFLOW = ".github/workflows/publish-release.yml"; + +/** A Publish release run's job that passes only when every one of its `checks` jobs did. */ +export const PUBLISH_CHECKS_VERIFY = "checks / verify"; + /** What a release PR may change freely: the notes, and the policy a person writes for it. */ export const FREE_RELEASE_FILES = ["CHANGELOG.md", "release-policy.json"]; @@ -40,6 +74,12 @@ export const VERSION_ONLY_RELEASE_FILES = [ "desktop/src-tauri/Cargo.lock", ]; +/** How many commits along each line of first parents are compared with the release commit. */ +export const MAX_CANDIDATES = 50; + +/** How many of the commits whose trees qualify are asked about, best first. */ +export const MAX_ASKED = 10; + /** * The paths that make a diff more than a release: every path outside the release files, and every * version file that changed beyond its version. Empty means the diff is the release files alone. @@ -77,6 +117,79 @@ function sameBesidesVersion( } } +/** One path that differs between two trees, with git's status letter (A, M, D, T). */ +export type TreeChange = { path: string; status: string }; + +export type Mode = "reuse" | "release-files" | "tests" | "full"; + +/** How a commit's tree differs from the release commit's, or why it cannot stand in for it. */ +export type Comparison = + | { mode: Exclude; tests: string[] } + | { reason: string }; + +const RANK: Record, number> = { + reuse: 0, + "release-files": 1, + tests: 2, +}; + +/** + * What the release commit `to` differs from `from` in, as far as the checks are concerned. Only the + * release files and the suite's own test files may differ; anything else, or a diff this cannot + * read, gives the reason the full suite runs. + */ +export function compareTrees( + from: string, + to: string, + deps: Pick, +): Comparison { + let changes: TreeChange[]; + try { + changes = deps.diff(from, to); + } catch (error) { + return { reason: `the diff could not be read: ${message(error)}` }; + } + const release = new Map(); + const tests: string[] = []; + for (const { path, status } of changes) { + if (unusualPath(path)) { + return { reason: "a changed path has control characters" }; + } + // Added, modified or deleted; a file turned into a link (T) or anything else is not reasoned about. + if (status !== "A" && status !== "M" && status !== "D") { + return { reason: `${path} changed (${status})` }; + } + if ( + FREE_RELEASE_FILES.includes(path) || + VERSION_ONLY_RELEASE_FILES.includes(path) + ) { + // A side that cannot be read is empty, which a version file reads as added or removed. + release.set(path, { + before: status === "A" ? "" : (deps.show(from, path) ?? ""), + after: status === "D" ? "" : (deps.show(to, path) ?? ""), + }); + } else if (isBunTest(path) && status !== "D") { + tests.push(path); + } else if (isBunTest(path)) { + // A deleted test is one fewer the suite runs, which only the suite's own floor checks. + return { reason: `${path} was deleted` }; + } else { + return { reason: `${path} is not a release file or a test` }; + } + } + const violations = releaseFileViolations(release); + if (violations.length > 0) return { reason: violations.join("; ") }; + return { + mode: + changes.length === 0 + ? "reuse" + : tests.length > 0 + ? "tests" + : "release-files", + tests: tests.sort(), + }; +} + /** The fields of a workflow run this reads, as the Actions API returns them. */ export type CiRun = { id: number; @@ -90,6 +203,9 @@ export type CiRun = { head_repository?: { full_name?: string } | null; }; +/** The fields of a run's job this reads, as the Actions API returns them. */ +export type CiJob = { name: string; conclusion: string | null }; + export type CiState = | { state: "passed"; run: CiRun } | { state: "running"; run: CiRun } @@ -98,6 +214,9 @@ export type CiState = /** The branch main's merge queue builds each group on, one per group. */ export const MAIN_QUEUE_BRANCH = "gh-readonly-queue/main/"; +const sameRepository = (run: CiRun, repository: string) => + run.head_repository?.full_name?.toLowerCase() === repository.toLowerCase(); + /** * Whether a run of ci.yml in this repository tested exactly `sha` as main has it: main's own run for * the push, or the merge queue's run of the group that became that commit. The queue merges the very @@ -111,8 +230,7 @@ export function testedMainAt( return ( run.path === CI_WORKFLOW && run.head_sha === sha && - run.head_repository?.full_name?.toLowerCase() === - repository.toLowerCase() && + sameRepository(run, repository) && ((run.event === "push" && run.head_branch === "main") || (run.event === "merge_group" && (run.head_branch ?? "").startsWith(MAIN_QUEUE_BRANCH))) @@ -120,37 +238,88 @@ export function testedMainAt( } /** - * What main's CI says about `parent`. Only a run of ci.yml for a push to this repository's main, or - * main's merge queue's run, at exactly that commit, counts: a pull request's run tests a merge of the - * PR rather than the commit itself, and skips the image builds unless it was labelled. main's own run - * of a commit the queue merged skips the checks the queue ran (scripts/ci-changes.ts), so for most - * commits the queue's run is the one that tested it. + * Whether a run is Publish release on a push of exactly `sha` to main or a release branch of this + * repository: the run whose `checks` call ci.yml on that commit, with every check. */ -export function ciOnParent( +export function publishedAt( + run: CiRun, + sha: string, + repository: string, +): boolean { + const branch = run.head_branch ?? ""; + return ( + run.path === PUBLISH_WORKFLOW && + run.head_sha === sha && + run.event === "push" && + sameRepository(run, repository) && + (branch === "main" || + (branch.startsWith("release/") && !branch.startsWith("release/publish/"))) + ); +} + +/** Every job of a finished run succeeded or was skipped, and there was at least one. */ +const everyJobPassed = (jobs: CiJob[]) => + jobs.length > 0 && + jobs.every( + (job) => job.conclusion === "success" || job.conclusion === "skipped", + ); + +/** + * What CI says about `sha`: a run that tested it and finished with every job succeeded or skipped, + * a run of ci.yml still in progress on it, or neither. A Publish release run counts only when its + * own `checks` ran (PUBLISH_CHECKS_VERIFY succeeded): one whose gate relied on another run proves + * nothing new. `currentRun` is left out. + */ +export function ciAt( runs: CiRun[], - parent: string, + sha: string, repository: string, + jobsOf: (run: CiRun) => CiJob[], + currentRun?: number, ): CiState { - const own = runs.filter((run) => testedMainAt(run, parent, repository)); - const passed = own.find( - (run) => run.status === "completed" && run.conclusion === "success", - ); - if (passed) return { state: "passed", run: passed }; - const running = own.find((run) => run.status !== "completed"); + const others = runs.filter((run) => run.id !== currentRun); + const ci = others.filter((run) => testedMainAt(run, sha, repository)); + const publish = others.filter((run) => publishedAt(run, sha, repository)); + const outcomes: string[] = []; + for (const run of [...ci, ...publish]) { + if (run.status !== "completed") continue; + if (run.conclusion !== "success") { + outcomes.push(run.conclusion ?? "unknown"); + continue; + } + const jobs = jobsOf(run); + if (!everyJobPassed(jobs)) { + outcomes.push("a job did not pass"); + } else if ( + run.path === PUBLISH_WORKFLOW && + !jobs.some( + (job) => + job.name === PUBLISH_CHECKS_VERIFY && job.conclusion === "success", + ) + ) { + outcomes.push("a publish whose checks did not run"); + } else { + return { state: "passed", run }; + } + } + const running = ci.find((run) => run.status !== "completed"); if (running) return { state: "running", run: running }; - if (own.length === 0) { - return { state: "none", reason: `main's CI never ran on ${parent}` }; + if (outcomes.length === 0) { + return { state: "none", reason: `CI never ran on ${sha}` }; } - const outcomes = [...new Set(own.map((run) => run.conclusion ?? "unknown"))]; return { state: "none", - reason: `main's CI on ${parent} did not pass (${outcomes.join(", ")})`, + reason: `CI on ${sha} did not pass (${[...new Set(outcomes)].join(", ")})`, }; } -export type Decision = { +export type Decision = TestsByEngine & { + mode: Mode; + /** Whether the full suite runs: `mode` is `full`. */ fullChecks: boolean; parent: string; + /** The commit whose passing run stands in, when the suite does not run. */ + baseline?: string; reason: string; run?: CiRun; }; @@ -158,25 +327,103 @@ export type Decision = { export type GateDeps = { /** The release commit's first parent. */ parent: (sha: string) => string; - /** Every path the release commit changes from its parent, with both sides. */ - changes: ( - parent: string, - sha: string, - ) => Map; - /** Every run of ci.yml at a commit. */ + /** The commits whose trees are compared, nearest first, the release commit included. */ + candidates: (sha: string) => string[]; + /** Every path that differs between two commits, renames read as a removal and an addition. */ + diff: (from: string, to: string) => TreeChange[]; + /** A file at a commit, or undefined. */ + show: (commit: string, path: string) => string | undefined; + /** A file in the checkout of the release commit, or undefined. */ + read: (path: string) => string | undefined; + /** The suite's test files that name any of these (paths, or file names without their extension). */ + mentions: (names: string[]) => string[]; + /** Every workflow run at a commit. */ runs: (sha: string) => CiRun[]; + /** Every job of a run's latest attempt. */ + jobs: (run: CiRun) => CiJob[]; + /** The run deciding, which never stands in for itself. */ + currentRun?: number; sleep: (seconds: number) => void; now: () => number; log: (line: string) => void; }; /** - * The longest the gate waits for main's CI on the parent, which is also the default. Past it the full + * The longest the gate waits for a run still in progress, which is also the default. Past it the full * suite runs on the release commit, rather than a hotfix waiting on main's slowest run. */ export const MAX_WAIT_SECONDS = 600; -/** Decides, waiting while main's CI on the parent is still running, MAX_WAIT_SECONDS at most. */ +const NO_TESTS: TestsByEngine = { + tests: [], + browserTests: [], + webkitTests: [], + desktopBrowserTests: [], +}; + +function message(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** A test file's name without its extension, which is how another test imports it. */ +const importName = (path: string) => + (path.split("/").pop() ?? path).replace(/\.tsx?$/, ""); + +/** The job in ci.yml that runs its list of the app's tests in WebKit as well as Chromium. */ +export const WEBKIT_JOB = "app-browser-webkit"; + +/** + * The app's tests CI's WebKit job runs, as its steps name them in ci.yml. A file runs in WebKit + * there by being on this list, not by anything in the file, so the list is read rather than + * guessed. A workflow this cannot find the list in throws, and the full suite runs. + */ +export function webkitList(ciWorkflow: string | undefined): Set { + if (ciWorkflow === undefined) throw new Error(`${CI_WORKFLOW} is missing`); + const workflow = Bun.YAML.parse(ciWorkflow) as { + jobs?: Record; + }; + const files = new Set(); + for (const step of workflow.jobs?.[WEBKIT_JOB]?.steps ?? []) { + for (const match of (step.run ?? "").matchAll( + /(?:^|\s)(app\/tests\/[^\s"'$]+\.test\.tsx?)(?=\s|$)/gm, + )) { + if (match[1]) files.add(match[1]); + } + } + if (files.size === 0) { + throw new Error(`${CI_WORKFLOW}'s ${WEBKIT_JOB} job names no test`); + } + return files; +} + +/** + * The tests to run for `changed`: those files, and every test of the suite that names one, by its + * path or by the name another file imports it by, each in every engine CI runs it in: `bun test`, + * a real browser, WebKit too for one on the WebKit job's list or that asks for it, and the desktop + * setup window's browser. + */ +export function testsFor( + changed: string[], + deps: Pick, +): TestsByEngine { + const names = [ + ...new Set(changed.flatMap((path) => [path, importName(path)])), + ]; + const files = [...changed, ...deps.mentions(names)].filter( + (path) => isBunTest(path) && deps.read(path) !== undefined, + ); + const sorted = byEngine(files, deps.read); + const webkit = webkitList(deps.read(CI_WORKFLOW)); + for (const file of files.filter((path) => webkit.has(path))) { + if (!sorted.browserTests.includes(file)) sorted.browserTests.push(file); + if (!sorted.webkitTests.includes(file)) sorted.webkitTests.push(file); + } + sorted.browserTests.sort(); + sorted.webkitTests.sort(); + return sorted; +} + +/** Decides, waiting while a run on a commit that would stand in is still in progress. */ export function decide( sha: string, repository: string, @@ -188,65 +435,297 @@ export function decide( MAX_WAIT_SECONDS, ); const parent = deps.parent(sha); - const violations = releaseFileViolations(deps.changes(parent, sha)); - if (violations.length > 0) { - return { - fullChecks: true, - parent, - reason: `The release commit changes more than the release files: ${violations.join("; ")}.`, - }; + const full = (reason: string): Decision => ({ + ...NO_TESTS, + mode: "full", + fullChecks: true, + parent, + reason, + }); + + let candidates: string[]; + try { + candidates = [...new Set([sha, ...deps.candidates(sha)])]; + } catch (error) { + return full(`The history could not be read: ${message(error)}`); + } + + // The trees first, which are local and cheap; only the commits that qualify are asked about. + const usable: { + sha: string; + mode: Exclude; + tests: string[]; + index: number; + }[] = []; + let againstParent = ""; + for (const [index, candidate] of candidates.entries()) { + const comparison = compareTrees(candidate, sha, deps); + if ("reason" in comparison) { + if (candidate === parent) againstParent = comparison.reason; + continue; + } + usable.push({ sha: candidate, ...comparison, index }); + } + if (usable.length === 0) { + return full( + `No commit within reach differs from the release commit only in release files and tests. Against its parent ${parent}: ${againstParent || "it was not compared"}.`, + ); } + // Least left to run first, then the nearest. + usable.sort( + (a, b) => + RANK[a.mode] - RANK[b.mode] || + a.tests.length - b.tests.length || + a.index - b.index, + ); + const asking = usable.slice(0, MAX_ASKED); + const deadline = deps.now() + waitSeconds * 1000; + const settled = new Map(); for (;;) { - // An answer the API could not give is not a pass: the full suite runs, which is never wrong. - let runs: CiRun[]; - try { - runs = deps.runs(parent); - } catch (error) { - return { - fullChecks: true, - parent, - reason: `The release commit changes only release files, but main's CI on ${parent} could not be read: ${error instanceof Error ? error.message : String(error)}`, - }; - } - const ci = ciOnParent(runs, parent, repository); - if (ci.state === "passed") { - return { - fullChecks: false, - parent, - run: ci.run, - reason: `The release commit changes only release files, and main's CI passed on ${parent}: ${ci.run.html_url}`, - }; + let running: CiRun | undefined; + for (const candidate of asking) { + if (settled.has(candidate.sha)) continue; + // An answer the API could not give is not a pass: the full suite runs, which is never wrong. + let ci: CiState; + try { + ci = ciAt( + deps.runs(candidate.sha), + candidate.sha, + repository, + deps.jobs, + deps.currentRun, + ); + } catch (error) { + return full( + `CI on ${candidate.sha}, whose tree would stand in, could not be read: ${message(error)}`, + ); + } + if (ci.state === "passed") { + let tests = NO_TESTS; + try { + if (candidate.mode === "tests") + tests = testsFor(candidate.tests, deps); + } catch (error) { + return full( + `The release commit differs from ${candidate.sha} in ${candidate.tests.join(", ")}, but which engines they run in could not be read: ${message(error)}`, + ); + } + if ( + candidate.mode === "tests" && + tests.tests.length + + tests.browserTests.length + + tests.desktopBrowserTests.length === + 0 + ) { + // Nothing to run for a diff that has tests in it is a guess, not a pass. + return full( + `The release commit differs from ${candidate.sha} in ${candidate.tests.join(", ")}, and none of them could be read to run.`, + ); + } + return { + ...tests, + mode: candidate.mode, + fullChecks: false, + parent, + baseline: candidate.sha, + run: ci.run, + reason: describe(candidate, sha, ci.run), + }; + } + // The release commit's own push run is the full suite on this tree, just started: waiting for + // it would only start the same suite later. Its merge-queue run is finishing, so that one is. + if (ci.state === "none") { + settled.set(candidate.sha, ci.reason); + } else if (candidate.sha !== sha || ci.run.event === "merge_group") { + running ??= ci.run; + } else { + settled.set( + candidate.sha, + `main's run of the release commit is still running: ${ci.run.html_url}`, + ); + } } - if (ci.state === "none") { - return { - fullChecks: true, - parent, - reason: `The release commit changes only release files, but ${ci.reason}.`, - }; + if (!running) { + return full( + `No commit whose tree would stand in passed CI: ${[...settled.values()].join("; ")}.${ + againstParent + ? ` Against its parent ${parent}: ${againstParent}.` + : "" + }`, + ); } if (deps.now() >= deadline) { - return { - fullChecks: true, - parent, - reason: `The release commit changes only release files, but main's CI on ${parent} was still running after ${waitSeconds} seconds: ${ci.run.html_url}`, - }; + return full( + `CI on a commit whose tree would stand in was still running after ${waitSeconds} seconds: ${running.html_url}`, + ); } deps.log( - `main's CI on ${parent} is ${ci.run.status}; waiting for it: ${ci.run.html_url}`, + `CI on ${running.head_sha} is ${running.status}; waiting for it: ${running.html_url}`, ); deps.sleep(pollSeconds); } } -function run(cmd: string[]): string { - const result = Bun.spawnSync(cmd, { stdout: "pipe", stderr: "pipe" }); +function describe( + candidate: { sha: string; mode: Exclude; tests: string[] }, + sha: string, + run: CiRun, +): string { + const where = candidate.sha === sha ? "the release commit" : candidate.sha; + switch (candidate.mode) { + case "reuse": + return `CI already passed on this tree, at ${where}: ${run.html_url}. Nothing runs again.`; + case "release-files": + return `The release commit differs from ${where}, where CI passed, only in the release files: ${run.html_url}. The checks that read them run.`; + case "tests": + return `The release commit differs from ${where}, where CI passed, only in the release files and ${candidate.tests.join(", ")}: ${run.html_url}. Those tests run, with the checks that read the release files.`; + } +} + +function run(cmd: string[], cwd?: string): string { + const result = Bun.spawnSync(cmd, { cwd, stdout: "pipe", stderr: "pipe" }); if (result.exitCode !== 0) { throw new Error(`${cmd.join(" ")}: ${result.stderr.toString().trim()}`); } return result.stdout.toString(); } +/** The branch a release branch's tree is compared with too. */ +export const MAIN_REF = "refs/remotes/origin/main"; + +/** + * What the decision reads from the checkout at `cwd`, a checkout of the release commit with its + * history: the commits to compare, their trees and files, and the tests that name a file. + */ +export function localDeps( + cwd: string, +): Pick< + GateDeps, + "parent" | "candidates" | "diff" | "show" | "read" | "mentions" +> { + const git = (...args: string[]) => run(["git", ...args], cwd); + const firstParents = (ref: string) => + git("rev-list", "--first-parent", `--max-count=${MAX_CANDIDATES}`, ref) + .split("\n") + .filter(Boolean); + return { + parent: (commit) => git("rev-parse", "--verify", `${commit}^1`).trim(), + candidates: (commit) => { + const main = Bun.spawnSync( + ["git", "rev-parse", "--verify", "--quiet", MAIN_REF], + { cwd, stdout: "pipe", stderr: "pipe" }, + ); + return [ + ...firstParents(commit), + ...(main.exitCode === 0 ? firstParents(MAIN_REF) : []), + ]; + }, + diff: (from, to) => { + const out = git( + "diff", + "--no-renames", + "--name-status", + "-z", + from, + to, + ).split("\0"); + // Entries come in status, path pairs, and the output ends in a separator. + if (out.pop() !== "" || out.length % 2 !== 0) { + throw new Error(`git diff ${from} ${to} gave output it could not read`); + } + const changes: TreeChange[] = []; + for (let index = 0; index < out.length; index += 2) { + const status = out[index] ?? ""; + const path = out[index + 1] ?? ""; + if (!/^[A-Z]/.test(status) || !path) { + throw new Error( + `git diff ${from} ${to} gave an entry it could not read`, + ); + } + changes.push({ path, status: status.charAt(0) }); + } + return changes; + }, + show: (commit, path) => { + const result = Bun.spawnSync(["git", "show", `${commit}:${path}`], { + cwd, + stdout: "pipe", + stderr: "pipe", + }); + return result.exitCode === 0 ? result.stdout.toString() : undefined; + }, + read: (path) => { + try { + return readFileSync(join(cwd, path), "utf8"); + } catch { + return undefined; + } + }, + mentions: (names) => { + if (names.length === 0) return []; + const result = Bun.spawnSync( + [ + "git", + "grep", + "-l", + "-z", + "-F", + ...names.flatMap((name) => ["-e", name]), + "--", + "*.test.ts", + "*.test.tsx", + ], + { cwd, stdout: "pipe", stderr: "pipe" }, + ); + // Exit 1 is "no file names any of them"; anything else is an answer this cannot trust. + if (result.exitCode !== 0 && result.exitCode !== 1) { + throw new Error(`git grep: ${result.stderr.toString().trim()}`); + } + return result.stdout.toString().split("\0").filter(Boolean); + }, + }; +} + +/** Every page of a list the Actions API returns through `gh api`, `key` naming the list in each. */ +function pages(path: string, key: string): T[] { + const all: T[] = []; + for (let page = 1; ; page++) { + const body = JSON.parse( + run(["gh", "api", `${path}&per_page=100&page=${page}`]), + ) as Record & { total_count: number }; + const items = body[key]; + if (!Array.isArray(items) || typeof body.total_count !== "number") { + throw new Error(`gh api ${path} gave no ${key}`); + } + all.push(...(items as T[])); + if (items.length < 100 || all.length >= body.total_count) return all; + } +} + +/** What the decision reads from the Actions API. */ +export function apiDeps(repository: string): Pick { + return { + runs: (commit) => + pages( + `repos/${repository}/actions/runs?head_sha=${commit}`, + "workflow_runs", + ), + jobs: (ciRun) => + pages( + `repos/${repository}/actions/runs/${ciRun.id}/jobs?filter=latest`, + "jobs", + ), + }; +} + +function writeOutput(name: string, value: string) { + const file = process.env.GITHUB_OUTPUT; + if (!file) return; + const delimiter = `EOF_${randomBytes(16).toString("hex")}`; + appendFileSync(file, `${name}<<${delimiter}\n${value}\n${delimiter}\n`); +} + if (import.meta.main) { try { const sha = process.argv[2]; @@ -260,17 +739,9 @@ if (import.meta.main) { sha, repository, { - parent: (commit) => - run(["git", "rev-parse", "--verify", `${commit}^1`]).trim(), - changes: changedFiles, - runs: (commit) => - JSON.parse( - run([ - "gh", - "api", - `repos/${repository}/actions/workflows/ci.yml/runs?head_sha=${commit}&per_page=100`, - ]), - ).workflow_runs as CiRun[], + ...localDeps(process.cwd()), + ...apiDeps(repository), + currentRun: Number(process.env.GITHUB_RUN_ID) || undefined, sleep: (seconds) => Bun.sleepSync(seconds * 1000), now: () => Date.now(), log: (line) => console.log(line), @@ -280,30 +751,46 @@ if (import.meta.main) { pollSeconds: Number(process.env.CI_POLL_SECONDS ?? 30), }, ); + const runs = { + full: "The full CI suite runs on the release commit.", + reuse: + "The full CI suite is not run again, and neither is anything else it ran on this tree.", + "release-files": + "The full CI suite is not run again. The checks that read the release files run in this job.", + tests: + "The full CI suite is not run again. The changed tests run in `release tests`, and the checks that read the release files in this job.", + }[decision.mode]; + const tests = [ + ...decision.tests, + ...decision.browserTests, + ...decision.desktopBrowserTests, + ]; console.log(decision.reason); - console.log( - decision.fullChecks - ? "The full checks run on the release commit." - : "The full checks are not run again; the checks that read the release files are.", + console.log(runs); + if (tests.length > 0) console.log(`Tests: ${tests.join(", ")}`); + writeOutput("mode", decision.mode); + writeOutput("full_checks", String(decision.fullChecks)); + writeOutput("parent", decision.parent); + writeOutput("baseline", decision.baseline ?? ""); + writeOutput("tests", JSON.stringify(decision.tests)); + writeOutput("browser_tests", JSON.stringify(decision.browserTests)); + writeOutput("webkit_tests", JSON.stringify(decision.webkitTests)); + writeOutput( + "desktop_browser_tests", + JSON.stringify(decision.desktopBrowserTests), ); - if (process.env.GITHUB_OUTPUT) { - appendFileSync( - process.env.GITHUB_OUTPUT, - `full_checks=${decision.fullChecks}\nparent=${decision.parent}\n`, - ); - } if (process.env.GITHUB_STEP_SUMMARY) { appendFileSync( process.env.GITHUB_STEP_SUMMARY, - `### Checks for this release\n\n${decision.reason}\n\n${ - decision.fullChecks - ? "The full CI suite runs on the release commit." - : "The full CI suite is not run again. The checks that read the release files run in this job." - }\n`, + `### Checks for this release\n\n${decision.reason}\n\n${runs}\n${ + tests.length > 0 + ? `\n${tests.map((file) => `- \`${file}\``).join("\n")}\n` + : "" + }`, ); } } catch (error) { - console.error(error instanceof Error ? error.message : error); + console.error(message(error)); process.exitCode = 1; } } diff --git a/scripts/release-publish-order.test.ts b/scripts/release-publish-order.test.ts index 81ac3c3bf0..b99f06017f 100644 --- a/scripts/release-publish-order.test.ts +++ b/scripts/release-publish-order.test.ts @@ -2,8 +2,9 @@ * The order publish-release.yml does things in, which is what decides how long a release takes and * what it guarantees on the way: * - * - the full CI suite runs on the release commit unless `gate` found it is only the release files on - * a commit main's CI passed, and nothing is built or tagged unless one or the other passed; + * - the full CI suite runs on the release commit unless `gate` found a tree CI passed that differs + * from it only in the release files and tests, and then only those run; nothing is built or + * tagged unless one or the other passed; * - the signing runs are started as soon as the release they attach to exists, not after a desktop * build of the publish workflow's own; * - a stable release builds no installers of its own, since the signing runs' builds are the only @@ -52,12 +53,24 @@ const expression = (body: string) => `\${{ ${body} }}`; /** A job's condition, with its whitespace collapsed, for comparing conditions. */ const condition = (name: string) => (job(name).if ?? "").replace(/\s+/g, " "); -test("the gate decides with release-ci-gate.ts, and re-runs the checks that read the release files when it skips the suite", () => { +const RELEASE_FILE_CHECKS = + "steps.decide.outputs.mode == 'release-files' || steps.decide.outputs.mode == 'tests'"; + +test("the gate decides with release-ci-gate.ts, and runs only what no passing run checked", () => { const gate = job("gate"); expect(needs("gate")).toEqual(["metadata", "verify"]); - expect(gate.outputs?.full_checks).toBe( - expression("steps.decide.outputs.full_checks"), - ); + for (const output of [ + "full_checks", + "mode", + "tests", + "browser_tests", + "webkit_tests", + "desktop_browser_tests", + ]) { + expect(gate.outputs?.[output]).toBe( + expression(`steps.decide.outputs.${output}`), + ); + } expect(gate.permissions).toEqual({ contents: "read", actions: "read" }); const steps = gate.steps ?? []; const decide = steps.find((step) => step.id === "decide"); @@ -65,22 +78,68 @@ test("the gate decides with release-ci-gate.ts, and re-runs the checks that read const checkout = steps.find((step) => step.uses?.startsWith("actions/checkout@"), ); - // The release commit and its parent. - expect(checkout?.with?.["fetch-depth"]).toBe(2); + // The history it compares trees along, without the file contents it does not read. + expect(checkout?.with?.["fetch-depth"]).toBe(0); + expect(checkout?.with?.filter).toBe("blob:none"); const after = steps.slice(steps.indexOf(decide as Step) + 1); - expect(after.length).toBeGreaterThan(0); + const named = (name: string) => { + const step = after.find((each) => each.name === name); + if (!step) throw new Error(`the gate has no step ${name}`); + return step; + }; + // Every step after the decision runs only when the full suite does not. for (const step of after) { - expect(step.if).toBe("steps.decide.outputs.full_checks == 'false'"); + expect(step.if ?? "").not.toBe(""); } - const runs = after.map((step) => step.run ?? "").join("\n"); - for (const check of [ - "bun run format:check", - "bun run lint", - "bun desktop/scripts/desktop-version.ts check", - "-e CHANGELOG.md -e release-policy.json", + // The release-file checks, when the release files differ from the tree that passed. + for (const name of [ + "Format and lint", + "Desktop version tracks the release version", + "The tests that read CHANGELOG.md and release-policy.json", ]) { - expect(runs).toContain(check); + expect(named(name).if).toBe(RELEASE_FILE_CHECKS); } + expect(named("Format and lint").run).toContain("bun run format:check"); + expect(named("Format and lint").run).toContain("bun run lint"); + expect( + named("The tests that read CHANGELOG.md and release-policy.json").run, + ).toContain("-e CHANGELOG.md -e release-policy.json"); + // Changed tests are type checked, as CI's `format, lint, types` would. + expect(named("Types")).toMatchObject({ + if: "steps.decide.outputs.mode == 'tests'", + run: "bun run typecheck", + }); + // The support window counts from the day of the release, so it runs whenever the suite does not, + // a tree that already passed included. + expect( + named("The 12-month support window holds on the day this is published").if, + ).toBe("steps.decide.outputs.full_checks == 'false'"); +}); + +test("the changed tests run on their own, in each engine, only when the gate says so", () => { + const tests = job("release-tests"); + expect(needs("release-tests")).toEqual(["metadata", "verify", "gate"]); + expect(condition("release-tests")).toBe( + "needs.metadata.outputs.is_release == 'true' && needs.gate.outputs.mode == 'tests'", + ); + const steps = tests.steps ?? []; + const runner = steps.find( + (step) => step.run === "bun scripts/ci-run-tests.ts", + ); + expect(runner).toBeDefined(); + expect((runner as Step & { env?: Record }).env).toEqual({ + TESTS: expression("needs.gate.outputs.tests"), + BROWSER_TESTS: expression("needs.gate.outputs.browser_tests"), + WEBKIT_TESTS: expression("needs.gate.outputs.webkit_tests"), + DESKTOP_BROWSER_TESTS: expression( + "needs.gate.outputs.desktop_browser_tests", + ), + }); + const runs = steps.map((step) => step.run ?? "").join("\n"); + expect(runs).toContain( + "playwright-core install --with-deps --no-shell chromium", + ); + expect(runs).toContain("playwright-core install --with-deps webkit"); }); test("the full checks run only when the gate says so", () => { @@ -92,14 +151,23 @@ test("the full checks run only when the gate says so", () => { }); // A skipped `checks` must not let anything through unless the gate decided to skip it and then -// passed, re-checks included. A failed gate, or a `checks` skipped for any other reason, stops it. +// passed, re-checks included, and the changed tests passed when it said they run. A failed gate, a +// failed `release tests`, or either skipped for any other reason, stops it. test("the images are built only after the full checks passed, or after the gate passed having skipped them", () => { - expect(needs("images")).toEqual(["metadata", "verify", "gate", "checks"]); + expect(needs("images")).toEqual([ + "metadata", + "verify", + "gate", + "release-tests", + "checks", + ]); expect(condition("images")).toBe( "!cancelled() && needs.metadata.outputs.is_release == 'true' && " + "needs.verify.result == 'success' && needs.gate.result == 'success' && " + "(needs.checks.result == 'success' || " + - "(needs.checks.result == 'skipped' && needs.gate.outputs.full_checks == 'false'))", + "(needs.checks.result == 'skipped' && needs.gate.outputs.full_checks == 'false' && " + + "(needs.release-tests.result == 'success' || " + + "(needs.release-tests.result == 'skipped' && needs.gate.outputs.mode != 'tests'))))", ); });