diff --git a/.config/cargo-ci.toml b/.config/cargo-ci.toml new file mode 100644 index 000000000..30eba421c --- /dev/null +++ b/.config/cargo-ci.toml @@ -0,0 +1,17 @@ +# The Workspace gate's additions to .config/cargo-dev.toml (scripts/ci-workspace-tests.sh passes both). The gate runs +# every test of these crates, and their tests spend nearly all their time in sample and pixel loops, which run several +# times faster at opt-level 1; locally they stay at 0, so an edit to them rebuilds fast. +[profile.dev.package.craft-audio-dsp] +opt-level = 1 + +[profile.dev.package.craft-audio] +opt-level = 1 + +[profile.dev.package.craft-media] +opt-level = 1 + +[profile.dev.package.craft-image-codecs] +opt-level = 1 + +[profile.dev.package.craft-imaging] +opt-level = 1 diff --git a/.config/cargo-dev.toml b/.config/cargo-dev.toml new file mode 100644 index 000000000..cec2fbc4f --- /dev/null +++ b/.config/cargo-dev.toml @@ -0,0 +1,25 @@ +# The dev-build tuning every craft-libs test build uses: `tools/cl` passes it to each cargo command locally, and +# scripts/ci-workspace-tests.sh passes it (`--config .config/cargo-dev.toml`) to the Workspace gate's builds, so local +# and CI builds are the same. It lives here and not in Cargo.toml's `[profile]` table, which the CI cache key hashes; +# the per-crate levels Cargo.toml sets (craft-video, craft-affinity) still apply. +# +# lto off: with cargo's default, rustc runs thin-local LTO across every optimised crate's codegen units on each rebuild; +# off, a one-line edit re-optimises only the changed units. Dependencies build at opt-level 2, once per target dir and +# cache entry: egui, text shaping, hashing and codecs run in nearly every test. +# craft-theme, craft-behavior and craft-proof run in every screen-test frame or in dictionary-sized tests and are rarely +# edited, so they build at opt-level 1; every other workspace crate stays at 0, where rustc shares generic +# instantiations across crates and an edit to the runtime (craft-ui-contract) rebuilds in seconds. +[profile.dev] +lto = "off" + +[profile.dev.package."*"] +opt-level = 2 + +[profile.dev.package.craft-theme] +opt-level = 1 + +[profile.dev.package.craft-behavior] +opt-level = 1 + +[profile.dev.package.craft-proof] +opt-level = 1 diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index d87302bfe..5cc803266 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -31,14 +31,16 @@ jobs: cache-paths: .test-inputs/photocraft/corpus cache-key: photocraft-corpus cache-key-files: scripts/ci-test-inputs.sh - command: cargo nextest run --workspace --all-features --locked --profile ci + # The gate's build (the same targets and profile overrides), with every test at its full count. + command: bash scripts/ci-workspace-tests.sh full - # Pull requests run the Workspace gate's Linux legs only, and pushes to next cancel each other's - # runs, so this starts one Workspace run on next a day that nothing cancels: next's macOS and - # Windows legs then run in full at least once a day, and its Linux leg builds from source and - # saves next's own workspace-crates cache entry, which pull requests into next restore. Main gets - # the same from workspace.yml's own scheduled runs. The only job here with `actions: write`; it checks out and runs nothing from - # the repository. + # The scheduled run is main's; this starts the full tests above on next too, where the gate + # runs the same fractions. It also starts one Workspace run on next a day that nothing cancels + # (pull requests run the Linux legs only, and pushes to next cancel each other's runs): next's + # macOS and Windows legs then run in full at least once a day, and its Linux leg builds from + # source and saves next's own workspace-crates cache entry, which pull requests into next + # restore. Main gets the same from workspace.yml's own scheduled runs. The only job here with + # `actions: write`; it checks out and runs nothing from the repository. workspace-next: name: Workspace on next if: github.event_name == 'schedule' @@ -51,8 +53,10 @@ jobs: uses: step-security/harden-runner@v2.22.4 with: egress-policy: audit - - name: Start the Workspace workflow on next + - name: Start the Workspace workflow and these full tests on next env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} - run: gh workflow run workspace.yml --repo "$REPO" --ref next + run: | + gh workflow run workspace.yml --repo "$REPO" --ref next + gh workflow run nightly.yml --repo "$REPO" --ref next diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index 988c94f91..bc6077bfa 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -42,6 +42,8 @@ jobs: platform: ${{ steps.select.outputs.platform }} tests: ${{ steps.select.outputs.tests }} filter: ${{ steps.select.outputs.filter }} + audit: ${{ steps.audit.outputs.audit }} + profile: ${{ steps.audit.outputs.profile }} steps: - name: Harden runner uses: step-security/harden-runner@v2.22.4 @@ -60,6 +62,27 @@ jobs: select-os: '["windows-latest","macos-latest"]' select-tests: true label: full-ci + # Whether the selection reaches a replay-audit crate, which runs the Linux leg as a build job + # and three test shards (see `native`), and the hash of the profile overrides every test build + # passes (scripts/ci-workspace-tests.sh), which names the Workspace legs' cache entries: + # rust-cache's key does not hash these files, and an entry built with other overrides would be + # rebuilt in full on every run. Other events than a pull request check out only these files. + - uses: actions/checkout@v7.0.1 + if: github.event_name != 'pull_request' + with: + persist-credentials: false + sparse-checkout: | + scripts/ci-workspace-tests.sh + .config/cargo-*.toml + sparse-checkout-cone-mode: false + - id: audit + env: + CRAFT_TESTS: ${{ steps.select.outputs.tests }} + CRAFT_TEST_FILTER: ${{ steps.select.outputs.filter }} + CRAFT_TEST_SKIP: ${{ steps.select.outputs.skip }} + run: | + echo "audit=$(bash scripts/ci-workspace-tests.sh audit)" >> "$GITHUB_OUTPUT" + echo "profile=$(cat .config/cargo-dev.toml .config/cargo-ci.toml | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT" # The Linux leg keeps the compiled workspace crates between runs (`cache-workspace-crates`): each # main run saves a rolling cache entry of its own, every run restores the newest one, and Cargo @@ -79,6 +102,7 @@ jobs: os: '["ubuntu-latest"]' cache-workspace-crates: true cache-save-on-dispatch: true + cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }} cold-build: ${{ github.event.schedule == '17 0 * * *' || github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/next' }} lint-cache: false # The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them. @@ -124,28 +148,17 @@ jobs: fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings - command: &command | - # The tests run once, with every feature, in parallel across test binaries; nextest skips - # doctests, so `cargo test --doc` runs them. Examples are not built, except the two whose - # tests run (stubicc, h264_h264enc_bench); clippy in the lint leg covers the rest. The default-feature compile is the lint leg's - # first clippy run; the last command runs the crates whose tests check behaviour with a - # feature off, which an all-features build cannot reach. - # Every build is the whole workspace's, as on main; the filter narrows only the run. The - # doctests run for the whole workspace: `cargo test -p ` would resolve features - # over the selected crates only and rebuild the dependencies whose features differ. - if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 - fi - cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench - # The replay audit (craft-libs#2336), on Linux: the selected UI crates' tests again, from the same build, with every - # memoized view that would replay also run for real and compared with its replay. - if [ "$RUNNER_OS" = Linux ]; then - CRAFT_UI_AUDIT_REPLAY=1 cargo nextest run --workspace --all-features --locked --profile ci -E "($CRAFT_TEST_FILTER) & (package(craft-ui-contract) | package(craft-ui-widgets) | package(craft-ui-panels) | package(craft-ui-patterns) | package(craft-ui-shell) | package(craft-ui-gallery) | package(craft-menu))" --no-tests=warn --lib --bins --tests - fi - cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests + # A selection that reaches a replay-audit crate builds once in a `build` job, which writes + # three nextest archives and then runs the doctests; three shard legs run them in parallel: + # every selected test, the replay audit, and the default-feature crates. Any other selection + # (and every macOS and Windows leg) builds and runs in one leg. scripts/ci-workspace-tests.sh + # holds every step. + test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }} + shard-archives: ${{ needs.platforms.outputs.audit == 'true' }} + archive-command: ${{ needs.platforms.outputs.audit == 'true' && 'bash scripts/ci-workspace-tests.sh archive' || '' }} + after-archive-command: bash scripts/ci-workspace-tests.sh doctest + shard-command: bash scripts/ci-workspace-tests.sh shard + command: &command bash scripts/ci-workspace-tests.sh run # The macOS and Windows legs, with the Linux leg's inputs. They take 1.5-2 hours against the Linux # leg's 15-40 minutes, so a pull request does not wait for them: they run after the merge, on @@ -159,6 +172,7 @@ jobs: with: os: '["windows-latest","macos-latest"]' lint-cache: false + cache-version: *cache-version timeout-minutes: *timeout tools: *tools craft-fonts-ref: *craft-fonts @@ -176,16 +190,6 @@ jobs: cache-key-files: *cache-key-files lint-command: *lint command: *command - windows-command: | - if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 - fi - powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' - cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests - cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench - cargo test --workspace --doc --all-features --locked - cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests # Each main run's Linux leg saves a rolling cache entry of its own (`cache-workspace-crates`), as # does the daily manual run on next, and every run restores only the newest. This deletes the diff --git a/scripts/ci-workspace-tests.sh b/scripts/ci-workspace-tests.sh new file mode 100755 index 000000000..e11754bf8 --- /dev/null +++ b/scripts/ci-workspace-tests.sh @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +# The Workspace gate's test steps (.github/workflows/workspace.yml), one per argument: +# +# run one leg builds and runs every test: each macOS and Windows leg, and the Linux leg when +# the selection reaches no replay-audit crate +# archive the Linux build job (gate.yml `archive-command`) builds once and writes one nextest +# archive per shard: 1 every selected test, 2 the replay audit's UI crates, 3 the +# default-feature crates +# shard a Linux shard leg runs its archive ($GATE_SHARD) +# doctest the doctests, in the build job after the archives (`after-archive-command`) +# audit prints whether the selection reaches a replay-audit crate (`true` or `false`) +# full the nightly run: every test, at the full sweep and proptest counts nightly.yml leaves set +# +# CRAFT_TESTS (all, some, none) and CRAFT_TEST_FILTER are the platforms job's selection; +# CRAFT_TEST_SKIP is its list of members whose tests do not run. +set -euo pipefail + +# Every build passes the same profile overrides, so the steps of one leg share their build and +# match local `tools/cl` builds (.config/cargo-dev.toml); .config/cargo-ci.toml adds the gate's own. +config=(--config .config/cargo-dev.toml --config .config/cargo-ci.toml) +# Every test once, with every feature. Examples are not built, except the two whose tests run; +# clippy in the lint leg covers the rest. Every build is the whole workspace's: the filter narrows +# only what runs. +all_features=(--workspace --all-features --locked --profile ci "${config[@]}") +targets=(--lib --bins --tests) +examples=(-p craft-aep -p craft-video --example stubicc --example h264_h264enc_bench) +# The crates whose tests check behaviour with a feature off, which an all-features build cannot reach. +default_features=(-p craft-image-codecs -p craft-text --locked --profile ci "${config[@]}") +# The replay audit (craft-libs#2336): these crates' tests again, with every memoized view that would +# replay also run for real and compared with its replay. +audit_packages=(craft-ui-contract craft-ui-widgets craft-ui-panels craft-ui-patterns craft-ui-shell craft-ui-gallery craft-menu) +audit_filter=$(printf ' | package(%s)' "${audit_packages[@]}") +audit_filter="(${CRAFT_TEST_FILTER:-all()}) & (${audit_filter:3})" +filter=${CRAFT_TEST_FILTER:-all()} + +doctests() { + # Whole-workspace: `cargo test -p ` would resolve features over the selected crates + # only and rebuild the dependencies whose features differ. + cargo test --workspace --doc --all-features --locked "${config[@]}" +} + +case "${1:-}" in + run) + if [ "${CRAFT_TESTS:-all}" = none ]; then + echo "No crate changed: no tests to run." + exit 0 + fi + if [ "${RUNNER_OS:-}" = Windows ]; then + # shellcheck disable=SC2016 # $ErrorActionPreference is PowerShell's + powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"' + fi + cargo nextest run "${all_features[@]}" -E "$filter" --no-tests=warn "${targets[@]}" + cargo nextest run "${examples[@]}" --all-features --locked --profile ci "${config[@]}" -E "$filter" --no-tests=warn + doctests + cargo nextest run "${default_features[@]}" -E "$filter" --no-tests=warn "${targets[@]}" + ;; + archive) + for shard in 1 2 3; do mkdir -p "$NEXTEST_ARCHIVE_DIR/$shard"; done + # The examples' two packages join the one build here, so their tests are in shard 1's archive. + cargo nextest archive "${all_features[@]}" "${targets[@]}" --example stubicc --example h264_h264enc_bench \ + -E "$filter" --archive-file "$NEXTEST_ARCHIVE_DIR/1/$NEXTEST_ARCHIVE_NAME" + # The same build, so nothing compiles again; only the audit crates' binaries. + cargo nextest archive "${all_features[@]}" "${targets[@]}" --example stubicc --example h264_h264enc_bench \ + -E "$audit_filter" --archive-file "$NEXTEST_ARCHIVE_DIR/2/$NEXTEST_ARCHIVE_NAME" + cargo nextest archive "${default_features[@]}" "${targets[@]}" \ + -E "$filter" --archive-file "$NEXTEST_ARCHIVE_DIR/3/$NEXTEST_ARCHIVE_NAME" + ;; + shard) + run=(cargo nextest run --archive-file "$NEXTEST_ARCHIVE_FILE" --workspace-remap . --profile ci --no-tests=warn) + case "${GATE_SHARD:-}" in + 1 | 3) "${run[@]}" ;; + 2) CRAFT_UI_AUDIT_REPLAY=1 "${run[@]}" ;; + *) echo "unknown shard: '${GATE_SHARD:-}'" >&2; exit 2 ;; + esac + ;; + doctest) + doctests + ;; + audit) + case "${CRAFT_TESTS:-all}" in + none) echo false ;; + all) echo true ;; + *) + reached=false + for package in "${audit_packages[@]}"; do + if [[ " ${CRAFT_TEST_SKIP:-} " != *" $package "* ]]; then reached=true; fi + done + echo "$reached" + ;; + esac + ;; + full) + cargo nextest run "${all_features[@]}" --no-tests=warn "${targets[@]}" + cargo nextest run "${examples[@]}" --all-features --locked --profile ci "${config[@]}" --no-tests=warn + ;; + *) + echo "usage: $0 run|archive|shard|doctest|audit|full" >&2 + exit 2 + ;; +esac diff --git a/scripts/test-workspace-tests.py b/scripts/test-workspace-tests.py index c2d0b82e9..77cdccd2e 100644 --- a/scripts/test-workspace-tests.py +++ b/scripts/test-workspace-tests.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 -"""Exercise the native workflow's command selection without compiling Rust.""" +"""Exercise the Workspace gate's lint block and test steps without compiling Rust.""" import os import re +import tempfile import subprocess import tomllib import unittest @@ -33,35 +34,9 @@ fi cargo clippy --workspace --all-targets --locked -- -D warnings cargo clippy --workspace --all-targets --all-features --locked -- -D warnings """ -# The `platforms` job's selection: no tests when no crate changed, otherwise a nextest filter. -SELECT_GUARD = """ -if [ "$CRAFT_TESTS" = none ]; then - echo "No crate changed: no tests to run." - exit 0 -fi -""" -# The Windows leg runs these without the replay audit, which runs on Linux only. -TEST_RUN = """ -cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests -cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench -cargo test --workspace --doc --all-features --locked -cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests -""" -TEST_SOURCE = SELECT_GUARD + """ -cargo nextest run --workspace --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests -cargo nextest run -p craft-aep -p craft-video --all-features --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --example stubicc --example h264_h264enc_bench -if [ "$RUNNER_OS" = Linux ]; then - CRAFT_UI_AUDIT_REPLAY=1 cargo nextest run --workspace --all-features --locked --profile ci -E "($CRAFT_TEST_FILTER) & (package(craft-ui-contract) | package(craft-ui-widgets) | package(craft-ui-panels) | package(craft-ui-patterns) | package(craft-ui-shell) | package(craft-ui-gallery) | package(craft-menu))" --no-tests=warn --lib --bins --tests -fi -cargo test --workspace --doc --all-features --locked -cargo nextest run -p craft-image-codecs -p craft-text --locked --profile ci -E "$CRAFT_TEST_FILTER" --no-tests=warn --lib --bins --tests -""" -WINDOWS_SETUP = """powershell.exe -NoProfile -Command '$ErrorActionPreference = "Stop"; Start-Service Spooler; Add-PrinterDriver -Name "Generic / Text Only"'""" -EXPECTED_SOURCE = { - "lint-command": LINT_SOURCE, - "command": TEST_SOURCE, - "windows-command": SELECT_GUARD + WINDOWS_SETUP + "\n" + TEST_RUN, -} +EXPECTED_SOURCE = {"lint-command": LINT_SOURCE} +SCRIPT = ROOT / "scripts/ci-workspace-tests.sh" +NIGHTLY = ROOT / ".github/workflows/nightly.yml" def source_lines(source): @@ -83,26 +58,47 @@ cargo() { if [ -n "$FAIL" ] && [ "$*" = "$FAIL" ]; then return 17; fi } python3() { :; } -case "$BLOCK" in - lint-command) -""" + LINT_SOURCE + """ - ;; - command) -""" + TEST_SOURCE + """ - ;; - *) exit 29 ;; -esac +""" + LINT_SOURCE + + +def lint(os_name, fail="", source=None): + validate_source(WORKFLOW.read_text() if source is None else source, "lint-command") + return subprocess.run( + ["bash", "-euo", "pipefail", "-c", HARNESS], + env={**os.environ, "RUNNER_OS": os_name, "FAIL": fail}, + text=True, capture_output=True, check=False, + ) + + +# Stand-ins for the programs the test steps start: each prints its arguments (cargo without its +# name, as above), and cargo fails with 17 on the command named in $FAIL. +FAKE_CARGO = """#!/usr/bin/env bash +line="$*" +if [ -n "${CRAFT_UI_AUDIT_REPLAY:-}" ]; then line="AUDIT $line"; fi +printf '%s\\n' "$line" +if [ -n "${FAIL:-}" ] && [ "$line" = "$FAIL" ]; then exit 17; fi +""" +FAKE_POWERSHELL = """#!/usr/bin/env bash +echo powershell.exe """ -def commands(os_name, fail="", name="command", source=None, tests="all", test_filter="all()"): - validate_source(WORKFLOW.read_text() if source is None else source, name) - return subprocess.run( - ["bash", "-euo", "pipefail", "-c", HARNESS], - env={**os.environ, "RUNNER_OS": os_name, "FAIL": fail, "BLOCK": name, - "CRAFT_TESTS": tests, "CRAFT_TEST_FILTER": test_filter}, - text=True, capture_output=True, check=False, - ) +def step(name, os_name="Linux", fail="", tests="all", test_filter="all()", **env): + with tempfile.TemporaryDirectory() as tmp: + for program, text in (("cargo", FAKE_CARGO), ("powershell.exe", FAKE_POWERSHELL)): + path = Path(tmp) / program + path.write_text(text) + path.chmod(0o755) + archives = Path(tmp) / "archives" + result = subprocess.run( + ["bash", str(SCRIPT), name], + env={**os.environ, "PATH": f"{tmp}:{os.environ['PATH']}", "RUNNER_OS": os_name, "FAIL": fail, + "CRAFT_TESTS": tests, "CRAFT_TEST_FILTER": test_filter, + "NEXTEST_ARCHIVE_DIR": str(archives), "NEXTEST_ARCHIVE_NAME": "a.tar.zst", **env}, + text=True, capture_output=True, check=False, cwd=ROOT, + ) + made = sorted(p.name for p in archives.iterdir()) if archives.exists() else [] + return result, made COMMON = [ @@ -110,25 +106,39 @@ COMMON = [ "clippy --workspace --all-targets --locked -- -D warnings", "clippy --workspace --all-targets --all-features --locked -- -D warnings", ] -def test_commands(test_filter="all()"): - return [line.strip()[len("cargo "):].replace('"$CRAFT_TEST_FILTER"', test_filter) - for line in TEST_RUN.splitlines() if line.strip()] +CONFIG = "--config .config/cargo-dev.toml --config .config/cargo-ci.toml" +ALL = f"--workspace --all-features --locked --profile ci {CONFIG}" +DEFAULT = f"-p craft-image-codecs -p craft-text --locked --profile ci {CONFIG}" +TARGETS = "--lib --bins --tests" +EXAMPLES = "--example stubicc --example h264_h264enc_bench" +AUDIT_PACKAGES = ("craft-ui-contract", "craft-ui-widgets", "craft-ui-panels", "craft-ui-patterns", + "craft-ui-shell", "craft-ui-gallery", "craft-menu") +AUDIT = " | ".join(f"package({name})" for name in AUDIT_PACKAGES) +DOCTESTS = f"test --workspace --doc --all-features --locked {CONFIG}" -AUDIT_PACKAGES = " | ".join( - f"package({name})" for name in ("craft-ui-contract", "craft-ui-widgets", "craft-ui-panels", "craft-ui-patterns", - "craft-ui-shell", "craft-ui-gallery", "craft-menu")) +def run_commands(test_filter="all()"): + return [ + f"nextest run {ALL} -E {test_filter} --no-tests=warn {TARGETS}", + f"nextest run -p craft-aep -p craft-video {EXAMPLES} --all-features --locked --profile ci {CONFIG} " + f"-E {test_filter} --no-tests=warn", + DOCTESTS, + f"nextest run {DEFAULT} -E {test_filter} --no-tests=warn {TARGETS}", + ] -def linux_test_commands(test_filter="all()"): - tests = test_commands(test_filter) - audit = (f"nextest run --workspace --all-features --locked --profile ci -E ({test_filter}) & ({AUDIT_PACKAGES}) " - "--no-tests=warn --lib --bins --tests") - return tests[:2] + [audit] + tests[2:] +def archive_commands(directory, test_filter="all()"): + return [ + f"nextest archive {ALL} {TARGETS} {EXAMPLES} -E {test_filter} --archive-file {directory}/1/a.tar.zst", + f"nextest archive {ALL} {TARGETS} {EXAMPLES} -E ({test_filter}) & ({AUDIT}) " + f"--archive-file {directory}/2/a.tar.zst", + f"nextest archive {DEFAULT} {TARGETS} -E {test_filter} --archive-file {directory}/3/a.tar.zst", + ] -TESTS = test_commands() -LINUX_TESTS = linux_test_commands() +def archive_dir(result): + # The harness's temporary directory, read back from the first archive path. + return re.search(r"--archive-file (\S+)/1/a\.tar\.zst", result.stdout)[1] class WorkspaceTests(unittest.TestCase): @@ -138,45 +148,90 @@ class WorkspaceTests(unittest.TestCase): # formatting. for os_name, expected in (("Linux", COMMON), ("macOS", COMMON), ("Windows", COMMON[1:])): with self.subTest(os=os_name): - result = commands(os_name, name="lint-command") + result = lint(os_name) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.splitlines(), expected) - def test_linux_and_macos_run_one_feature_set_with_doctests(self): - for os_name, expected in (("Linux", LINUX_TESTS), ("macOS", TESTS)): + def test_one_leg_runs_one_feature_set_with_doctests_and_the_feature_off_crates(self): + for os_name, expected in (("Linux", run_commands()), ("macOS", run_commands()), + ("Windows", ["powershell.exe"] + run_commands())): with self.subTest(os=os_name): - result = commands(os_name) + result, _ = step("run", os_name) self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.splitlines(), expected) def test_a_selection_filters_every_nextest_run_and_none_runs_nothing(self): selected = "package(=craft-geom) | package(=craft-svg)" - result = commands("Linux", tests="some", test_filter=selected) + result, _ = step("run", tests="some", test_filter=selected) self.assertEqual(result.returncode, 0, result.stderr) - self.assertEqual(result.stdout.splitlines(), linux_test_commands(selected)) - # The doctests stay whole-workspace; every nextest run carries the filter, and the replay - # audit runs only the selected UI crates. - self.assertIn("test --workspace --doc --all-features --locked", result.stdout.splitlines()) - filters = [re.search(r" -E (.*) --no-tests=warn ", line)[1] - for line in result.stdout.splitlines() if line.startswith("nextest")] - self.assertEqual(filters, [selected, selected, f"({selected}) & ({AUDIT_PACKAGES})", selected]) - result = commands("Linux", tests="none", test_filter="none()") + # The doctests stay whole-workspace; every nextest run carries the filter. + self.assertEqual(result.stdout.splitlines(), run_commands(selected)) + result, _ = step("run", tests="none", test_filter="none()") self.assertEqual(result.returncode, 0, result.stderr) self.assertEqual(result.stdout.splitlines(), ["No crate changed: no tests to run."]) - def test_each_stage_failure_remains_fatal(self): - for name, stages in (("lint-command", COMMON), ("command", LINUX_TESTS)): - for index, command in enumerate(stages): - with self.subTest(block=name, command=command): - result = commands("Linux", command, name) - self.assertEqual(result.returncode, 17, result.stderr) - self.assertEqual(result.stdout.splitlines(), stages[:index + 1]) + def test_the_build_job_writes_one_archive_per_shard_from_one_build(self): + selected = "package(=craft-ui-widgets) | package(=craft-svg)" + result, made = step("archive", tests="some", test_filter=selected) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(made, ["1", "2", "3"]) + self.assertEqual(result.stdout.splitlines(), archive_commands(archive_dir(result), selected)) + # The audit's archive is the same build as shard 1's: only the filter and the file differ. + first, audit = (re.sub(r" -E .* --archive-file .*", "", line) for line in result.stdout.splitlines()[:2]) + self.assertEqual(first, audit) + result, _ = step("doctest") + self.assertEqual(result.stdout.splitlines(), [DOCTESTS]) - def test_windows_runs_the_same_tests(self): - validate_source(WORKFLOW.read_text(), "windows-command") - source = block(WORKFLOW.read_text(), "windows-command") - cargo = [line.strip() for line in source.splitlines() if line.strip().startswith("cargo ")] - self.assertEqual(cargo, [line.strip() for line in TEST_RUN.splitlines() if line.strip()]) + def test_every_build_passes_the_profile_overrides(self): + # A step without them would build the workspace a second time. + lines = [] + for name in ("run", "archive", "doctest", "full"): + result, _ = step(name) + self.assertEqual(result.returncode, 0, result.stderr) + lines += result.stdout.splitlines() + for line in lines: + with self.subTest(command=line): + self.assertIn(CONFIG, line) + + def test_each_shard_runs_its_archive_and_shard_2_audits(self): + expected = "nextest run --archive-file /a/b.tar.zst --workspace-remap . --profile ci --no-tests=warn" + for shard, prefix in (("1", ""), ("2", "AUDIT "), ("3", "")): + with self.subTest(shard=shard): + result, _ = step("shard", GATE_SHARD=shard, NEXTEST_ARCHIVE_FILE="/a/b.tar.zst") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.splitlines(), [prefix + expected]) + result, _ = step("shard", GATE_SHARD="4", NEXTEST_ARCHIVE_FILE="/a/b.tar.zst") + self.assertEqual(result.returncode, 2) + self.assertEqual(result.stdout, "") + + def test_the_audit_runs_when_the_selection_reaches_an_audit_crate(self): + everything_but = " ".join(AUDIT_PACKAGES) + for tests, skip, expected in (("none", "", "false"), ("all", "", "true"), + ("some", everything_but + " craft-svg", "false"), + ("some", everything_but.replace("craft-menu", "craft-svg"), "true")): + with self.subTest(tests=tests, skip=skip): + result, _ = step("audit", tests=tests, CRAFT_TEST_SKIP=skip) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout.strip(), expected) + + def test_each_stage_failure_remains_fatal(self): + for index, command in enumerate(COMMON): + with self.subTest(block="lint-command", command=command): + result = lint("Linux", command) + self.assertEqual(result.returncode, 17, result.stderr) + self.assertEqual(result.stdout.splitlines(), COMMON[:index + 1]) + for index, command in enumerate(run_commands()): + with self.subTest(step="run", command=command): + result, _ = step("run", fail=command) + self.assertEqual(result.returncode, 17, result.stderr) + self.assertEqual(result.stdout.splitlines(), run_commands()[:index + 1]) + for index in range(3): + with self.subTest(step="archive", stage=index): + with tempfile.TemporaryDirectory() as tmp: + command = archive_commands(tmp + "/archives")[index] + result, _ = step("archive", fail=command, NEXTEST_ARCHIVE_DIR=tmp + "/archives") + self.assertEqual(result.returncode, 17, result.stderr) + self.assertEqual(result.stdout.splitlines(), archive_commands(tmp + "/archives")[:index + 1]) def test_workflow_source_is_rejected_before_starting_any_process(self): source = WORKFLOW.read_text() @@ -186,7 +241,7 @@ class WorkspaceTests(unittest.TestCase): with self.subTest(payload=payload), patch("subprocess.run") as child: changed = source.replace("cargo fmt --check", payload, 1) with self.assertRaisesRegex(AssertionError, "unexpected command source"): - commands("Linux", name="lint-command", source=changed) + lint("Linux", source=changed) child.assert_not_called() def test_added_or_missing_stage_is_rejected_before_execution(self): @@ -194,10 +249,20 @@ class WorkspaceTests(unittest.TestCase): for replacement in ("", "cargo fmt --check\n cargo fmt --check"): with self.subTest(replacement=replacement), patch("subprocess.run") as child: with self.assertRaisesRegex(AssertionError, "unexpected command source"): - commands("Linux", name="lint-command", - source=source.replace("cargo fmt --check", replacement, 1)) + lint("Linux", source=source.replace("cargo fmt --check", replacement, 1)) child.assert_not_called() + def test_profile_overrides_name_only_workspace_members(self): + # Cargo warns on every command about an override for a package outside the workspace. + members = {tomllib.loads(path.read_text())["package"]["name"] for path in ROOT.glob("crates/*/Cargo.toml")} + for name in ("cargo-dev.toml", "cargo-ci.toml"): + with self.subTest(file=name): + config = tomllib.loads((ROOT / ".config" / name).read_text()) + self.assertEqual(set(config), {"profile"}) + self.assertEqual(set(config["profile"]), {"dev"}) + packages = set(config["profile"]["dev"].get("package", {})) - {"*"} + self.assertLessEqual(packages, members) + def test_ci_profile_keeps_its_failure_policy_without_retries_or_filtering(self): config = tomllib.loads((ROOT / ".config/nextest.toml").read_text()) self.assertIs(config["profile"]["ci"]["fail-fast"], False) @@ -239,18 +304,26 @@ class WorkspaceTests(unittest.TestCase): self.assertIn(" CRAFT_TESTS=${{ needs.platforms.outputs.tests }}\n" " CRAFT_TEST_FILTER=${{ needs.platforms.outputs.filter }}\n", source) self.assertIn(" env: *env\n", source) - # The macOS and Windows legs run the Linux leg's blocks, not copies of them. + # The macOS and Windows legs run the Linux leg's blocks and steps, not copies of them. self.assertIn(" lint-command: &lint |\n", source) - self.assertIn(" command: &command |\n", source) + self.assertIn(" command: &command bash scripts/ci-workspace-tests.sh run\n", source) self.assertIn(" lint-command: *lint\n", source) self.assertIn(" command: *command\n", source) + self.assertNotIn("windows-command", source) + # Only the Linux leg splits into a build job and shards, and only for the audit. + self.assertEqual(source.count("test-shards:"), 1) + self.assertIn("test-shards: ${{ needs.platforms.outputs.audit == 'true' && 3 || 0 }}", source) + # Every Workspace leg's cache entry is named after the profile overrides it was built with. + self.assertIn("cache-version: &cache-version v2-${{ needs.platforms.outputs.profile }}\n", source) + self.assertIn(" cache-version: *cache-version\n", source) # Only the Linux leg keeps workspace crates; the cache budget has no room for the others. self.assertEqual(source.count("cache-workspace-crates: true"), 1) self.assertIn(" msrv:", source) self.assertIn(" wasm:", source) self.assertIn("python3 scripts/test-workspace-tests.py", block(source, "lint-command")) + # The nightly run builds as the gate does. + self.assertIn("command: bash scripts/ci-workspace-tests.sh full\n", NIGHTLY.read_text()) if __name__ == "__main__": unittest.main() - diff --git a/tools/cl b/tools/cl index 39078a29b..fc3b8fc3e 100755 --- a/tools/cl +++ b/tools/cl @@ -60,6 +60,7 @@ import shlex import subprocess import sys import time +import tomllib from concurrent.futures import ThreadPoolExecutor FRAMEWORK = ["craft-ui-contract", "craft-ui-widgets", "craft-ui-panels", "craft-ui-canvas", "craft-ui-patterns", "craft-ui-shell", "craft-ui"] @@ -97,21 +98,26 @@ APP_FEATURE_FLAGS = ("--features", "-F", "--no-default-features") # Set by main() from the workspace's `[workspace.metadata.cl]` in an app workspace; None in craft-libs. APP = None DRY_RUN = bool(os.environ.get("CL_DRY_RUN")) -# The dev-build tuning of craft-libs, passed to every cargo command as `--config`. It lives here and not in Cargo.toml -# because CI builds with the `[profile]` table of main (its cache key hashes that table), so CI's artifacts and cache -# match main's; these settings speed up local screen tests, the debug gallery and design-lint. -# lto off: with cargo's default rustc runs thin-local LTO across every optimised crate's codegen units on each rebuild; -# off, a one-line edit re-optimises only the changed units. Dependencies build at opt-level 2, once per target dir. -# craft-theme, craft-behavior and craft-proof run in every screen-test frame or in dictionary-sized tests and are rarely -# edited, so they build at opt-level 1; every other workspace crate stays at 0, where rustc shares generic -# instantiations across crates and an edit to the runtime (craft-ui-contract) rebuilds in seconds. -DEV_PROFILE_CONFIG = [ - 'profile.dev.lto="off"', - 'profile.dev.package."*".opt-level=2', - "profile.dev.package.craft-theme.opt-level=1", - "profile.dev.package.craft-behavior.opt-level=1", - "profile.dev.package.craft-proof.opt-level=1", -] +# The dev-build tuning of craft-libs (.config/cargo-dev.toml, which the CI gate passes too), as the `--config` +# KEY=VALUE pairs passed to every cargo command. +DEV_PROFILE_FILE = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), ".config", "cargo-dev.toml") + + +def dev_profile_config(): + def key(part): + return part if re.fullmatch(r"[A-Za-z0-9_-]+", part) else json.dumps(part) + + def flatten(table, path): + for name, value in table.items(): + if isinstance(value, dict): + yield from flatten(value, path + [key(name)]) + else: + yield ".".join(path + [key(name)]) + "=" + json.dumps(value) + + with open(DEV_PROFILE_FILE, "rb") as f: + return list(flatten(tomllib.load(f), [])) + + # What cl.log records about this command; filled in as it runs. RECORD = {"start": time.time(), "target": None, "build": None, "run": 0.0, "report": ""} # The manifest lines the one feature set rests on: (file, regex that must match, what its absence brings back). @@ -374,7 +380,7 @@ def cargo(top, cargo_args, json_out=False, timings=True): if timings: cargo_args = cargo_args[:1] + ["--timings"] + cargo_args[1:] # An app workspace keeps its own profile settings. - config = [] if APP else [x for c in DEV_PROFILE_CONFIG for x in ("--config", c)] + config = [] if APP else [x for c in dev_profile_config() for x in ("--config", c)] cmd = shlex.split(env.get("CL_LAUNCHER", "")) + ["cargo"] + config + cargo_args print("cl: " + " ".join(cmd) + f" (target {target})", file=sys.stderr) sys.stdout.flush()