From 6927affc24b077461fb92b5abfd3589b63f613fd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Fri, 27 Nov 2026 19:55:45 -0800 Subject: [PATCH] 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)