gate: build the tests once per runner and keep workspace crates in a rolling cache entry

With archive-command, a build (<os>) job per runner builds the tests once
into a nextest archive; the shard legs download it and build nothing, and
only they wait for the build job. after-archive-command runs in the build
job after the upload. With cache-workspace-crates, the saving leg writes a
rolling dependency entry that keeps the workspace crates, and every leg
restores the newest one with restore-mtimes. The lint legs move to a lint
job of their own that never waits for the build. Every job's setup is
actions/gate-setup; commands run through actions/gate-run. Every new input
defaults to today's behaviour.

The save-condition guards read the cache-save and writes inputs every job
passes to gate-setup: the build and lint jobs carry the approved condition,
the gate job the same narrowed to its one saving leg per runner.

Result markers are files named after their leg and download with
merge-multiple, so one shard or one build lands where the check reads it.
The archive upload overwrites on a re-run. archive-command without
test-shards is an error.

The first-party actions are pinned to the commit that added gate-setup.
This commit is contained in:
aiongg committed 2026-11-19 09:30:18 +00:00
1 parent 7513b173b4
commit 528446563c
6 files changed
+681 -380

No files matched your search

+296 -239
View File
@@ -3,7 +3,9 @@ name: "Gate"
# The quality gate the craft apps run on pull requests and pushes to main: one job per runner in
# `os`, each running `command` (by default `cargo xtask ci`) with the suite's shared setup, and with
# `lint-command` a second job per runner that runs the lint checks beside it. With `test-shards`,
# each runner runs its tests as that many shard jobs instead of one.
# each runner runs its tests as that many shard jobs instead of one, and with `archive-command` a
# `build (<os>)` job builds the tests once for all of them. The setup every job shares is
# actions/gate-setup; each job's command runs through actions/gate-run.
# App-specific checks (fuzzing, corpora, web builds) belong here too, as shared workflows or
# inputs: an app's workflows only call this repository's workflows.
on:
@@ -30,7 +32,7 @@ on:
required: false
default: ""
warm-command:
description: "Optional build that fills the dependency cache, for example `cargo test --workspace --no-run --locked`; empty (default) runs none. Where the dependency cache saves, a `cache warm (<os>)` leg beside the gate runs it and saves the `gate` entry as soon as it succeeds, so a failing test no longer keeps the entry from being saved. Give it the build the gate does (same features, profile and targets) and nothing else; the gate legs then only restore"
description: "Optional build that fills the dependency cache, for example `cargo test --workspace --no-run --locked`; empty (default) runs none. Where the dependency cache saves, a `cache warm (<os>)` leg beside the gate runs it and saves the `gate` entry as soon as it succeeds, so a failing test no longer keeps the entry from being saved. Give it the build the gate does (same features, profile and targets) and nothing else; the gate legs then only restore. With archive-command the build job saves the entry, and no warm leg runs"
type: string
required: false
default: ""
@@ -70,7 +72,22 @@ on:
required: false
default: 0
shard-command:
description: "With test-shards: each shard leg's command, which builds and runs its share of the tests. `GATE_SHARD` (1..N), `GATE_SHARDS` (N) and `NEXTEST_PARTITION` (`hash:<k>/<N>`) say which share, for example `cargo nextest run --workspace --locked --partition \"$NEXTEST_PARTITION\"`"
description: "With test-shards: each shard leg's command, which builds and runs its share of the tests (with archive-command, runs it from the archive at $NEXTEST_ARCHIVE_FILE). `GATE_SHARD` (1..N), `GATE_SHARDS` (N) and `NEXTEST_PARTITION` (`hash:<k>/<N>`) say which share, for example `cargo nextest run --workspace --locked --partition \"$NEXTEST_PARTITION\"`"
type: string
required: false
default: ""
archive-command:
description: "With test-shards: build the tests once per runner, in a `build (<os>)` job that runs this command to write a nextest archive to $NEXTEST_ARCHIVE_FILE. The shard legs download the archive instead of building, and only they wait for the build job. Where the dependency cache saves, the build job saves the `gate` entry. A failed build skips the shards of every runner in the call, so give each runner a call of its own. Empty (default): each shard builds its own tests; test-shards: 0 with an archive-command is an error"
type: string
required: false
default: ""
archive-file:
description: "File name of the archive archive-command writes, in the runner's temporary directory"
type: string
required: false
default: "nextest-archive.tar.zst"
after-archive-command:
description: "With archive-command: a command the build job runs after it has uploaded the archive, for checks that need the build directory (doctests, say). The shards wait for the whole build job, so its time adds to the gate's. `gate (<os>)` passes only when it passed too. Empty runs none"
type: string
required: false
default: ""
@@ -176,6 +193,16 @@ on:
required: false
# Same default as actions/rust-cache, which explains the v2 bump.
default: "v2"
cache-workspace-crates:
description: "Keep the workspace crates' compiled libraries and unit-test executables in the dependency cache as a rolling entry: the leg that saves writes an entry of its own each run, every leg restores the newest one, and actions/restore-mtimes resets source mtimes from the diff against the commit that entry was built from, so Cargo rebuilds only what changed. The lint legs keep their usual entry"
type: boolean
required: false
default: false
cold-build:
description: "With cache-workspace-crates: restore no dependency cache and build everything from source; where the cache saves, the saving leg still writes a fresh entry (a nightly cold run is the safety net for the restored mtimes, and it starts the rolling entry afresh)"
type: boolean
required: false
default: false
cache-save-on-dispatch:
description: "Allow manually dispatched branch runs to save their branch-scoped dependency cache; pull requests never write"
type: boolean
@@ -200,7 +227,7 @@ jobs:
# in `os`.
select:
name: select legs
if: (inputs.select-os != '' && inputs.select-os != '[]') || inputs.test-shards != 0
if: (inputs.select-os != '' && inputs.select-os != '[]') || inputs.test-shards != 0 || inputs.archive-command != ''
runs-on: ubuntu-24.04
timeout-minutes: 5
outputs:
@@ -220,24 +247,28 @@ jobs:
fetch-depth: 2
- id: select
if: inputs.select-os != '' && inputs.select-os != '[]'
uses: storytold/craft-common-actions/actions/select-platforms@139cccb97f9dc462b56f39ee2830718aaa782fed
uses: storytold/craft-common-actions/actions/select-platforms@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
os: ${{ inputs.os }}
select-os: ${{ inputs.select-os }}
paths: ${{ inputs.select-paths }}
crates: ${{ inputs.select-crates }}
label: ${{ inputs.select-label }}
# The gate job's `shard` dimension, and the lint and warm legs it must not repeat: those
# keep one leg per runner, as shard 1.
# The gate job's `shard` dimension, and the warm leg it must not repeat: that keeps one leg
# per runner, as shard 1.
- name: Shards
id: shards
if: inputs.test-shards != 0
if: inputs.test-shards != 0 || inputs.archive-command != ''
shell: bash
env:
SHARDS: ${{ inputs.test-shards }}
SHARD: ${{ inputs.shard-command }}
run: |
set -euo pipefail
if [ "$SHARDS" = 0 ]; then
echo "::error::archive-command needs test-shards: the shard legs are what run its archive"
exit 1
fi
if [[ ! "$SHARDS" =~ ^[1-9][0-9]*$ ]]; then
echo "::error::test-shards must be 0 or a positive whole number, got '$SHARDS'"
exit 1
@@ -248,37 +279,33 @@ jobs:
fi
exclude=
for shard in $(seq 2 "$SHARDS"); do
exclude+="${exclude:+,}{\"part\":\"lint\",\"shard\":$shard},{\"part\":\"warm\",\"shard\":$shard}"
exclude+="${exclude:+,}{\"part\":\"warm\",\"shard\":$shard}"
done
echo "shards=[$(seq -s, 1 "$SHARDS")]" >> "$GITHUB_OUTPUT"
echo "exclude=[$exclude]" >> "$GITHUB_OUTPUT"
gate:
# With archive-command: the tests are built once per runner into a nextest archive, which the
# shard legs download instead of building. Where the dependency cache saves, this job saves the
# gate's entry (and, with cache-workspace-crates, records the commit the entry was built from).
build:
needs: select
# A skipped select (no select-os, no test-shards) still runs the gate; a failed one does not.
if: ${{ !cancelled() && needs.select.result != 'failure' }}
# The test part keeps the `gate (<os>)` check name callers already know. With test-shards the
# shard legs take its place, and the `result` job reports `gate (<os>)`.
name: ${{ matrix.part == 'lint' && 'lint' || matrix.part == 'warm' && 'cache warm' || matrix.part == 'shard' && format('test {0}/{1}', matrix.shard, inputs.test-shards) || 'gate' }} (${{ matrix.os }})
# A skipped select (no select-os) still runs the build; a failed one does not.
if: ${{ !cancelled() && needs.select.result != 'failure' && inputs.test-shards != 0 && inputs.archive-command != '' }}
name: build (${{ matrix.os }})
runs-on: ${{ matrix.os }}
timeout-minutes: ${{ inputs.timeout-minutes }}
strategy:
# A failing leg must not cancel the others and hide their failures.
fail-fast: false
matrix:
os: ${{ fromJSON(needs.select.outputs.os || inputs.os) }}
# One job definition for every part, so the shared setup is written once.
part: ${{ fromJSON(format('["{0}"{1}{2}]', inputs.test-shards != 0 && 'shard' || 'test', inputs.lint-command != '' && ',"lint"' || '', inputs.warm-command != '' && github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) && ',"warm"' || '')) }}
# With test-shards, 1..N for the shard part; lint and warm run once, as shard 1. Otherwise 0.
shard: ${{ fromJSON(needs.select.outputs.shards || '[0]') }}
exclude: ${{ fromJSON(needs.select.outputs.exclude || '[]') }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
CARGO_NET_RETRY: 10
RUST_BACKTRACE: 1
steps:
- name: Harden runner
- &harden-runner
name: Harden runner
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
@@ -314,198 +341,233 @@ jobs:
security.ubuntu.com:443
static.crates.io:443
static.rust-lang.org:443
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check out craft-fonts
if: inputs.craft-fonts-ref != ''
- &checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
repository: storytold/craft-fonts
ref: ${{ inputs.craft-fonts-ref }}
path: craft-fonts
persist-credentials: false
- name: Build with craft-fonts
if: inputs.craft-fonts-ref != ''
shell: bash
env:
CRAFT_FONTS_DIR: ${{ github.workspace }}/craft-fonts
REQUIRED: ${{ inputs.require-craft-fonts }}
run: |
echo "CRAFT_FONTS_DIR=$CRAFT_FONTS_DIR" >> "$GITHUB_ENV"
if [ "$REQUIRED" = true ]; then echo "CRAFT_FONTS_REQUIRED=1" >> "$GITHUB_ENV"; fi
# Does nothing unless the repository has craft-i18n.rev; then builds require the translations.
- name: Check out craft-i18n
uses: storytold/craft-common-actions/actions/checkout-craft-i18n@139cccb97f9dc462b56f39ee2830718aaa782fed
# Before the cache step: rust-cache keys on CARGO_* and RUST* variables.
- name: Caller environment
if: inputs.env != '' || inputs.linux-env != '' || inputs.windows-env != '' || inputs.dev-debug != '' || inputs.dev-strip
shell: bash
env:
ALL: ${{ inputs.env }}
LINUX: ${{ inputs.linux-env }}
WINDOWS: ${{ inputs.windows-env }}
DEV_DEBUG: ${{ inputs.dev-debug }}
DEV_STRIP: ${{ inputs.dev-strip }}
run: |
set -euo pipefail
case "$RUNNER_OS" in
Linux) extra=$LINUX ;;
Windows) extra=$WINDOWS ;;
*) extra= ;;
esac
if [ -n "$DEV_DEBUG" ]; then echo "CARGO_PROFILE_DEV_DEBUG=$DEV_DEBUG" >> "$GITHUB_ENV"; fi
if [ "$DEV_STRIP" = true ]; then
echo "CARGO_PROFILE_TEST_DEBUG=0" >> "$GITHUB_ENV"
echo "CARGO_PROFILE_TEST_STRIP=symbols" >> "$GITHUB_ENV"
fi
printf '%s\n%s\n' "$ALL" "$extra" | while IFS= read -r line; do
[ -n "$line" ] || continue
if ! [[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]]; then
echo "::error::env: expected KEY=VALUE, got '$line'"
exit 1
fi
echo "$line" >> "$GITHUB_ENV"
done
# Nothing waits on it: the space is free before the build needs it.
- name: Free disk space
if: runner.os == 'Linux' && inputs.free-disk-space
run: |
nohup sudo rm -rf /usr/local/lib/android /usr/share/dotnet /opt/ghc /usr/local/.ghcup \
/opt/hostedtoolcache/CodeQL </dev/null >/dev/null 2>&1 &
- name: Install Linux build dependencies
if: runner.os == 'Linux' && inputs.packages != ''
uses: storytold/craft-common-actions/actions/install-apt-packages@139cccb97f9dc462b56f39ee2830718aaa782fed
# Default-branch writes remain the default. Maintainers can explicitly opt manual branch runs
# into branch-scoped writes; pull-request runs never save a cache.
- name: Setup
uses: storytold/craft-common-actions/actions/gate-setup@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
require-craft-fonts: ${{ inputs.require-craft-fonts }}
env: ${{ inputs.env }}
linux-env: ${{ inputs.linux-env }}
windows-env: ${{ inputs.windows-env }}
dev-debug: ${{ inputs.dev-debug }}
dev-strip: ${{ inputs.dev-strip }}
free-disk-space: ${{ inputs.free-disk-space }}
packages: ${{ inputs.packages }}
# The channel in rust-toolchain.toml wins over `toolchain`, so the gate builds with the
# toolchain contributors use and a new Rust release does not invalidate the cache.
- name: Install Rust
shell: bash
env:
TOOLCHAIN: ${{ inputs.toolchain }}
TARGETS: ${{ inputs.targets }}
run: |
set -euo pipefail
if [ -f rust-toolchain.toml ]; then
channel=$(sed -n 's/^[[:space:]]*channel[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' rust-toolchain.toml)
TOOLCHAIN=${channel:-$TOOLCHAIN}
fi
args=(--profile minimal --no-self-update --component clippy --component rustfmt)
for target in ${TARGETS//,/ }; do args+=(--target "$target"); done
rustup toolchain install "$TOOLCHAIN" "${args[@]}"
rustup default "$TOOLCHAIN"
rustc --version
- name: Install cargo tools
if: inputs.tools != ''
uses: step-security/taiki-e-install-action@76747d22a7567cc4438546a84f11bdf18e670ab8 # v2.87.32
with:
tool: ${{ inputs.tools }}
# Default-branch writes remain the default. Maintainers can explicitly opt manual
# branch runs into branch-scoped writes; pull-request runs never save a cache. The key
# (the canonical root [profile] table included) lives in the shared action, so an app job
# that builds the same workspace restores this entry instead of copying the formula.
# No save on failure: a main run that fails at fmt or clippy has not built the test
# profile, and rust-cache never replaces an exact-key entry, so that half-filled entry
# would be restored by every run until Cargo.lock changes.
# The lint part builds in check mode, so it keeps an entry of its own (`<profile>-lint`)
# instead of racing the test part for the `gate` entry. Shard legs restore the test part's
# entry, and shard 1 alone saves it, so the shards do not race each other for it.
- uses: storytold/craft-common-actions/actions/rust-cache@139cccb97f9dc462b56f39ee2830718aaa782fed
with:
toolchain: ${{ inputs.toolchain }}
targets: ${{ inputs.targets }}
tools: ${{ inputs.tools }}
cache-version: ${{ inputs.cache-version }}
job: ${{ matrix.part == 'lint' && 'lint' || inputs.cache-name != '' && format('gate-{0}', inputs.cache-name) || '' }}
save-if: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) && (matrix.part == 'lint' || matrix.part == 'warm' || inputs.warm-command == '' && matrix.shard <= 1) }}
cache-on-failure: "false"
cache-job: ${{ inputs.cache-name != '' && format('gate-{0}', inputs.cache-name) || 'gate' }}
cache-save: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) }}
cache-workspace-crates: ${{ inputs.cache-workspace-crates }}
cold-build: ${{ inputs.cold-build }}
sccache: ${{ inputs.sccache }}
writes: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) }}
cache-paths: ${{ inputs.cache-paths }}
cache-key: ${{ inputs.cache-key }}
cache-key-files: ${{ inputs.cache-key-files }}
setup-command: ${{ inputs.setup-command }}
# After rust-cache, so its key does not depend on RUSTC_WRAPPER.
- name: Install sccache
if: inputs.sccache
uses: Mozilla-Actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
with:
version: v0.18.0
- name: Use sccache
if: inputs.sccache
- name: Archive path
shell: bash
env:
WRITES: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) }}
# sccache leaves `--check-cfg` out of its key, so after a change to the expected cfgs a
# cached compile would replay its old `unexpected_cfgs` warnings. A change to the files
# that declare them (Cargo.toml lints, build scripts), or to cache-version, starts a
# fresh sccache cache instead.
VERSION: ${{ inputs.cache-version }}-${{ hashFiles('**/Cargo.toml', '**/build.rs') }}
run: |
echo "SCCACHE_GHA_ENABLED=true" >> "$GITHUB_ENV"
echo "RUSTC_WRAPPER=sccache" >> "$GITHUB_ENV"
if [ -z "${SCCACHE_GHA_VERSION:-}" ]; then
echo "SCCACHE_GHA_VERSION=$VERSION" >> "$GITHUB_ENV"
fi
if [ -z "${SCCACHE_GHA_RW_MODE:-}" ] && [ "$WRITES" != true ]; then
echo "SCCACHE_GHA_RW_MODE=READ_ONLY" >> "$GITHUB_ENV"
fi
FILE: ${{ runner.temp }}/${{ inputs.archive-file }}
run: echo "NEXTEST_ARCHIVE_FILE=$FILE" >> "$GITHUB_ENV"
# Data the caller's setup fetches (test corpora, fixtures), keyed on the caller's pins. The
# key is fixed by those pins, so one entry stays valid until a pin moves.
- name: Caller cache key
id: caller-key
if: inputs.cache-paths != '' && matrix.part != 'lint'
- name: Build the test archive
uses: storytold/craft-common-actions/actions/gate-run@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
command: ${{ inputs.archive-command }}
timeout-minutes: ${{ inputs.gate-timeout-minutes }}
# The marker is saved with the cache entry in rust-cache's post step.
- name: Record the cache commit
if: inputs.cache-workspace-crates
uses: storytold/craft-common-actions/actions/restore-mtimes@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
mode: record
# A build that changed Cargo.lock ran against a lockfile that is not the one in the repository.
- name: Lockfile unchanged
shell: bash
run: git diff --exit-code -- Cargo.lock
- name: Archive size
shell: bash
run: ls -l "$NEXTEST_ARCHIVE_FILE"
# Uncompressed: a zstd archive barely shrinks, and level 0 uploads it in seconds.
- name: Upload the test archive
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: gate-archive-${{ matrix.os }}
path: ${{ runner.temp }}/${{ inputs.archive-file }}
if-no-files-found: error
# A re-run of the build job replaces the archive of the attempt before.
overwrite: true
compression-level: 0
retention-days: 1
- name: After the archive
if: inputs.after-archive-command != ''
uses: storytold/craft-common-actions/actions/gate-run@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
command: ${{ inputs.after-archive-command }}
timeout-minutes: ${{ inputs.gate-timeout-minutes }}
# The `result` job reads it: the build job's result covers every runner.
- name: Record the build's result
if: always()
shell: bash
env:
KEY: ${{ inputs.cache-key }}
FILES: ${{ inputs.cache-key-files }}
FILES_HASH: ${{ inputs.cache-key-files != '' && hashFiles(inputs.cache-key-files) || '' }}
run: |
set -euo pipefail
if [ -z "$KEY" ]; then
echo "::error::cache-paths needs a cache-key naming the pins of what it holds"
exit 1
fi
if [ -n "$FILES" ] && [ -z "$FILES_HASH" ]; then
echo "::error::cache-key-files matches no file: $FILES"
exit 1
fi
echo "key=gate-caller-$KEY${FILES_HASH:+-$FILES_HASH}" >> "$GITHUB_OUTPUT"
RESULT: ${{ runner.temp }}/gate-result/gate-build-${{ matrix.os }}
STATUS: ${{ job.status }}
run: mkdir -p "$(dirname "$RESULT")" && echo "$STATUS" > "$RESULT"
- name: Restore caller cache
id: caller-cache
if: inputs.cache-paths != '' && matrix.part != 'lint'
uses: actions/cache/restore@caa296126883cff596d87d8935842f9db880ef25 # v5
- name: Upload the build's result
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
path: ${{ inputs.cache-paths }}
key: ${{ steps.caller-key.outputs.key }}
enableCrossOsArchive: true
name: gate-build-${{ matrix.os }}
path: ${{ runner.temp }}/gate-result/gate-build-${{ matrix.os }}
if-no-files-found: error
overwrite: true
retention-days: 1
- name: Caller setup
if: inputs.setup-command != '' && matrix.part != 'lint'
# With lint-command: one `lint (<os>)` leg per runner beside the gate's legs, off their critical
# path. It builds in check mode, so it keeps a dependency-cache entry of its own (`lint`), skips
# setup-command and the caller cache, and never waits for the build job.
lint:
needs: select
if: ${{ !cancelled() && needs.select.result != 'failure' && inputs.lint-command != '' }}
name: lint (${{ matrix.os }})
runs-on: ${{ matrix.os }}
timeout-minutes: ${{ inputs.timeout-minutes }}
strategy:
fail-fast: false
matrix:
os: ${{ fromJSON(needs.select.outputs.os || inputs.os) }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
CARGO_NET_RETRY: 10
RUST_BACKTRACE: 1
steps:
- *harden-runner
- *checkout
- name: Setup
uses: storytold/craft-common-actions/actions/gate-setup@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
require-craft-fonts: ${{ inputs.require-craft-fonts }}
env: ${{ inputs.env }}
linux-env: ${{ inputs.linux-env }}
windows-env: ${{ inputs.windows-env }}
dev-debug: ${{ inputs.dev-debug }}
dev-strip: ${{ inputs.dev-strip }}
free-disk-space: ${{ inputs.free-disk-space }}
packages: ${{ inputs.packages }}
toolchain: ${{ inputs.toolchain }}
targets: ${{ inputs.targets }}
tools: ${{ inputs.tools }}
cache-version: ${{ inputs.cache-version }}
cache-job: lint
cache-save: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) }}
sccache: ${{ inputs.sccache }}
writes: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) }}
caller-setup: "false"
- name: Gate
uses: storytold/craft-common-actions/actions/gate-run@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
command: ${{ inputs.lint-command }}
timeout-minutes: ${{ inputs.gate-timeout-minutes }}
- name: Lockfile unchanged
shell: bash
run: git diff --exit-code -- Cargo.lock
gate:
needs: [select, build]
# A skipped select (no select-os, no test-shards) or build (no archive-command) still runs the
# gate; a failed one does not.
if: ${{ !cancelled() && needs.select.result != 'failure' && needs.build.result != 'failure' && needs.build.result != 'cancelled' }}
# The test part keeps the `gate (<os>)` check name callers already know. With test-shards the
# shard legs take its place, and the `result` job reports `gate (<os>)`.
name: ${{ matrix.part == 'warm' && 'cache warm' || matrix.part == 'shard' && format('test {0}/{1}', matrix.shard, inputs.test-shards) || 'gate' }} (${{ matrix.os }})
runs-on: ${{ matrix.os }}
timeout-minutes: ${{ inputs.timeout-minutes }}
strategy:
# A failing leg must not cancel the others and hide their failures.
fail-fast: false
matrix:
os: ${{ fromJSON(needs.select.outputs.os || inputs.os) }}
# One job definition for every part, so the shared setup is written once.
part: ${{ fromJSON(format('["{0}"{1}]', inputs.test-shards != 0 && 'shard' || 'test', inputs.warm-command != '' && inputs.archive-command == '' && github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) && ',"warm"' || '')) }}
# With test-shards, 1..N for the shard part; the warm leg runs once, as shard 1. Otherwise 0.
shard: ${{ fromJSON(needs.select.outputs.shards || '[0]') }}
exclude: ${{ fromJSON(needs.select.outputs.exclude || '[]') }}
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
CARGO_NET_RETRY: 10
RUST_BACKTRACE: 1
steps:
- *harden-runner
- *checkout
# Shard legs restore the test part's entry, and shard 1 alone saves it (the warm leg, when
# there is one), so the shards do not race each other for it. Shards that run the build
# job's archive build nothing and restore no cache.
- name: Setup
uses: storytold/craft-common-actions/actions/gate-setup@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
craft-fonts-ref: ${{ inputs.craft-fonts-ref }}
require-craft-fonts: ${{ inputs.require-craft-fonts }}
env: ${{ inputs.env }}
linux-env: ${{ inputs.linux-env }}
windows-env: ${{ inputs.windows-env }}
dev-debug: ${{ inputs.dev-debug }}
dev-strip: ${{ inputs.dev-strip }}
free-disk-space: ${{ inputs.free-disk-space }}
packages: ${{ inputs.packages }}
toolchain: ${{ inputs.toolchain }}
targets: ${{ inputs.targets }}
tools: ${{ inputs.tools }}
rust-cache: ${{ !(matrix.part == 'shard' && inputs.archive-command != '') }}
cache-version: ${{ inputs.cache-version }}
cache-job: ${{ inputs.cache-name != '' && format('gate-{0}', inputs.cache-name) || 'gate' }}
cache-save: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) && (matrix.part == 'warm' || inputs.warm-command == '' && matrix.shard <= 1) }}
cache-workspace-crates: ${{ inputs.cache-workspace-crates }}
cold-build: ${{ inputs.cold-build }}
sccache: ${{ inputs.sccache }}
writes: ${{ github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch')) }}
cache-paths: ${{ inputs.cache-paths }}
cache-key: ${{ inputs.cache-key }}
cache-key-files: ${{ inputs.cache-key-files }}
setup-command: ${{ inputs.setup-command }}
- name: Download the test archive
if: matrix.part == 'shard' && inputs.archive-command != ''
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: gate-archive-${{ matrix.os }}
path: ${{ runner.temp }}/gate-archive
- name: Archive path
if: matrix.part == 'shard' && inputs.archive-command != ''
shell: bash
env:
SETUP: ${{ inputs.setup-command }}
run: |
set -euo pipefail
printf '%s\n' "$SETUP" > "$RUNNER_TEMP/gate-setup.sh"
bash -euo pipefail "$RUNNER_TEMP/gate-setup.sh"
# Saved where the dependency cache is saved, as soon as the setup has filled it. Every leg
# tries; the first to finish writes the entry and the others find it reserved.
- name: Save caller cache
if: >-
inputs.cache-paths != '' && matrix.part != 'lint' && steps.caller-cache.outputs.cache-hit != 'true'
&& github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch'))
uses: actions/cache/save@caa296126883cff596d87d8935842f9db880ef25 # v5
with:
path: ${{ inputs.cache-paths }}
key: ${{ steps.caller-key.outputs.key }}
enableCrossOsArchive: true
FILE: ${{ runner.temp }}/gate-archive/${{ inputs.archive-file }}
run: echo "NEXTEST_ARCHIVE_FILE=$FILE" >> "$GITHUB_ENV"
# Which share of the tests a shard leg runs.
- name: Shard environment
@@ -522,47 +584,27 @@ jobs:
} >> "$GITHUB_ENV"
- name: Gate
shell: bash
env:
GATE: >-
${{ matrix.part == 'lint' && inputs.lint-command || matrix.part == 'warm' && inputs.warm-command
uses: storytold/craft-common-actions/actions/gate-run@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
command: >-
${{ matrix.part == 'warm' && inputs.warm-command
|| matrix.part == 'shard' && (runner.os == 'Windows' && inputs.windows-shard-command != '' && inputs.windows-shard-command || inputs.shard-command)
|| runner.os == 'Windows' && inputs.windows-command != '' && inputs.windows-command || inputs.command }}
GATE_TIMEOUT: ${{ inputs.gate-timeout-minutes }}
run: |
printf '%s\n' "$GATE" > "$RUNNER_TEMP/gate.sh"
# gate-timeout-minutes: GNU timeout stops a hung command before the job's own timeout
# would, so the log says which processes hung instead of just "cancelled".
if [[ ! "$GATE_TIMEOUT" =~ ^[1-9][0-9]*$ ]] || ! timeout --version >/dev/null 2>&1; then
[[ "$GATE_TIMEOUT" =~ ^0*$ ]] || echo "::warning title=Gate timeout not set::gate-timeout-minutes '$GATE_TIMEOUT' needs a whole number of minutes and GNU timeout"
exec bash -euo pipefail "$RUNNER_TEMP/gate.sh"
fi
snapshot() {
echo "::group::Processes running one minute before the gate timeout"
if [ "$RUNNER_OS" = Windows ]; then ps -W; else ps -eo pid,ppid,etime,args; fi || true
echo "::endgroup::"
}
(
sleep $(( GATE_TIMEOUT * 60 - 60 )) & sleeper=$!
trap 'kill "$sleeper" 2>/dev/null; exit 0' TERM
wait "$sleeper" && snapshot
) &
watchdog=$!
status=0
timeout --kill-after=30s "${GATE_TIMEOUT}m" bash -euo pipefail "$RUNNER_TEMP/gate.sh" || status=$?
kill "$watchdog" 2>/dev/null || true
wait "$watchdog" 2>/dev/null || true
if [ "$status" -eq 124 ] || [ "$status" -eq 137 ]; then
echo "::error title=Gate timed out::the gate command ran for over $GATE_TIMEOUT min and was stopped. The 'Processes running one minute before the gate timeout' group shows what was still running; for cargo test, the 'has been running for over 60 seconds' lines name the hung tests."
fi
exit "$status"
timeout-minutes: ${{ inputs.gate-timeout-minutes }}
# The marker is saved with the cache entry in rust-cache's post step, where the leg saves.
- name: Record the cache commit
if: inputs.cache-workspace-crates && !(matrix.part == 'shard' && inputs.archive-command != '')
uses: storytold/craft-common-actions/actions/restore-mtimes@d82b20d6b7fdd7bdbf674aef95db3b72a5efb283
with:
mode: record
# A gate that changed Cargo.lock ran against a lockfile that is not the one in the repository.
- name: Lockfile unchanged
shell: bash
run: git diff --exit-code -- Cargo.lock
# Only the unsharded test/build producer uploads: lint/warm/shard parts must not race it.
# Only the unsharded test/build producer uploads: warm/shard parts must not race it.
- name: Upload artifact
if: inputs.artifact-name != '' && matrix.part == 'test'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
@@ -580,25 +622,26 @@ jobs:
if: always() && matrix.part == 'shard'
shell: bash
env:
RESULT: ${{ runner.temp }}/gate-shard
RESULT: ${{ runner.temp }}/gate-result/gate-shard-${{ matrix.os }}-${{ matrix.shard }}
STATUS: ${{ job.status }}
run: mkdir -p "$RESULT" && echo "$STATUS" > "$RESULT/status"
run: mkdir -p "$(dirname "$RESULT")" && echo "$STATUS" > "$RESULT"
- name: Upload the leg's result
if: always() && matrix.part == 'shard'
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: gate-shard-${{ matrix.os }}-${{ matrix.shard }}
path: ${{ runner.temp }}/gate-shard/status
path: ${{ runner.temp }}/gate-result/gate-shard-${{ matrix.os }}-${{ matrix.shard }}
if-no-files-found: error
overwrite: true
retention-days: 1
# With test-shards, the gate's result per runner under the `gate (<os>)` name the unsharded leg
# has, so required checks stay as they are: it passes only when every one of that runner's shards
# passed. It waits for every gate leg, since a matrix job's `needs` cannot pick one runner's legs.
# passed, and with archive-command its build job too. It waits for every gate leg, since a matrix
# job's `needs` cannot pick one runner's legs.
result:
needs: [select, gate]
needs: [select, build, gate]
if: ${{ !cancelled() && inputs.test-shards != 0 }}
name: gate (${{ matrix.os }})
runs-on: ubuntu-24.04
@@ -612,23 +655,37 @@ jobs:
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
with:
egress-policy: audit
# Each marker lands in a directory named after it; a runner with no recorded leg downloads none.
- name: Download the legs' results
# Each marker is a file named after its leg, so the markers merge into one directory however
# many there are; a runner with no recorded leg downloads none.
- name: Download the shards' results
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: gate-shard-${{ matrix.os }}-*
path: ${{ runner.temp }}/gate-shard
path: ${{ runner.temp }}/gate-result
merge-multiple: true
- name: Download the build's result
if: inputs.archive-command != ''
uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: gate-build-${{ matrix.os }}
path: ${{ runner.temp }}/gate-result
merge-multiple: true
- name: Every leg passed
shell: bash
env:
RESULT: ${{ runner.temp }}/gate-shard
RESULT: ${{ runner.temp }}/gate-result
OS: ${{ matrix.os }}
SHARDS: ${{ inputs.test-shards }}
BUILD: ${{ inputs.archive-command != '' }}
run: |
set -uo pipefail
status=0
if [ "${BUILD:-false}" = true ] && [ "$(cat "$RESULT/gate-build-$OS" 2>/dev/null)" != success ]; then
echo "::error::build ($OS) did not pass"
status=1
fi
for shard in $(seq 1 "$SHARDS"); do
if [ "$(cat "$RESULT/gate-shard-$OS-$shard/status" 2>/dev/null)" != success ]; then
if [ "$(cat "$RESULT/gate-shard-$OS-$shard" 2>/dev/null)" != success ]; then
echo "::error::test $shard/$SHARDS ($OS) did not pass"
status=1
fi
+48 -3
View File
@@ -557,7 +557,8 @@ succeeds. The gate legs then only restore. Without it, the gate saves at the end
so a main whose tests fail never saves and every pull request builds cold. Pull requests never
get the leg. Give the command the build the gate does (same features, profile and targets), since
the entry holds what that build compiled; the leg has the same setup, environment and
`setup-command` as the gate.
`setup-command` as the gate. With `archive-command` the build job saves the entry and no warm leg
runs.
With `lint-command`, each runner in `os` also gets a `lint (<os>)` leg beside its `gate (<os>)`
leg. It has the same setup except `setup-command`, runs `lint-command` (fmt, clippy, other checks
@@ -585,8 +586,8 @@ above.
saves instead. The other shards only restore.
- `lint (<os>)` and `cache warm (<os>)` still run once per runner.
- A `gate (<os>)` job passes only when every shard of that runner passed, so required checks keep
their names. It waits for every leg of the gate job; the shards themselves start at once.
- Each shard leg records its status in an artifact named after the runner label
their names. It waits for every shard leg; the shards themselves start at once.
- Each shard leg records its status in an artifact and a file named after the runner label
(`gate-shard-<os>-<k>`), so a workflow run can hold one sharded gate call per runner label. A
re-run replaces the status of every leg it runs.
@@ -596,6 +597,50 @@ above.
shard-command: cargo nextest run --workspace --locked --profile ci --partition "$NEXTEST_PARTITION"
```
With `archive-command` as well, each runner builds its tests once instead of once per shard:
- A `build (<os>)` job runs `archive-command`, which writes a nextest archive to
`$NEXTEST_ARCHIVE_FILE`, and uploads it as the `gate-archive-<os>` artifact (uncompressed: the
archive is already zstd). Where the dependency cache saves, this job saves the `gate` entry.
- The shard legs wait for it, download the archive, restore no cache and build nothing:
`shard-command` runs the tests from `$NEXTEST_ARCHIVE_FILE`
(`cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" ...`). The lint legs never wait for
the build job.
- `after-archive-command` runs in the build job after the upload, for checks that need the build
directory, such as doctests. The shards wait for the whole build job, its cache save included,
so this command's time adds to the gate's wall time. `gate (<os>)` passes only when the build
job passed too.
- `test-shards` must be set: the shards are what run the archive.
- A failed build skips the shards of every runner in the call. Give each runner its own call to
keep one runner's build failure from hiding another runner's test results.
```yaml
with:
test-shards: 4
archive-command: cargo nextest archive --workspace --locked --archive-file "$NEXTEST_ARCHIVE_FILE"
after-archive-command: cargo test --doc --workspace --locked
shard-command: cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" --workspace-remap . --partition "$NEXTEST_PARTITION"
```
With `cache-workspace-crates: true`, the dependency entry also keeps the workspace crates'
compiled libraries and unit-test executables, so a change rebuilds only the crates it reaches:
- The entry rolls: the saving leg (the build job, else the warm leg or shard 1) writes an entry of
its own each run (`<job>-crates-<os>-<arch>-<run id>-<attempt>`), and every leg restores the
newest one by its prefix. A fixed key would never be replaced, so its commit would fall ever
further behind.
- After the restore, `actions/restore-mtimes` gives every tracked file an old mtime and touches
the files that differ from the commit the entry was built from (`.ci-cache-meta/commit`, saved
with the entry), so Cargo's fingerprints see exactly those as changed. The craft-fonts and
craft-i18n checkouts keep old mtimes while they are at the commits recorded with the entry.
Without a marker, or when that commit cannot be fetched, every source stays new and Cargo
rebuilds all workspace crates.
- `cold-build: true` restores nothing and builds everything, and where the cache saves it writes a
fresh entry. Run it on a schedule as the safety net for the restored mtimes; it also starts the
rolling entry afresh, which drops artifacts of older toolchains and lockfiles.
- The lint legs keep their usual entry. An app job restores the rolling entry with
`actions/rust-cache`'s `cache-workspace-crates: "true"`.
With `select-os`, a pull request runs those legs (macOS and Windows, say) only when it can change
platform behaviour; pushes, schedules and manual runs still run every leg. A `select legs` job
(`actions/select-platforms`) compares the merge commit with its first parent and runs every leg
+311 -106
View File
@@ -1,5 +1,7 @@
"""The shared gate workflow: pinned actions, a cache with explicit manual-branch opt-in, and caller
input that reaches the shell only through the environment, and tests sharded from one build."""
input that reaches the shell only through the environment, and tests sharded from one build. The
setup every job shares (actions/gate-setup) and the command runner (actions/gate-run) are tested
here too, as the legs run them."""
from pathlib import Path
import json
import os
@@ -15,17 +17,36 @@ WORKFLOW = yaml.load((ROOT / '.github/workflows/gate.yml').read_text(), Loader=y
INPUTS = WORKFLOW['on']['workflow_call']['inputs']
JOBS = WORKFLOW['jobs']
STEPS = JOBS['gate']['steps']
OWN_ACTION_REV = '139cccb97f9dc462b56f39ee2830718aaa782fed'
SETUP = yaml.load((ROOT / 'actions/gate-setup/action.yml').read_text(), Loader=yaml.BaseLoader)
SETUP_STEPS = SETUP['runs']['steps']
RUN_STEP = yaml.load((ROOT / 'actions/gate-run/action.yml').read_text(), Loader=yaml.BaseLoader)['runs']['steps'][0]
# The reviewed revision of the first-party actions gate.yml calls: the commit that added
# gate-setup, gate-run and restore-mtimes. gate-setup pins its own (tests/test_gate_setup.py).
OWN_ACTION_REV = 'd82b20d6b7fdd7bdbf674aef95db3b72a5efb283'
SETUP_ACTION = 'storytold/craft-common-actions/actions/gate-setup@' + OWN_ACTION_REV
CACHE = 'storytold/craft-common-actions/actions/rust-cache@fabe5cc9f4f5c4756fe8667bfd07632ce5cebb40'
# Pushes to the default branch and opted-in manual runs: the runs that write caches.
WRITES = ("github.event_name != 'pull_request' && (github.ref_name == github.event.repository.default_branch"
" || (inputs.cache-save-on-dispatch && github.event_name == 'workflow_dispatch'))")
def step(name):
return next(s for s in STEPS if s.get('name') == name)
"""A step of the gate job, or else of the shared setup."""
return next(s for s in STEPS + SETUP_STEPS if s.get('name') == name)
def setup(job='gate'):
"""The `with` a job passes to the shared setup."""
return next(s for s in JOBS[job]['steps'] if s.get('uses') == SETUP_ACTION)['with']
def all_steps():
for job_id, job in JOBS.items():
for s in job['steps']:
yield job_id, s
for s in SETUP_STEPS:
yield 'gate-setup', s
yield 'gate-run', RUN_STEP
class Expression:
@@ -210,9 +231,25 @@ def scalar(value):
return int(value) if isinstance(value, str) and value.isdigit() else value
def composite(action, given, context):
"""The steps of a composite action that run, with their evaluated `with` and `env`. Its inputs
arrive as strings, as GitHub passes them."""
inputs = {name: spec.get('default', '') for name, spec in action['inputs'].items()}
inputs.update({name: Expression.string(value) for name, value in given.items()})
expression = Expression({**context, 'inputs': inputs})
def fields(values):
return {key: Expression.string(expression(value)) for key, value in (values or {}).items()}
return [(s.get('name') or s['uses'], fields(s.get('with')), fields(s.get('env')))
for s in action['runs']['steps']
if 'if' not in s or Expression.truthy(expression.evaluate(s['if'].strip().removeprefix('${{').removesuffix('}}')))]
def graph(workflow=WORKFLOW, **call):
"""The legs a call runs, as GitHub would expand them: (job, name, matrix, steps that run with
their evaluated `with` and `env`). Every leg and step is assumed to pass."""
their evaluated `with` and `env`, the shared setup's steps in its place). Every leg and step is
assumed to pass."""
jobs = workflow['jobs']
context = caller(**call)
expression = Expression(context)
@@ -232,11 +269,13 @@ def graph(workflow=WORKFLOW, **call):
if status:
raise AssertionError(out)
select['outputs'].update(line.split('=', 1) for line in outputs)
context['needs'] = {'select': select}
needs = context['needs'] = {'select': select}
legs = []
for job_id in ('gate', 'result'):
for job_id in ('build', 'lint', 'gate', 'result'):
job = jobs.get(job_id)
if job is None or not condition(job['if']):
runs = job is not None and condition(job['if'])
needs[job_id] = {'result': 'success' if runs else 'skipped'}
if not runs:
continue
matrix = {key: expression(value) if isinstance(value, str) else [scalar(v) for v in value]
for key, value in job['strategy']['matrix'].items()}
@@ -250,8 +289,14 @@ def graph(workflow=WORKFLOW, **call):
context['matrix'] = combo
context['runner'] = {'os': 'Windows' if combo['os'].startswith('windows') else 'Linux',
'temp': '/runner/temp'}
steps = [(s.get('name') or s['uses'], fields(s.get('with')), fields(s.get('env')))
for s in job['steps'] if 'if' not in s or condition(s['if'])]
steps = []
for s in job['steps']:
if 'if' in s and not condition(s['if']):
continue
if s.get('uses') == SETUP_ACTION:
steps.extend(composite(SETUP, fields(s.get('with')), context))
else:
steps.append((s.get('name') or s['uses'], fields(s.get('with')), fields(s.get('env'))))
legs.append((job_id, expression(job['name']), combo, steps))
return legs
@@ -272,23 +317,30 @@ class GateWorkflowTests(unittest.TestCase):
self.assertRegex(s['uses'], r'@[0-9a-f]{40}$')
def test_first_party_actions_share_reviewed_revision(self):
expected = {'select-platforms', 'checkout-craft-i18n', 'install-apt-packages', 'rust-cache'}
expected = {'select-platforms', 'gate-setup', 'gate-run', 'restore-mtimes'}
actual = set()
prefix = 'storytold/craft-common-actions/actions/'
for _, item in all_steps():
uses = item.get('uses', '')
if uses.startswith(prefix):
for _, job in JOBS.items():
for item in job['steps']:
uses = item.get('uses', '')
if not uses.startswith(prefix):
continue
name, revision = uses[len(prefix):].split('@')
self.assertEqual(revision, OWN_ACTION_REV)
self.assertEqual(revision, OWN_ACTION_REV, name)
actual.add(name)
self.assertEqual(actual, expected)
def test_manual_branch_saves_require_explicit_opt_in(self):
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))
# The approved condition token by token. Substrings were the gap: appending `|| true` to the
# expression keeps every one of them intact. Formatting stays free; a token does not.
self.assertEqual(tokens(condition_of(cache)), tokens(APPROVED_CONDITION))
# The approved condition token by token, in every job that writes: substrings were the gap,
# since appending `|| true` keeps every one of them intact. Formatting stays free; a token
# does not.
for job in SAVING_JOBS:
with self.subTest(job=job):
self.assertEqual(tokens(cache_condition(job)), tokens(approved_condition(job)))
self.assertEqual(tokens(condition_of(setup(job), 'writes')), tokens(APPROVED_CONDITION))
self.assertEqual(WORKFLOW['on']['workflow_call']['inputs']['cache-save-on-dispatch']['default'], 'false')
self.assertEqual(step('Save caller cache')['if'].split('&&')[-1].strip(), "inputs.writes == 'true'")
self.assertEqual(step('Use sccache')['env']['WRITES'], '${{ inputs.writes }}')
def test_packages_are_optional_and_empty_installs_none(self):
packages = WORKFLOW['on']['workflow_call']['inputs']['packages']
@@ -334,7 +386,7 @@ class GateWorkflowTests(unittest.TestCase):
class GateTimeoutTests(unittest.TestCase):
STEP = step('Gate')
STEP = RUN_STEP
def run_gate(self, command, minutes, fake_timeout=None):
with tempfile.TemporaryDirectory() as directory:
@@ -354,7 +406,11 @@ class GateTimeoutTests(unittest.TestCase):
def test_input_defaults_to_no_limit(self):
self.assertEqual(WORKFLOW['on']['workflow_call']['inputs']['gate-timeout-minutes']['default'], '0')
self.assertEqual(set(self.STEP['env']), {'GATE', 'GATE_TIMEOUT'})
self.assertEqual(self.STEP['env'], {'GATE': '${{ inputs.command }}', 'GATE_TIMEOUT': '${{ inputs.timeout-minutes }}'})
for job_id, s in all_steps():
if s.get('uses') == 'storytold/craft-common-actions/actions/gate-run@' + OWN_ACTION_REV:
with self.subTest(job=job_id, step=s['name']):
self.assertEqual(s['with']['timeout-minutes'], '${{ inputs.gate-timeout-minutes }}')
def test_no_limit_runs_the_command_as_before(self):
self.assertEqual(self.run_gate('echo ran; exit 3', '0'), (3, 'ran\n'))
@@ -438,7 +494,10 @@ class CallerSetupTests(unittest.TestCase):
def test_setup_input_is_passed_through_env_before_the_gate(self):
self.assertEqual(set(self.STEP['env']), {'SETUP'})
self.assertLess(STEPS.index(self.STEP), STEPS.index(step('Gate')))
for job in ('build', 'gate'):
names = [s.get('name') for s in JOBS[job]['steps']]
self.assertLess(names.index('Setup'), names.index('Build the test archive' if job == 'build' else 'Gate'))
self.assertEqual(setup(job)['setup-command'], '${{ inputs.setup-command }}')
self.assertNotIn('${{', self.STEP['run'])
def test_setup_can_provision_data_and_export_its_path(self):
@@ -451,24 +510,23 @@ class CallerSetupTests(unittest.TestCase):
class CallerCacheTests(unittest.TestCase):
def test_restored_before_the_setup_and_saved_after_it(self):
restore, setup, save = step('Restore caller cache'), step('Caller setup'), step('Save caller cache')
self.assertLess(STEPS.index(restore), STEPS.index(setup))
self.assertEqual(STEPS.index(save), STEPS.index(setup) + 1)
restore, caller, save = step('Restore caller cache'), step('Caller setup'), step('Save caller cache')
self.assertLess(SETUP_STEPS.index(restore), SETUP_STEPS.index(caller))
self.assertEqual(SETUP_STEPS.index(save), SETUP_STEPS.index(caller) + 1)
for s in (restore, save):
with self.subTest(step=s['name']):
self.assertEqual(s['with']['key'], '${{ steps.caller-key.outputs.key }}')
self.assertEqual(s['with']['path'], '${{ inputs.cache-paths }}')
self.assertIn("inputs.cache-paths != '' && matrix.part != 'lint'", s['if'])
self.assertIn("inputs.cache-paths != '' && inputs.caller-setup == 'true'", s['if'])
def test_saved_only_where_the_dependency_cache_saves(self):
rust = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))['with']['save-if']
policy = re.sub(r'\s+', ' ', rust.removeprefix('${{').removesuffix('}}')).strip()
condition = re.sub(r'\s+', ' ', step('Save caller cache')['if'])
# The test part leaves the save to the cache-warm leg when there is one.
writes = policy.removesuffix("&& (matrix.part == 'lint' || matrix.part == 'warm' || inputs.warm-command == '' && matrix.shard <= 1)").strip()
self.assertNotEqual(writes, policy)
self.assertTrue(condition.endswith(f'&& {writes}'), condition)
self.assertTrue(condition.endswith("&& inputs.writes == 'true'"), condition)
self.assertIn("steps.caller-cache.outputs.cache-hit != 'true'", condition)
saves = graph(cache_paths='corpus', cache_key='k', setup_command='true')
self.assertTrue(ran(leg(saves, 'gate (ubuntu-24.04)'), 'Save caller cache'))
self.assertIsNone(ran(leg(graph(event='pull_request', ref='x', cache_paths='corpus', cache_key='k'),
'gate (ubuntu-24.04)'), 'Save caller cache'))
def run_key(self, key, files='', files_hash=''):
with tempfile.TemporaryDirectory() as directory:
@@ -492,63 +550,63 @@ class CallerCacheTests(unittest.TestCase):
class WarmPartTests(unittest.TestCase):
JOB = WORKFLOW['jobs']['gate']
def test_the_warm_leg_exists_only_where_the_cache_saves(self):
inputs = WORKFLOW['on']['workflow_call']['inputs']
self.assertEqual(inputs['warm-command']['default'], '')
def test_the_warm_leg_exists_only_where_the_cache_saves_and_without_an_archive(self):
self.assertEqual(INPUTS['warm-command']['default'], '')
part = re.sub(r'\s+', ' ', self.JOB['strategy']['matrix']['part'])
save = re.sub(r'\s+', ' ', next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))['with']['save-if'])
writes = save.removeprefix('${{').split("&& (matrix.part")[0].strip()
self.assertIn(f"inputs.warm-command != '' && {writes} && ',\"warm\"'", part)
self.assertIn(f"inputs.warm-command != '' && inputs.archive-command == '' && {WRITES} && ',\"warm\"'", part)
def test_the_warm_leg_runs_its_command_and_saves_the_gate_entry(self):
self.assertTrue(step('Gate')['env']['GATE'].startswith(
"${{ matrix.part == 'lint' && inputs.lint-command || matrix.part == 'warm' && inputs.warm-command || "))
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))['with']
self.assertEqual(cache['job'], "${{ matrix.part == 'lint' && 'lint' || inputs.cache-name != '' && format('gate-{0}', inputs.cache-name) || '' }}")
self.assertIn("matrix.part == 'lint' || matrix.part == 'warm' || inputs.warm-command == '' && matrix.shard <= 1", cache['save-if'])
self.assertEqual(cache['cache-on-failure'], 'false')
self.assertTrue(step('Gate')['with']['command'].startswith(
"${{ matrix.part == 'warm' && inputs.warm-command || "))
self.assertEqual(setup()['cache-job'], "${{ inputs.cache-name != '' && format('gate-{0}', inputs.cache-name) || 'gate' }}")
self.assertIn("(matrix.part == 'warm' || inputs.warm-command == '' && matrix.shard <= 1)", setup()['cache-save'])
self.assertEqual(next(s for s in SETUP_STEPS if s.get('uses') == CACHE)['with']['cache-on-failure'], 'false')
class LintPartTests(unittest.TestCase):
JOB = WORKFLOW['jobs']['gate']
JOB = WORKFLOW['jobs']['lint']
def test_lint_legs_exist_only_when_a_lint_command_is_given(self):
inputs = WORKFLOW['on']['workflow_call']['inputs']
self.assertEqual(inputs['lint-command']['default'], '')
part = re.sub(r'\s+', ' ', self.JOB['strategy']['matrix']['part'])
self.assertIn("inputs.lint-command != '' && ',\"lint\"'", part)
self.assertTrue(part.startswith("${{ fromJSON(format('[\"{0}\"{1}{2}]', inputs.test-shards != 0 && 'shard' || 'test', "), part)
self.assertEqual(INPUTS['lint-command']['default'], '')
self.assertIn("inputs.lint-command != ''", self.JOB['if'])
self.assertEqual(graph(lint_command=''), graph())
def test_lint_never_waits_for_the_build(self):
self.assertEqual(self.JOB['needs'], 'select')
def test_the_test_part_keeps_the_gate_check_name(self):
names = [name for _, name, _, _ in graph(lint_command='cargo clippy', warm_command='cargo test --no-run',
os='["ubuntu-24.04","windows-latest"]')]
self.assertEqual(names, ['gate (ubuntu-24.04)', 'lint (ubuntu-24.04)', 'cache warm (ubuntu-24.04)',
'gate (windows-latest)', 'lint (windows-latest)', 'cache warm (windows-latest)'])
self.assertEqual(names, ['lint (ubuntu-24.04)', 'lint (windows-latest)',
'gate (ubuntu-24.04)', 'cache warm (ubuntu-24.04)',
'gate (windows-latest)', 'cache warm (windows-latest)'])
def test_lint_runs_its_own_command_and_skips_the_test_setup(self):
gate = step('Gate')['env']['GATE']
self.assertTrue(gate.startswith("${{ matrix.part == 'lint' && inputs.lint-command || "), gate)
self.assertIn("matrix.part != 'lint'", step('Caller setup')['if'])
steps = leg(graph(lint_command='cargo clippy', cache_paths='corpus', cache_key='k', setup_command='true'),
'lint (ubuntu-24.04)')
self.assertEqual(ran(steps, 'Gate')[0]['command'], 'cargo clippy')
for name in ('Caller setup', 'Restore caller cache', 'Restore mtimes'):
self.assertIsNone(ran(steps, name), name)
def test_cache_name_gives_each_call_its_own_entry(self):
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))
self.assertIn("inputs.cache-name != '' && format('gate-{0}', inputs.cache-name)", cache['with']['job'])
self.assertEqual(WORKFLOW['on']['workflow_call']['inputs']['cache-name']['default'], '')
self.assertIn("inputs.cache-name != '' && format('gate-{0}', inputs.cache-name)", setup()['cache-job'])
self.assertEqual(INPUTS['cache-name']['default'], '')
cache, _ = ran(leg(graph(cache_name='msrv'), 'gate (ubuntu-24.04)'), CACHE)
self.assertEqual(cache['job'], 'gate-msrv')
def test_dev_strip_is_off_by_default_and_sets_the_test_profile(self):
self.assertEqual(str(WORKFLOW['on']['workflow_call']['inputs']['dev-strip']['default']).lower(), 'false')
self.assertEqual(str(INPUTS['dev-strip']['default']).lower(), 'false')
run = step('Caller environment')['run']
self.assertIn('CARGO_PROFILE_TEST_STRIP=symbols', run)
self.assertIn('CARGO_PROFILE_TEST_DEBUG=0', run)
def test_lint_keeps_a_cache_entry_of_its_own(self):
cache = next(s for s in STEPS if 'rust-cache' in s.get('uses', ''))
self.assertEqual(cache['with']['job'], "${{ matrix.part == 'lint' && 'lint' || inputs.cache-name != '' && format('gate-{0}', inputs.cache-name) || '' }}")
cache, _ = ran(leg(graph(lint_command='cargo clippy', cache_workspace_crates=True), 'lint (ubuntu-24.04)'), CACHE)
self.assertEqual((cache['job'], cache['save-if'], cache['cache-workspace-crates']), ('lint', 'true', 'false'))
SHARDED = dict(test_shards=3, shard_command='cargo nextest run --workspace --partition "$NEXTEST_PARTITION"')
TWO_RUNNERS = '["ubuntu-24.04","windows-latest"]'
CACHE = 'storytold/craft-common-actions/actions/rust-cache@' + OWN_ACTION_REV
class ShardTests(unittest.TestCase):
@@ -558,8 +616,8 @@ class ShardTests(unittest.TestCase):
self.assertEqual((INPUTS['test-shards']['type'], INPUTS['test-shards']['default']), ('number', '0'))
legs = graph(os=TWO_RUNNERS, lint_command='cargo clippy')
self.assertEqual([(job, name) for job, name, _, _ in legs], [
('gate', 'gate (ubuntu-24.04)'), ('gate', 'lint (ubuntu-24.04)'),
('gate', 'gate (windows-latest)'), ('gate', 'lint (windows-latest)')])
('lint', 'lint (ubuntu-24.04)'), ('lint', 'lint (windows-latest)'),
('gate', 'gate (ubuntu-24.04)'), ('gate', 'gate (windows-latest)')])
for _, _, _, steps in legs:
names = [n for n, _, _ in steps]
for added in ('Shard environment', "Record the leg's result", "Upload the leg's result"):
@@ -568,14 +626,15 @@ class ShardTests(unittest.TestCase):
def test_each_runner_runs_its_shards_once_lint_once_and_reports_one_gate_result(self):
legs = graph(os=TWO_RUNNERS, lint_command='cargo clippy', warm_command='cargo test --no-run', **SHARDED)
self.assertEqual([(job, name) for job, name, _, _ in legs], [
('lint', 'lint (ubuntu-24.04)'), ('lint', 'lint (windows-latest)'),
('gate', 'test 1/3 (ubuntu-24.04)'), ('gate', 'test 2/3 (ubuntu-24.04)'), ('gate', 'test 3/3 (ubuntu-24.04)'),
('gate', 'lint (ubuntu-24.04)'), ('gate', 'cache warm (ubuntu-24.04)'),
('gate', 'cache warm (ubuntu-24.04)'),
('gate', 'test 1/3 (windows-latest)'), ('gate', 'test 2/3 (windows-latest)'), ('gate', 'test 3/3 (windows-latest)'),
('gate', 'lint (windows-latest)'), ('gate', 'cache warm (windows-latest)'),
('gate', 'cache warm (windows-latest)'),
('result', 'gate (ubuntu-24.04)'), ('result', 'gate (windows-latest)')])
# The shards are legs of the gate job, so they wait only for `select`, as the gate leg does.
self.assertEqual(JOBS['gate']['needs'], 'select')
self.assertEqual(JOBS['result']['needs'], ['select', 'gate'])
# Without archive-command the build job is skipped, so the shards wait only for `select`.
self.assertEqual(JOBS['gate']['needs'], ['select', 'build'])
self.assertEqual(JOBS['result']['needs'], ['select', 'build', 'gate'])
def test_every_shard_restores_the_gate_entry_and_only_shard_1_saves_it(self):
legs = graph(**SHARDED)
@@ -583,25 +642,25 @@ class ShardTests(unittest.TestCase):
with self.subTest(shard=k):
steps = leg(legs, f'test {k}/3 (ubuntu-24.04)')
cache, _ = ran(steps, CACHE)
self.assertEqual((cache['job'], cache['save-if']), ('', k == 1))
self.assertEqual(ran(steps, 'Gate')[1]['GATE'], SHARDED['shard_command'])
self.assertEqual((cache['job'], cache['save-if']), ('gate', 'true' if k == 1 else 'false'))
self.assertEqual(ran(steps, 'Gate')[0]['command'], SHARDED['shard_command'])
self.assertEqual(ran(steps, 'Shard environment')[1], {'SHARD': k, 'SHARDS': 3})
self.assertEqual(ran(steps, "Upload the leg's result")[0]['name'], f'gate-shard-ubuntu-24.04-{k}')
self.assertFalse(any(ran(leg(graph(event='pull_request', ref='x', **SHARDED), f'test {k}/3 (ubuntu-24.04)'),
CACHE)[0]['save-if'] for k in (1, 2, 3)))
self.assertEqual({ran(leg(graph(event='pull_request', ref='x', **SHARDED), f'test {k}/3 (ubuntu-24.04)'),
CACHE)[0]['save-if'] for k in (1, 2, 3)}, {'false'})
def test_with_a_warm_leg_the_warm_leg_saves_and_no_shard_does(self):
legs = graph(warm_command='cargo test --no-run', lint_command='cargo clippy', **SHARDED)
for k in (1, 2, 3):
self.assertFalse(ran(leg(legs, f'test {k}/3 (ubuntu-24.04)'), CACHE)[0]['save-if'])
self.assertTrue(ran(leg(legs, 'cache warm (ubuntu-24.04)'), CACHE)[0]['save-if'])
self.assertEqual(ran(leg(legs, f'test {k}/3 (ubuntu-24.04)'), CACHE)[0]['save-if'], 'false')
self.assertEqual(ran(leg(legs, 'cache warm (ubuntu-24.04)'), CACHE)[0]['save-if'], 'true')
lint, _ = ran(leg(legs, 'lint (ubuntu-24.04)'), CACHE)
self.assertEqual((lint['job'], lint['save-if']), ('lint', True))
self.assertEqual((lint['job'], lint['save-if']), ('lint', 'true'))
def test_windows_shard_command_overrides_on_windows_legs_only(self):
legs = graph(os=TWO_RUNNERS, windows_shard_command='shard.ps1', **SHARDED)
self.assertEqual(ran(leg(legs, 'test 1/3 (windows-latest)'), 'Gate')[1]['GATE'], 'shard.ps1')
self.assertEqual(ran(leg(legs, 'test 1/3 (ubuntu-24.04)'), 'Gate')[1]['GATE'], SHARDED['shard_command'])
self.assertEqual(ran(leg(legs, 'test 1/3 (windows-latest)'), 'Gate')[0]['command'], 'shard.ps1')
self.assertEqual(ran(leg(legs, 'test 1/3 (ubuntu-24.04)'), 'Gate')[0]['command'], SHARDED['shard_command'])
class ShardInputTests(unittest.TestCase):
@@ -611,13 +670,20 @@ class ShardInputTests(unittest.TestCase):
status, out, outputs, _ = run_script(self.STEP['run'], {'SHARDS': shards, 'SHARD': shard})
return status, out, outputs
def test_outputs_the_shards_and_the_lint_and_warm_legs_to_leave_out(self):
def test_an_archive_without_shards_is_an_error(self):
# The select job runs for an archive-command alone, so the step can refuse it.
self.assertIn("inputs.archive-command != ''", JOBS['select']['if'])
self.assertIn("inputs.archive-command != ''", self.STEP['if'])
status, out, outputs = self.run_step('0')
self.assertEqual((status, outputs), (1, []))
self.assertIn('archive-command needs test-shards', out)
def test_outputs_the_shards_and_the_warm_legs_to_leave_out(self):
status, _, outputs = self.run_step()
self.assertEqual(status, 0)
self.assertEqual(outputs[0], 'shards=[1,2,3]')
self.assertEqual(json.loads(outputs[1].removeprefix('exclude=')),
[{'part': 'lint', 'shard': 2}, {'part': 'warm', 'shard': 2},
{'part': 'lint', 'shard': 3}, {'part': 'warm', 'shard': 3}])
[{'part': 'warm', 'shard': 2}, {'part': 'warm', 'shard': 3}])
self.assertEqual(self.run_step('1')[2], ['shards=[1]', 'exclude=[]'])
def test_rejects_what_cannot_run(self):
@@ -639,12 +705,12 @@ class ShardEnvironmentTests(unittest.TestCase):
class ResultTests(unittest.TestCase):
STEP = next(s for s in JOBS['result']['steps'] if s.get('name') == 'Every leg passed')
def run_step(self, markers, os='ubuntu-24.04', shards='3'):
def run_step(self, markers, os='ubuntu-24.04', shards='3', build='false'):
with tempfile.TemporaryDirectory() as directory:
for marker, leg_status in markers.items():
Path(directory, marker).mkdir()
Path(directory, marker, 'status').write_text(leg_status + '\n')
status, out, _, _ = run_script(self.STEP['run'], {'RESULT': directory, 'OS': os, 'SHARDS': shards})
Path(directory, marker).write_text(leg_status + '\n')
status, out, _, _ = run_script(self.STEP['run'], {'RESULT': directory, 'OS': os, 'SHARDS': shards,
'BUILD': build})
return status, re.findall(r'::error::(.*)', out)
def test_passes_when_every_shard_passed(self):
@@ -657,9 +723,38 @@ class ResultTests(unittest.TestCase):
self.assertEqual(self.run_step(markers), (1, ['test 2/3 (ubuntu-24.04) did not pass',
'test 3/3 (ubuntu-24.04) did not pass']))
def test_with_an_archive_the_build_job_must_have_passed_too(self):
shards = {f'gate-shard-ubuntu-24.04-{k}': 'success' for k in (1, 2, 3)}
self.assertEqual(self.run_step(shards, build='true'), (1, ['build (ubuntu-24.04) did not pass']))
self.assertEqual(self.run_step({**shards, 'gate-build-ubuntu-24.04': 'failure'}, build='true'),
(1, ['build (ubuntu-24.04) did not pass']))
self.assertEqual(self.run_step({**shards, 'gate-build-ubuntu-24.04': 'success'}, build='true'), (0, []))
def test_every_shard_leg_records_its_status_even_when_it_fails(self):
for name in ("Record the leg's result", "Upload the leg's result"):
self.assertTrue(step(name)['if'].startswith('always()'), name)
for s in JOBS['build']['steps']:
if s.get('name') in ("Record the build's result", "Upload the build's result"):
self.assertEqual(s['if'], 'always()')
def test_every_marker_lands_where_the_check_reads_it(self):
# Each marker is one file named after its leg, and the downloads merge them into one
# directory: with one shard, or one build, a pattern matching a single artifact would
# otherwise drop it into `path` without the directory named after it.
result = '${{ runner.temp }}/gate-result'
uploads = {s['with']['name']: s['with']['path'] for job in ('build', 'gate') for s in JOBS[job]['steps']
if s.get('name') in ("Upload the build's result", "Upload the leg's result")}
self.assertEqual(uploads, {
'gate-build-${{ matrix.os }}': f'{result}/gate-build-${{{{ matrix.os }}}}',
'gate-shard-${{ matrix.os }}-${{ matrix.shard }}': f'{result}/gate-shard-${{{{ matrix.os }}}}-${{{{ matrix.shard }}}}'})
downloads = [s for s in JOBS['result']['steps'] if s.get('uses', '').startswith('actions/download-artifact@')]
self.assertEqual({s['with']['pattern'] for s in downloads},
{'gate-shard-${{ matrix.os }}-*', 'gate-build-${{ matrix.os }}'})
for s in downloads:
self.assertEqual((s['with']['path'], s['with']['merge-multiple']), (result, 'true'))
self.assertEqual(JOBS['result']['steps'][-1]['env']['RESULT'], result)
self.assertIn('"$RESULT/gate-build-$OS"', self.STEP['run'])
self.assertIn('"$RESULT/gate-shard-$OS-$shard"', self.STEP['run'])
def test_the_result_job_keeps_the_gate_check_name_and_runs_after_failures(self):
self.assertEqual(JOBS['result']['name'], 'gate (${{ matrix.os }})')
@@ -698,7 +793,7 @@ SAVE_CONDITIONS = [
('workflow_dispatch', 'feature', 'main', True, True),
]
TOKEN = re.compile(r"\s*(?:('[^']*')|(==|!=|&&|\|\||!|\(|\))|([A-Za-z_][A-Za-z0-9_.-]*)|(-?\d+))")
TOKEN = re.compile(r"\s*(?:('[^']*')|(==|!=|<=|>=|&&|\|\||!|<|>|\(|\))|([A-Za-z_][A-Za-z0-9_.-]*)|(-?\d+))")
def tokens(expression):
@@ -713,9 +808,9 @@ def tokens(expression):
return found
def condition_of(cache_step):
"""The gate's save-if as the one expression the action receives."""
value = cache_step['with']['save-if'].strip()
def condition_of(values, field='cache-save'):
"""A job's save condition (its `with` for the shared setup) as the one expression it passes."""
value = values[field].strip()
if not (value.startswith('${{') and value.endswith('}}')):
raise AssertionError(f'the gate save condition is not one expression: {value!r}')
inner = value[3:-2]
@@ -724,8 +819,18 @@ def condition_of(cache_step):
return inner
def cache_condition():
return condition_of(next(s for s in STEPS if 'rust-cache' in s.get('uses', '')))
# The jobs whose setup may save the dependency cache. The gate job saves from one leg per runner
# (the warm leg, else shard 1), so its condition is the approved one narrowed by that.
SAVING_JOBS = ('build', 'lint', 'gate')
WARM_ALLOWANCE = "(matrix.part == 'warm' || inputs.warm-command == '' && matrix.shard <= 1)"
def approved_condition(job):
return f'{APPROVED_CONDITION} && {WARM_ALLOWANCE}' if job == 'gate' else APPROVED_CONDITION
def cache_condition(job):
return condition_of(setup(job))
class BoundedExpression:
@@ -776,10 +881,14 @@ class BoundedExpression:
def comparison(self, context):
left = self.operand(context)
if self.peek() in ('==', '!='):
if self.peek() in ('==', '!=', '<=', '>=', '<', '>'):
operator = self.take()
right = self.operand(context)
return left == right if operator == '==' else left != right
if operator in ('==', '!='):
return (left == right) == (operator == '==')
if not (isinstance(left, int) and isinstance(right, int)):
raise AssertionError(f'{operator!r} compares numbers only in a cache condition')
return {'<=': left <= right, '>=': left >= right, '<': left < right, '>': left > right}[operator]
return left
def operand(self, context):
@@ -801,32 +910,49 @@ class BoundedExpression:
return context[found]
def evaluates(expression, event, ref, default_branch, optin):
# The gate job's leg that saves: the warm-leg allowance holds for it.
SAVING_LEG = {'matrix.part': 'shard', 'matrix.shard': 1, 'inputs.warm-command': ''}
# Every kind of leg, saving or not.
LEGS = [{'matrix.part': part, 'matrix.shard': shard, 'inputs.warm-command': warm}
for part in ('test', 'shard', 'warm') for shard in (0, 1, 2) for warm in ('', 'cargo test --no-run')]
def evaluates(expression, event, ref, default_branch, optin, leg=SAVING_LEG):
"""What the workflow engine would hand the action as the save-if input, as the action sees it."""
return str(BoundedExpression(expression).evaluate({
'github.event_name': event,
'github.ref_name': ref,
'github.event.repository.default_branch': default_branch,
'inputs.cache-save-on-dispatch': optin,
**leg,
})).lower()
class SaveConditionTests(unittest.TestCase):
def test_only_the_default_branch_and_opted_in_dispatch_save(self):
for event, ref, default_branch, optin, saves in SAVE_CONDITIONS:
with self.subTest(event=event, ref=ref, default_branch=default_branch, optin=optin):
self.assertEqual(evaluates(cache_condition(), event, ref, default_branch, optin),
'true' if saves else 'false')
for job in SAVING_JOBS:
for event, ref, default_branch, optin, saves in SAVE_CONDITIONS:
with self.subTest(job=job, event=event, ref=ref, default_branch=default_branch, optin=optin):
self.assertEqual(evaluates(cache_condition(job), event, ref, default_branch, optin),
'true' if saves else 'false')
def test_a_pull_request_run_never_saves(self):
# The default-branch clause is what a rewrite can accidentally reorder, so a pull request
# from the default branch must restore only, with or without the dispatch opt-in.
for event, ref, default_branch, optin, saves in SAVE_CONDITIONS:
if event != 'pull_request':
continue
with self.subTest(ref=ref, optin=optin):
self.assertEqual(evaluates(cache_condition(), event, ref, default_branch, optin), 'false')
for job in SAVING_JOBS:
for event, ref, default_branch, optin, saves in SAVE_CONDITIONS:
if event != 'pull_request':
continue
for leg in LEGS:
with self.subTest(job=job, ref=ref, optin=optin, leg=leg):
self.assertEqual(evaluates(cache_condition(job), event, ref, default_branch, optin, leg),
'false')
def test_the_gate_job_saves_from_one_leg_per_runner(self):
saving = [leg for leg in LEGS if evaluates(cache_condition('gate'), 'push', 'main', 'main', False, leg) == 'true']
self.assertEqual(saving, [leg for leg in LEGS if leg['matrix.part'] == 'warm'
or leg['inputs.warm-command'] == '' and leg['matrix.shard'] <= 1])
class SaveConditionShapeTests(unittest.TestCase):
@@ -869,16 +995,95 @@ class GateCacheContractTests(unittest.TestCase):
return output.read_text() if output.exists() else ''
def test_the_action_reads_the_condition_as_the_decision_it_is(self):
condition = cache_condition()
for event, ref, default_branch, optin, saves in SAVE_CONDITIONS:
decision = evaluates(condition, event, ref, default_branch, optin)
with self.subTest(event=event, ref=ref, optin=optin, decision=decision):
for job, (event, ref, default_branch, optin, saves) in (
(job, row) for job in SAVING_JOBS for row in SAVE_CONDITIONS):
decision = evaluates(cache_condition(job), event, ref, default_branch, optin)
with self.subTest(job=job, event=event, ref=ref, optin=optin, decision=decision):
# The value the workflow engine passes is already a decision; the action must not
# turn it into anything else, and a canonical one must never be reported as blank.
self.assertEqual(decision, 'true' if saves else 'false')
with tempfile.TemporaryDirectory() as directory:
self.assertEqual(self.save_output(directory, decision), f'save={decision}\n')
ARCHIVED = dict(SHARDED, archive_command='cargo xtask ci archive', lint_command='cargo clippy',
warm_command='cargo test --no-run')
class ArchiveTests(unittest.TestCase):
def test_off_by_default(self):
self.assertEqual((INPUTS['archive-command']['default'], INPUTS['after-archive-command']['default']), ('', ''))
self.assertNotIn('build', [job for job, _, _, _ in graph(**SHARDED)])
def test_one_build_per_runner_and_no_warm_leg(self):
legs = graph(os=TWO_RUNNERS, **ARCHIVED)
self.assertEqual([(job, name) for job, name, _, _ in legs if job != 'gate'], [
('build', 'build (ubuntu-24.04)'), ('build', 'build (windows-latest)'),
('lint', 'lint (ubuntu-24.04)'), ('lint', 'lint (windows-latest)'),
('result', 'gate (ubuntu-24.04)'), ('result', 'gate (windows-latest)')])
self.assertEqual([name for job, name, _, _ in legs if job == 'gate'],
[f'test {k}/3 ({os})' for os in ('ubuntu-24.04', 'windows-latest') for k in (1, 2, 3)])
def test_the_build_job_builds_uploads_and_saves_the_gate_entry_on_main(self):
steps = leg(graph(after_archive_command='cargo test --doc', **ARCHIVED), 'build (ubuntu-24.04)')
names = [name for name, _, _ in steps]
self.assertEqual(ran(steps, 'Archive path')[1], {'FILE': '/runner/temp/nextest-archive.tar.zst'})
self.assertEqual(ran(steps, 'Build the test archive')[0]['command'], ARCHIVED['archive_command'])
# The after-archive command runs after the upload; the shards still wait for the whole job.
self.assertLess(names.index('Upload the test archive'), names.index('After the archive'))
# A re-run of the build job replaces the archive its first attempt uploaded.
self.assertEqual(ran(steps, 'Upload the test archive')[0]['overwrite'], 'true')
self.assertEqual(ran(steps, 'After the archive')[0]['command'], 'cargo test --doc')
self.assertEqual(ran(steps, 'Upload the test archive')[0]['name'], 'gate-archive-ubuntu-24.04')
self.assertEqual(ran(steps, CACHE)[0]['job'], 'gate')
self.assertEqual(ran(steps, CACHE)[0]['save-if'], 'true')
pull = leg(graph(event='pull_request', ref='x', **ARCHIVED), 'build (ubuntu-24.04)')
self.assertEqual(ran(pull, CACHE)[0]['save-if'], 'false')
def test_shards_download_the_archive_and_restore_no_cache(self):
steps = leg(graph(**ARCHIVED), 'test 2/3 (ubuntu-24.04)')
self.assertIsNone(ran(steps, CACHE))
self.assertEqual(ran(steps, 'Download the test archive')[0]['name'], 'gate-archive-ubuntu-24.04')
self.assertEqual(ran(steps, 'Archive path')[1], {'FILE': '/runner/temp/gate-archive/nextest-archive.tar.zst'})
self.assertEqual(ran(steps, 'Gate')[0]['command'], SHARDED['shard_command'])
def test_only_the_shards_wait_for_the_build(self):
self.assertEqual(JOBS['lint']['needs'], 'select')
self.assertEqual(JOBS['gate']['needs'], ['select', 'build'])
self.assertIn("needs.build.result != 'failure'", JOBS['gate']['if'])
class WorkspaceCrateTests(unittest.TestCase):
def test_off_by_default(self):
self.assertEqual((INPUTS['cache-workspace-crates']['default'], INPUTS['cold-build']['default']), ('false', 'false'))
steps = leg(graph(**ARCHIVED), 'build (ubuntu-24.04)')
self.assertEqual(ran(steps, CACHE)[0]['cache-workspace-crates'], 'false')
self.assertIsNone(ran(steps, 'Restore mtimes'))
self.assertIsNone(ran(steps, 'Record the cache commit'))
def test_the_saving_leg_restores_mtimes_and_records_its_commit(self):
steps = leg(graph(cache_workspace_crates=True, **ARCHIVED), 'build (ubuntu-24.04)')
cache, _ = ran(steps, CACHE)
self.assertEqual((cache['cache-workspace-crates'], cache['restore'], cache['save-if']), ('true', 'true', 'true'))
names = [name for name, _, _ in steps]
self.assertLess(names.index(CACHE), names.index('Restore mtimes'))
self.assertEqual(ran(steps, 'Restore mtimes')[0]['mode'], 'restore')
self.assertLess(names.index('Build the test archive'), names.index('Record the cache commit'))
self.assertEqual(ran(steps, 'Record the cache commit')[0]['mode'], 'record')
def test_without_an_archive_every_building_leg_restores_mtimes(self):
legs = graph(cache_workspace_crates=True, **SHARDED)
for k in (1, 2, 3):
steps = leg(legs, f'test {k}/3 (ubuntu-24.04)')
self.assertTrue(ran(steps, 'Restore mtimes'))
self.assertTrue(ran(steps, 'Record the cache commit'))
def test_a_cold_build_restores_nothing_and_still_saves(self):
steps = leg(graph(cache_workspace_crates=True, cold_build=True, **ARCHIVED), 'build (ubuntu-24.04)')
cache, _ = ran(steps, CACHE)
self.assertEqual((cache['restore'], cache['save-if']), ('false', 'true'))
self.assertIsNone(ran(steps, 'Restore mtimes'))
self.assertTrue(ran(steps, 'Record the cache commit'))
# The profile half of the cache key, and the rest of the key's layout, are tested where they now
# live: tests/test_rust_cache.py.
+7 -1
View File
@@ -98,7 +98,13 @@ class NextestVersionTests(unittest.TestCase):
def test_gate_default_still_reaches_the_installer_and_allows_caller_overrides(self):
gate = self.documents[GATE]
self.assertEqual(gate['on']['workflow_call']['inputs']['tools']['default'], PIN)
installers = [step for step in gate['jobs']['gate']['steps']
# Every gate job installs the tools through the shared setup, which passes them on.
for job in ('build', 'lint', 'gate'):
setup = next(step for step in gate['jobs'][job]['steps']
if step.get('uses', '').startswith('storytold/craft-common-actions/actions/gate-setup@'))
self.assertEqual(setup['with']['tools'], '${{ inputs.tools }}', job)
action = yaml.safe_load((ROOT / 'actions/gate-setup/action.yml').read_text())
installers = [step for step in action['runs']['steps']
if step.get('uses', '').startswith('step-security/taiki-e-install-action@')]
self.assertEqual(len(installers), 1)
self.assertEqual(installers[0]['with']['tool'], '${{ inputs.tools }}')
+9 -24
View File
@@ -15,7 +15,6 @@ ACTION = yaml.load((ROOT / 'actions/rust-cache/action.yml').read_text(), Loader=
INPUTS = ACTION['inputs']
STEPS = ACTION['runs']['steps']
GATE = yaml.load((ROOT / '.github/workflows/gate.yml').read_text(), Loader=yaml.BaseLoader)
GATE_STEPS = GATE['jobs']['gate']['steps']
OWN_ACTION = re.compile(r'^storytold/craft-common-actions/actions/[a-z0-9-]+@main$')
PINNED = re.compile(r'^[A-Za-z0-9-]+/[A-Za-z0-9._-]+@[0-9a-f]{40}$')
CACHES = [s for s in STEPS if 'rust-cache' in s.get('uses', '')]
@@ -457,42 +456,28 @@ class AlignEnvironmentTests(unittest.TestCase):
class GateTests(unittest.TestCase):
"""gate.yml's side of the key. gate-setup's call of this action: tests/test_gate_setup.py."""
def test_fixed_gate_environment_is_part_of_the_restore_contract(self):
# Callers can add build variables through env/dev-debug. Photo opts out of the debug
# override; changing this shared fixed part still splits its restore from the gate.
for job in ('build', 'lint'):
self.assertEqual(GATE['jobs'][job]['env'], GATE['jobs']['gate']['env'], job)
fixed = GATE['jobs']['gate']['env']
hashed = {name: value for name, value in fixed.items()
if name.startswith(('CARGO', 'CC', 'CFLAGS', 'CXX', 'CMAKE', 'RUST'))}
self.assertEqual(hashed, {'CARGO_TERM_COLOR': 'always', 'CARGO_INCREMENTAL': '0',
'CARGO_NET_RETRY': '10', 'RUST_BACKTRACE': '1'})
install = next(s for s in GATE_STEPS if s.get('name') == 'Install Rust')
# Replacing rustup with an action that exports CARGO_HOME needs a cache-contract review.
self.assertNotIn('GITHUB_ENV', install['run'])
def test_setup_shell_steps_do_not_add_cargo_home_to_the_key(self):
cache = next(i for i, s in enumerate(GATE_STEPS)
if s.get('uses') == 'storytold/craft-common-actions/actions/rust-cache@139cccb97f9dc462b56f39ee2830718aaa782fed')
for setup in GATE_STEPS[:cache]:
# Conservative source guard, not shell data-flow analysis. An opaque setup action
# still needs a hosted key comparison; callers' generic env input remains supported.
self.assertNotIn('CARGO_HOME', setup.get('run', ''), setup.get('name', setup.get('uses')))
def test_gate_and_action_cache_version_defaults_agree(self):
default = GATE['on']['workflow_call']['inputs']['cache-version']['default']
self.assertEqual(default, INPUTS['cache-version']['default'])
def test_the_gate_restores_through_the_action(self):
calls = [s for s in GATE_STEPS
if s.get('uses') == 'storytold/craft-common-actions/actions/rust-cache@139cccb97f9dc462b56f39ee2830718aaa782fed']
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0]['with']['cache-version'], '${{ inputs.cache-version }}')
self.assertEqual(calls[0]['with']['cache-on-failure'], 'false')
def test_no_second_copy_of_the_key_remains(self):
for s in GATE_STEPS:
with self.subTest(step=s.get('name')):
self.assertNotRegex(s.get('uses', ''), r'^[^/]+/rust-cache@')
self.assertNotIn('Cache profile key', [s.get('name') for s in GATE_STEPS])
def test_no_gate_job_keys_the_cache_itself(self):
for name, job in GATE['jobs'].items():
for s in job['steps']:
with self.subTest(job=name, step=s.get('name')):
self.assertNotRegex(s.get('uses', ''), r'/rust-cache@')
if __name__ == '__main__':
+10 -7
View File
@@ -158,15 +158,18 @@ class PlatformCfgTests(unittest.TestCase):
class GateSelectJobTests(unittest.TestCase):
def test_the_gate_reads_its_legs_from_the_select_job_or_os(self):
gate = GATE['jobs']['gate']
self.assertEqual(gate['needs'], 'select')
self.assertEqual(gate['strategy']['matrix']['os'], '${{ fromJSON(needs.select.outputs.os || inputs.os) }}')
self.assertEqual(gate['if'], "${{ !cancelled() && needs.select.result != 'failure' }}")
def test_every_job_reads_its_legs_from_the_select_job_or_os(self):
for name in ('build', 'lint', 'gate'):
with self.subTest(job=name):
job = GATE['jobs'][name]
self.assertIn('select', job['needs'])
self.assertEqual(job['strategy']['matrix']['os'], '${{ fromJSON(needs.select.outputs.os || inputs.os) }}')
self.assertTrue(job['if'].startswith("${{ !cancelled() && needs.select.result != 'failure'"), job['if'])
def test_select_runs_only_with_select_os_or_shards(self):
def test_select_runs_only_with_select_os_shards_or_an_archive(self):
select = GATE['jobs']['select']
self.assertEqual(select['if'], "(inputs.select-os != '' && inputs.select-os != '[]') || inputs.test-shards != 0")
self.assertEqual(select['if'], "(inputs.select-os != '' && inputs.select-os != '[]') || inputs.test-shards != 0"
" || inputs.archive-command != ''")
self.assertEqual(GATE['on']['workflow_call']['inputs']['select-os']['default'], '[]')
checkout = next(s for s in select['steps'] if 'actions/checkout' in s.get('uses', ''))
self.assertEqual(checkout['with']['fetch-depth'], '2')