mirror of
https://github.com/storytold/photocraft.git
synced 2026-12-02 06:20:48 +01:00
Merge pull request #15828 from aiongg/ci-cache-budget
CI: keep the Actions cache within its budget (trim saved entries, prune replaced ones as they land)
This commit is contained in:
4 files changed
+155
-32
No files matched your search
@@ -0,0 +1,37 @@
|
||||
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
|
||||
# build job 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 cancelled 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
|
||||
with:
|
||||
content-keys: corpus
|
||||
+28
-30
@@ -157,7 +157,7 @@ jobs:
|
||||
# test-seconds over 3 shards are ~8.5-10.5 min each.
|
||||
# The build keeps the compiled workspace crates between runs (`cache-workspace-crates`), so a
|
||||
# pull request rebuilds only the crates its changes reach. Each main run's build job saves a
|
||||
# rolling entry of its own, which `test (without heif)` restores too; `gate-cache-prune` keeps
|
||||
# rolling entry of its own, which `test (without heif)` restores too; `cache-prune` keeps
|
||||
# the newest one. The lint legs keep no cache (`lint-cache: false`): a cold lint leg costs
|
||||
# minutes, and their entries (~1 GB per OS) would not fit the 10 GB cache budget.
|
||||
gate:
|
||||
@@ -244,14 +244,21 @@ jobs:
|
||||
test-shards: 6
|
||||
shard-command: bash scripts/ci-test-shard.sh
|
||||
|
||||
# The Linux gate's build job saves a rolling cache entry of its own on every main and nightly run
|
||||
# (`cache-workspace-crates`), about 3.8 GB, and every run restores only the newest. This deletes
|
||||
# the older ones at once instead of leaving them to the 10 GB budget's eviction, which would
|
||||
# evict other entries too.
|
||||
gate-cache-prune:
|
||||
needs: gate
|
||||
if: ${{ !cancelled() && github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
|
||||
timeout-minutes: 5
|
||||
# Keeps one Actions cache entry per family on main, so the repository stays within its 10 GB
|
||||
# budget and GitHub never evicts an entry a run still needs (an evicted Windows entry makes the
|
||||
# Windows build cold, about 60 instead of 21 minutes). It runs beside the run's jobs and prunes
|
||||
# each time a job that saves an entry finishes: the gate's build jobs (the Linux rolling entry,
|
||||
# about 4 GB, and the Windows dependency entry), web and corpus. A skipped job is listed under its
|
||||
# own name (a skipped reusable-workflow call under the caller job's), so a run that skips one
|
||||
# still ends. No `needs`: the gate is one reusable call, and waiting for it would leave the
|
||||
# replaced entry in place until every shard has run. A failed prune warns instead of failing the
|
||||
# run, and cache-prune.yml prunes again after every attempt, re-runs of failed jobs included.
|
||||
cache-prune:
|
||||
name: cache prune
|
||||
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/main'
|
||||
# A cold Windows build takes about an hour, and the watch ends when it does; `watch-minutes`
|
||||
# ends it before this limit.
|
||||
timeout-minutes: 120
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
actions: write
|
||||
@@ -260,27 +267,18 @@ jobs:
|
||||
uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4
|
||||
with:
|
||||
egress-policy: audit
|
||||
- name: Delete all but the newest rolling entry of each job and runner
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
REPO: ${{ github.repository }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# `<version>-rust-<profile>-<job>-crates-<os>-<arch>-<run>-<attempt>-...`, newest first.
|
||||
gh cache list --repo "$REPO" --ref refs/heads/main --limit 100 --sort created_at --order desc --json id,key \
|
||||
--jq '.[] | "\(.id) \(.key)"' > "$RUNNER_TEMP/caches"
|
||||
declare -A kept
|
||||
while read -r id key; do
|
||||
[[ "$key" =~ ^.+-rust-[0-9a-f]{64}-(.+-crates-[A-Za-z_]+-[a-z0-9]+)-[0-9]+-[0-9]+- ]] || continue
|
||||
entry=${BASH_REMATCH[1]}
|
||||
if [ -n "${kept[$entry]:-}" ]; then
|
||||
echo "delete $key"
|
||||
gh cache delete "$id" --repo "$REPO"
|
||||
else
|
||||
kept[$entry]=1
|
||||
echo "keep $key"
|
||||
fi
|
||||
done < "$RUNNER_TEMP/caches"
|
||||
- name: Prune replaced cache entries
|
||||
uses: storytold/craft-common-actions/actions/cache-prune@main
|
||||
continue-on-error: true
|
||||
with:
|
||||
watch: true
|
||||
watch-minutes: 110
|
||||
content-keys: corpus
|
||||
saving-jobs: |
|
||||
^gate( / build \(.*\))?$
|
||||
^windows( / build \(.*\))?$
|
||||
^web build and wasm size gate$
|
||||
^corpus tests$
|
||||
|
||||
# The same codecs without the optional decoder: HEIC must stay a clear "not in this build" error
|
||||
# for distributors who leave it out. Runs beside the gate and restores the gate's newest rolling
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
//! The build units a CI build used, for the cache entry the gate saves.
|
||||
//!
|
||||
//! In a gate leg that saves the dependency cache, craft-common-actions' rust-cache action names a
|
||||
//! file in `CRAFT_CACHE_UNITS`, and its cache-trim action deletes every unit of the target
|
||||
//! directory that the file does not name before the entry is saved. Cargo prints a JSON message for
|
||||
//! every unit a build compiled or found fresh; these builds append those messages to the file, so
|
||||
//! the saved entry holds this build and no older builds of updated dependencies.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
/// The record file, when this leg saves the cache.
|
||||
pub fn file() -> Option<PathBuf> {
|
||||
std::env::var_os("CRAFT_CACHE_UNITS").filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
}
|
||||
|
||||
/// Runs `cmd`, a cargo build already told to print Cargo's JSON messages on stdout
|
||||
/// (`json-render-diagnostics`, so diagnostics stay readable on stderr), appends the messages to the
|
||||
/// record and passes every other stdout line (test output) through.
|
||||
pub fn run(mut cmd: Command, what: &str) -> Result<(), String> {
|
||||
let Some(file) = file() else { return crate::run(cmd, what) };
|
||||
eprintln!("$ {what}");
|
||||
let mut record = OpenOptions::new().create(true).append(true).open(&file).map_err(|e| format!("{}: {e}", file.display()))?;
|
||||
let mut child = cmd.stdout(Stdio::piped()).spawn().map_err(|e| format!("{what}: failed to spawn: {e}"))?;
|
||||
let stdout = child.stdout.take().expect("piped stdout");
|
||||
let routed = route(BufReader::new(stdout), &mut record, &mut std::io::stdout().lock());
|
||||
let status = child.wait().map_err(|e| format!("{what}: {e}"))?;
|
||||
routed.map_err(|e| format!("{what}: recording the build units in {}: {e}", file.display()))?;
|
||||
if status.success() { Ok(()) } else { Err(format!("{what}: exited with {status}")) }
|
||||
}
|
||||
|
||||
/// Records xtask's own units: `cargo xtask` builds it before it can record anything, and an
|
||||
/// unrecorded unit is trimmed from the entry and rebuilt next run. The build is fresh, so this only
|
||||
/// prints the messages.
|
||||
pub fn record_xtask() -> Result<(), String> {
|
||||
if file().is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut c = crate::cargo();
|
||||
c.args(["build", "-p", "xtask", "--message-format", "json-render-diagnostics"]);
|
||||
run(c, "cargo build -p xtask --message-format json-render-diagnostics")
|
||||
}
|
||||
|
||||
/// Lines that are Cargo's JSON messages go to `record`, every other line to `out`.
|
||||
fn route(mut input: impl BufRead, record: &mut impl Write, out: &mut impl Write) -> std::io::Result<()> {
|
||||
let mut line = Vec::new();
|
||||
while input.read_until(b'\n', &mut line)? != 0 {
|
||||
if line.starts_with(b"{\"reason\":") {
|
||||
record.write_all(&line)?;
|
||||
if !line.ends_with(b"\n") {
|
||||
record.write_all(b"\n")?;
|
||||
}
|
||||
} else {
|
||||
out.write_all(&line)?;
|
||||
}
|
||||
line.clear();
|
||||
}
|
||||
record.flush()?;
|
||||
out.flush()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cargo_messages_are_recorded_and_test_output_passes_through() {
|
||||
let input = "{\"reason\":\"compiler-artifact\",\"fresh\":true}\nrunning 3 tests\ntest a ... ok\n{\"reason\":\"build-finished\",\"success\":true}";
|
||||
let (mut record, mut out) = (Vec::new(), Vec::new());
|
||||
route(input.as_bytes(), &mut record, &mut out).unwrap();
|
||||
assert_eq!(String::from_utf8(record).unwrap(), "{\"reason\":\"compiler-artifact\",\"fresh\":true}\n{\"reason\":\"build-finished\",\"success\":true}\n");
|
||||
assert_eq!(String::from_utf8(out).unwrap(), "running 3 tests\ntest a ... ok\n");
|
||||
}
|
||||
}
|
||||
+14
-2
@@ -3,6 +3,7 @@
|
||||
//! Pure Rust (std + serde_json). External tools (`cargo`, `curl`, `tar`) are
|
||||
//! invoked through `std::process::Command`.
|
||||
|
||||
mod cache_units;
|
||||
mod cargo_env;
|
||||
mod corpus;
|
||||
mod corpus_pins;
|
||||
@@ -330,8 +331,11 @@ fn step_clippy(_: &CiOptions) -> Result<(), String> {
|
||||
fn step_doctest(o: &CiOptions) -> Result<(), String> {
|
||||
let mut c = cargo();
|
||||
c.arg("test").args(gate_args(&o.exclude)).arg("--doc");
|
||||
if cache_units::file().is_some() {
|
||||
c.args(["--message-format", "json-render-diagnostics"]);
|
||||
}
|
||||
let what = shown(&c);
|
||||
run(c, &what)
|
||||
cache_units::run(c, &what)
|
||||
}
|
||||
|
||||
fn step_i18n(_: &CiOptions) -> Result<(), String> {
|
||||
@@ -458,17 +462,25 @@ fn step_tests(o: &CiOptions, panic_hunt: bool) -> Result<(), String> {
|
||||
/// Builds the test steps' binaries without running them: what every shard builds, so the cache
|
||||
/// warm-up's entry covers each shard's build.
|
||||
fn build_tests(o: &CiOptions) -> Result<(), String> {
|
||||
cache_units::record_xtask()?;
|
||||
let recording = cache_units::file().is_some();
|
||||
let mut c = cargo();
|
||||
match &o.archive {
|
||||
Some(file) => {
|
||||
c.args(["nextest", "archive", "--profile", "ci"]).args(test_build_args(&o.exclude)).arg("--archive-file").arg(file);
|
||||
if recording {
|
||||
c.args(["--cargo-message-format", "json-render-diagnostics"]);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
c.args(["test", "--no-run"]).args(test_build_args(&o.exclude));
|
||||
if recording {
|
||||
c.args(["--message-format", "json-render-diagnostics"]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let what = shown(&c);
|
||||
run(c, &what)
|
||||
cache_units::run(c, &what)
|
||||
}
|
||||
|
||||
/// nextest does not run doctests.
|
||||
|
||||
Reference in new issue
Block a user