From 2eef0b81b5d3c427ab2f20d4a0c20b3e16a06584 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 15:32:51 -0800 Subject: [PATCH 1/3] CI: the gate keeps the compiled workspace crates between runs Turn on the shared gate's cache-workspace-crates. Each main run's cache warm leg saves a rolling entry that also holds the workspace crates' compiled libraries and test executables, and every leg restores the newest one, so a pull request's shards rebuild only the crates its changes reach. A cache prune job keeps one rolling entry on main, and a nightly cold build restores nothing and starts the entry afresh. --- .github/workflows/ci.yml | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ce472c2fdb..b9081f89c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,10 +1,14 @@ name: CI # Quality gates for every push to main and every pull request (`cargo xtask ci`), through the -# suite's shared gate workflow in craft-common-actions. +# suite's shared gate workflow in craft-common-actions. Every night the gate runs a cold build: +# the safety net for the workspace crates it keeps between runs (`cache-workspace-crates`), and a +# fresh start for that cache entry. on: push: branches: [main] + schedule: + - cron: "37 3 * * *" pull_request: workflow_dispatch: @@ -39,7 +43,38 @@ jobs: test-shards: 5 shard-command: cargo xtask ci shard warm-command: cargo xtask ci warm + # The dependency cache also keeps the compiled workspace crates and test executables, so a + # pull request's shards rebuild only the crates its changes reach. Each main run's `cache + # warm` leg saves a rolling entry of its own, every leg restores the newest one, and + # `cache-prune` below deletes the one it replaced. The nightly run restores nothing and + # builds everything from source. + cache-workspace-crates: true + cold-build: ${{ github.event_name == 'schedule' }} packages: >- pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcb1-dev libxcursor-dev libxrandr-dev libxi-dev libfontconfig1-dev libfreetype-dev mesa-vulkan-drivers libgl1-mesa-dev + + # Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache + # budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A + # failed prune warns instead of failing the run; the next main run's prune deletes what it missed. + cache-prune: + name: cache prune + if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' + runs-on: ubuntu-24.04 + timeout-minutes: 120 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Prune replaced cache entries + uses: storytold/craft-common-actions/actions/cache-prune@main + continue-on-error: true + with: + watch: true + watch-minutes: 110 + saving-jobs: | + ^gate( / cache warm \(.*\))?$ From a70c571415f67a36527c1d84bb9c3f3c07e61762 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 16:27:38 -0800 Subject: [PATCH 2/3] CI: a cold cache warm leg fits its timeout and the old rolling entry goes first After Rust stable moved to 1.100.1, main's cache warm leg built cold and was canceled at the 90-minute timeout with three steps still to run, so no entry was saved and every leg stayed cold. The legs now get 150 minutes, and the cache prune watch runs for 160. The nightly cold run restores nothing, so the old rolling entry and the new one would be in the cache together while it saves, over the 10 GB limit. A cold cache clear job deletes the old rolling entries when the cache warm leg starts saving (scripts/ci-clear-rolling-cache.py). It deletes nothing when the leg fails or is canceled, and fails itself so that re-running the failed jobs runs it again with the leg. cache-prune.yml prunes after every CI attempt on main, so a re-run of the cache warm leg does not leave the entry it replaced in place. --- .github/workflows/cache-prune.yml | 35 ++++++++ .github/workflows/ci.yml | 39 +++++++- scripts/ci-clear-rolling-cache.py | 145 ++++++++++++++++++++++++++++++ 3 files changed, 215 insertions(+), 4 deletions(-) create mode 100644 .github/workflows/cache-prune.yml create mode 100644 scripts/ci-clear-rolling-cache.py diff --git a/.github/workflows/cache-prune.yml b/.github/workflows/cache-prune.yml new file mode 100644 index 0000000000..a79f1ed907 --- /dev/null +++ b/.github/workflows/cache-prune.yml @@ -0,0 +1,35 @@ +name: Cache prune + +# A pass of the cache prune after every CI attempt on main. ci.yml's `cache prune` job prunes while +# a run's jobs save their entries, but "Re-run failed jobs" re-runs only the failed jobs: a re-run +# `cache warm` leg saves a new entry, and the prune job, which succeeded in the first attempt, does +# not run again. The entry it replaced would stay until the next main run, and with it the cache +# would be over its 10 GB budget, where GitHub evicts entries a run still needs. This runs once +# after every attempt, re-runs and canceled runs included (craft-common-actions actions/cache-prune). +on: + workflow_run: + workflows: [CI] + types: [completed] + branches: [main] + +permissions: + contents: read + +jobs: + cache-prune: + name: cache prune + # A fork's pull request from a branch named main also matches `branches`. + if: github.event.workflow_run.event != 'pull_request' + timeout-minutes: 10 + runs-on: ubuntu-24.04 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + # A failed pass warns; the next run's prune deletes what it missed. + - name: Prune replaced cache entries + uses: storytold/craft-common-actions/actions/cache-prune@main + continue-on-error: true diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b9081f89c0..e5ca11d896 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -27,7 +27,10 @@ jobs: with: # Same craft-fonts commit as release.yml. craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 - timeout-minutes: 90 + # A cold `cache warm` leg (the nightly run, or any run after a toolchain or lockfile change) + # took 90 minutes to reach its last three steps on 2026-11-27 and was canceled there; with + # those steps and the save it needs about two hours. + timeout-minutes: 150 # The gate's test binaries carry no debug info and no symbols (CARGO_PROFILE_TEST_DEBUG=0, # CARGO_PROFILE_TEST_STRIP=symbols), as photocraft's do: linking ~100 test binaries with line # tables ran the hosted runner out of resources, and it stopped mid-link with "received a @@ -57,12 +60,14 @@ jobs: # Keeps one rolling gate entry on main, so the repository stays within its 10 GB Actions cache # budget. It runs beside the gate and prunes each time the `cache warm` leg finishes saving. A - # failed prune warns instead of failing the run; the next main run's prune deletes what it missed. + # failed prune warns instead of failing the run, and cache-prune.yml prunes again after every + # attempt, re-runs of failed jobs included. `watch-minutes` is longer than the gate's + # `timeout-minutes`, so the watch outlasts a cold `cache warm` leg. cache-prune: name: cache prune if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main' runs-on: ubuntu-24.04 - timeout-minutes: 120 + timeout-minutes: 170 permissions: actions: write steps: @@ -75,6 +80,32 @@ jobs: continue-on-error: true with: watch: true - watch-minutes: 110 + watch-minutes: 160 saving-jobs: | ^gate( / cache warm \(.*\))?$ + + # The nightly cold run never restores the rolling crates entry, so the old entry is only overlap + # while the cold run saves its own: two entries of about 4.6 GB, which with the others go over the + # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes + # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). + # When the leg fails or is canceled it saves nothing, and this job fails too, so "Re-run failed + # jobs" runs it again beside the re-run leg. + cold-cache-clear: + name: cold cache clear + if: github.event_name == 'schedule' + runs-on: ubuntu-24.04 + timeout-minutes: 170 + permissions: + actions: write + steps: + - name: Harden runner + uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Delete the old rolling entries before the save + env: + GH_TOKEN: ${{ github.token }} + run: python3 scripts/ci-clear-rolling-cache.py diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py new file mode 100644 index 0000000000..c8368552e2 --- /dev/null +++ b/scripts/ci-clear-rolling-cache.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""The nightly cold run deletes the rolling crates entries just before it saves its own. + + python3 scripts/ci-clear-rolling-cache.py needs GH_TOKEN, GITHUB_REPOSITORY, GITHUB_RUN_ID, GITHUB_RUN_ATTEMPT + +The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to +the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over +the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The +gate's `cache warm` leg saves in its `Post` steps; this deletes the old entries when the first of +them starts. Pull requests and pushes that start in the minutes between restore nothing from the +deleted entry and build cold once. Deleting is the only write; the entry the cold run saves does not +exist yet when this runs. Only entries created before this run started are deleted: a push or pull +request run in the same minutes may have saved an entry of its own, and the cold run's own save is +never touched. A leg that failed or was canceled saves nothing: its old entries stay, and this +exits 1, so "Re-run failed jobs" runs it again beside the re-run leg. It also exits 1 when the leg +has not reached its save after GIVE_UP_SECONDS. An absent warm leg is treated as finished only +when the most recent earlier attempt that lists it reports success and the current attempt lists +no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling +because reusable-workflow dependencies may still be scheduling it. +""" + +from datetime import datetime +import json +import os +import re +import subprocess +import sys +import time + +REF = 'refs/heads/main' +WARM_JOB = re.compile(r'^gate / cache warm \(') +# The jobs the gate's legs need (craft-common-actions .github/workflows/gate.yml): when one of +# them fails or is canceled, the legs are skipped and no warm leg is listed. +NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') +PRUNE_JOB = 'cache prune' +ROLLING = '-gate-crates-' +POLL_SECONDS = 20 +# Longer than the gate's `timeout-minutes` in ci.yml, so a cold leg that runs to its limit still +# reaches its save before this gives up. +GIVE_UP_SECONDS = 160 * 60 +STOPPED = ('failure', 'cancelled', 'timed_out') +# Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. +TOLERATED_FAILURES = ('Trim the cache entry to this build',) +NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg' + + +def saving(job): + """True once the job's post steps (the cache save) have started.""" + return any(s['name'].startswith('Post ') and s['status'] in ('in_progress', 'completed') for s in job.get('steps', [])) + + +def failed(job): + """True when a step before the post steps failed or was canceled: the leg then saves no entry.""" + return any(not s['name'].startswith('Post ') and s['name'] not in TOLERATED_FAILURES and s.get('conclusion') in STOPPED for s in job.get('steps', [])) + + +def warm_job(jobs): + return next((j for j in jobs if WARM_JOB.match(j['name'])), None) + + +def legs_stopped(jobs): + """True when a job the gate's legs need failed or was canceled, so the warm leg never starts.""" + return any(NEEDED_JOBS.match(j['name']) and j['status'] == 'completed' and j.get('conclusion') in STOPPED for j in jobs) + + +def not_in_attempt(jobs, earlier_jobs): + """True when no prune job is listed and the most recent earlier warm leg succeeded.""" + if any(j['name'] == PRUNE_JOB for j in jobs): + return False + for attempt in sorted(earlier_jobs, reverse=True): + job = warm_job(earlier_jobs[attempt]) + if job is not None: + return job.get('conclusion') == 'success' + return False + + +def rolling_entries(caches): + return [c for c in caches if ROLLING in c['key']] + + +def created_before(entries, started): + """The entries created before `started`, an ISO 8601 timestamp (`run_started_at`).""" + limit = parse_time(started) + return [c for c in entries if parse_time(c['created_at']) < limit] + + +def parse_time(text): + return datetime.fromisoformat(text.replace('Z', '+00:00')) + + +def gh(*args): + out = subprocess.run(['gh', 'api', *args], check=True, capture_output=True, text=True).stdout + return json.loads(out) if out.strip() else None + + +def main(): + repo, run, attempt = os.environ['GITHUB_REPOSITORY'], os.environ['GITHUB_RUN_ID'], os.environ.get('GITHUB_RUN_ATTEMPT', '1') + deadline = time.monotonic() + GIVE_UP_SECONDS + earlier_jobs = {} + while True: + jobs = gh(f'repos/{repo}/actions/runs/{run}/attempts/{attempt}/jobs?per_page=100') or {} + job = warm_job(jobs.get('jobs', [])) + if job and saving(job): + break + if job is None: + for earlier in range(int(attempt) - 1, 0, -1): + if earlier not in earlier_jobs: + previous = gh(f'repos/{repo}/actions/runs/{run}/attempts/{earlier}/jobs?per_page=100') or {} + earlier_jobs[earlier] = previous.get('jobs', []) + if warm_job(earlier_jobs[earlier]) is not None: + break + if not_in_attempt(jobs.get('jobs', []), earlier_jobs): + print('the cache warm leg is not part of this attempt (it succeeded in an earlier one); nothing deleted') + return + if legs_stopped(jobs.get('jobs', [])): + print('::error::the gate stopped before its cache warm leg started; nothing deleted') + return 1 + if job and job['status'] == 'completed': + if job.get('conclusion') in STOPPED: + print(f'::error::{NO_SAVE}') + return 1 + print('the cache warm leg finished without a save step; nothing deleted') + return + if time.monotonic() > deadline: + print('::error::the cache warm leg never reached its save; nothing deleted') + return 1 + time.sleep(POLL_SECONDS) + if failed(job): + print(f'::error::{NO_SAVE}') + return 1 + started = gh(f'repos/{repo}/actions/runs/{run}')['run_started_at'] + caches = (gh(f'repos/{repo}/actions/caches?ref={REF}&per_page=100') or {}).get('actions_caches', []) + for c in created_before(rolling_entries(caches), started): + print(f"delete {c['key']} ({c['size_in_bytes'] / 1e9:.2f} GB)") + result = subprocess.run(['gh', 'api', '-X', 'DELETE', f"repos/{repo}/actions/caches/{c['id']}"], capture_output=True, text=True) + if result.returncode: + if '(HTTP 404)' in result.stderr: + print(f"already deleted {c['key']}") + else: + print(result.stderr, end='', file=sys.stderr) + return result.returncode + + +if __name__ == '__main__': + sys.exit(main()) From 6927affc24b077461fb92b5abfd3589b63f613fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 19:55:45 -0800 Subject: [PATCH 3/3] CI: the cold cache clear waits for the warm leg's own save and reads every cache page scripts/ci-clear-rolling-cache.py: - The 160-minute wait is timed from the cache warm leg's start, not from the script's start. The clear job starts with the run, and the leg starts after gate / select legs and a free runner. The job's timeout goes from 170 to 200 minutes to leave room for that delay. - The leg counts as saving when its Post Setup step (the gate-setup action's cache save) starts, not when any Post step starts. A leg that ends canceled or failed before that step succeeds deletes nothing and exits 1, as a leg that failed before its save already did. - actions/caches is read one page at a time, sorted by creation, until a page holds fewer than 100 entries. scripts/ci-clear-rolling-cache-tests.py checks the script with recorded API answers, and Nightly check runs it when either file changes. --- .github/workflows/ci.yml | 6 +- .github/workflows/nightly-check.yml | 9 +- scripts/ci-clear-rolling-cache-tests.py | 142 ++++++++++++++++++++++++ scripts/ci-clear-rolling-cache.py | 65 ++++++++--- 4 files changed, 204 insertions(+), 18 deletions(-) create mode 100644 scripts/ci-clear-rolling-cache-tests.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e5ca11d896..cdd51349fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -89,12 +89,14 @@ jobs: # 10 GB cache limit and get the corpus, SonarCloud and Windows ARM64 entries evicted. This deletes # the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py). # When the leg fails or is canceled it saves nothing, and this job fails too, so "Re-run failed - # jobs" runs it again beside the re-run leg. + # jobs" runs it again beside the re-run leg. The script's 160-minute wait starts when the leg + # starts, which is after `gate / select legs` and a free runner, so this job's timeout leaves + # 40 minutes for that. cold-cache-clear: name: cold cache clear if: github.event_name == 'schedule' runs-on: ubuntu-24.04 - timeout-minutes: 170 + timeout-minutes: 200 permissions: actions: write steps: diff --git a/.github/workflows/nightly-check.yml b/.github/workflows/nightly-check.yml index 48d08decb3..4ec39820d1 100644 --- a/.github/workflows/nightly-check.yml +++ b/.github/workflows/nightly-check.yml @@ -3,13 +3,14 @@ name: Nightly check # The app-side Nightly pieces, checked without a feed run: the Python suites that read the archive, # plist and signing scripts, the workflow contracts, and (on Windows) the packaging and signing # PowerShell suites. The producer itself is .github/workflows/nightly.yml; the Apple-silicon bundle -# is built and verified by nightly-macos.yml behind the `full-ci` label. +# is built and verified by nightly-macos.yml behind the `full-ci` label. The same job also runs the +# suite for scripts/ci-clear-rolling-cache.py, which ci.yml's nightly cold run calls. on: push: branches: [main, release] - paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"] + paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"] pull_request: - paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs"] + paths: [".github/workflows/nightly*.yml", "packaging/**", "apps/vectorcraft/**", "crates/ui-egui/src/os_window.rs", "scripts/ci-clear-rolling-cache*.py"] workflow_dispatch: permissions: @@ -34,6 +35,8 @@ jobs: persist-credentials: false - name: Run the synthetic suites run: python3 packaging/nightly-tests.py + - name: Run the cold cache clear suite + run: python3 scripts/ci-clear-rolling-cache-tests.py - name: Parse every nightly shell script run: | set -euo pipefail diff --git a/scripts/ci-clear-rolling-cache-tests.py b/scripts/ci-clear-rolling-cache-tests.py new file mode 100644 index 0000000000..815ae88a0f --- /dev/null +++ b/scripts/ci-clear-rolling-cache-tests.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +"""Checks for ci-clear-rolling-cache.py with recorded GitHub API answers; no network. + + python3 scripts/ci-clear-rolling-cache-tests.py +""" +from datetime import datetime, timedelta, timezone +import importlib.util +from pathlib import Path +import unittest + +_spec = importlib.util.spec_from_file_location("clear", Path(__file__).with_name("ci-clear-rolling-cache.py")) +clear = importlib.util.module_from_spec(_spec) +_spec.loader.exec_module(clear) + +WARM = "gate / cache warm (ubuntu-24.04)" +ME = [{"name": "cold cache clear", "status": "in_progress"}] + + +def warm_job(status, conclusion=None, steps=(), started_at="2026-11-28T03:40:00Z"): + return { + "name": WARM, + "status": status, + "conclusion": conclusion, + "started_at": started_at, + "steps": [{"name": n, "status": s, "conclusion": c} for n, s, c in steps], + } + + +def earlier(conclusion): + return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}] + + +class SaveStep(unittest.TestCase): + def test_the_leg_is_saving_once_its_save_step_starts(self): + self.assertFalse(clear.saving(warm_job("in_progress", steps=[("Setup", "completed", "success"), ("Gate", "in_progress", None)]))) + self.assertTrue(clear.saving(warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]))) + + def test_other_post_steps_are_not_the_save(self): + job = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Harden runner", "in_progress", None)]) + self.assertFalse(clear.saving(job)) + + def test_a_leg_canceled_during_its_save_saves_nothing(self): + job = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")]) + self.assertTrue(clear.saving(job)) + self.assertTrue(clear.saves_nothing(job)) + + def test_a_leg_that_ended_with_its_save_still_running_saves_nothing(self): + job = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]) + self.assertTrue(clear.saves_nothing(job)) + + def test_a_running_or_finished_save_counts_as_saved(self): + running = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]) + done = warm_job("completed", "failure", [("Gate", "completed", "success"), ("Post Setup", "completed", "success"), + ("Post Harden runner", "completed", "failure")]) + self.assertFalse(clear.saves_nothing(running)) + self.assertFalse(clear.saves_nothing(done)) + + def test_a_failed_step_before_the_save_saves_nothing(self): + job = lambda c: warm_job("in_progress", steps=[("Gate", "completed", c), ("Post Setup", "in_progress", None)]) + self.assertTrue(clear.saves_nothing(job("failure"))) + self.assertTrue(clear.saves_nothing(job("cancelled"))) + self.assertFalse(clear.saves_nothing(job("success"))) + tolerated = warm_job("in_progress", steps=[("Gate", "completed", "success"), ("Trim the cache entry to this build", "completed", "failure"), + ("Post Setup", "in_progress", None)]) + self.assertFalse(clear.saves_nothing(tolerated)) + + +class Deadline(unittest.TestCase): + began = datetime(2026, 11, 28, 3, 37, tzinfo=timezone.utc) + + def test_the_wait_is_timed_from_the_leg_start(self): + late = warm_job("in_progress", started_at="2026-11-28T04:00:00Z") + before_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS - 60) + after_limit = clear.parse_time("2026-11-28T04:00:00Z") + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) + self.assertGreater((before_limit - self.began).total_seconds(), clear.GIVE_UP_SECONDS) + self.assertFalse(clear.gave_up(late, before_limit, self.began)) + self.assertTrue(clear.gave_up(late, after_limit, self.began)) + + def test_a_leg_that_never_starts_is_timed_from_the_script_start(self): + queued = warm_job("queued", started_at="2026-11-28T03:38:00Z") + later = self.began + timedelta(seconds=clear.GIVE_UP_SECONDS + 60) + self.assertFalse(clear.gave_up(None, self.began + timedelta(minutes=10), self.began)) + self.assertTrue(clear.gave_up(None, later, self.began)) + self.assertTrue(clear.gave_up(queued, later, self.began)) + + +class Jobs(unittest.TestCase): + def test_only_the_warm_leg_counts(self): + jobs = [{"name": "gate / test 1/5 (ubuntu-24.04)"}, {"name": "gate / build (${{ matrix.os }})"}, {"name": WARM}] + self.assertEqual(clear.warm_job(jobs), jobs[2]) + + def test_a_rerun_of_this_job_alone_skips_a_leg_that_succeeded(self): + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success")})) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("success"), 2: [{"name": "cold cache clear"}]})) + self.assertTrue(clear.not_in_attempt(ME, {1: earlier("failure"), 2: [{"name": "cold cache clear"}], 3: earlier("success")})) + + def test_a_leg_that_did_not_succeed_is_waited_for(self): + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("cancelled")})) + self.assertFalse(clear.not_in_attempt(ME, {})) + self.assertFalse(clear.not_in_attempt(ME, {1: earlier("success"), 2: earlier("failure")})) + + def test_a_rerun_of_all_jobs_is_waited_for(self): + self.assertFalse(clear.not_in_attempt(ME + [{"name": "cache prune", "status": "in_progress"}], {1: earlier("success")})) + + def test_a_failed_select_or_build_stops_the_wait(self): + done = lambda n, c: {"name": n, "status": "completed", "conclusion": c} + self.assertTrue(clear.legs_stopped([done("gate / select legs", "failure")])) + self.assertTrue(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (ubuntu-24.04)", "cancelled")])) + self.assertFalse(clear.legs_stopped([done("gate / select legs", "success"), done("gate / build (${{ matrix.os }})", "skipped")])) + self.assertFalse(clear.legs_stopped([done("gate / test 1/5 (ubuntu-24.04)", "failure")])) + + +class Caches(unittest.TestCase): + def test_every_page_is_read(self): + entries = [{"id": n, "key": f"v2-rust-a013-gate-crates-Linux-x64-{n}"} for n in range(2 * clear.PAGE_SIZE + 3)] + pages = [] + + def fetch(page): + pages.append(page) + start = (page - 1) * clear.PAGE_SIZE + return {"actions_caches": entries[start:start + clear.PAGE_SIZE]} + + self.assertEqual(clear.all_caches(fetch), entries) + self.assertEqual(pages, [1, 2, 3]) + + def test_only_rolling_crates_entries_are_deleted(self): + caches = [ + {"key": "v2-rust-a013-gate-crates-Linux-x64-46055934-01d60c35"}, + {"key": "v2-rust-a013-gate-Linux-x64-46055934-01d60c35"}, + {"key": "v1-affinity-rust-a013-gate-Linux-x64-b541f517-01d60c35"}, + {"key": "v0-rust-build-Linux-x64-1fd829d9-01d60c35"}, + ] + self.assertEqual(clear.rolling_entries(caches), caches[:1]) + + def test_entries_created_after_the_run_started_are_kept(self): + rolling = lambda created: {"key": "v2-rust-ab-gate-crates-Linux-x64-1", "created_at": created} + old, same_minute_push = rolling("2026-11-27T03:00:00.5Z"), rolling("2026-11-28T03:40:00Z") + self.assertEqual(clear.created_before([old, same_minute_push], "2026-11-28T03:37:10Z"), [old]) + + +if __name__ == "__main__": + unittest.main(verbosity=2) diff --git a/scripts/ci-clear-rolling-cache.py b/scripts/ci-clear-rolling-cache.py index c8368552e2..f8105a4973 100644 --- a/scripts/ci-clear-rolling-cache.py +++ b/scripts/ci-clear-rolling-cache.py @@ -6,20 +6,21 @@ The cold run (ci.yml, `cold-build`) never restores the rolling entry, so the old one only adds to the cache while the new one is saved: two entries of about 4.6 GB each, beside the others, go over the repository's 10 GB limit and GitHub evicts the corpus, SonarCloud and Windows ARM64 entries. The -gate's `cache warm` leg saves in its `Post` steps; this deletes the old entries when the first of -them starts. Pull requests and pushes that start in the minutes between restore nothing from the +gate's `cache warm` leg saves in its `Post Setup` step; this deletes the old entries when that step +starts. Pull requests and pushes that start in the minutes between restore nothing from the deleted entry and build cold once. Deleting is the only write; the entry the cold run saves does not exist yet when this runs. Only entries created before this run started are deleted: a push or pull request run in the same minutes may have saved an entry of its own, and the cold run's own save is never touched. A leg that failed or was canceled saves nothing: its old entries stay, and this -exits 1, so "Re-run failed jobs" runs it again beside the re-run leg. It also exits 1 when the leg -has not reached its save after GIVE_UP_SECONDS. An absent warm leg is treated as finished only +exits 1, so "Re-run failed jobs" runs it again beside the re-run leg. The same holds for a leg that +ends, canceled or failed, before its save step finished. It also exits 1 when the leg has not +reached its save GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only when the most recent earlier attempt that lists it reports success and the current attempt lists no `cache prune` job, which runs from the start of "Re-run all jobs". Otherwise this keeps polling because reusable-workflow dependencies may still be scheduling it. """ -from datetime import datetime +from datetime import datetime, timezone import json import os import re @@ -34,9 +35,13 @@ WARM_JOB = re.compile(r'^gate / cache warm \(') NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \()') PRUNE_JOB = 'cache prune' ROLLING = '-gate-crates-' +# The gate-setup action's post step, which saves the dependency cache (craft-common-actions +# actions/gate-setup, under the gate's `Setup` step). +SAVE_STEP = 'Post Setup' POLL_SECONDS = 20 -# Longer than the gate's `timeout-minutes` in ci.yml, so a cold leg that runs to its limit still -# reaches its save before this gives up. +PAGE_SIZE = 100 +# Longer than the gate's `timeout-minutes` in ci.yml and timed from the leg's own start, so a cold +# leg that starts late and runs to its limit still reaches its save before this gives up. GIVE_UP_SECONDS = 160 * 60 STOPPED = ('failure', 'cancelled', 'timed_out') # Steps with continue-on-error in craft-common-actions .github/workflows/gate.yml. @@ -44,9 +49,14 @@ TOLERATED_FAILURES = ('Trim the cache entry to this build',) NO_SAVE = 'the cache warm leg failed or was canceled and saves no entry; nothing deleted. Re-running the failed jobs runs this job again with the leg' +def save_step(job): + return next((s for s in job.get('steps', []) if s['name'] == SAVE_STEP), None) + + def saving(job): - """True once the job's post steps (the cache save) have started.""" - return any(s['name'].startswith('Post ') and s['status'] in ('in_progress', 'completed') for s in job.get('steps', [])) + """True once the job's save step has started.""" + step = save_step(job) + return step is not None and step['status'] in ('in_progress', 'completed') def failed(job): @@ -54,6 +64,35 @@ def failed(job): return any(not s['name'].startswith('Post ') and s['name'] not in TOLERATED_FAILURES and s.get('conclusion') in STOPPED for s in job.get('steps', [])) +def saves_nothing(job): + """True when the leg saves no entry: a step before the save stopped, the save step did not + succeed, or the job ended before its save step finished.""" + if failed(job): + return True + step = save_step(job) + if step is not None and step['status'] == 'completed': + return step.get('conclusion') != 'success' + return job.get('status') == 'completed' + + +def gave_up(job, now, began): + """True once GIVE_UP_SECONDS have passed since the warm leg started, or since `began` (this + script's start) while the leg has not started.""" + started = job.get('started_at') if job and job.get('status') in ('in_progress', 'completed') else None + return (now - (parse_time(started) if started else began)).total_seconds() > GIVE_UP_SECONDS + + +def all_caches(fetch): + """Every cache entry, one page at a time: `fetch(page)` returns one page of actions/caches.""" + entries, page = [], 1 + while True: + batch = (fetch(page) or {}).get('actions_caches', []) + entries += batch + if len(batch) < PAGE_SIZE: + return entries + page += 1 + + def warm_job(jobs): return next((j for j in jobs if WARM_JOB.match(j['name'])), None) @@ -95,7 +134,7 @@ def gh(*args): def main(): repo, run, attempt = os.environ['GITHUB_REPOSITORY'], os.environ['GITHUB_RUN_ID'], os.environ.get('GITHUB_RUN_ATTEMPT', '1') - deadline = time.monotonic() + GIVE_UP_SECONDS + began = datetime.now(timezone.utc) earlier_jobs = {} while True: jobs = gh(f'repos/{repo}/actions/runs/{run}/attempts/{attempt}/jobs?per_page=100') or {} @@ -121,15 +160,15 @@ def main(): return 1 print('the cache warm leg finished without a save step; nothing deleted') return - if time.monotonic() > deadline: + if gave_up(job, datetime.now(timezone.utc), began): print('::error::the cache warm leg never reached its save; nothing deleted') return 1 time.sleep(POLL_SECONDS) - if failed(job): + if saves_nothing(job): print(f'::error::{NO_SAVE}') return 1 started = gh(f'repos/{repo}/actions/runs/{run}')['run_started_at'] - caches = (gh(f'repos/{repo}/actions/caches?ref={REF}&per_page=100') or {}).get('actions_caches', []) + caches = all_caches(lambda page: gh(f'repos/{repo}/actions/caches?ref={REF}&sort=created_at&direction=asc&per_page={PAGE_SIZE}&page={page}')) for c in created_before(rolling_entries(caches), started): print(f"delete {c['key']} ({c['size_in_bytes'] / 1e9:.2f} GB)") result = subprocess.run(['gh', 'api', '-X', 'DELETE', f"repos/{repo}/actions/caches/{c['id']}"], capture_output=True, text=True)