From 49052a2b3263d308eb4e6ffb6cf60f46c5713b45 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Wed, 28 Oct 2026 22:45:39 +1100 Subject: [PATCH 1/5] docs(ci): record the decisions that bring CI spending under budget CI for this repository cost about $4,000 a month on Blacksmith at the pace of October 2026. The budget for this repository and the others that share it is $1,000 a month. ADR 0002 moves light jobs to GitHub-hosted runners and heavy jobs to RunsOn machines in our own AWS account. ADR 0003 runs the expensive checks once, in merge queues on main and next, not on every push. The glossary at .github/CONTEXT.md defines the terms both records use. CONTEXT-MAP.md links to it. --- .github/CONTEXT.md | 87 ++++++++++ CONTEXT-MAP.md | 2 + ...ub-hosted-runners-heavy-jobs-on-runs-on.md | 55 ++++++ ...ks-run-in-merge-queues-on-main-and-next.md | 158 ++++++++++++++++++ 4 files changed, 302 insertions(+) create mode 100644 .github/CONTEXT.md create mode 100644 docs/adr/0002-light-ci-jobs-on-github-hosted-runners-heavy-jobs-on-runs-on.md create mode 100644 docs/adr/0003-expensive-ci-checks-run-in-merge-queues-on-main-and-next.md diff --git a/.github/CONTEXT.md b/.github/CONTEXT.md new file mode 100644 index 0000000000..9d9b099a09 --- /dev/null +++ b/.github/CONTEXT.md @@ -0,0 +1,87 @@ +# CI + +This context covers the checks that verify a change, and the machines that run +them. It covers the GitHub Actions workflows of `cipherstash/stack`. It also +covers the CI spend of the other repositories that share its budget. + +## Language + +**CI budget**: +The most that the repositories sharing it may spend on CI in one calendar +month. Vendor invoices measure it, including fixed costs such as licences and +cloud infrastructure. When an invoice also covers other repositories, only the +part for these repositories counts. List-price estimates track it between +invoices, but do not replace it. +_Avoid_: build minutes, runner minutes + +**PR push**: +A new head commit on a pull request's branch. Each one starts the push checks +again. +_Avoid_: PR run, CI run + +**Push check**: +A check that runs on every PR push, so the author learns of a failure while +still working on the change. +_Avoid_: fast check, PR check + +**Gate check**: +A check that runs when a pull request is in a merge queue, instead of on every +PR push. `main` and `next` each have a merge queue. An author can ask for a +gate check to run earlier on the pull request. A failed gate check blocks the +merge. +_Avoid_: heavy check, full CI, merge check + +**Early run**: +A run of the gate checks on a pull request before it joins a merge queue. An +author asks for one by adding the `ci:full` label. Each time the label is +added gives one early run. +_Avoid_: full run, ci:full run + +**Queue commit**: +The commit GitHub builds for a pull request in a merge queue. It contains +the entry ahead of it, plus the pull request. Checks in the queue test this commit. +_Avoid_: merge group commit, temporary branch + +**Trigger paths**: +The paths whose change makes a check run, on PR pushes and in the merge queue. +Every check has them, or a written reason for running on every change. +_Avoid_: path filter, relevance filter, affected checks + +**Selector job**: +The first job of a workflow. It selects the checks that run, by comparing the +files a change touches with each check's trigger paths. When it cannot decide, +it fails. The change then cannot merge until someone runs it again. +_Avoid_: path-filter job, decider, router + +**Summary job**: +The last job of a workflow. It passes when every check that the selector job +selected has passed. It is the only job of the workflow that branch rules +require. +_Avoid_: required job, status job + +**Failsafe**: +The test that fails when the selector job does not decide whether a job runs. +A job with a written exemption passes. The failsafe reads workflow files. It +does not act while a workflow runs. +_Avoid_: lint, selector guard, path-filter lint + +**Light job**: +A job that runs acceptably on a GitHub-hosted standard runner. Whether a job is +light says where it runs, not when: a light job can be a gate check. +_Avoid_: small job, cheap job + +**Heavy job**: +A job that needs more machine than a GitHub-hosted standard runner gives it, +and runs on a self-provisioned cloud runner instead. Whether a job is heavy +says where it runs, not when: a heavy job can be a push check. +_Avoid_: big job, 16-core job + +## Relationships + +- Three separate choices apply to each check. Its trigger paths decide whether + it runs at all. Being a push check or a gate check decides when it runs. + Being a light job or a heavy job decides where it runs. +- The fuzz regression replay, for example, is a light job and a gate check. +- Mutation testing is expensive but important. So it runs only once the + design and implementation of a change are settled. Its failures must be + fixed before the change merges. That makes it a heavy job and a gate check. diff --git a/CONTEXT-MAP.md b/CONTEXT-MAP.md index af93fdfbdf..ec9b360eea 100644 --- a/CONTEXT-MAP.md +++ b/CONTEXT-MAP.md @@ -7,6 +7,8 @@ - [Stack Encrypt](./packages/stack-encrypt/CONTEXT.md) — encrypts values under per-value ZeroKMS data keys and derives searchable terms from them, for Rust and, through a WASI guest, Go. +- [CI](./.github/CONTEXT.md) — runs the checks that verify a change, and pays + for the machines that run them, within a shared monthly budget. ## Relationships diff --git a/docs/adr/0002-light-ci-jobs-on-github-hosted-runners-heavy-jobs-on-runs-on.md b/docs/adr/0002-light-ci-jobs-on-github-hosted-runners-heavy-jobs-on-runs-on.md new file mode 100644 index 0000000000..65cc84528f --- /dev/null +++ b/docs/adr/0002-light-ci-jobs-on-github-hosted-runners-heavy-jobs-on-runs-on.md @@ -0,0 +1,55 @@ +--- +status: accepted +--- + +# Move CI from Blacksmith to GitHub-hosted runners and RunsOn + +We decided in October 2026 to stop running CI on Blacksmith. Light jobs run on +GitHub-hosted standard runners. Those runners cost nothing for this public +repository. + +Heavy jobs run on RunsOn. RunsOn starts a machine in our own AWS account for +each job. Heavy jobs use c8a machines with 8 vCPUs. Mutants uses a +c8a machine with 16 vCPUs. The other repositories that share the CI budget +move their Blacksmith jobs to RunsOn too. + +We made the change because of cost. CI for this repository cost about $3,865 a +month on Blacksmith at October 2026's pace. That was 20 times September's +cost. The CI budget for this repository and the others that share it is +$1,000 a month. + +```mermaid +flowchart LR + job[A CI job] --> size{Does a GitHub-hosted standard runner give it enough machine?} + size -- "Yes: light job" --> gh[GitHub-hosted runner. Free for this public repository. At most 60 jobs at a time for the organisation.] + size -- "No: heavy job" --> ro[RunsOn machine in our AWS account. c8a with 8 vCPUs. Mutants uses 16 vCPUs.] +``` + +## Considered options + +- **Stay on Blacksmith and run fewer jobs.** We modelled October's jobs with + gate checks in place. This repository alone still came to about $2,000 a + month at Blacksmith's prices. +- **Run every job on RunsOn.** Light jobs would then cost money. GitHub-hosted + runners run them for nothing. +- **Run every job on GitHub-hosted runners.** In the runner trial in pull + request #1297, jobs took 2.46 times as long overall. The integration suites + took up to 4.8 times as long. + +## Consequences + +- GitHub runs at most 60 jobs at a time for the organisation on the Team plan. + Light jobs wait for a runner when more than 60 jobs are queued. +- We simulated October's light jobs against that limit, with gate checks in + place. One job in a hundred waited between 7 and 11 minutes. +- A RunsOn job starts 40 to 50 seconds later than a Blacksmith job did. +- RunsOn uses discounted spot machines. When AWS has no spare c8a machines, a + job runs at the full price. The full price is more than twice the spot + price. The `family=c8a+m8a` label lets RunsOn try a second machine type + first. +- Every job sets `timeout-minutes`. In the trial, one job without a limit ran + for over 2 hours. +- We maintain the RunsOn resources in AWS. They cost $40 to $60 a month. +- RunsOn's pricing page limits its free licence to non-commercial use. The + trial licence ends in November 2026. Buying a licence is a separate + decision. diff --git a/docs/adr/0003-expensive-ci-checks-run-in-merge-queues-on-main-and-next.md b/docs/adr/0003-expensive-ci-checks-run-in-merge-queues-on-main-and-next.md new file mode 100644 index 0000000000..deab67402f --- /dev/null +++ b/docs/adr/0003-expensive-ci-checks-run-in-merge-queues-on-main-and-next.md @@ -0,0 +1,158 @@ +--- +status: accepted +--- + +# Run the expensive CI checks in merge queues on `main` and `next` + +We decided in October 2026 to split this repository's CI checks into push +checks and gate checks. Push checks run on every push to a pull request. Gate +checks run once, when the pull request is in a merge queue. `main` and `next` +each get a merge queue. + +We made the change because of cost. From 1 to 20 October 2026, 89% of this +repository's CI spending came from pull request runs. Each push ran the +expensive checks again. ADR 0002 moves jobs to cheaper machines. This decision +runs the expensive jobs less often. + +`.github/CONTEXT.md` defines the terms used here. + +```mermaid +flowchart TD + push["An author pushes to a pull request"] --> sel1{"Selector job: does the pull request have the ci:full label?"} + sel1 -- "No" --> pc["The push checks whose trigger paths changed run"] + sel1 -- "Yes" --> early["Push checks and gate checks run once. A job removes the label."] + pc --> ready["The pull request is approved. Its summary jobs pass."] + early --> ready + ready --> queue["The pull request joins the merge queue of main or next"] + queue --> sel2["Selector job compares the queue commit with the entry ahead of it"] + sel2 --> all["Push checks and gate checks run. Mutants starts at once."] + all --> sum{"Does every summary job pass?"} + sum -- "Yes" --> merge["GitHub merges the tested commit"] + sum -- "No" --> out["The pull request leaves the queue"] +``` + +## What runs where + +These are the gate checks: + +- the Test EQL suites that need a database: the PostgreSQL shards, the e2e + property suite, and the test archive build +- Mutants +- CRAP +- the fuzz regression replay +- Go on Windows and macOS, and the Go live tests +- the Drizzle, prisma-next, Supabase, and protect-ffi integration suites +- the two Prisma E2E suites +- udeps and Miri + +Every other check is a push check. + +- The merge queue runs the push checks and the gate checks against the queue + commit. A failure removes the pull request from the queue. +- Pushes to `main` no longer run the tests. The queue has already tested the + commit that GitHub merges. +- `next` gets the same branch rules as `main`, including the merge queue. + Until now, `next` had no protection. Pushes to it ran no workflows. +- Each queue builds at most 3 entries at once. The weekly cost report will + show whether to change this. +- The queues merge with merge commits, as `main` does today. The comparison + with the entry ahead needs merge commits or squash merges. + +## How a workflow decides what runs + +- A selector job starts every workflow, on a GitHub-hosted runner. It selects + the checks whose trigger paths the change touches. +- In a merge queue, the selector job compares the queue commit with its + parent. The parent is the entry ahead, so the difference is this pull + request alone. The entries ahead run their own checks. If one fails, GitHub + rebuilds the entries behind it. +- When the selector job cannot decide, it fails. The change cannot merge until + someone runs it again. So a fault in the selector job is seen at once. +- A summary job ends every workflow. It is the only job of the workflow that + branch rules require. +- The failsafe is a test in `scripts/__tests__/`, run by + `pnpm run test:scripts`. It fails when the selector job does not decide + whether a job runs. A job is exempt only with a written reason. An exemption + that matches no job also fails. + +## Early runs + +An author can add the `ci:full` label to run the gate checks early on the pull +request. A job removes the label when the early run starts. So each early run +is a deliberate request. The queue still runs the gate checks again. + +## Mutants + +- Mutants is a required gate check. It tests only the lines that the pull + request changes. In a merge queue, it finds them the same way as the + selector job. +- It runs in every queue entry except the merge of `next` into `main`. Each + change on `next` has already passed Mutants in the `next` queue. +- It runs as 4 parallel shards on c8a machines with 16 vCPUs. +- It starts at the same time as the push checks, in the queue and on early + runs. A watcher job cancels it when a push check fails. +- On an early run, a cancelled Mutants run counts as a failure. The pull + request cannot join the queue until Mutants runs again. +- The other heavy gate checks also start at once. + +## Considered options + +- **Run gate checks when a draft pull request becomes ready for review.** + Agents push to pull requests that are already ready. So most pushes would + still run everything. +- **Run gate checks when a pull request is approved.** On `main`, an approval + stays valid after later pushes. So code pushed after an approval would merge + without gate checks. +- **Run gate checks only when an author adds a label, with no merge queue.** + That depends on people remembering to add it. +- **Filter workflows by path in `on:`, not in a selector job.** GitHub cannot + filter `merge_group` events by path. A workflow that a path filter skips + leaves its required checks pending. GitHub's documentation on required + status checks says that blocks the merge. +- **Compare each queue commit with the base branch.** With 3 entries + building, the third entry's difference includes the two ahead of it. + Mutants would test their lines again. A failure could point to another + author's lines. +- **Run every check when the selector job cannot decide.** No needed check + would be skipped. But nobody would notice a fault in the selector job. Each + fault would also cost a full run. +- **Run Mutants on the merge of `next` into `main` as well.** That run tests + every line `next` added, a second time. In October 2026, it reached its + 120-minute timeout at least twice on pull request #1229. +- **Run Mutants only in the `main` queue.** All of `next` would be tested at + once, when it merges into `main`. A failure would then point to anyone who + changed `next`. +- **Start Mutants after every push check passes.** That spends nothing on + failing commits. But it adds up to 14 minutes to each queue entry and early + run. In the queue, push checks rarely fail. A pull request joins only after + its required checks pass. +- **Keep the `ci:full` label until the author removes it.** A forgotten label + would run every gate check on every later push. + +## Consequences + +- Authors learn of a gate check failure in the queue, unless they ask for an + early run. +- A merge waits for the slowest gate check. Each queue's status check timeout + must be longer than that check takes. +- Every workflow with a required summary job must also run on `merge_group`. + GitHub's merge queue documentation says the queue starts no workflow + without it. The queue would then wait for a check that never reports. +- The queue setting "Only merge non-failing pull requests" stays on. Without + it, a pull request that failed could merge with the one behind it. +- The smallest group the queue merges is 1 pull request. So a lone pull + request never waits for others. +- Workflows must start when any label is added, because GitHub cannot filter + that event by label name. That run reports under the same check names as + the push run. A test branch must show that it cannot replace an earlier + failure. +- Commits made by the merge queue must pass the rule that requires signed + commits. A test branch must show this before the queues start. +- A test branch must also confirm that a queue commit's parent is the entry + ahead of it. GitHub's webhook schema calls `base_sha` the merge group's + parent commit. It does not say which commit that is. +- After a flaky push check on an early run, the author must re-run Mutants as + well. +- While it waits, the watcher holds one of the organisation's 60 + GitHub-hosted job slots. It waits up to about 14 minutes. +- This decision covers this repository only. `proxy` may follow later. From 8cd07860f5e28750d597f8d1afc8920d7a0f2a9b Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Wed, 28 Oct 2026 22:45:59 +1100 Subject: [PATCH 2/5] ci(test-eql): run the Postgres suite only for changes to EQL Test EQL decided whether to run its heavy jobs from one list of paths. That list included the stack-* crates, so a pull request that changed only stack-encrypt ran the whole Postgres suite. Only the Rust workspace crates job compiles those crates, through the stack-encrypt feature of eql-bindings. The SQLx suite and the codegen crates never enable it. The first job is now the selector job from ADR 0003. It runs on a GitHub-hosted runner, because every gated job waits for it. The selector has two filters. Nine jobs read eql. The Rust workspace crates job reads rust_crates. That filter adds the stack-* crates and the root Cargo.toml. On a pull request, the selector now fails when a filter gives no answer. Before, a missing answer skipped every gated job, and ci-required counts skipped as passed. eql-selector.test.mjs runs the selector's own script for a simulated pull request and evaluates each job's if: against its outputs. --- .github/workflows/test-eql.yml | 123 ++++++---- scripts/__tests__/eql-selector.test.mjs | 212 ++++++++++++++++++ scripts/__tests__/eql-suite-ci.test.mjs | 34 ++- .../__tests__/eql-workflow-filters.test.mjs | 71 ++---- scripts/__tests__/lib/paths-filter.mjs | 25 +++ .../workflow-dispatch-job-conditions.test.mjs | 6 +- .../workflow-paths-filter-parity.test.mjs | 4 +- 7 files changed, 368 insertions(+), 107 deletions(-) create mode 100644 scripts/__tests__/eql-selector.test.mjs diff --git a/.github/workflows/test-eql.yml b/.github/workflows/test-eql.yml index b3d0c2d601..cd330d1c2a 100644 --- a/.github/workflows/test-eql.yml +++ b/.github/workflows/test-eql.yml @@ -31,8 +31,8 @@ name: "Test EQL" # in every shard instead of saying what was missing. # # NB: NO path filter on `pull_request`. A workflow skipped by a path filter -# leaves its required checks stuck Pending and blocks merge. Relevance is -# computed by the `changes` job and applied per-job via `if:` instead. `push` +# leaves its required checks stuck Pending and blocks merge. The `selector` job +# decides which jobs a pull request needs, and each job's `if:` reads it. `push` # carries one because nothing waits on a push run, so a skipped one costs # nothing — and the two lists are kept identical by # `scripts/__tests__/eql-workflow-filters.test.mjs`. @@ -70,7 +70,7 @@ on: pull_request: {} push: branches: [main] - # Identical to the `relevant:` filter in the `changes` job below. GitHub + # Identical to the union of the `selector` job's filters below. GitHub # Actions has no YAML anchors, so the list is written twice; the guard named # above fails a one-sided edit. # @@ -148,14 +148,23 @@ concurrency: cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: - # Runs on EVERY event and MUST always succeed (never skipped, never failed) — - # downstream heavy jobs `needs: [changes]`, and a skipped/failed `changes` - # would either skip the merge-queue matrix or deadlock `ci-required`. - changes: - name: "Detect relevant changes" - runs-on: blacksmith-16vcpu-ubuntu-2204 + # The selector job: it decides which gated jobs a pull request needs. It runs + # on EVERY event and is never skipped, because every gated job `needs:` it. + # When it cannot decide it FAILS, which fails `ci-required`: a selector that + # answered nothing would skip every gated job, and `ci-required` counts + # skipped as passed (ADR 0003). + # + # On a GitHub-hosted runner because every gated job waits for it, and a + # self-provisioned machine takes longer to start. + selector: + name: "Selector" + runs-on: ubuntu-latest + # Each output is named after the filter that decides it; + # `scripts/__tests__/eql-selector.test.mjs` follows a job's `if:` to its + # filter by that name. outputs: - relevant: ${{ steps.r.outputs.relevant }} + eql: ${{ steps.r.outputs.eql }} + rust_crates: ${{ steps.r.outputs.rust_crates }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 with: @@ -177,8 +186,9 @@ jobs: # matrix on changes that cannot affect EQL, and (worse) NOT firing on # EQL's own `src/`, since nothing at the repo root is called that. # - # Identical to the `push` `paths:` list at the top of this file — the - # same question asked of two mechanisms GitHub gives no way to share. + # The union of the two filters is identical to the `push` `paths:` + # list at the top of this file — the same question asked of two + # mechanisms GitHub gives no way to share. # `scripts/__tests__/eql-workflow-filters.test.mjs` compares them, and # also fails any entry here that matches no tracked file (a dead # `packages/eql/sql/**` sat in this list from the port: there is no @@ -191,8 +201,14 @@ jobs: # copies are held EQUAL — see the note above the `push` list, and the # reasoning on `bench-eql.yml`'s own filter for why equal beats # minimal. + # + # `rust_crates` adds the stack-* crates to `eql`. Only `rust-crates` + # compiles them, through eql-bindings' `stack-encrypt` feature; + # `tests/sqlx` and the codegen crates never enable it. With the crates + # on one shared list, a change to stack-encrypt alone ran the whole + # Postgres suite. dorny flattens the `*eql` alias into the list. filters: | - relevant: + eql: &eql - ".github/workflows/test-eql.yml" - ".github/actions/require-cs-secrets/**" - "packages/eql/src/**" @@ -207,6 +223,8 @@ jobs: - "packages/eql/docker/**" - "packages/eql/README.md" - "packages/eql/SUPABASE.md" + rust_crates: + - *eql - "packages/stack-encrypt/**" - "packages/stack-encrypt-derive/**" - "packages/stack-kms/**" @@ -217,25 +235,38 @@ jobs: # Explicit default (not `|| 'true'`, which trips GitHub's inconsistent # treatment of the string 'false'). push/schedule/merge_group/dispatch # never run the filter above — it needs a base ref that only a pull - # request has — so they take the default, and `push` is already narrowed + # request has — so they select every job, and `push` is already narrowed # by its own `on:`-level `paths:`. # - # The event arrives through `env:`, not through a `${{ }}` interpolated - # into the body. That is what lets + # On a pull request, an answer other than `true` or `false` means the + # filter did not decide, so the step fails rather than write it. + # + # The event and the answers arrive through `env:`, not through a `${{ }}` + # interpolated into the body. That is what lets + # `scripts/__tests__/eql-selector.test.mjs` and # `scripts/__tests__/eql-matrix-triggers.test.mjs` EXECUTE this script - # once per event and read back what it wrote, rather than reimplementing - # the branch and agreeing with a rewritten one by luck. + # and read back what it wrote, rather than reimplementing the branch and + # agreeing with a rewritten one by luck. - id: r env: EVENT_NAME: ${{ github.event_name }} - FILTER_RELEVANT: ${{ steps.f.outputs.relevant }} + EQL: ${{ steps.f.outputs.eql }} + RUST_CRATES: ${{ steps.f.outputs.rust_crates }} run: | set -euo pipefail - if [ "$EVENT_NAME" = "pull_request" ]; then - echo "relevant=$FILTER_RELEVANT" >> "$GITHUB_OUTPUT" - else - echo "relevant=true" >> "$GITHUB_OUTPUT" + if [ "$EVENT_NAME" != "pull_request" ]; then + EQL=true + RUST_CRATES=true fi + for answer in "eql=$EQL" "rust_crates=$RUST_CRATES"; do + case "${answer#*=}" in + true|false) echo "$answer" >> "$GITHUB_OUTPUT" ;; + *) + echo "::error::The path filter answered '${answer#*=}' for ${answer%%=*}. The selector cannot decide which jobs to run." + exit 1 + ;; + esac + done # Pure bash; no checkout/toolchain. Derives the PG-version + shard fan-out # from the event: PR and manual dispatch -> PG17 x 4 shards (latency lane); @@ -292,7 +323,7 @@ jobs: # when relevant files changed (docs-only PRs never pay the ~4-min compile). build-archive: name: "Build test archive" - needs: [changes] + needs: [selector] # This repo is PUBLIC and accepts fork PRs (the approval policy only gates # first-time contributors). build-archive is the sole holder of the CS_* # credentials below, so it must never run on a fork PR. The trailing clause @@ -310,7 +341,7 @@ jobs: # `scripts/__tests__/workflow-dispatch-job-conditions.test.mjs`. if: >- (github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true') + || needs.selector.outputs.eql == 'true') && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) runs-on: blacksmith-16vcpu-ubuntu-2204 @@ -392,11 +423,11 @@ jobs: # shards start right after build-archive. test: name: "Shard PG${{ matrix.postgres-version }} ${{ matrix.shard }}/${{ needs.setup.outputs.shard-total }}" - needs: [changes, setup, build-archive] + needs: [selector, setup, build-archive] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 strategy: fail-fast: false @@ -454,11 +485,11 @@ jobs: # of the old per-version test job so they run ONCE per version, not per shard. validate: name: "Validate (Postgres ${{ matrix.postgres-version }})" - needs: [changes, setup] + needs: [selector, setup] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 strategy: fail-fast: false @@ -513,11 +544,11 @@ jobs: schema: name: "JSON Schema validation" - needs: [changes] + needs: [selector] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 @@ -542,11 +573,13 @@ jobs: rust-crates: name: "Rust workspace crates" - needs: [changes] - # Exclusion, not an allowlist — see the note on `build-archive`. + needs: [selector] + # Exclusion, not an allowlist — see the note on `build-archive`. Reads + # `rust_crates`, not `eql`: this is the one job that compiles the stack-* + # crates. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.rust_crates == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 services: encryption-postgres: @@ -670,11 +703,11 @@ jobs: codegen: name: "Encrypted-domain codegen" - needs: [changes] + needs: [selector] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 @@ -702,11 +735,11 @@ jobs: self-contained-v3: name: "eql_v3 self-containment" - needs: [changes] + needs: [selector] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 @@ -738,11 +771,11 @@ jobs: matrix-coverage: name: "Matrix coverage inventory" - needs: [changes] + needs: [selector] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6 @@ -780,11 +813,11 @@ jobs: splinter: name: "Supabase splinter" - needs: [changes] + needs: [selector] # Exclusion, not an allowlist — see the note on `build-archive`. if: >- github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true' + || needs.selector.outputs.eql == 'true' runs-on: blacksmith-16vcpu-ubuntu-2204 env: POSTGRES_VERSION: "17" @@ -947,12 +980,12 @@ jobs: # fork-PR guard to keep the secrets off fork runs. e2e: name: "e2e property suite (fresh encryption)" - needs: [changes, setup] + needs: [selector, setup] # Exclusion, not an allowlist — see the note on `build-archive`, which # carries the same two clauses for the same two reasons. if: >- (github.event_name != 'pull_request' - || needs.changes.outputs.relevant == 'true') + || needs.selector.outputs.eql == 'true') && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository) runs-on: blacksmith-16vcpu-ubuntu-2204 @@ -1002,7 +1035,7 @@ jobs: # source job is itself in `needs` and reports failure. ci-required: name: "ci-required" - needs: [changes, setup, build-archive, test, validate, schema, rust-crates, + needs: [selector, setup, build-archive, test, validate, schema, rust-crates, codegen, self-contained-v3, matrix-coverage, splinter, docs-static, known-failures, doc-anchors, e2e] if: always() diff --git a/scripts/__tests__/eql-selector.test.mjs b/scripts/__tests__/eql-selector.test.mjs new file mode 100644 index 0000000000..99afe4fab2 --- /dev/null +++ b/scripts/__tests__/eql-selector.test.mjs @@ -0,0 +1,212 @@ +import { spawnSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import yaml from 'js-yaml' +import { afterAll, describe, expect, it } from 'vitest' +import { runsWhen } from './lib/expressions.mjs' +import { pathsGlobToRegExp } from './lib/paths-filter.mjs' +import { readWorkflow } from './lib/workflows.mjs' + +/** + * Test EQL's selector job decides which checks a pull request runs, by + * matching the changed files against each check's trigger paths. + * + * Only `rust-crates` compiles the stack-* crates, through eql-bindings' + * `stack-encrypt` feature. Every other job builds `tests/sqlx` or the + * codegen crates, which do not enable it. While the crates sat on the one list + * that gated every job, a pull request touching only stack-encrypt ran the + * whole Postgres suite. + * + * The selector is exercised the way GitHub runs it: the filter results go + * into the real decision script, and each job's real `if:` reads its outputs. + */ + +const WORKFLOW = '.github/workflows/test-eql.yml' +const SELECTOR = 'selector' +const REPO = 'cipherstash/stack' + +const wf = readWorkflow(WORKFLOW) +const selector = wf?.jobs?.[SELECTOR] + +const stepOutput = (expression) => + /steps\.([A-Za-z0-9_-]+)\.outputs\.([A-Za-z0-9_-]+)/.exec( + String(expression ?? ''), + ) + +const filterStep = (selector?.steps ?? []).find((step) => + String(step?.uses ?? '').startsWith('dorny/paths-filter@'), +) + +// dorny flattens a list that includes an anchored list; so does this. +const FILTERS = Object.fromEntries( + Object.entries(yaml.load(filterStep?.with?.filters ?? '') ?? {}).map( + ([name, globs]) => [name, [globs].flat(Infinity)], + ), +) + +const decideStepId = stepOutput(Object.values(selector?.outputs ?? {})[0])?.[1] +const decideStep = (selector?.steps ?? []).find( + (step) => step?.id === decideStepId, +) + +const GATED = Object.entries(wf?.jobs ?? {}) + .map(([id, job]) => ({ + id, + job, + output: new RegExp(`needs\\.${SELECTOR}\\.outputs\\.([A-Za-z0-9_-]+)`).exec( + String(job?.if ?? ''), + )?.[1], + })) + .filter((entry) => entry.output) + +const SCRATCH = mkdtempSync(join(tmpdir(), 'eql-selector-')) +afterAll(() => rmSync(SCRATCH, { recursive: true, force: true })) +let runCounter = 0 + +/** + * Runs the decision script with the filter results GitHub would substitute. + * An env entry that names no filter result gets the empty string, as GitHub + * substitutes for an expression that resolves to nothing. + */ +function decide(eventName, filterResults) { + runCounter += 1 + const outputFile = join(SCRATCH, `outputs-${runCounter}.txt`) + writeFileSync(outputFile, '') + const env = { PATH: process.env.PATH, GITHUB_OUTPUT: outputFile } + for (const [key, value] of Object.entries(decideStep?.env ?? {})) { + const text = String(value) + if (/github\.event_name/.test(text)) env[key] = eventName + else env[key] = filterResults[stepOutput(text)?.[2]] ?? '' + } + const run = spawnSync('bash', ['-c', String(decideStep?.run)], { + cwd: SCRATCH, + env, + encoding: 'utf8', + }) + const written = Object.fromEntries( + readFileSync(outputFile, 'utf8') + .split('\n') + .filter(Boolean) + .map((line) => [ + line.slice(0, line.indexOf('=')), + line.slice(line.indexOf('=') + 1), + ]), + ) + const outputs = Object.fromEntries( + Object.entries(selector?.outputs ?? {}).map(([name, expression]) => [ + name, + written[stepOutput(expression)?.[2]], + ]), + ) + return { status: run.status, stderr: `${run.stdout}${run.stderr}`, outputs } +} + +/** The gated jobs a same-repository pull request runs, given its files. */ +function jobsRunFor(changedFiles) { + const filterResults = Object.fromEntries( + Object.entries(FILTERS).map(([name, globs]) => [ + name, + String( + changedFiles.some((file) => + globs.some((glob) => pathsGlobToRegExp(glob).test(file)), + ), + ), + ]), + ) + const { status, stderr, outputs } = decide('pull_request', filterResults) + expect(status, stderr).toBe(0) + const context = { + github: { + event_name: 'pull_request', + repository: REPO, + event: { pull_request: { head: { repo: { full_name: REPO } } } }, + }, + needs: { [SELECTOR]: { result: 'success', outputs } }, + vars: {}, + } + return GATED.filter(({ job }) => runsWhen(job.if, context)) + .map(({ id }) => id) + .sort() +} + +const ALL_GATED = GATED.map(({ id }) => id).sort() + +describe('the Test EQL selector job', () => { + it('finds the selector, its filters, and the jobs it gates', () => { + expect(selector, `${WORKFLOW} has no \`${SELECTOR}\` job.`).toBeTruthy() + expect( + Object.keys(FILTERS), + 'The selector has no path filters.', + ).not.toEqual([]) + expect( + decideStep, + 'No step produces the selector job outputs.', + ).toBeTruthy() + expect(ALL_GATED).toContain('rust-crates') + expect(ALL_GATED.length).toBeGreaterThan(1) + }) + + it('runs on a GitHub-hosted runner', () => { + // ADR 0003: a RunsOn machine takes 40 to 50 seconds to start, and every + // other job in the run waits for this one. + expect(String(selector?.['runs-on'])).toMatch(/^ubuntu-/) + }) + + it('names each output after the path filter that decides it', () => { + // eql-suite-ci.test.mjs follows a job's `if:` to its filter by this name. + for (const { id, output } of GATED) { + expect( + Object.keys(FILTERS), + `"${id}" reads \`needs.${SELECTOR}.outputs.${output}\`, and the selector has no path filter called "${output}".`, + ).toContain(output) + } + }) + + it('runs only rust-crates for a change to a stack crate', () => { + expect(jobsRunFor(['packages/stack-encrypt/src/lib.rs'])).toEqual([ + 'rust-crates', + ]) + expect(jobsRunFor(['Cargo.toml'])).toEqual(['rust-crates']) + }) + + it('runs every gated job for a change to EQL', () => { + expect(jobsRunFor(['packages/eql/src/v3/schema.sql'])).toEqual(ALL_GATED) + expect(jobsRunFor([WORKFLOW])).toEqual(ALL_GATED) + }) + + it('runs no gated job for a change outside EQL and the crates', () => { + expect( + jobsRunFor(['languages/typescript/packages/stack/src/index.ts']), + ).toEqual([]) + }) + + it('opens every output on events other than pull_request', () => { + // The filter runs only on pull_request. Every other event takes the + // default, and a wrong default skips every gated job behind a green run. + for (const event of [ + 'push', + 'schedule', + 'merge_group', + 'workflow_dispatch', + ]) { + const { status, outputs } = decide(event, {}) + expect(status).toBe(0) + for (const name of Object.keys(selector?.outputs ?? {})) + expect(outputs[name], `${name} on ${event}`).toBe('true') + } + }) + + it('fails when a pull request filter gives no answer', () => { + // A missing answer would skip every gated job, and `ci-required` counts + // skipped as passed: a green run that ran nothing. + expect(decideStep?.run).toBeTruthy() + for (const bad of [ + {}, + Object.fromEntries(Object.keys(FILTERS).map((name) => [name, 'maybe'])), + ]) { + const { status } = decide('pull_request', bad) + expect(status).not.toBe(0) + } + }) +}) diff --git a/scripts/__tests__/eql-suite-ci.test.mjs b/scripts/__tests__/eql-suite-ci.test.mjs index ee00032a80..2f37dcc384 100644 --- a/scripts/__tests__/eql-suite-ci.test.mjs +++ b/scripts/__tests__/eql-suite-ci.test.mjs @@ -209,13 +209,15 @@ describe('the relevance filter still selects the imported tree', () => { * parsed rather than pattern-matched — a regex over the raw block would also * match the surrounding commentary. */ - const filterPaths = Object.values(wf?.jobs ?? {}) - .flatMap((job) => job?.steps ?? []) - .filter((step) => (step?.uses ?? '').startsWith('dorny/paths-filter@')) - .flatMap((step) => { - const filters = yaml.load(step?.with?.filters ?? '') - return Object.values(filters ?? {}).flat() - }) + const filters = Object.assign( + {}, + ...Object.values(wf?.jobs ?? {}) + .flatMap((job) => job?.steps ?? []) + .filter((step) => (step?.uses ?? '').startsWith('dorny/paths-filter@')) + .map((step) => yaml.load(step?.with?.filters ?? '') ?? {}), + ) + // A filter that includes an anchored list parses to a nested list. + const filterPaths = [...new Set(Object.values(filters).flat(Infinity))] it('finds the paths-filter step', () => { // Without this the check below iterates an empty list and passes having @@ -395,17 +397,29 @@ describe('the relevance filter still selects the imported tree', () => { // The other direction: a path dependency outside the subtree that the // filter does NOT select is a job that compiles a crate and never runs on // a change to it — the gap commit 7219ea1ad repaired by hand, now derived. + // + // Checked against the filter the `rust-crates` job reads, not the union: + // that job is the one that compiles them, and the other jobs' filter + // leaves them out on purpose (eql-selector.test.mjs). + const filterName = /needs\.selector\.outputs\.([A-Za-z0-9_-]+)/.exec( + String(wf?.jobs?.['rust-crates']?.if ?? ''), + )?.[1] + const rustCratesPaths = [filters[filterName] ?? []].flat(Infinity) + expect( + rustCratesPaths, + `The \`rust-crates\` job in ${EQL_WORKFLOW} reads no selector filter, so this check has nothing to compare.`, + ).not.toEqual([]) const missing = externalPathDependencies.dirs .map((dir) => `${dir}/**`) - .filter((glob) => !filterPaths.includes(glob)) + .filter((glob) => !rustCratesPaths.includes(glob)) if ( externalPathDependencies.inherits && - !filterPaths.includes('Cargo.toml') + !rustCratesPaths.includes('Cargo.toml') ) missing.push('Cargo.toml') expect( missing, - `The EQL workspace compiles these by path and the relevance filter in ${EQL_WORKFLOW} does not select them, so the \`rust-crates\` job skips on a change that can break it. Add each to the filter — and, because the three copies are held equal, to the \`push: paths:\` list and to bench-eql.yml in the same edit.\n${missing.map((p) => ` ${p}`).join('\n')}`, + `The EQL workspace compiles these by path and the \`${filterName}\` filter in ${EQL_WORKFLOW} does not select them, so the \`rust-crates\` job skips on a change that can break it. Add each to that filter — and, because the copies are held equal, to the \`push: paths:\` list and to bench-eql.yml in the same edit.\n${missing.map((p) => ` ${p}`).join('\n')}`, ).toEqual([]) }) }) diff --git a/scripts/__tests__/eql-workflow-filters.test.mjs b/scripts/__tests__/eql-workflow-filters.test.mjs index 5f230772d7..a6fb919600 100644 --- a/scripts/__tests__/eql-workflow-filters.test.mjs +++ b/scripts/__tests__/eql-workflow-filters.test.mjs @@ -3,6 +3,7 @@ import { readFileSync } from 'node:fs' import { join } from 'node:path' import yaml from 'js-yaml' import { describe, expect, it } from 'vitest' +import { pathsGlobToRegExp } from './lib/paths-filter.mjs' import { REPO_ROOT } from './lib/repo-root.mjs' import { readWorkflow } from './lib/workflows.mjs' @@ -12,9 +13,10 @@ import { readWorkflow } from './lib/workflows.mjs' * * `test-eql.yml` writes its list TWICE and in two different mechanisms: an * `on: push: paths:` filter (which decides whether the workflow starts at all - * after a merge) and a `dorny/paths-filter` `relevant:` filter (which decides - * whether the heavy jobs run inside a pull-request run). GitHub gives no way to - * share them. `bench-eql.yml` writes a third copy, for the same tree, on its own + * after a merge) and the selector job's `dorny/paths-filter` filters (which + * decide which heavy jobs run inside a pull-request run). GitHub gives no way + * to share them. The selector splits its list by job, so the copy compared + * here is the union of its filters. `bench-eql.yml` writes a third copy, for the same tree, on its own * `push` trigger. * * Three properties, and each of them was violated by the imported files: @@ -73,21 +75,26 @@ function pushPaths(relPath) { /** * Every path listed by a `dorny/paths-filter` step, across every filter it - * declares. `filters:` is a YAML document embedded in a YAML string, so it is - * parsed rather than pattern-matched — a regex over the raw block would also - * match the commentary around it. + * declares, once each. `filters:` is a YAML document embedded in a YAML string, + * so it is parsed rather than pattern-matched — a regex over the raw block + * would also match the commentary around it. */ function dornyFilterPaths(relPath) { const wf = readWorkflow(relPath) - return Object.values(wf?.jobs ?? {}) - .flatMap((job) => job?.steps ?? []) - .filter((step) => - String(step?.uses ?? '').startsWith('dorny/paths-filter@'), - ) - .flatMap((step) => - Object.values(yaml.load(step?.with?.filters ?? '') ?? {}), - ) - .flat() + return [ + ...new Set( + Object.values(wf?.jobs ?? {}) + .flatMap((job) => job?.steps ?? []) + .filter((step) => + String(step?.uses ?? '').startsWith('dorny/paths-filter@'), + ) + .flatMap((step) => + Object.values(yaml.load(step?.with?.filters ?? '') ?? {}), + ) + // An entry that is an anchored list parses to a nested list. + .flat(Infinity), + ), + ] } /** The local composite actions a workflow reaches through `uses: ./…`. */ @@ -114,37 +121,7 @@ function trackedUnder(pathspec) { .filter(Boolean) } -/** - * Approximates picomatch, which is what `dorny/paths-filter` and GitHub's own - * `paths:` matcher are built on: `*` stops at a separator, `**` does not. - * - * No implicit-descendants tail here, unlike the `@actions/glob` approximation - * in `ffi-binding-action.test.mjs` — a bare directory name is NOT a prefix - * match in a `paths:` filter, which is the difference that makes a - * `.../require-cs-secrets` entry without its `/**` cover nothing. - */ -function globToRegExp(pattern) { - let source = '^' - for (let i = 0; i < pattern.length; i += 1) { - const ch = pattern[i] - if (ch === '*') { - if (pattern[i + 1] === '*') { - source += '.*' - i += 1 - if (pattern[i + 1] === '/') i += 1 - } else { - source += '[^/]*' - } - } else if (ch === '?') { - source += '[^/]' - } else { - source += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&') - } - } - return new RegExp(`${source}$`) -} - -const matches = (pattern, path) => globToRegExp(pattern).test(path) +const matches = (pattern, path) => pathsGlobToRegExp(pattern).test(path) /** Everything in the index a filter entry could plausibly select. */ const TRACKED = trackedUnder('.') @@ -152,7 +129,7 @@ const TRACKED = trackedUnder('.') /** The list each mechanism carries, keyed for the messages below. */ const LISTS = [ { id: `${TEST_EQL} (on.push.paths)`, entries: pushPaths(TEST_EQL) }, - { id: `${TEST_EQL} (dorny relevant:)`, entries: dornyFilterPaths(TEST_EQL) }, + { id: `${TEST_EQL} (selector filters)`, entries: dornyFilterPaths(TEST_EQL) }, { id: `${BENCH_EQL} (on.push.paths)`, entries: pushPaths(BENCH_EQL) }, ] diff --git a/scripts/__tests__/lib/paths-filter.mjs b/scripts/__tests__/lib/paths-filter.mjs index 29710f536c..57e77c10ce 100644 --- a/scripts/__tests__/lib/paths-filter.mjs +++ b/scripts/__tests__/lib/paths-filter.mjs @@ -1,3 +1,28 @@ +// Approximates picomatch, the matcher behind dorny/paths-filter and GitHub's +// `paths:`: `*` stops at a separator and `**` does not. A bare directory name +// is not a prefix match, so `.../require-cs-secrets` without `/**` covers +// nothing. +export function pathsGlobToRegExp(pattern) { + let source = '^' + for (let i = 0; i < pattern.length; i += 1) { + const ch = pattern[i] + if (ch === '*') { + if (pattern[i + 1] === '*') { + source += '.*' + i += 1 + if (pattern[i + 1] === '/') i += 1 + } else { + source += '[^/]*' + } + } else if (ch === '?') { + source += '[^/]' + } else { + source += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&') + } + } + return new RegExp(`${source}$`) +} + const globPrefix = (pattern) => { const segments = pattern.split('/') const at = segments.findIndex((segment) => /[*?[]/.test(segment)) diff --git a/scripts/__tests__/workflow-dispatch-job-conditions.test.mjs b/scripts/__tests__/workflow-dispatch-job-conditions.test.mjs index 3b02b86e77..e727e71fef 100644 --- a/scripts/__tests__/workflow-dispatch-job-conditions.test.mjs +++ b/scripts/__tests__/workflow-dispatch-job-conditions.test.mjs @@ -174,13 +174,13 @@ function extractForkClause(condition) { * held open — otherwise a job that skips for an unrelated reason reads as a * job the fork guard skipped, and the assertion below would be satisfied by * the wrong mechanism. `test-eql.yml`'s two credentialed jobs are `&&`-ed with - * `needs.changes.outputs.relevant == 'true'`, which is that unrelated reason: + * `needs.selector.outputs.eql == 'true'`, which is that unrelated reason: * with `needs` absent the path resolves to null, `null == 'true'` is false, * and both jobs read as skipped on EVERY event including the ones that must * run. */ const PERMISSIVE_NEEDS = { - changes: { outputs: { relevant: 'true' } }, + selector: { outputs: { eql: 'true', rust_crates: 'true' } }, // The release workflows' gates, none of which is about how the run was // triggered. Held open, or "skips because there is nothing to publish" would // be indistinguishable from "skips on a dispatch". @@ -447,7 +447,7 @@ describe('the fork-PR guard keeps its meaning', () => { expect( verdicts, - ` if: ${condition}\nEvaluated with every OTHER gate held open (needs.changes.outputs.relevant = 'true'), so a false here is the fork guard's doing and nothing else.`, + ` if: ${condition}\nEvaluated with every OTHER gate held open (needs.selector.outputs.* = 'true'), so a false here is the fork guard's doing and nothing else.`, ).toEqual(expected) }) } diff --git a/scripts/__tests__/workflow-paths-filter-parity.test.mjs b/scripts/__tests__/workflow-paths-filter-parity.test.mjs index 5e719237c9..74ab3af627 100644 --- a/scripts/__tests__/workflow-paths-filter-parity.test.mjs +++ b/scripts/__tests__/workflow-paths-filter-parity.test.mjs @@ -159,9 +159,9 @@ const EXPECTED_ASYMMETRIES = new Map([ // `push` one, so the PR introducing a change never runs the suite — is // unreachable when `pull_request` has no filter at all. The push list is // not unchecked: `eql-workflow-filters.test.mjs` compares it against the - // `relevant:` filter in the `changes` job, which is the second copy of the + // union of the selector job's filters, which is the second copy of the // same list and the one this file cannot see. - 'pull_request is deliberately unfiltered (per-job relevance instead), so PRs run a superset of what push runs; the push list is compared against the `changes` job filter by eql-workflow-filters.test.mjs', + 'pull_request is deliberately unfiltered (per-job relevance instead), so PRs run a superset of what push runs; the push list is compared against the selector job filters by eql-workflow-filters.test.mjs', ], [ '.github/workflows/bench-eql.yml', From 219e15eae71cee3867ca81ed29531852d81fcddf Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Wed, 28 Oct 2026 23:38:22 +1100 Subject: [PATCH 3/5] test(ci): add the failsafe for selector jobs The selector job decides which checks run on a pull request. A job that does not read its answer runs on every change. That costs money, and nothing shows it. The failsafe reads every workflow that runs on pull_request or merge_group. It fails when the selector job does not decide whether a job runs, unless the job has a written reason to run on every change. An exemption that matches nothing also fails, so the lists stay true. Only test-eql.yml has a selector job so far. Every other workflow starts as an exemption, and each conversion removes its entry. The two review bot workflows are exempt for good: they are not checks, and no branch rule requires them. --- scripts/__tests__/failsafe.test.mjs | 282 ++++++++++++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 scripts/__tests__/failsafe.test.mjs diff --git a/scripts/__tests__/failsafe.test.mjs b/scripts/__tests__/failsafe.test.mjs new file mode 100644 index 0000000000..c8145aebeb --- /dev/null +++ b/scripts/__tests__/failsafe.test.mjs @@ -0,0 +1,282 @@ +import { describe, expect, it } from 'vitest' +import { readWorkflow, workflowFiles } from './lib/workflows.mjs' + +/** + * The failsafe: the test that fails when the selector job does not decide + * whether a job runs. + * + * ADR 0003 and `.github/CONTEXT.md` describe the design. A selector job starts + * each workflow that runs on a pull request or in a merge queue. It compares + * the files a change touches with each check's trigger paths. Each job's `if:` + * reads its answer. A job that does not read it runs on every change. That + * costs money, and nobody notices. This test makes it visible. + * + * It reads every workflow that runs on `pull_request` or `merge_group`. In + * each one, a job passes when one of these is true: + * + * - It is the selector job, or the summary job that ends the workflow. + * - Its `needs:` includes the selector job and its `if:` reads the selector + * job's outputs. Each output it reads must be one the selector job declares: + * an output that does not exist is empty, and the job would never run. + * - It needs a job that passes by the rule above, and its `if:` calls no + * `always()`, `failure()` or `cancelled()`. GitHub then skips it whenever + * that job is skipped, so the selector decides it too. + * - It has a written reason in `RUNS_ON_EVERY_CHANGE`. + * + * A whole workflow can be exempt, with a written reason, in `NOT_CHECKS` or + * `NOT_YET_CONVERTED`. An exemption that matches nothing, or is no longer + * needed, fails the test. So the lists only hold what is true today. + * + * The failsafe reads workflow files. It does not act while a workflow runs. + */ + +const SELECTOR = 'selector' + +/** + * Workflows that will never have a selector job. They are not checks, and no + * branch rule requires them. + */ +const NOT_CHECKS = { + '.github/workflows/claude-review.yml': + 'Review bot, not a check. No branch rule requires it.', + '.github/workflows/code-review.yml': + 'Review bot, not a check. No branch rule requires it.', +} + +/** + * Workflows that do not have a selector job yet. Each conversion removes its + * entry, and this list shrinks to empty. + */ +const NOT_YET_CONVERTED = Object.fromEntries( + [ + 'codeql.yml', + 'crap-crates.yml', + 'fta-v3.yml', + 'fuzz.yml', + 'impact.yml', + 'integration-drizzle.yml', + 'integration-prisma-next.yml', + 'integration-protect-ffi.yml', + 'integration-supabase.yml', + 'lint-release.yml', + 'miri.yml', + 'musl-build-image.yml', + 'mutants.yml', + 'osv-scanner.yml', + 'prisma-example-readme-e2e.yml', + 'prisma-next-e2e.yml', + 'require-auth-npm-changeset.yml', + 'tests-auth-refresh.yml', + 'tests-bench.yml', + 'tests-crates.yml', + 'tests-golang.yml', + 'tests-rust.yml', + 'tests-supply-chain.yml', + 'tests.yml', + 'udeps.yml', + ].map((name) => [ + `.github/workflows/${name}`, + 'Not yet converted to a selector job.', + ]), +) + +/** + * Jobs in a workflow with a selector job that run on every change, on + * purpose. Keyed `#`. + */ +const RUNS_ON_EVERY_CHANGE = { + '.github/workflows/test-eql.yml#setup': + 'Sets the Postgres versions and shard count that the gated jobs read. It is a bash step with no checkout.', + '.github/workflows/test-eql.yml#docs-static': + 'Checks the SQL documentation on every pull request, including the docs-only ones the selector skips. It needs no database or credentials.', + '.github/workflows/test-eql.yml#known-failures': + 'Checks that each suppressed test names an open issue, on every pull request. It needs no database or credentials.', + '.github/workflows/test-eql.yml#doc-anchors': + 'Checks Markdown anchor links. Its inputs are the docs themselves, which the selector does not select for.', +} + +const IN_SCOPE_EVENTS = ['pull_request', 'merge_group'] + +function events(workflow) { + // `on:` parses as the boolean `true` under YAML 1.1. + const on = workflow?.on ?? workflow?.[true] + if (typeof on === 'string') return [on] + if (Array.isArray(on)) return on + return Object.keys(on ?? {}) +} + +const needsOf = (job) => [job?.needs ?? []].flat() + +const ifText = (job) => String(job?.if ?? '') + +/** The selector outputs a job's `if:` reads. */ +const outputsRead = (job) => + [ + ...ifText(job).matchAll( + new RegExp(`needs\\.${SELECTOR}\\.outputs\\.([A-Za-z0-9_-]+)`, 'g'), + ), + ].map((match) => match[1]) + +/** A status function stops GitHub skipping a job when a job it needs skipped. */ +const keepsRunningAfterSkip = (job) => + /\b(always|failure|cancelled)\s*\(/.test(ifText(job)) + +/** + * The job that ends the workflow: its `if:` is `always()` and it needs every + * other job. + */ +function summaryJobId(jobs) { + const ids = Object.keys(jobs) + const last = ids.at(-1) + const others = ids.filter((id) => id !== last).sort() + const needs = [...needsOf(jobs[last])].sort() + const isSummary = + ifText(jobs[last]).trim() === 'always()' && + JSON.stringify(needs) === JSON.stringify(others) + return isSummary ? last : undefined +} + +/** The ids of the jobs the selector job decides, directly or through `needs:`. */ +function decidedJobIds(jobs) { + const declared = Object.keys(jobs[SELECTOR]?.outputs ?? {}) + const readsSelector = (job) => { + const read = outputsRead(job) + return read.length > 0 && read.every((name) => declared.includes(name)) + } + const decided = new Set( + Object.entries(jobs) + .filter( + ([, job]) => needsOf(job).includes(SELECTOR) && readsSelector(job), + ) + .map(([id]) => id), + ) + let grew = true + while (grew) { + grew = false + for (const [id, job] of Object.entries(jobs)) { + if (decided.has(id) || keepsRunningAfterSkip(job)) continue + if (needsOf(job).some((need) => decided.has(need))) { + decided.add(id) + grew = true + } + } + } + return decided +} + +const WORKFLOWS = workflowFiles() + .map((file) => ({ file, workflow: readWorkflow(file) })) + .filter(({ workflow }) => + events(workflow).some((event) => IN_SCOPE_EVENTS.includes(event)), + ) + +const hasSelector = ({ workflow }) => Boolean(workflow?.jobs?.[SELECTOR]) + +const isExemptWorkflow = ({ file }) => + file in NOT_CHECKS || file in NOT_YET_CONVERTED + +/** The workflows checked job by job. */ +const CHECKED = WORKFLOWS.filter( + (entry) => hasSelector(entry) && !isExemptWorkflow(entry), +).map(({ file, workflow }) => { + const jobs = workflow.jobs + return { + file, + jobs, + summary: summaryJobId(jobs), + decided: decidedJobIds(jobs), + } +}) + +const reasonMissing = (map) => + Object.entries(map) + .filter(([, reason]) => typeof reason !== 'string' || !reason.trim()) + .map(([key]) => key) + +describe('the failsafe', () => { + it('finds the workflows it checks', () => { + // An empty scan would pass every check below. + expect(WORKFLOWS.length).toBeGreaterThan(0) + expect(CHECKED.map(({ file }) => file)).toContain( + '.github/workflows/test-eql.yml', + ) + }) + + it('fails when the selector job does not decide whether a job runs', () => { + const undecided = CHECKED.flatMap(({ file, jobs, summary, decided }) => + Object.keys(jobs) + .filter((id) => id !== SELECTOR && id !== summary) + .filter((id) => !decided.has(id)) + .map((id) => `${file}#${id}`) + .filter((ref) => !(ref in RUNS_ON_EVERY_CHANGE)), + ) + expect( + undecided, + `The selector job does not decide whether these jobs run, so they run on every change. Give each one \`needs: [${SELECTOR}]\` and an \`if:\` that reads an output the selector job declares. If a job must run on every change, add it to RUNS_ON_EVERY_CHANGE with the reason. If the summary job is listed, make it the last job, with \`if: always()\` and every other job in its \`needs:\`.`, + ).toEqual([]) + }) + + it('fails when a workflow on pull requests or in a merge queue has no selector job', () => { + const missing = WORKFLOWS.filter( + (entry) => !hasSelector(entry) && !isExemptWorkflow(entry), + ).map(({ file }) => file) + expect( + missing, + `These workflows run on pull requests or in a merge queue and have no \`${SELECTOR}\` job. Add one (ADR 0003), or exempt the workflow with a reason.`, + ).toEqual([]) + }) + + it('fails when an exemption has no written reason', () => { + expect([ + ...reasonMissing(NOT_CHECKS), + ...reasonMissing(NOT_YET_CONVERTED), + ...reasonMissing(RUNS_ON_EVERY_CHANGE), + ]).toEqual([]) + }) + + it('fails when a workflow exemption matches no workflow it would exempt', () => { + const inScope = new Map(WORKFLOWS.map((entry) => [entry.file, entry])) + const stale = [ + ...Object.keys(NOT_CHECKS) + .filter((file) => !inScope.has(file)) + .map( + (file) => + `${file}: in NOT_CHECKS, but it runs on no pull request or merge queue`, + ), + ...Object.keys(NOT_YET_CONVERTED) + .filter((file) => !inScope.has(file)) + .map( + (file) => + `${file}: in NOT_YET_CONVERTED, but it runs on no pull request or merge queue`, + ), + ...Object.keys(NOT_YET_CONVERTED) + .filter((file) => inScope.has(file) && hasSelector(inScope.get(file))) + .map( + (file) => + `${file}: in NOT_YET_CONVERTED, but it has a selector job. Remove the entry.`, + ), + ...Object.keys(NOT_CHECKS) + .filter((file) => file in NOT_YET_CONVERTED) + .map((file) => `${file}: in both NOT_CHECKS and NOT_YET_CONVERTED`), + ] + expect(stale).toEqual([]) + }) + + it('fails when a job exemption matches no job the selector leaves undecided', () => { + const undecidedRefs = new Set( + CHECKED.flatMap(({ file, jobs, summary, decided }) => + Object.keys(jobs) + .filter((id) => id !== SELECTOR && id !== summary) + .filter((id) => !decided.has(id)) + .map((id) => `${file}#${id}`), + ), + ) + const stale = Object.keys(RUNS_ON_EVERY_CHANGE).filter( + (ref) => !undecidedRefs.has(ref), + ) + expect( + stale, + 'These exemptions match no job that the selector job leaves undecided. The job is gone, its workflow is exempt as a whole, or the selector now decides it. Remove each entry.', + ).toEqual([]) + }) +}) From 57493fbcd89f6ca2a5a07a89a66f6c3ab2880d69 Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Wed, 28 Oct 2026 23:42:59 +1100 Subject: [PATCH 4/5] test(ci): exempt the change impact report from the failsafe for good impact.yml posts an advisory report on every pull request. It is not a check, and no branch rule requires it, so it will not get a selector job. It moves from the temporary "not yet converted" list to the permanent one, next to the two review bots. --- scripts/__tests__/failsafe.test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/scripts/__tests__/failsafe.test.mjs b/scripts/__tests__/failsafe.test.mjs index c8145aebeb..1590788d2f 100644 --- a/scripts/__tests__/failsafe.test.mjs +++ b/scripts/__tests__/failsafe.test.mjs @@ -41,6 +41,8 @@ const NOT_CHECKS = { 'Review bot, not a check. No branch rule requires it.', '.github/workflows/code-review.yml': 'Review bot, not a check. No branch rule requires it.', + '.github/workflows/impact.yml': + 'Advisory report, not a check. No branch rule requires it.', } /** @@ -53,7 +55,6 @@ const NOT_YET_CONVERTED = Object.fromEntries( 'crap-crates.yml', 'fta-v3.yml', 'fuzz.yml', - 'impact.yml', 'integration-drizzle.yml', 'integration-prisma-next.yml', 'integration-protect-ffi.yml', From 5eb7542742bd4607cc2cd10ccd56872940a15d1e Mon Sep 17 00:00:00 2001 From: Lindsay Holmwood Date: Thu, 29 Oct 2026 00:00:21 +1100 Subject: [PATCH 5/5] test(ci): name the failsafe's job exemptions for what they are The per-job list was called RUNS_ON_EVERY_CHANGE. Some jobs the selector job does not decide never run on a pull request at all, such as a fuzz campaign that runs only on a schedule. EXEMPT_JOBS fits both kinds. Each entry still needs its reason. --- scripts/__tests__/failsafe.test.mjs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/scripts/__tests__/failsafe.test.mjs b/scripts/__tests__/failsafe.test.mjs index 1590788d2f..a1c26d8c04 100644 --- a/scripts/__tests__/failsafe.test.mjs +++ b/scripts/__tests__/failsafe.test.mjs @@ -21,7 +21,7 @@ import { readWorkflow, workflowFiles } from './lib/workflows.mjs' * - It needs a job that passes by the rule above, and its `if:` calls no * `always()`, `failure()` or `cancelled()`. GitHub then skips it whenever * that job is skipped, so the selector decides it too. - * - It has a written reason in `RUNS_ON_EVERY_CHANGE`. + * - It has a written reason in `EXEMPT_JOBS`. * * A whole workflow can be exempt, with a written reason, in `NOT_CHECKS` or * `NOT_YET_CONVERTED`. An exemption that matches nothing, or is no longer @@ -82,10 +82,11 @@ const NOT_YET_CONVERTED = Object.fromEntries( ) /** - * Jobs in a workflow with a selector job that run on every change, on - * purpose. Keyed `#`. + * Jobs in a workflow with a selector job that the selector job does not + * decide, on purpose. Most run on every change. Some never run on a pull + * request at all. Keyed `#`. */ -const RUNS_ON_EVERY_CHANGE = { +const EXEMPT_JOBS = { '.github/workflows/test-eql.yml#setup': 'Sets the Postgres versions and shard count that the gated jobs read. It is a bash step with no checkout.', '.github/workflows/test-eql.yml#docs-static': @@ -209,11 +210,11 @@ describe('the failsafe', () => { .filter((id) => id !== SELECTOR && id !== summary) .filter((id) => !decided.has(id)) .map((id) => `${file}#${id}`) - .filter((ref) => !(ref in RUNS_ON_EVERY_CHANGE)), + .filter((ref) => !(ref in EXEMPT_JOBS)), ) expect( undecided, - `The selector job does not decide whether these jobs run, so they run on every change. Give each one \`needs: [${SELECTOR}]\` and an \`if:\` that reads an output the selector job declares. If a job must run on every change, add it to RUNS_ON_EVERY_CHANGE with the reason. If the summary job is listed, make it the last job, with \`if: always()\` and every other job in its \`needs:\`.`, + `The selector job does not decide whether these jobs run, so they can run on every change. Give each one \`needs: [${SELECTOR}]\` and an \`if:\` that reads an output the selector job declares. If the selector job must not decide a job, add it to EXEMPT_JOBS with the reason. If the summary job is listed, make it the last job, with \`if: always()\` and every other job in its \`needs:\`.`, ).toEqual([]) }) @@ -231,7 +232,7 @@ describe('the failsafe', () => { expect([ ...reasonMissing(NOT_CHECKS), ...reasonMissing(NOT_YET_CONVERTED), - ...reasonMissing(RUNS_ON_EVERY_CHANGE), + ...reasonMissing(EXEMPT_JOBS), ]).toEqual([]) }) @@ -272,7 +273,7 @@ describe('the failsafe', () => { .map((id) => `${file}#${id}`), ), ) - const stale = Object.keys(RUNS_ON_EVERY_CHANGE).filter( + const stale = Object.keys(EXEMPT_JOBS).filter( (ref) => !undecidedRefs.has(ref), ) expect(