Merge pull request #10081 from dotCooCoo/feat/split-cache-warm

CI: the cache warm on main builds its six shards in parallel
This commit is contained in:
.CooCoo authored and GitHub committed 2026-12-01 01:35:00 -08:00
commit 3b1cea04f5
5 files changed
+270 -32

No files matched your search

+10 -4
View File
@@ -47,6 +47,9 @@ jobs:
test-shards: 6
shard-command: cargo xtask ci shard
warm-command: cargo xtask ci warm
# The warm build runs as one `cache warm <k>/6` leg per shard, in parallel (each builds what
# its shard builds), and `cache warm` puts their files into the one entry it saves.
warm-split: true
# 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
@@ -65,14 +68,17 @@ jobs:
# the old entries when the `cache warm` leg starts saving (scripts/ci-clear-rolling-cache.py).
# When the leg fails or is canceled, before its save or during it, this job fails too, so "Re-run
# failed jobs" runs it again beside the re-run leg. The leg starts after `gate / select legs` and a
# free runner: the script fails when the leg has not started within 120 minutes, and then waits
# up to 160 minutes from the leg's start. This job's timeout is longer than both together, so the
# script reports a leg that starts late with its own error before the job times out.
# free runner, and with `warm-split` after every `cache warm <k>/6` leg. The script suspends its
# start deadline while any split leg is queued or running, then allows 180 minutes from the last
# split completion for the saving leg to start. Without split legs, it allows 180 minutes from
# the script's start. A failed split leg fails this job too. The script then waits up to 160
# minutes from the saving leg's start. GitHub's 360-minute job limit can end this job before the
# script's deadlines expire when split builds or runner waits take too long.
cold-cache-clear:
name: cold cache clear
if: github.event_name == 'schedule'
runs-on: ubuntu-24.04
timeout-minutes: 290
timeout-minutes: 360
permissions:
actions: write
steps:
+108 -3
View File
@@ -36,6 +36,11 @@ def earlier(conclusion):
return [{"name": WARM, "conclusion": conclusion}, {"name": "cold cache clear", "conclusion": "failure"}]
def split_job(shard, status, completed_at=None):
return {"name": f"gate / cache warm {shard}/5 (ubuntu-24.04)", "status": status,
"conclusion": "success" if status == "completed" else None, "completed_at": completed_at}
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)])))
@@ -99,6 +104,34 @@ class Deadline(unittest.TestCase):
self.assertFalse(clear.started_late(warm_job("queued"), self.began))
self.assertFalse(clear.started_late(None, self.began))
def test_split_progress_suspends_the_start_deadline(self):
for status in ("queued", "in_progress"):
with self.subTest(status=status):
jobs = [split_job(1, "completed", "2026-11-28T06:00:00Z"), split_job(2, status)]
ready = clear.start_wait_began(jobs, self.began)
self.assertIsNone(ready)
now = self.began + timedelta(seconds=clear.START_SECONDS + 60)
self.assertFalse(clear.start_overdue(None, now, ready))
self.assertFalse(clear.started_late(warm_job("in_progress", started_at=now.isoformat()), ready))
def test_the_last_split_completion_starts_the_wait(self):
jobs = [split_job(1, "completed", "2026-11-28T08:00:00Z"),
split_job(2, "completed", "2026-11-28T07:00:00Z")]
ready = clear.start_wait_began(jobs, self.began)
self.assertEqual(ready, clear.parse_time("2026-11-28T08:00:00Z"))
self.assertFalse(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS), ready))
self.assertTrue(clear.start_overdue(None, ready + timedelta(seconds=clear.START_SECONDS + 1), ready))
self.assertFalse(clear.started_late(warm_job("in_progress", started_at="2026-11-28T08:01:00Z"), ready))
late = warm_job("in_progress", started_at=(ready + timedelta(seconds=clear.START_SECONDS + 1)).isoformat())
self.assertTrue(clear.started_late(late, ready))
def test_without_split_legs_the_script_start_starts_the_wait(self):
self.assertEqual(clear.start_wait_began([], self.began), self.began)
self.assertEqual(clear.start_wait_began(ME + [warm_job("queued")], self.began), self.began)
def test_a_split_completion_without_a_timestamp_does_not_start_the_wait(self):
self.assertIsNone(clear.start_wait_began([split_job(1, "completed")], self.began))
class Workflow(unittest.TestCase):
ci = (Path(__file__).resolve().parent.parent / ".github" / "workflows" / "ci.yml").read_text()
@@ -116,10 +149,17 @@ class Workflow(unittest.TestCase):
self.fail(f"no timeout-minutes under {job}")
def test_the_job_outlasts_the_start_wait_and_the_save_wait(self):
# Five minutes are left for the steps before the script and for the deletion.
# Without split legs, five minutes remain for setup and deletion.
spare = self.timeout_minutes("cold-cache-clear") * 60 - clear.START_SECONDS - clear.GIVE_UP_SECONDS
self.assertGreaterEqual(spare, 5 * 60)
def test_the_job_allows_both_warm_builds_within_the_hosted_job_limit(self):
# Runner waits and the full start allowance may exceed the 360-minute job limit.
timeout = self.timeout_minutes("cold-cache-clear")
spare = timeout * 60 - self.timeout_minutes("gate") * 60 - clear.GIVE_UP_SECONDS
self.assertGreaterEqual(spare, 5 * 60)
self.assertEqual(timeout, 360)
def test_the_save_wait_outlasts_the_gate(self):
self.assertGreater(clear.GIVE_UP_SECONDS, self.timeout_minutes("gate") * 60)
@@ -156,6 +196,9 @@ class Jobs(unittest.TestCase):
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")]))
# With warm-split, the saving `cache warm (<os>)` leg also needs every `cache warm <k>/<N>` leg.
self.assertTrue(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "failure")]))
self.assertFalse(clear.legs_stopped([done("gate / cache warm 2/5 (ubuntu-24.04)", "success")]))
class Caches(unittest.TestCase):
@@ -192,6 +235,60 @@ class Clock(datetime):
return datetime(2026, 11, 28, 4, 0, tzinfo=timezone.utc)
class BeforeSaving(unittest.TestCase):
def run_main(self, polls):
began = Clock.now()
current = began
remaining = iter(polls)
class PollClock(datetime):
@classmethod
def now(cls, tz=None):
return current
def gh(url):
nonlocal current
if "/jobs?" in url:
minutes, jobs = next(remaining)
current = began + timedelta(minutes=minutes)
return {"jobs": ME + jobs}
if "/caches?" in url:
return {"actions_caches": []}
return {"run_started_at": began.isoformat()}
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"}
with mock.patch.object(clear, "gh", gh), mock.patch.object(clear.time, "sleep"), \
mock.patch.object(clear, "datetime", PollClock), mock.patch.dict(os.environ, env), \
mock.patch.object(clear.subprocess, "run") as delete, contextlib.redirect_stdout(io.StringIO()):
status = clear.main()
delete.assert_not_called()
return status
def test_queued_and_running_split_legs_can_outlast_the_original_start_deadline(self):
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
saved = warm_job("completed", "success", [("Post Setup", "completed", "success")],
started_at="2026-11-28T07:50:00Z")
self.assertFalse(self.run_main([
(181, [split_job(1, "queued")]),
(201, [split_job(1, "in_progress"), warm_job("queued")]),
(220, [done, warm_job("queued")]),
(230, [done, saved]),
]))
def test_a_saving_leg_that_never_starts_expires_after_the_last_split_completion(self):
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
self.assertEqual(self.run_main([
(220, [done, warm_job("queued")]),
(401, [done, warm_job("queued")]),
]), 1)
def test_a_late_start_after_split_completion_is_rejected_even_if_already_saving(self):
done = split_job(1, "completed", "2026-11-28T07:40:00Z")
late = warm_job("in_progress", steps=[("Post Setup", "in_progress", None)],
started_at="2026-11-28T10:40:01Z")
self.assertEqual(self.run_main([(401, [done, late])]), 1)
class AfterDeletion(unittest.TestCase):
SAVING = [("Gate", "completed", "success"), ("Post Setup", "in_progress", None)]
@@ -230,9 +327,17 @@ class AfterDeletion(unittest.TestCase):
canceled = warm_job("completed", "cancelled", [("Gate", "completed", "success"), ("Post Setup", "completed", "cancelled")])
self.assertEqual(self.run_main(canceled), 1)
def test_a_saving_leg_skipped_after_a_failed_split_warm_leg_fails_this_job(self):
skipped = warm_job("completed", conclusion="skipped")
failed = {"name": "gate / cache warm 2/5 (ubuntu-24.04)", "status": "completed", "conclusion": "failure"}
env = {"GITHUB_REPOSITORY": "storytold/vectorcraft", "GITHUB_RUN_ID": "1", "GITHUB_RUN_ATTEMPT": "1"}
with mock.patch.object(clear, "gh", lambda url: {"jobs": ME + [failed, skipped]}), mock.patch.object(clear.time, "sleep"), \
mock.patch.object(clear, "datetime", Clock), mock.patch.dict(os.environ, env), contextlib.redirect_stdout(io.StringIO()):
self.assertEqual(clear.main(), 1)
def test_a_leg_that_starts_late_and_saves_deletes_nothing(self):
# Clock.now() is 04:00, so the leg starts 120 minutes 5 seconds after the script.
late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T06:00:05Z")
# Clock.now() is 04:00, so the leg starts 180 minutes 5 seconds after the script.
late = warm_job("in_progress", steps=self.SAVING, started_at="2026-11-28T07:00:05Z")
deleted = []
def run(args, **kwargs):
+32 -18
View File
@@ -16,8 +16,10 @@ save step started saves nothing: its old entries stay, and this exits 1, so "Re-
runs it again beside the re-run leg. A save step that is canceled or fails after the old entries
were deleted leaves no rolling entry, so the next run starts cold, and this exits 1 too. A failure
in a later post step does not count once the save step has succeeded. This also exits 1 when the
leg has not started START_SECONDS after this script started, and when the leg has not reached its
save, or its save has not finished, GIVE_UP_SECONDS after the leg started. An absent warm leg is treated as finished only
leg has not started START_SECONDS after the last split warm leg completed (or after this script
started when there are no split legs). The start deadline does not expire while a split leg is
queued or running. This exits 1 when the leg has not reached its save, or its save has not finished,
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 still
lists no `gate / select legs` job RERUN_GRACE_SECONDS after this script started: "Re-run all
jobs" lists that job from its start, and "Re-run failed jobs" after a successful leg does not.
@@ -34,9 +36,11 @@ import time
REF = 'refs/heads/main'
WARM_JOB = re.compile(r'^gate / cache warm \(')
SPLIT_WARM_JOB = re.compile(r'^gate / cache warm \d+/\d+ \(')
# 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 \()')
# them fails or is canceled, the legs are skipped and no warm leg is listed. With `warm-split` the
# saving leg also needs every `cache warm <k>/<N>` leg.
NEEDED_JOBS = re.compile(r'^gate / (select legs$|build \(|cache warm \d+/\d+ \()')
# The gate's first job. "Re-run all jobs" lists it; "Re-run failed jobs" lists it only when it
# failed, and then no warm leg succeeded before.
SELECT_JOB = 'gate / select legs'
@@ -52,12 +56,11 @@ 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
# How long the leg may take to start, timed from this script's start: the leg waits for
# `gate / select legs` and then for a runner, which took 44 minutes on a push to main on
# 2026-11-28. The `cold-cache-clear` job's `timeout-minutes` in ci.yml is longer than
# START_SECONDS and GIVE_UP_SECONDS together, so this exits with its own error before the job
# times out.
START_SECONDS = 120 * 60
# How long the saving leg may take to start after the last split warm leg completed, or after
# this script started when there are no split legs. Queued or running split legs suspend this
# deadline. The `cold-cache-clear` job's 360-minute timeout in ci.yml can end the wait before
# this deadline or GIVE_UP_SECONDS expires when split builds or runner waits take too long.
START_SECONDS = 180 * 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',)
@@ -103,16 +106,25 @@ def started_at(job):
return parse_time(started) if started else None
def start_wait_began(jobs, began):
"""The last split warm completion, the script's start without splits, or None while waiting."""
splits = [j for j in jobs if SPLIT_WARM_JOB.match(j['name'])]
if not splits:
return began
if any(j['status'] != 'completed' or not j.get('completed_at') for j in splits):
return None
return max(parse_time(j['completed_at']) for j in splits)
def start_overdue(job, now, began):
"""True once START_SECONDS have passed since `began` (this script's start) and the warm leg
has not started."""
return started_at(job) is None and (now - began).total_seconds() > START_SECONDS
"""True once START_SECONDS have passed since the start wait began and the leg has not started."""
return began is not None and started_at(job) is None and (now - began).total_seconds() > START_SECONDS
def started_late(job, began):
"""True when the warm leg started more than START_SECONDS after `began` (this script's start)."""
"""True when the warm leg started more than START_SECONDS after the start wait began."""
started = started_at(job)
return started is not None and (started - began).total_seconds() > START_SECONDS
return began is not None and started is not None and (started - began).total_seconds() > START_SECONDS
def gave_up(job, now):
@@ -180,7 +192,8 @@ def main():
while True:
jobs = gh(jobs_url) or {}
job = warm_job(jobs.get('jobs', []))
if started_late(job, began):
ready = start_wait_began(jobs.get('jobs', []), began)
if started_late(job, ready):
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
return 1
if job and saving(job):
@@ -199,13 +212,14 @@ def main():
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:
# A saving leg skipped because a leg it needs failed (a `cache warm <k>/<N>` leg).
if job.get('conclusion') in STOPPED or job.get('conclusion') == 'skipped' and legs_stopped(jobs.get('jobs', [])):
print(f'::error::{NO_SAVE}')
return 1
print('the cache warm leg finished without a save step; nothing deleted')
return
now = datetime.now(timezone.utc)
if start_overdue(job, now, began):
if start_overdue(job, now, ready):
print(f'::error::the cache warm leg did not start within {START_SECONDS // 60} minutes; nothing deleted')
return 1
if gave_up(job, now):
+23 -7
View File
@@ -49,6 +49,7 @@ commands:
ci shard shard $GATE_SHARD of $GATE_SHARDS of ci (xtask/src/shards.rs): a test shard runs
the tests and doctests of its crates, the last shard the other steps
ci warm build what every shard builds, without running it (fills the gate's cache); with
GATE_SHARD of GATE_SHARDS set, only what that shard builds; with
CRAFT_CACHE_UNITS set, appends Cargo's JSON messages for each build to that file
shards list the crates each shard tests; fails when a member is in no shard or in two,
or builds with other features in its shard than in the whole workspace
@@ -410,18 +411,26 @@ fn cmd_ci_shard() -> Result<(), String> {
/// shards run, and cargo does not warn (`cargo::unused_dependencies`) about a dev-dependency that
/// only an integration test uses.
///
/// With `GATE_SHARD` and `GATE_SHARDS` set (the gate's split warm legs), it builds only what that
/// shard builds: a test shard's tests, or the checks shard's builds. A split's later parts build
/// nothing in either case, since part 1 builds the same tests.
///
/// In a leg that saves the cache, every build records its units in `CRAFT_CACHE_UNITS`
/// (xtask/src/cache_units.rs), xtask's own build included.
fn cmd_ci_warm() -> Result<(), String> {
let var = |key: &str| match std::env::var(key) {
Ok(value) => Ok(Some(value)),
Err(std::env::VarError::NotPresent) => Ok(None),
Err(std::env::VarError::NotUnicode(_)) => Err(format!("ci warm: {key} is not valid Unicode")),
};
let (shard, count) = (var("GATE_SHARD")?, var("GATE_SHARDS")?);
let only = shards::warm_only(shard.as_deref(), count.as_deref())?;
cache_units::record_xtask()?;
let checked = shards::run()?;
let (tests, checks) = shards::warm_plan(&checked, only);
let mut steps: Vec<Step> = Vec::new();
for shard in checked {
// A split's later parts build the same tests as its first.
if let shards::Shard::Tests(crates, part) = shard {
if part.is_some_and(|p| !p.is_first()) {
continue;
}
for i in tests {
if let shards::Shard::Tests(crates, _) = checked[i].clone() {
steps.push((
"build tests",
Box::new(move || {
@@ -431,6 +440,14 @@ fn cmd_ci_warm() -> Result<(), String> {
));
}
}
if checks {
push_warm_checks(&mut steps);
}
run_steps(&steps)
}
/// The builds of the checks shard that [`cmd_ci_warm`] runs.
fn push_warm_checks(steps: &mut Vec<Step>) {
steps.push((
"clippy",
Box::new(|| {
@@ -454,7 +471,6 @@ fn cmd_ci_warm() -> Result<(), String> {
}),
));
steps.push(("wasm", Box::new(cmd_wasm)));
run_steps(&steps)
}
/// The command `ci warm` builds one test shard's tests with, and its description.
+97
View File
@@ -364,10 +364,107 @@ pub fn run() -> Result<Vec<Shard>, String> {
Ok(shards)
}
/// The shard `cargo xtask ci warm` builds alone, as an index into [`GROUPS`], from the gate's
/// `GATE_SHARD` and `GATE_SHARDS`: `None` (every shard) when neither is set. Setting only one,
/// a value that is not a number, a count other than the number of shards, or a shard out of range
/// is an error.
pub fn warm_only(shard: Option<&str>, count: Option<&str>) -> Result<Option<usize>, String> {
let (shard, count) = match (shard, count) {
(None, None) => return Ok(None),
(Some(shard), Some(count)) => (shard, count),
_ => return Err("ci warm: GATE_SHARD and GATE_SHARDS are set together or not at all".into()),
};
let number =
|key: &str, value: &str| -> Result<usize, String> { value.trim().parse().map_err(|_| format!("ci warm: {key} is `{value}`, not a number")) };
let (shard, count) = (number("GATE_SHARD", shard)?, number("GATE_SHARDS", count)?);
if count != GROUPS.len() {
return Err(format!(
"ci warm: GATE_SHARDS is {count}, and xtask/src/shards.rs has {} shards (test-shards in .github/workflows/ci.yml)",
GROUPS.len()
));
}
if !(1..=count).contains(&shard) {
return Err(format!("ci warm: GATE_SHARD is {shard}, not 1 to {count}"));
}
Ok(Some(shard - 1))
}
/// What `cargo xtask ci warm` builds of `shards`: the indices of the test shards whose tests it
/// builds, and whether it runs the checks shard's builds. With `only` (from [`warm_only`]) it
/// builds that shard alone, and without it every shard. A split's later parts build nothing: they
/// build the same tests as part 1, whose leg puts them in the cache.
pub fn warm_plan(shards: &[Shard], only: Option<usize>) -> (Vec<usize>, bool) {
let mut tests = Vec::new();
let mut checks = false;
for (i, shard) in shards.iter().enumerate() {
if only.is_some_and(|k| k != i) {
continue;
}
match shard {
Shard::Checks => checks = true,
Shard::Tests(_, part) if part.is_some_and(|p| !p.is_first()) => {}
Shard::Tests(..) => tests.push(i),
}
}
(tests, checks)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warm_builds_every_shard_unless_the_gate_names_one() {
let n = GROUPS.len().to_string();
assert_eq!(warm_only(None, None), Ok(None));
assert_eq!(warm_only(Some("1"), Some(&n)), Ok(Some(0)));
assert_eq!(warm_only(Some(&n), Some(&n)), Ok(Some(GROUPS.len() - 1)));
for (shard, count) in [(Some("1"), None), (None, Some(n.as_str())), (Some("0"), Some(n.as_str())), (Some("x"), Some(n.as_str()))] {
assert!(warm_only(shard, count).is_err(), "{shard:?} of {count:?}");
}
let past = (GROUPS.len() + 1).to_string();
assert!(warm_only(Some(&past), Some(&n)).is_err());
assert!(warm_only(Some("1"), Some(&past)).is_err());
}
#[test]
fn warm_builds_each_shard_of_the_plan() {
let ws = [m("a"), m("b")];
let shards = assign(&[Group::Part(&SPLIT, 1), Group::Part(&SPLIT, 2), Group::Rest, Group::Checks], &ws).unwrap();
assert_eq!(warm_plan(&shards, None), (vec![0, 2], true));
assert_eq!(warm_plan(&shards, Some(0)), (vec![0], false));
assert_eq!(warm_plan(&shards, Some(1)), (vec![], false));
assert_eq!(warm_plan(&shards, Some(2)), (vec![2], false));
assert_eq!(warm_plan(&shards, Some(3)), (vec![], true));
// The real plan: every leg the gate names builds its own shard (a split's later part
// builds nothing), and the legs together, like a full warm, build every crate's tests
// once and the checks.
let real = assign(GROUPS, &members(&crate::metadata().unwrap()).unwrap()).unwrap();
let mut owned: Vec<&str> = real.iter().flat_map(owners).collect();
owned.sort_unstable();
let (mut legs, mut leg_checks) = (Vec::new(), 0);
for i in 0..GROUPS.len() {
let n = GROUPS.len().to_string();
let only = warm_only(Some(&(i + 1).to_string()), Some(&n)).unwrap();
let (tests, checks) = warm_plan(&real, only);
let want = match &real[i] {
Shard::Checks => (vec![], true),
Shard::Tests(_, Some(p)) if !p.is_first() => (vec![], false),
Shard::Tests(..) => (vec![i], false),
};
assert_eq!((tests.clone(), checks), want, "shard {}", i + 1);
legs.extend(tests);
leg_checks += usize::from(checks);
}
let (tests, checks) = warm_plan(&real, None);
assert!(checks);
assert_eq!(leg_checks, 1);
assert_eq!(tests, legs);
let mut built: Vec<&str> = tests.iter().flat_map(|&i| crates(&real[i])).collect();
built.sort_unstable();
assert_eq!(built, owned);
}
fn m(name: &str) -> Member {
Member { name: name.into(), id: format!("path+file:///w/{name}#0.1.0"), version: "0.1.0".into(), doctests: true }
}