From 3f28dd6751a3a82a680b3f4def28629365f63fdc Mon Sep 17 00:00:00 2001 From: aiongg Date: Thu, 19 Nov 2026 22:06:59 +0000 Subject: [PATCH] CI shards: check the plan against the archive and mode; times only from full runs - A shard fails unless its plan's GPU mode matches --gpu/--no-gpu and its archive holds exactly the binaries its plan names; a single-archive build deletes any shard plan left in the target dir. - Shard runs pass --no-tests warn: a shard may hold no runnable test, and the build job's check already guarantees that every test runs once. - scripts/ci-test-times.py takes only main's push and nightly runs (pull requests leave packages out on Windows) unless given --force, and names binaries a refresh drops. - target_dir() moves from perf.rs to main.rs for both users. --- scripts/ci-test-times.py | 38 ++++++++++++++++-- scripts/test-ci-test-times.py | 11 ++++++ xtask/src/main.rs | 73 ++++++++++++++++++++--------------- xtask/src/perf.rs | 7 +--- xtask/src/shards.rs | 54 ++++++++++++++++++++++++++ 5 files changed, 143 insertions(+), 40 deletions(-) diff --git a/scripts/ci-test-times.py b/scripts/ci-test-times.py index 93c2ef8b46..5a748d3b18 100644 --- a/scripts/ci-test-times.py +++ b/scripts/ci-test-times.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 """Refresh .config/ci-test-times.tsv from the gate's test shards of one CI run. - python3 scripts/ci-test-times.py [--repo storytold/photocraft] + python3 scripts/ci-test-times.py [--repo storytold/photocraft] [--force] The gate's build job balances its per-shard archives by these times (xtask/src/shards.rs). Take a -green main run, which runs every test; refresh after large test changes. A run without Windows +green main run, which runs every test; refresh after large test changes. The script refuses other +runs (pull requests leave packages out of the Windows tests) unless given --force. A run without Windows shards refreshes the Linux rows only and keeps the Windows ones. Needs an authenticated `gh`. Rows, tab-separated: @@ -72,6 +73,30 @@ def merge(old_text, fresh, run): return HEADER.format(run=run) + '\n'.join(body) + '\n' +def refusal(run, default_branch='main'): + """Why a run cannot refresh the times, or None: only main's pushes and nightly runs test every + package.""" + if run['event'] not in ('push', 'schedule') or run['headBranch'] != default_branch: + return (f"run {run.get('databaseId', '')} is a {run['event']} run on {run['headBranch']}: only main's push and " + 'nightly runs test every package (pull requests leave some out on Windows); --force takes it anyway') + return None + + +def vanished(old_text, fresh): + """Binaries the old file has for an OS in `fresh` ({os: rows}) that the fresh rows lack.""" + def binaries(lines): + out = {} + for line in lines: + cols = line.split('\t') + if len(cols) == 5 and cols[0] == 'bin': + out.setdefault(cols[1], set()).add(cols[2]) + return out + old = binaries(line for line in old_text.splitlines() if not line.startswith("#")) + new = binaries(row for rows in fresh.values() for row in rows) + return {os_name: sorted(old.get(os_name, set()) - new.get(os_name, set())) for os_name in fresh + if old.get(os_name, set()) - new.get(os_name, set())} + + def gh(*args): return subprocess.run(['gh', *args], check=True, capture_output=True, text=True).stdout @@ -80,8 +105,13 @@ def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument('run') parser.add_argument('--repo', default='storytold/photocraft') + parser.add_argument('--force', action='store_true', help='take a run that is not a main push or nightly run') args = parser.parse_args() - jobs = json.loads(gh('run', 'view', args.run, '-R', args.repo, '--json', 'jobs'))['jobs'] + run = json.loads(gh('run', 'view', args.run, '-R', args.repo, '--json', 'databaseId,event,headBranch,jobs')) + reason = refusal(run) + if reason and not args.force: + sys.exit(reason) + jobs = run['jobs'] fresh = {} for os_name, (pattern, skip) in JOBS.items(): times = {} @@ -100,6 +130,8 @@ def main(): if not fresh: sys.exit(f'run {args.run} has no gate test shards') old = TIMES.read_text() if TIMES.exists() else '' + for os_name, binaries in vanished(old, fresh).items(): + print(f"warning: {os_name}: the run has no tests of {', '.join(binaries)}; their rows go", file=sys.stderr) TIMES.write_text(merge(old, fresh, args.run)) print(f'wrote {TIMES}', file=sys.stderr) diff --git a/scripts/test-ci-test-times.py b/scripts/test-ci-test-times.py index 917339f293..4f89ae8ec6 100644 --- a/scripts/test-ci-test-times.py +++ b/scripts/test-ci-test-times.py @@ -43,6 +43,17 @@ class TestTimes(unittest.TestCase): self.assertEqual(body, ['bin\tlinux\tfresh\t1\t2.00', 'bin\twindows\tw\t1\t9.00']) self.assertIn('run 123', new) + def test_only_runs_that_test_every_package_refresh_the_times(self): + self.assertIsNone(times.refusal({'event': 'push', 'headBranch': 'main'})) + self.assertIsNone(times.refusal({'event': 'schedule', 'headBranch': 'main'})) + self.assertIn('pull_request', times.refusal({'event': 'pull_request', 'headBranch': 'ci-x'})) + self.assertIsNotNone(times.refusal({'event': 'push', 'headBranch': 'ci-x'})) + + def test_names_the_binaries_a_refresh_drops(self): + old = 'bin\twindows\tgpu::it\t1\t9.00\nbin\twindows\tui\t1\t9.00\nbin\tlinux\tgpu::it\t1\t1.00\n' + self.assertEqual(times.vanished(old, {'windows': ['bin\twindows\tui\t1\t2.00']}), {'windows': ['gpu::it']}) + self.assertEqual(times.vanished(old, {'linux': ['bin\tlinux\tgpu::it\t1\t2.00']}), {}) + if __name__ == '__main__': unittest.main() diff --git a/xtask/src/main.rs b/xtask/src/main.rs index eda793a262..dcc7816f36 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -142,6 +142,12 @@ pub fn metadata() -> Result { serde_json::from_slice(&out.stdout).map_err(|e| format!("cargo metadata: bad JSON: {e}")) } +/// The workspace's cargo target directory. +pub fn target_dir() -> Result { + let m = metadata()?; + m.get("target_directory").and_then(serde_json::Value::as_str).map(PathBuf::from).ok_or_else(|| "cargo metadata: no target_directory".into()) +} + /// Two egui revisions in one build give two incompatible `Ui` types, so the workspace's egui /// `[patch]` must name the revision the craft framework is built with. fn cmd_egui_fork() -> Result<(), String> { @@ -403,18 +409,10 @@ fn read_gpu_filter() -> Result { /// The nextest command line of a test step. `panic_hunt` runs only the engine's `#[ignore]`d panic /// hunt (AGENTS.md Rule 9), with the same build arguments as the tests, so nothing rebuilds. `gpu` is -/// the group's filter, read only when the selection needs it. nextest's `ci` profile terminates -/// hung tests and repeats every failure at the end of the log (.config/nextest.toml). -/// What `ci tests --shard` runs, from the plan the shard's archive carries. -struct ShardRun { - /// The shard's part of the split binaries. - filter: Option, - /// The plan gave the shard no tests. - empty: bool, -} - -/// `shard`: the shard's part of the plan (`ci tests --shard`). -fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>, shard: Option<&ShardRun>) -> Vec { +/// the group's filter, read only when the selection needs it. `shard` is the filterset of the shard's +/// part of the split binaries (`ci tests --shard`). nextest's `ci` profile terminates hung tests and +/// repeats every failure at the end of the log (.config/nextest.toml). +fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>, shard: Option<&str>) -> Vec { let mut args: Vec = ["nextest", "run", "--profile", "ci"].map(String::from).to_vec(); let mut filters = Vec::new(); if panic_hunt { @@ -440,9 +438,10 @@ fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>, shard: Optio if let Some(partition) = &o.partition { args.extend(["--partition".to_string(), partition.clone()]); } - // A partition, a shard or a selection may hold no panic hunt; the shard that does runs it. A - // shard the plan gave nothing runs nothing. - if (panic_hunt && (o.partition.is_some() || o.shard.is_some() || o.selection != Selection::All)) || shard.is_some_and(|s| s.empty) { + // A partition or a selection may hold no panic hunt; the shard that does runs it. A shard of the + // build job's plan may hold no runnable test at all; the build job checked that every test runs + // on exactly one shard. + if (panic_hunt && (o.partition.is_some() || o.selection != Selection::All)) || o.shard.is_some() { args.extend(["--no-tests", "warn"].map(String::from)); } match (o.selection, gpu) { @@ -453,7 +452,7 @@ fn nextest_args(o: &CiOptions, panic_hunt: bool, gpu: Option<&str>, shard: Optio (Selection::NoGpu, Some(gpu)) => filters.push(format!("not ({gpu})")), _ => {} } - if let Some(filter) = shard.and_then(|s| s.filter.as_ref()) { + if let Some(filter) = shard { filters.push(format!("({filter})")); } if !filters.is_empty() { @@ -481,10 +480,10 @@ fn step_tests(o: &CiOptions, panic_hunt: bool) -> Result<(), String> { } else { let gpu = if o.selection == Selection::All { None } else { Some(read_gpu_filter()?) }; let shard = match (&o.from, o.shard) { - (Some(from), Some(k)) => read_shard_filter(from, k)?, + (Some(from), Some(k)) => read_shard_filter(from, k, o.selection)?, _ => None, }; - c.args(nextest_args(o, panic_hunt, gpu.as_deref(), shard.as_ref())); + c.args(nextest_args(o, panic_hunt, gpu.as_deref(), shard.as_deref())); } let what = shown(&c); run(c, &what) @@ -496,6 +495,13 @@ fn build_tests(o: &CiOptions) -> Result<(), String> { let mut c = cargo(); match &o.archive { Some(Archive::File(file)) => { + // A shard plan left in the target directory by a per-shard build would go into this + // archive (.config/nextest.toml) and mislead its shards. + let plan = target_dir()?.join(shards::PLAN_FILE); + match std::fs::remove_file(&plan) { + Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(format!("{}: {e}", plan.display())), + _ => {} + } c.args(["nextest", "archive", "--profile", "ci"]).args(test_build_args(&o.exclude)).arg("--archive-file").arg(file); } Some(Archive::Shards { dir, name, shards, gpu_shard }) => return build_shard_archives(o, dir, name, *shards, *gpu_shard), @@ -563,18 +569,26 @@ fn build_shard_archives(o: &CiOptions, dir: &Path, name: &str, shards: usize, gp Ok(()) } -/// Shard `k`'s part of the plan its archive carries, extracted to `from`. -fn read_shard_filter(from: &Path, k: usize) -> Result, String> { - let path = from.join("target").join(shards::PLAN_FILE); - let text = std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display()))?; - let plan: shards::Plan = serde_json::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; - let shard = plan.shards.get(k.wrapping_sub(1)).ok_or_else(|| format!("{}: no shard {k}", path.display()))?; +/// Shard `k`'s filterset from the plan its archive carries, extracted to `from`, once the plan is +/// checked against the archive and the selection. +fn read_shard_filter(from: &Path, k: usize, selection: Selection) -> Result, String> { + let read = |path: PathBuf| -> Result { std::fs::read_to_string(&path).map_err(|e| format!("{}: {e}", path.display())) }; + let plan_path = from.join("target").join(shards::PLAN_FILE); + let plan: shards::Plan = serde_json::from_str(&read(plan_path.clone())?).map_err(|e| format!("{}: {e}", plan_path.display()))?; + let metadata_path = from.join("target").join("nextest").join("binaries-metadata.json"); + let metadata: serde_json::Value = serde_json::from_str(&read(metadata_path.clone())?).map_err(|e| format!("{}: {e}", metadata_path.display()))?; + let gpu = match selection { + Selection::All => None, + Selection::Gpu => Some(true), + Selection::NoGpu => Some(false), + }; + let shard = shards::shard_to_run(&plan, k, gpu, &shards::archived_binaries(&metadata)?)?; eprintln!( "shard {k}: {} test binaries{}", shard.binaries.len(), if shard.parts.is_empty() { String::new() } else { format!(", part of {}", shard.parts.keys().cloned().collect::>().join(", ")) } ); - Ok(Some(ShardRun { filter: shard.filter(), empty: shard.binaries.is_empty() })) + Ok(shard.filter()) } /// nextest does not run doctests. @@ -777,14 +791,11 @@ mod ci_tests { fn a_shard_archive_runs_its_part_and_no_partition() { let (_, options) = ci_from_args(&["tests", "--from", "x", "--shard", "2", "--no-gpu"], Vec::new()).unwrap(); assert_eq!((options.shard, options.partition.as_deref()), (Some(2), None)); - let run = ShardRun { filter: Some("not (binary_id(=ui))".into()), empty: false }; - let args = nextest_args(&options, true, Some("package(g)"), Some(&run)).join(" "); + let args = nextest_args(&options, true, Some("package(g)"), Some("not (binary_id(=ui))")).join(" "); assert!(args.contains("--no-tests warn") && !args.contains("--partition"), "{args}"); assert!(args.ends_with("-E binary_id(photocraft-engine::panic_hunt) & not (package(g)) & (not (binary_id(=ui)))"), "{args}"); - let tests = nextest_args(&options, false, None, Some(&run)).join(" "); - assert!(!tests.contains("--no-tests"), "{tests}"); - let empty = nextest_args(&options, false, None, Some(&ShardRun { filter: None, empty: true })).join(" "); - assert!(empty.contains("--no-tests warn"), "{empty}"); + // A shard may hold no runnable test; the build job's plan check guarantees the coverage. + assert!(nextest_args(&options, false, None, None).join(" ").contains("--no-tests warn")); assert!(ci_from_args(&["tests", "--shard", "2"], Vec::new()).is_err(), "--shard without --from"); assert!(ci_from_args(&["tests", "--from", "x", "--shard", "0"], Vec::new()).is_err()); assert!(ci_from_args(&["lint", "--gpu-shard"], Vec::new()).is_err()); diff --git a/xtask/src/perf.rs b/xtask/src/perf.rs index 23c05f61c7..3ff076f3b1 100644 --- a/xtask/src/perf.rs +++ b/xtask/src/perf.rs @@ -853,11 +853,6 @@ fn parse_opts(rest: &[&str]) -> Result { Ok(o) } -fn target_dir() -> Result { - let m = crate::metadata()?; - m.get("target_directory").and_then(Value::as_str).map(PathBuf::from).ok_or_else(|| "cargo metadata: no target_directory".into()) -} - fn write(path: &Path, text: &str) -> Result<(), String> { if let Some(dir) = path.parent() { std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?; @@ -880,7 +875,7 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { } let mode = if o.quick { "quick" } else { "full" }; let threshold = o.threshold.unwrap_or(budgets.settings.regression_pct); - let target = target_dir()?; + let target = crate::target_dir()?; let out_dir = target.join("perf"); // Which benches run in this mode. diff --git a/xtask/src/shards.rs b/xtask/src/shards.rs index 64c3ed3dea..cfe3e64e93 100644 --- a/xtask/src/shards.rs +++ b/xtask/src/shards.rs @@ -364,6 +364,45 @@ pub fn plan(binaries: &[Binary], times: &Times, shards: usize, gpu_shard: bool) Ok(plan) } +/// The binaries in a nextest archive's `target/nextest/binaries-metadata.json`. +pub fn archived_binaries(json: &serde_json::Value) -> Result, String> { + let binaries = json.get("rust-binaries").and_then(serde_json::Value::as_object).ok_or("binaries-metadata.json: no rust-binaries")?; + binaries + .values() + .map(|b| { + b.get("binary-id") + .and_then(serde_json::Value::as_str) + .map(String::from) + .ok_or_else(|| "binaries-metadata.json: a binary without binary-id".to_string()) + }) + .collect() +} + +/// Shard `k` (1-based) of `plan`, checked against how the shard runs and what its archive holds: +/// `gpu` is `Some(true)` for `--gpu`, `Some(false)` for `--no-gpu` and `None` for every test, and +/// `archived` the binaries of the archive. A plan from another build or another mode would lose or +/// repeat tests without an error. +pub fn shard_to_run<'a>(plan: &'a Plan, k: usize, gpu: Option, archived: &BTreeSet) -> Result<&'a Shard, String> { + let shard = plan.shards.get(k.wrapping_sub(1)).ok_or_else(|| format!("the shard plan has no shard {k}"))?; + let expected = match (plan.gpu_shard, k) { + (false, _) => None, + (true, 1) => Some(true), + (true, _) => Some(false), + }; + if gpu != expected { + let mode = |g: Option| match g { + Some(true) => "the gpu group", + Some(false) => "the tests outside the gpu group", + None => "every test", + }; + return Err(format!("shard {k} runs {}, but the shard plan has it run {}", mode(gpu), mode(expected))); + } + if &shard.binaries != archived { + return Err(format!("shard {k}'s archive does not hold the binaries its plan names: the plan is from another build")); + } + Ok(shard) +} + /// Every test runs on exactly one shard: each binary with tests outside the gpu group on one shard /// or, split, every such test in exactly one part across the shards that hold it, and with a GPU /// shard, that shard holds exactly the binaries with GPU tests. Without a GPU shard every test @@ -511,6 +550,21 @@ bin\twindows\tui\t6\t600 assert_eq!(Shard::default().filter(), None); } + #[test] + fn a_shard_runs_only_the_plan_its_archive_and_mode_match() { + let times = Times::parse(TIMES, "linux").unwrap(); + let plan = plan(&build(), ×, 3, true).unwrap(); + let held = |k: usize| plan.shards[k - 1].binaries.clone(); + assert!(shard_to_run(&plan, 1, Some(true), &held(1)).is_ok()); + assert!(shard_to_run(&plan, 2, Some(false), &held(2)).is_ok()); + assert!(shard_to_run(&plan, 1, Some(false), &held(1)).is_err(), "the GPU shard run as a CPU shard"); + assert!(shard_to_run(&plan, 2, None, &held(2)).is_err(), "a GPU-shard plan run without --gpu-shard"); + assert!(shard_to_run(&plan, 2, Some(false), &held(3)).is_err(), "another shard's archive"); + assert!(shard_to_run(&plan, 4, Some(false), &held(2)).is_err()); + let json: serde_json::Value = serde_json::from_str(r#"{"rust-binaries": {"a": {"binary-id": "a"}, "b::it": {"binary-id": "b::it"}}}"#).unwrap(); + assert_eq!(archived_binaries(&json).unwrap(), BTreeSet::from(["a".to_string(), "b::it".to_string()])); + } + #[test] fn the_listing_marks_gpu_tests_and_skipped_binaries() { let json: serde_json::Value = serde_json::from_str(