mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-28 09:21:55 +01:00
Merge pull request #9817 from dotCooCoo/chore/ci-cache-workspace-crates
CI: the gate keeps the compiled workspace crates between runs
This commit is contained in:
5 files changed
+437
-5
No files matched your search
@@ -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
|
||||
@@ -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:
|
||||
|
||||
@@ -23,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
|
||||
@@ -39,7 +46,68 @@ 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, 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: 170
|
||||
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: 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. 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: 200
|
||||
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
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,184 @@
|
||||
#!/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 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. 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, timezone
|
||||
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-'
|
||||
# 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
|
||||
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.
|
||||
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 save step has started."""
|
||||
step = save_step(job)
|
||||
return step is not None and step['status'] in ('in_progress', 'completed')
|
||||
|
||||
|
||||
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 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)
|
||||
|
||||
|
||||
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')
|
||||
began = datetime.now(timezone.utc)
|
||||
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 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 saves_nothing(job):
|
||||
print(f'::error::{NO_SAVE}')
|
||||
return 1
|
||||
started = gh(f'repos/{repo}/actions/runs/{run}')['run_started_at']
|
||||
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)
|
||||
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())
|
||||
Reference in new issue
Block a user