diff --git a/.github/workflows/perf-nightly.yml b/.github/workflows/perf-nightly.yml index 64592d9cf0..71afc03e14 100644 --- a/.github/workflows/perf-nightly.yml +++ b/.github/workflows/perf-nightly.yml @@ -4,10 +4,13 @@ name: Perf (nightly) # Metal), every night and on demand. It never runs on pull requests, so it can't block one. # It fails when an enforced budget in perf/budgets.toml breaks or a scenario's p50 regresses # more than 15 % against perf/baseline.json from the same machine class (other classes are -# never compared). The table goes to the job summary; results.json is uploaded as an artifact. +# never compared; a baseline built from several runs is judged against its highest p50). The +# table goes to the job summary; results.json is uploaded as the `perf-results` artifact. # -# To give this runner class its own baseline: run it by hand with "update_baseline", download -# the `perf-baseline` artifact and commit it as perf/baseline.json in a PR. +# To give this runner class its own baseline: download the `perf-results` artifact of the last +# five or more nightly runs (`gh run download -n perf-results -D runs/`), run +# `cargo xtask perf --update-baseline --from runs//results.json ... --allow-contended` (this +# runner is never idle) and commit perf/baseline.json and docs/scorecard.md in a PR. on: schedule: @@ -58,7 +61,8 @@ jobs: run: | args=() if [ "$QUICK" = "true" ]; then args+=(--quick); fi - if [ "$UPDATE" = "true" ]; then args+=(--update-baseline); fi + # This runner is never idle: a baseline from it is recorded labelled as contended. + if [ "$UPDATE" = "true" ]; then args+=(--update-baseline --allow-contended); fi cargo xtask perf "${args[@]}" - name: Job summary diff --git a/docs/development.md b/docs/development.md index 50ba4e5254..41d74bae67 100644 --- a/docs/development.md +++ b/docs/development.md @@ -406,7 +406,8 @@ cargo xtask scorecard # regenerate docs/scorecard.md cargo xtask scorecard --check # what CI runs: fails if the committed file is stale cargo xtask perf # full benchmark run (tens of minutes, release build) cargo xtask perf --quick # small synthetic documents (about a minute once built) -cargo xtask perf --update-baseline # also write perf/baseline.json from this run +cargo xtask perf --update-baseline # also write perf/baseline.json from this run (refused when contended) +cargo xtask perf --update-baseline --from a/results.json --from b/results.json ... # baseline from saved runs ``` **Sources.** The scorecard reads only committed files, so it is deterministic: @@ -422,7 +423,9 @@ cargo xtask perf --update-baseline # also write perf/baseline.json from this r a number. - `perf/baseline.json`: the numbers the scorecard shows, written only by `cargo xtask perf --update-baseline`, with the machine (CPU, RAM, GPU adapter, OS), its machine - class, commit, date and load average. + class, commit, date, load average, core count and how many runs it was built from. A baseline + recorded with `--allow-contended` carries `"contended": true`, and the scorecard labels any + contended baseline (one whose 1-minute load at the start was above `max_load_per_core` per core). - `crates/io/tests/it/corpus.rs`: the corpus floors (every `Source { .. }` constant). - `xtask/*-corpus.sha256`: file counts for pinned corpora, so stale counts in doc comments cannot change the reported denominators. No downloaded corpus is needed to generate the scorecard. @@ -439,11 +442,27 @@ breaks, when a scenario's p50 regresses more than 15 % (`--threshold`, or `regre against a baseline from the same machine class and mode, or when a bench fails. Runs from different machine classes are never compared, and `--quick` numbers are only compared with a quick baseline. Machines that run other work give noisy numbers: check the load average in the -summary before trusting a regression, and record it next to any number you quote. +summary before trusting a regression, and record it next to any number you quote. A run whose +1-minute load at the start (sampled before the release build, so the harness's own compile doesn't +count) is above `settings.max_load_per_core` per core is marked **contended** +in the summary, and `--update-baseline` refuses to record it unless `--allow-contended` is given. + +**Recording a baseline.** One run is noisy, especially on the shared nightly runner, so build the +baseline from several: download the last five or more nightly `perf-results` artifacts +(`gh run download -n perf-results -D runs/`), then run +`cargo xtask perf --update-baseline --from runs//results.json --from runs//results.json ...` +(add `--allow-contended` for the GitHub runner, which is never idle). It needs at least +`settings.baseline_min_runs` runs of one machine class and mode, all from a clean tree. Each +scenario gets the median p50 and the highest p50 of the runs; a regression is judged against that +highest p50 (the runs' own noise), so only changes bigger than the runner's spread flag. It also +prints which budgets could be enforced (within `settings.enforce_margin` of the budget in every +run) and which enforced budgets went over in some run. Commit `perf/baseline.json` and the +regenerated `docs/scorecard.md` in a PR. **Measuring one scenario.** A full run is tens of minutes; one row is seconds once its bench is -built. `xtask perf`'s own flags are `--quick`, `--update-baseline`, `--threshold`, `--bench` -(repeatable, one bench per name), `--skip-build` and `--reuse`; it has no way to pick a single +built. `xtask perf`'s own flags are `--quick`, `--update-baseline` (with `--from` and +`--allow-contended`), `--threshold`, `--bench` (repeatable, one bench per name), `--skip-build` +and `--reuse`; it has no way to pick a single *row*. The bench binary takes those filters itself — `--only ` (row names are matched with `contains`), `--group ` and `--reps N` — so to time one row run the bench directly: diff --git a/docs/scorecard.md b/docs/scorecard.md index 95e84060ce..b9f9bb0a1e 100644 --- a/docs/scorecard.md +++ b/docs/scorecard.md @@ -18,9 +18,11 @@ Generated by `cargo xtask scorecard` from `perf/budgets.toml`, `perf/baseline.js ## Performance -Budgets: `perf/budgets.toml` (targets from #209, #210, #211). Numbers: the committed baseline (`perf/baseline.json`, full run), updated only by `cargo xtask perf --update-baseline`. The nightly `perf-nightly` workflow runs `cargo xtask perf` on a fixed macOS runner and fails on a broken enforced budget or a p50 regression over 15 % against a baseline from the same machine class. "Over budget" rows are targets the code doesn't meet yet: they are reported, and only their regressions fail. +Budgets: `perf/budgets.toml` (targets from #209, #210, #211). Numbers: the committed baseline (`perf/baseline.json`, full run), updated only by `cargo xtask perf --update-baseline`. The nightly `perf-nightly` workflow runs `cargo xtask perf` on a fixed macOS runner and fails on a broken enforced budget. Its p50 regression check (over 15 %, against the baseline's highest p50 when it was built from several runs) runs only on machine class `macos-aarch64-apple-m4-pro-apple-m4-pro`, the baseline's. "Over budget" rows are targets the code doesn't meet yet: they are reported, and only their regressions fail. -Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pro, macOS 15.6; load average 224.90 / 226.31 / 196.03 (1/5/15 min) at the start of the run. +Baseline: 2026-10-05, 1 run, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pro, macOS 15.6; load average 224.90 / 226.31 / 196.03 (1/5/15 min) at the start of the run. + +**contended baseline** (load 224.90 on 14 cores): these numbers measure machine load, not the code. | Id | Scenario | Target | p50 ms | p95 ms | max ms | Peak RSS | GPU | Status | Issue | |---|---|---|---:|---:|---:|---:|---:|---|---| @@ -48,7 +50,7 @@ Baseline: 2026-10-05, commit `f5d2bcb54a`, Apple M4 Pro (48 GB), GPU Apple M4 Pr | P21 | Content-Aware Fill on 10 MP | ≤ 1500 ms p95 | 218 | 256 | 256 | 1.8 GB | 1.8 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) | | P22 | Spot Healing stroke on 10 MP | ≤ 500 ms p95 | 157 | 247 | 247 | 1.8 GB | 1.9 GB | pass | [#210](https://github.com/storytold/photocraft/issues/210) | | P24 | Import 500 brushes (longest UI-thread step) | ≤ 100 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) | -| P25 | Cancel a Gaussian Blur job on 24 MP (until the worker exits) | ≤ 200 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) | +| P25 | Cancel a Gaussian Blur job on 24 MP (until the worker exits) | ≤ 200 ms p95 | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) | | P49 | Cancel a Content-Aware Fill job on 24 MP (until the worker exits) | ≤ 200 ms max | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) | | P50 | App frame time while a 24 MP Gaussian Blur job runs | ≤ 16 ms p95 | – | – | – | – | – | not run | [#210](https://github.com/storytold/photocraft/issues/210) | | P26 | Select › Modify › Smooth on 24 MP (radius 50) | ≤ 100 ms p95 | 99.9 | 216 | 251 | 1.0 GB | – | over budget (target not met yet) | [#211](https://github.com/storytold/photocraft/issues/211) | diff --git a/perf/budgets.toml b/perf/budgets.toml index d2ba30473f..b538808553 100644 --- a/perf/budgets.toml +++ b/perf/budgets.toml @@ -16,6 +16,16 @@ regression_pct = 15.0 # …and by more than this many milliseconds (timer noise on very fast rows). regression_min_ms = 1.0 +# A run whose 1-minute load at the start is above this many per core is contended: its numbers +# measure the machine's load, so `--update-baseline` refuses it (`--allow-contended` records it, +# labelled as contended, and the scorecard says so). +max_load_per_core = 1.0 +# `--update-baseline --from ...` needs at least this many saved runs. Each scenario +# gets the median p50 and the highest (the noise ceiling regressions are judged against). +baseline_min_runs = 5 +# `--from` lists a budget as "could enforce" when its metric stays within this share of the +# budget in every run. +enforce_margin = 0.6 [[bench]] name = "perf_scenarios" @@ -245,7 +255,10 @@ issue = 209 bench = "perf_scenarios" row = "brush dab 60 px on 32-bit 20 layers + refresh" budget_ms = 100 -enforce = false # over budget in the 2026-10-05 baseline +# Not enforced: met on an idle M4 Pro (p95 2.95 ms), but over budget once in the 8 nightlies on +# macos-15 (p95 103.7 ms on 2026-10-18). `cargo xtask perf --update-baseline --from` over those +# 8 nightlies (2026-10-18 to 10-25) lists it as flaky. Budget enforcement applies on the runner. +enforce = false [[scenario]] id = "P17" @@ -331,7 +344,9 @@ title = "Cancel a Gaussian Blur job on 24 MP (until the worker exits)" issue = 210 bench = "perf_scenarios" row = "cancel Gaussian Blur r 50 job on 24 MP" -metric = "max" +# Judged on p95, not max. Note: with n <= 20, `rank()` makes p95 equal max, so on the nightly +# runner (n = 8) this has no effect until reps >= 21. The 2026-10-18 nightly read 299 ms either way. +metric = "p95" budget_ms = 200 [[scenario]] diff --git a/xtask/src/perf.rs b/xtask/src/perf.rs index c1890d1cbd..d900669984 100644 --- a/xtask/src/perf.rs +++ b/xtask/src/perf.rs @@ -2,13 +2,20 @@ //! by scenario id, and check it against `perf/budgets.toml` and `perf/baseline.json` (#221). //! //! ```text -//! cargo xtask perf [--quick] [--update-baseline] [--threshold PCT] [--bench NAME]... [--skip-build] [--reuse] +//! cargo xtask perf [--quick] [--update-baseline [--allow-contended]] [--threshold PCT] [--bench NAME]... [--skip-build] [--reuse] +//! cargo xtask perf --update-baseline --from results.json [--from results.json]... [--allow-contended] //! ``` //! //! - `--quick`: only the benches with `quick_args` (small synthetic documents; minutes, not tens //! of minutes). Quick numbers are compared only with a quick baseline, and budgets don't apply //! (they are set for the full-size documents). //! - `--update-baseline`: write this run into `perf/baseline.json` (the only way it changes). +//! A contended run (1-minute load at the start above `settings.max_load_per_core` per core) is +//! refused; `--allow-contended` records it, labelled `"contended": true`. +//! - `--from FILE`: with `--update-baseline`, build the baseline from saved `results.json` files +//! (at least `settings.baseline_min_runs`, one machine class and mode, clean trees) instead of +//! running: per scenario the median p50 and the highest (the noise ceiling regressions are +//! judged against). Prints which budgets could be enforced and which enforced ones are flaky. //! - `--threshold PCT`: the regression threshold (default `settings.regression_pct`, 15 %). //! - `--bench NAME`: run only these benches (repeatable). //! - `--skip-build`: don't run `cargo build` first. `--reuse`: don't run the benches either; @@ -18,7 +25,8 @@ //! nightly job posts as its summary) and one `target/perf/.json` per bench. //! //! Exit status: non-zero when an enforced budget breaks (full mode), a scenario's p50 regresses -//! more than the threshold against a baseline from the same machine class and mode, or a bench +//! more than the threshold against a baseline from the same machine class and mode (against its +//! noise ceiling when it was built from several runs), or a bench //! fails. Runs from different machine classes are never compared. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] @@ -54,11 +62,18 @@ pub struct Settings { pub regression_pct: f64, /// …and by more than this many milliseconds (timer noise on sub-millisecond rows). pub regression_min_ms: f64, + /// A run is contended when its 1-minute load at the start exceeds this many per core: its + /// numbers measure the machine's load, so `--update-baseline` refuses it. + pub max_load_per_core: f64, + /// `--update-baseline --from` needs at least this many saved runs. + pub baseline_min_runs: usize, + /// A budget could be enforced when its metric stays within this share of the budget in every run. + pub enforce_margin: f64, } impl Default for Settings { fn default() -> Self { - Self { regression_pct: 15.0, regression_min_ms: 1.0 } + Self { regression_pct: 15.0, regression_min_ms: 1.0, max_load_per_core: 1.0, baseline_min_runs: 5, enforce_margin: 0.6 } } } @@ -171,6 +186,15 @@ pub fn parse_budgets(text: &str) -> Result { if !(b.settings.regression_min_ms.is_finite() && b.settings.regression_min_ms >= 0.0) { return Err(format!("{BUDGETS}: settings.regression_min_ms must be finite and >= 0")); } + if !(b.settings.max_load_per_core.is_finite() && b.settings.max_load_per_core > 0.0) { + return Err(format!("{BUDGETS}: settings.max_load_per_core must be > 0")); + } + if b.settings.baseline_min_runs == 0 { + return Err(format!("{BUDGETS}: settings.baseline_min_runs must be >= 1")); + } + if !(b.settings.enforce_margin.is_finite() && b.settings.enforce_margin > 0.0 && b.settings.enforce_margin <= 1.0) { + return Err(format!("{BUDGETS}: settings.enforce_margin must be in (0, 1]")); + } Ok(b) } @@ -185,6 +209,8 @@ pub struct Stats { pub max: Option, pub peak_rss: Option, pub gpu_bytes: Option, + /// A baseline built from several runs: the highest p50 among them (its noise ceiling). + pub p50_max: Option, } impl Stats { @@ -197,7 +223,12 @@ impl Stats { } pub fn to_json(&self) -> Value { - json!({"n": self.n, "p50_ms": self.p50, "p95_ms": self.p95, "max_ms": self.max, "peak_rss_bytes": self.peak_rss, "gpu_bytes": self.gpu_bytes}) + let mut v = + json!({"n": self.n, "p50_ms": self.p50, "p95_ms": self.p95, "max_ms": self.max, "peak_rss_bytes": self.peak_rss, "gpu_bytes": self.gpu_bytes}); + if let (Some(m), Some(o)) = (self.p50_max, v.as_object_mut()) { + o.insert("p50_max_ms".into(), json!(m)); + } + v } pub fn from_json(v: &Value) -> Self { @@ -208,6 +239,7 @@ impl Stats { max: v.get("max_ms").and_then(Value::as_f64), peak_rss: v.get("peak_rss_bytes").and_then(Value::as_u64), gpu_bytes: v.get("gpu_bytes").and_then(Value::as_u64), + p50_max: v.get("p50_max_ms").and_then(Value::as_f64), } } } @@ -237,6 +269,7 @@ pub fn row_stats(row: &Value) -> Stats { max: f("max_ms"), peak_rss: row.get("peak_rss_bytes").and_then(Value::as_u64), gpu_bytes: row.get("gpu_bytes").and_then(Value::as_u64), + p50_max: None, }; if !samples.is_empty() { s.p50 = rank(&samples, 0.5); @@ -310,8 +343,10 @@ pub struct Outcome { } /// Budget and regression verdict for one scenario. `budgets_apply` is false in quick mode. +/// A regression is judged against the baseline's noise ceiling (the highest p50 of the runs it was +/// built from), or its p50 when it came from one run. pub fn verdict(sc: &Scenario, stats: &Stats, base: Option<&Stats>, settings: &Settings, threshold: f64, budgets_apply: bool) -> Status { - if let (Some(cur), Some(b)) = (stats.p50, base.and_then(|b| b.p50)) + if let (Some(cur), Some(b)) = (stats.p50, base.and_then(|b| b.p50_max.or(b.p50))) && regressed(cur, b, threshold, settings.regression_min_ms) { return Status::Regressed; @@ -590,34 +625,181 @@ pub fn baseline_for(baseline: &Value, class: &str, mode: &str) -> Result, results: &Value) -> Value { - let class = results.get("machine").and_then(|m| m.get("class")).cloned().unwrap_or(Value::Null); - let mode = results.get("mode").and_then(Value::as_str).unwrap_or("full").to_string(); +/// A run is contended when its 1-minute load at the start exceeds `max_per_core` per core: +/// its numbers measure the machine's load, not the code. +/// Without a load (Windows) or a core count, nothing can be judged: not contended. +pub fn contended(load: Option<[f64; 3]>, cores: Option, max_per_core: f64) -> bool { + match (load, cores) { + (Some([one, _, _]), Some(c)) if c > 0 => one > c as f64 * max_per_core, + _ => false, + } +} + +fn load_of(v: Option<&Value>) -> Option<[f64; 3]> { + let a = v?.as_array()?; + Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?, a.get(2)?.as_f64()?]) +} + +fn cores_of(machine: Option<&Value>) -> Option { + machine?.get("cores")?.as_u64().map(|c| c as usize) +} + +/// Whether a `results.json` (or a baseline mode plus its machine) was contended at the start. +pub fn run_contended(load_avg_start: Option<&Value>, machine: Option<&Value>, max_per_core: f64) -> bool { + contended(load_of(load_avg_start), cores_of(machine), max_per_core) +} + +/// What `baseline_from_runs` accepts. +pub struct BaselineRules { + /// Fewer runs are refused. + pub min_runs: usize, + pub max_load_per_core: f64, + /// Accept contended runs (the baseline then records `"contended": true`). + pub allow_contended: bool, +} + +fn median(v: &mut [f64]) -> Option { + v.sort_by(f64::total_cmp); + let n = v.len(); + match n { + 0 => None, + _ if n % 2 == 1 => v.get(n / 2).copied(), + _ => Some((v.get(n / 2 - 1)? + v.get(n / 2)?) / 2.0), + } +} + +/// `old` with one mode replaced by a baseline built from `runs` (saved `results.json` values of +/// one machine class and mode), or a fresh baseline when the machine class changed. Per scenario: +/// `p50_ms` is the median of the runs' p50 and, from two runs on, `p50_max_ms` their maximum (the +/// noise ceiling regressions are judged against); p95 is the median, max and memory the maximum. +/// One run is the plain `--update-baseline` case. Refused: too few runs, mixed machine classes or +/// modes, dirty trees when there are several runs, and contended runs unless allowed. +pub fn baseline_from_runs(old: Option<&Value>, runs: &[Value], rules: &BaselineRules) -> Result { + if runs.len() < rules.min_runs.max(1) { + return Err(format!("a baseline needs at least {} run(s), got {}", rules.min_runs.max(1), runs.len())); + } + let class_of = |r: &Value| r.get("machine").and_then(|m| m.get("class")).cloned().unwrap_or(Value::Null); + let mode_of = |r: &Value| r.get("mode").and_then(Value::as_str).unwrap_or("full").to_string(); + let mut runs: Vec<&Value> = runs.iter().collect(); + runs.sort_by_key(|r| r.get("date").and_then(Value::as_str).unwrap_or("").to_string()); + let Some(last) = runs.last().copied() else { return Err("no runs".into()) }; + let (class, mode) = (class_of(last), mode_of(last)); + if runs.iter().any(|r| class_of(r) != class) { + return Err("the runs are from different machine classes: a baseline needs one".into()); + } + if runs.iter().any(|r| mode_of(r) != mode) { + return Err("the runs mix full and quick modes: a baseline needs one".into()); + } + if runs.len() > 1 + && let Some(r) = runs.iter().find(|r| r.get("dirty").and_then(Value::as_bool) == Some(true)) + { + return Err(format!("run {} was taken on a dirty tree: a baseline needs committed code", r.get("date").and_then(Value::as_str).unwrap_or("?"))); + } + let is_contended = |r: &Value| run_contended(r.get("load_avg_start"), r.get("machine"), rules.max_load_per_core); + let any_contended = runs.iter().any(|r| is_contended(r)); + if any_contended && !rules.allow_contended { + let msgs: Vec = runs + .iter() + .filter(|r| is_contended(r)) + .map(|r| { + format!( + "load {} on {} cores at the start of {}", + load_of(r.get("load_avg_start")).map_or_else(|| "?".into(), |l| format!("{:.2}", l[0])), + cores_of(r.get("machine")).map_or_else(|| "?".into(), |c| c.to_string()), + r.get("date").and_then(Value::as_str).unwrap_or("the run") + ) + }) + .collect(); + return Err(format!( + "contended run, baseline not written: {} (above {} per core). Its numbers measure machine load; rerun on an idle machine, or pass --allow-contended to record it labelled as contended", + msgs.join("; "), + rules.max_load_per_core + )); + } + + let mut per: BTreeMap> = BTreeMap::new(); + let mut failed = serde_json::Map::new(); + for r in &runs { + for (k, v) in r.get("scenarios").and_then(Value::as_object).into_iter().flatten() { + if v.get("p50_ms").is_some_and(|x| !x.is_null()) { + per.entry(k.clone()).or_default().push(Stats::from_json(v)); + } else if let Some(e) = v.get("status").and_then(Value::as_str).and_then(|s| s.strip_prefix(MISSING_PREFIX)) { + // A crashed row (a crash the bench found): kept so the scorecard says so. + failed.insert(k.clone(), json!(e)); + } + } + } + let mut scenarios = serde_json::Map::new(); + for (k, st) in &per { + // A row that crashed in any run stays failed, and one missing from some runs is left + // out: no partial aggregate under a full run count. + if failed.contains_key(k) || st.len() != runs.len() { + continue; + } + let mut p50: Vec = st.iter().filter_map(|s| s.p50).collect(); + let mut p95: Vec = st.iter().filter_map(|s| s.p95).collect(); + let fmax = |f: fn(&Stats) -> Option| st.iter().filter_map(f).reduce(f64::max); + let umax = |f: fn(&Stats) -> Option| st.iter().filter_map(f).max(); + let s = Stats { + n: st.iter().map(|s| s.n).sum(), + p50_max: (runs.len() > 1).then(|| fmax(|s| s.p50)).flatten(), + p50: median(&mut p50), + p95: median(&mut p95), + max: fmax(|s| s.max), + peak_rss: umax(|s| s.peak_rss), + gpu_bytes: umax(|s| s.gpu_bytes), + }; + scenarios.insert(k.clone(), s.to_json()); + } + let mut modes = old.filter(|o| o.get("machine_class") == Some(&class)).and_then(|o| o.get("modes")).and_then(Value::as_object).cloned().unwrap_or_default(); - let scenarios: serde_json::Map = results - .get("scenarios") - .and_then(Value::as_object) - .map(|m| m.iter().filter(|(_, v)| v.get("p50_ms").is_some_and(|x| !x.is_null())).map(|(k, v)| (k.clone(), Stats::from_json(v).to_json())).collect()) - .unwrap_or_default(); - // Scenarios whose bench row failed (a crash the bench found): kept so the scorecard says so. - let failed: serde_json::Map = results - .get("scenarios") - .and_then(Value::as_object) - .map(|m| m.iter().filter_map(|(k, v)| v.get("status")?.as_str()?.strip_prefix(MISSING_PREFIX).map(|e| (k.clone(), json!(e)))).collect()) - .unwrap_or_default(); - modes.insert( - mode, - json!({ - "date": results.get("date"), - "commit": results.get("commit"), - "load_avg_start": results.get("load_avg_start"), - "load_avg_end": results.get("load_avg_end"), - "scenarios": scenarios, - "failed": failed, - }), - ); - json!({"schema": 1, "machine_class": class, "machine": results.get("machine"), "modes": modes}) + let mut entry = json!({ + "date": last.get("date"), + "commit": last.get("commit"), + "load_avg_start": last.get("load_avg_start"), + "load_avg_end": last.get("load_avg_end"), + "cores": cores_of(last.get("machine")), + "runs": runs.len(), + "scenarios": scenarios, + "failed": failed, + }); + if let Some(o) = entry.as_object_mut() { + if any_contended { + o.insert("contended".into(), json!(true)); + } + if runs.len() > 1 { + let each: Vec = runs + .iter() + .map(|r| json!({"date": r.get("date"), "commit": r.get("commit"), "load_avg_start": r.get("load_avg_start"), "contended": is_contended(r)})) + .collect(); + o.insert("run_list".into(), json!(each)); + } + } + modes.insert(mode, entry); + Ok(json!({"schema": 1, "machine_class": class, "machine": last.get("machine"), "modes": modes})) +} + +/// From saved runs: budgets that could be enforced (not enforced, and within `enforce_margin` of +/// the budget in every run) and enforced budgets that went over in some run (flaky). +pub fn enforce_report(budgets: &Budgets, runs: &[Value]) -> (Vec, Vec) { + let (mut could, mut flaky) = (Vec::new(), Vec::new()); + let margin = budgets.settings.enforce_margin; + for sc in &budgets.scenario { + let (Some(budget), None) = (sc.budget_ms, &sc.not_measurable) else { continue }; + let key = format!("{}_ms", sc.metric.label()); + let vals: Vec = runs.iter().filter_map(|r| r.get("scenarios")?.get(&sc.id)?.get(&key)?.as_f64()).collect(); + let Some(worst) = vals.iter().copied().reduce(f64::max) else { continue }; + let m = sc.metric.label(); + if sc.enforce { + let over = vals.iter().filter(|v| **v > budget).count(); + if over > 0 { + flaky.push(format!("{} {}: over {} ms in {over} of {} runs (worst {m} {})", sc.id, sc.title, fmt_num(budget), runs.len(), fmt_num(worst))); + } + } else if vals.len() == runs.len() && worst <= margin * budget { + could.push(format!("{} {}: worst {m} {} ms ≤ {margin} × {} ms in all {} runs", sc.id, sc.title, fmt_num(worst), fmt_num(budget), runs.len())); + } + } + (could, flaky) } // ---- running --------------------------------------------------------------------------------- @@ -629,10 +811,22 @@ struct Opts { benches: Vec, skip_build: bool, reuse: bool, + /// `--update-baseline --from`: build the baseline from these saved `results.json` files. + from: Vec, + allow_contended: bool, } fn parse_opts(rest: &[&str]) -> Result { - let mut o = Opts { quick: false, update_baseline: false, threshold: None, benches: Vec::new(), skip_build: false, reuse: false }; + let mut o = Opts { + quick: false, + update_baseline: false, + threshold: None, + benches: Vec::new(), + skip_build: false, + reuse: false, + from: Vec::new(), + allow_contended: false, + }; let mut it = rest.iter(); while let Some(a) = it.next() { match *a { @@ -648,9 +842,14 @@ fn parse_opts(rest: &[&str]) -> Result { o.threshold = Some(v); } "--bench" => o.benches.push(it.next().ok_or("--bench needs a name")?.to_string()), + "--from" => o.from.push(PathBuf::from(it.next().ok_or("--from needs a results.json path")?)), + "--allow-contended" => o.allow_contended = true, other => return Err(format!("perf: unknown option `{other}`")), } } + if !o.from.is_empty() && !o.update_baseline { + return Err("--from builds a baseline: use it with --update-baseline".into()); + } Ok(o) } @@ -670,6 +869,10 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { let o = parse_opts(rest)?; let text = std::fs::read_to_string(root.join(BUDGETS)).map_err(|e| format!("read {BUDGETS}: {e}"))?; let budgets = parse_budgets(&text)?; + let baseline_value: Option = std::fs::read_to_string(root.join(BASELINE)).ok().and_then(|t| serde_json::from_str(&t).ok()); + if !o.from.is_empty() { + return baseline_from_files(root, &budgets, baseline_value.as_ref(), &o); + } let mode = if o.quick { "quick" } else { "full" }; let threshold = o.threshold.unwrap_or(budgets.settings.regression_pct); let target = target_dir()?; @@ -699,6 +902,9 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { plan.push((b, args)); } + // Sampled before the build: the harness's own compile isn't contention. The load after the + // build is still recorded, as the first bench's `load_avg_before`. + let load_start = load_avg(); if !o.skip_build { let mut by_pkg: BTreeMap<&str, Vec<&str>> = BTreeMap::new(); for (b, _) in &plan { @@ -714,7 +920,6 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { } } - let load_start = load_avg(); let mut reports: BTreeMap> = BTreeMap::new(); let mut bench_meta = serde_json::Map::new(); for (b, args) in &plan { @@ -786,7 +991,6 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { obj.insert("class".into(), json!(class)); } - let baseline_value: Option = std::fs::read_to_string(root.join(BASELINE)).ok().and_then(|t| serde_json::from_str(&t).ok()); let (baseline, baseline_note) = match baseline_value.as_ref().map(|b| baseline_for(b, &class, mode)) { Some(Ok(b)) => (Some(b), None), Some(Err(e)) => (None, Some(e)), @@ -823,6 +1027,7 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { let bench_failures: Vec = reports.iter().filter_map(|(n, r)| r.as_ref().err().map(|e| format!("bench {n}: {e}"))).collect(); let commit = git(root, &["rev-parse", "HEAD"]); let dirty = git(root, &["status", "--porcelain"]).is_some_and(|s| !s.is_empty()); + let is_contended = contended(load_start, m.get("cores").and_then(Value::as_u64).map(|c| c as usize), budgets.settings.max_load_per_core); let results = json!({ "schema": 1, "mode": mode, @@ -832,6 +1037,7 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { "machine": m, "load_avg_start": load_start, "load_avg_end": load_end, + "contended": is_contended, "threshold_pct": threshold, "baseline_note": baseline_note, "benches": bench_meta, @@ -846,14 +1052,54 @@ pub fn run(root: &Path, rest: &[&str]) -> Result<(), String> { println!("\n{summary}"); println!("wrote {}", out_dir.join("results.json").display()); + let mut errors: Vec = Vec::new(); if o.update_baseline { - let nb = updated_baseline(baseline_value.as_ref(), &results); - let text = serde_json::to_string_pretty(&nb).map_err(|e| format!("encode baseline: {e}"))?; - write(&root.join(BASELINE), &format!("{text}\n"))?; - println!("updated {BASELINE} ({mode}, machine class {class})"); + // The results are written either way; a contended run never silently becomes the baseline. + let rules = BaselineRules { min_runs: 1, max_load_per_core: budgets.settings.max_load_per_core, allow_contended: o.allow_contended }; + match baseline_from_runs(baseline_value.as_ref(), std::slice::from_ref(&results), &rules) { + Ok(nb) => { + write_baseline(root, &nb)?; + println!("updated {BASELINE} ({mode}, machine class {class}{})", if is_contended { ", labelled contended" } else { "" }); + } + // A refused baseline still reports this run's perf failures below. + Err(e) => errors.push(e), + } } let all: Vec<&String> = failures.iter().chain(&bench_failures).collect(); - if all.is_empty() { Ok(()) } else { Err(format!("{} perf failure(s):\n {}", all.len(), all.iter().map(|s| s.as_str()).collect::>().join("\n "))) } + if !all.is_empty() { + errors.push(format!("{} perf failure(s):\n {}", all.len(), all.iter().map(|s| s.as_str()).collect::>().join("\n "))); + } + if errors.is_empty() { Ok(()) } else { Err(errors.join("\n")) } +} + +fn write_baseline(root: &Path, baseline: &Value) -> Result<(), String> { + let text = serde_json::to_string_pretty(baseline).map_err(|e| format!("encode baseline: {e}"))?; + write(&root.join(BASELINE), &format!("{text}\n")) +} + +/// `--update-baseline --from ...`: no benches run. Prints the enforcement report. +fn baseline_from_files(root: &Path, budgets: &Budgets, old: Option<&Value>, o: &Opts) -> Result<(), String> { + let runs = o + .from + .iter() + .map(|p| { + let t = std::fs::read_to_string(p).map_err(|e| format!("read {}: {e}", p.display()))?; + serde_json::from_str::(&t).map_err(|e| format!("{}: {e}", p.display())) + }) + .collect::, _>>()?; + let (could, flaky) = enforce_report(budgets, &runs); + let list = |v: &[String]| if v.is_empty() { " none".to_string() } else { v.iter().map(|l| format!(" {l}")).collect::>().join("\n") }; + println!("Budgets that could be enforced (within {} of the budget in every run):\n{}", budgets.settings.enforce_margin, list(&could)); + println!("Enforced budgets that went over in some run (flaky):\n{}", list(&flaky)); + let rules = BaselineRules { + min_runs: budgets.settings.baseline_min_runs, + max_load_per_core: budgets.settings.max_load_per_core, + allow_contended: o.allow_contended, + }; + let nb = baseline_from_runs(old, &runs, &rules)?; + write_baseline(root, &nb)?; + println!("updated {BASELINE} from {} runs (machine class {})", runs.len(), nb.get("machine_class").and_then(Value::as_str).unwrap_or("?")); + Ok(()) } /// The committed baseline's full-mode numbers judged against the budgets (what the scorecard @@ -911,6 +1157,9 @@ pub fn render_summary(results: &Value, outcomes: &[Outcome], baseline_note: Opti fmt_load(results.get("load_avg_start")), fmt_load(results.get("load_avg_end")), ); + if results.get("contended").and_then(Value::as_bool) == Some(true) { + out.push_str("- **contended run**: numbers measure machine load (the 1-minute load at the start was above `max_load_per_core` per core)\n"); + } if let Some(n) = baseline_note { out.push_str(&format!("- {n}\n")); } @@ -1068,10 +1317,199 @@ not_measurable = "needs a frame harness" assert_eq!(counts(&out), (0, 0, 0, 1), "not-run scenarios are not tracked; the scorecard counts them separately"); } + fn rules(min_runs: usize, allow_contended: bool) -> BaselineRules { + BaselineRules { min_runs, max_load_per_core: 1.0, allow_contended } + } + + /// The plain `--update-baseline` case: one run. + fn one(old: Option<&Value>, results: &Value) -> Value { + baseline_from_runs(old, std::slice::from_ref(results), &rules(1, false)).unwrap() + } + + /// A saved run of class `c` with one p50 (and p95) per scenario. + fn run_of(date: &str, load: f64, rows: &[(&str, f64)]) -> Value { + let sc: serde_json::Map = + rows.iter().map(|(k, v)| (k.to_string(), json!({"n": 5, "p50_ms": v, "p95_ms": v * 1.5, "max_ms": v * 2.0}))).collect(); + json!({"mode": "full", "date": date, "commit": format!("c-{date}"), "dirty": false, "machine": {"class": "c", "cores": 3}, "load_avg_start": [load, load, load], "scenarios": sc}) + } + + #[test] + fn contention_is_judged_on_start_load_per_core() { + assert!(contended(Some([224.9, 226.31, 196.03]), Some(14), 1.0), "the committed 2026-10-05 baseline"); + assert!(!contended(Some([0.5, 3.0, 9.0]), Some(12), 1.0), "only the 1-minute load counts"); + assert!(!contended(None, Some(12), 1.0), "no load (Windows): can't judge"); + assert!(!contended(Some([50.0, 0.0, 0.0]), None, 1.0)); + assert!(!contended(Some([9.5, 0.0, 0.0]), Some(3), 4.0), "the threshold is configurable"); + assert!(contended(Some([9.5, 0.0, 0.0]), Some(3), 3.0)); + assert!(run_contended(Some(&json!([224.9, 226.31, 196.03])), Some(&json!({"cores": 14})), 1.0)); + } + + #[test] + fn update_baseline_refuses_contended_run_unless_allowed() { + let mut r = run_of("2026-10-05", 224.9, &[("P1", 3.0)]); + r["machine"]["cores"] = json!(14); + let e = baseline_from_runs(None, std::slice::from_ref(&r), &rules(1, false)).unwrap_err(); + assert!(e.contains("224.90") && e.contains("14 cores") && e.contains("--allow-contended"), "{e}"); + let b = baseline_from_runs(None, std::slice::from_ref(&r), &rules(1, true)).unwrap(); + let m = &b["modes"]["full"]; + assert_eq!(m["contended"], json!(true)); + assert_eq!(m["cores"], json!(14)); + assert_eq!(m["runs"], json!(1)); + // A quiet run isn't labelled, and one run has no noise ceiling. + let b = one(None, &run_of("d", 0.5, &[("P1", 3.0)])); + assert!(b["modes"]["full"].get("contended").is_none()); + assert!(b["modes"]["full"]["scenarios"]["P1"].get("p50_max_ms").is_none()); + } + + #[test] + fn baseline_from_runs_takes_median_and_noise_ceiling() { + let runs: Vec = [(1, 2174.0, 30.5), (2, 2868.0, 45.3), (3, 2000.0, 28.0), (4, 2500.0, 31.0), (5, 2300.0, 40.0)] + .iter() + .map(|(d, a, b)| run_of(&format!("2026-10-2{d}"), 1.0, &[("P44", *a), ("P46", *b)])) + .collect(); + let b = baseline_from_runs(None, &runs, &rules(5, false)).unwrap(); + let m = &b["modes"]["full"]; + assert_eq!(m["runs"], json!(5)); + assert_eq!(m["date"], json!("2026-10-25"), "the latest run dates the baseline"); + assert_eq!(m["run_list"].as_array().map(Vec::len), Some(5)); + assert_eq!(m["run_list"][0]["load_avg_start"], json!([1.0, 1.0, 1.0])); + assert_eq!(m["run_list"][0]["contended"], json!(false)); + let got = baseline_for(&b, "c", "full").unwrap(); + let p44 = &got["P44"]; + assert_eq!((p44.p50, p44.p50_max, p44.n), (Some(2300.0), Some(2868.0), 25)); + assert_eq!(got["P46"].p50, Some(31.0)); + assert_eq!(median(&mut [4.0, 1.0, 3.0, 2.0]), Some(2.5)); + } + + #[test] + fn baseline_from_runs_keeps_a_row_failed_in_any_run() { + let mut runs: Vec = (1..=3).map(|d| run_of(&format!("2026-10-2{d}"), 1.0, &[("P1", 3.0), ("P2", 5.0)])).collect(); + runs[1]["scenarios"]["P1"] = json!({"status": format!("{MISSING_PREFIX}bench crashed")}); + let b = baseline_from_runs(None, &runs, &rules(3, false)).unwrap(); + let m = &b["modes"]["full"]; + assert!(m["scenarios"].get("P1").is_none(), "no partial aggregate: {m}"); + assert_eq!(m["failed"]["P1"], json!("bench crashed")); + assert_eq!(m["scenarios"]["P2"]["p50_ms"], json!(5.0)); + assert!(m["failed"].get("P2").is_none()); + } + + #[test] + fn baseline_from_runs_leaves_out_a_row_missing_from_some_runs() { + let mut runs: Vec = (1..=3).map(|d| run_of(&format!("2026-10-2{d}"), 1.0, &[("P1", 3.0), ("P2", 5.0)])).collect(); + runs[0]["scenarios"].as_object_mut().unwrap().remove("P1"); + let b = baseline_from_runs(None, &runs, &rules(3, false)).unwrap(); + let m = &b["modes"]["full"]; + assert!(m["scenarios"].get("P1").is_none(), "2 of 3 runs is no baseline: {m}"); + assert_eq!(m["scenarios"]["P2"]["p50_ms"], json!(5.0)); + assert_eq!(m["runs"], json!(3)); + } + + #[test] + fn baseline_from_runs_rejects_mixed_classes_modes_dirty_and_too_few() { + let runs: Vec = (1..=5).map(|d| run_of(&format!("2026-10-2{d}"), 1.0, &[("P1", 3.0)])).collect(); + assert!(baseline_from_runs(None, &runs, &rules(5, false)).is_ok()); + assert!(baseline_from_runs(None, &runs[..4], &rules(5, false)).unwrap_err().contains("at least 5")); + let mut m = runs.clone(); + m[2]["machine"]["class"] = json!("other"); + assert!(baseline_from_runs(None, &m, &rules(5, false)).unwrap_err().contains("machine classes")); + let mut m = runs.clone(); + m[2]["mode"] = json!("quick"); + assert!(baseline_from_runs(None, &m, &rules(5, false)).unwrap_err().contains("modes")); + let mut m = runs.clone(); + m[2]["dirty"] = json!(true); + assert!(baseline_from_runs(None, &m, &rules(5, false)).unwrap_err().contains("dirty")); + let mut m = runs.clone(); + m[2]["load_avg_start"] = json!([9.5, 9.0, 9.0]); + assert!(baseline_from_runs(None, &m, &rules(5, false)).unwrap_err().contains("contended")); + assert_eq!(baseline_from_runs(None, &m, &rules(5, true)).unwrap()["modes"]["full"]["run_list"][2]["contended"], json!(true)); + } + + #[test] + fn regression_is_judged_against_the_noise_ceiling() { + // Runner numbers (macos-15, 7 nightlies): median and highest p50 per row. + let b = parse_budgets(TOML).unwrap(); + let s = &b.settings; + let sc = &b.scenario[1]; // no enforced budget in play: opacity, budget 20, not enforced + let base = |p50: f64, max: f64| Stats { p50: Some(p50), p50_max: Some(max), ..Default::default() }; + let cur = |p50: f64| Stats { p50: Some(p50), ..Default::default() }; + assert_eq!(verdict(sc, &cur(3935.0), Some(&base(2174.0, 2868.0)), s, 15.0, false), Status::Regressed, "P44 +81 % (#5694)"); + assert_eq!(verdict(sc, &cur(76.9), Some(&base(30.5, 45.3)), s, 15.0, false), Status::Regressed, "P46 +152 % (#5697)"); + assert_eq!(verdict(sc, &cur(387.0), Some(&base(258.0, 448.0)), s, 15.0, false), Status::Tracked, "P11 +50 % (#5695) is within runner noise"); + // A single-run baseline falls back to its p50. + let single = Stats { p50: Some(258.0), ..Default::default() }; + assert_eq!(verdict(sc, &cur(387.0), Some(&single), s, 15.0, false), Status::Regressed); + } + + #[test] + fn enforce_report_needs_margin_in_every_run() { + let toml = r#" +[[bench]] +name = "b" +package = "p" + +[[scenario]] +id = "P16" +title = "dab" +bench = "b" +row = "r16" +budget_ms = 100 +enforce = false + +[[scenario]] +id = "P29" +title = "wand" +bench = "b" +row = "r29" +budget_ms = 100 +enforce = false + +[[scenario]] +id = "P30" +title = "liquify" +bench = "b" +row = "r30" +budget_ms = 100 +enforce = false + +[[scenario]] +id = "P25" +title = "cancel" +bench = "b" +row = "r25" +budget_ms = 200 + +[[scenario]] +id = "P99" +title = "track" +bench = "b" +row = "r99" +"#; + let b = parse_budgets(toml).unwrap(); + // run_of stores p95 = 1.5 × p50 (the default metric is p95). + let runs: Vec = [(30.0, 20.0, 30.0, 100.0), (35.2, 22.0, 45.0, 110.0), (20.0, 22.0, 30.0, 199.4)] + .iter() + .enumerate() + .map(|(i, (a, c, d, e))| run_of(&format!("d{i}"), 1.0, &[("P16", *a), ("P29", *c), ("P30", *d), ("P25", *e), ("P99", 1.0)])) + .collect(); + let (could, flaky) = enforce_report(&b, &runs); + assert_eq!(could.len(), 2, "{could:?}"); + assert!(could[0].starts_with("P16 ") && could[0].contains("52.8"), "{could:?}"); + assert!(could[1].starts_with("P29 ")); + assert!(!could.iter().any(|l| l.starts_with("P30")), "67.5 > 60 once: not suggested"); + assert_eq!(flaky.len(), 1, "{flaky:?}"); + assert!(flaky[0].starts_with("P25 ") && flaky[0].contains("in 1 of 3 runs"), "{flaky:?}"); + // A row missing from one run can't be vouched for. + let mut gap = runs.clone(); + if let Some(o) = gap[1]["scenarios"].as_object_mut() { + o.remove("P29"); + } + assert!(!enforce_report(&b, &gap).0.iter().any(|l| l.starts_with("P29"))); + } + #[test] fn baselines_never_cross_machine_classes() { let results = json!({"mode": "full", "date": "d", "commit": "c", "machine": {"class": "macos-aarch64-m4"}, "scenarios": {"P1": {"p50_ms": 3.0, "p95_ms": 4.0, "max_ms": 5.0, "n": 3}, "P3": {"status": "not measurable yet"}}}); - let b = updated_baseline(None, &results); + let b = one(None, &results); let got = baseline_for(&b, "macos-aarch64-m4", "full").unwrap(); assert_eq!(got.get("P1").and_then(|s| s.p50), Some(3.0)); assert!(!got.contains_key("P3"), "rows without numbers are not baselined"); @@ -1079,18 +1517,18 @@ not_measurable = "needs a frame harness" assert!(baseline_for(&b, "macos-aarch64-m4", "quick").is_err()); // Same class: the other mode is kept. New class: replaced. let quick = json!({"mode": "quick", "machine": {"class": "macos-aarch64-m4"}, "scenarios": {"P1": {"p50_ms": 1.0}}}); - let b2 = updated_baseline(Some(&b), &quick); + let b2 = one(Some(&b), &quick); assert!(baseline_for(&b2, "macos-aarch64-m4", "full").is_ok()); assert!(baseline_for(&b2, "macos-aarch64-m4", "quick").is_ok()); // A crashed row is kept as a failure, and the scorecard shows it. let crashed = json!({"mode": "full", "machine": {"class": "c"}, "scenarios": {"P1": {"status": "**missing**: panicked: boom"}}}); - let bc = updated_baseline(None, &crashed); + let bc = one(None, &crashed); let b = parse_budgets(TOML).unwrap(); let o = outcomes_from_baseline(&b, Some(&bc)); assert_eq!(o[0].status, Status::Missing("panicked: boom".into())); assert_eq!(o[1].status, Status::NotRun); let other = json!({"mode": "quick", "machine": {"class": "other"}, "scenarios": {}}); - let b3 = updated_baseline(Some(&b2), &other); + let b3 = one(Some(&b2), &other); assert!(baseline_for(&b3, "other", "full").is_err()); } @@ -1127,5 +1565,11 @@ not_measurable = "needs a frame harness" assert!(o.quick && o.reuse && o.skip_build); assert_eq!(o.threshold, Some(20.0)); assert_eq!(o.benches, ["a"]); + assert!(!o.allow_contended && o.from.is_empty()); + let o = parse_opts(&["--update-baseline", "--from", "a.json", "--from", "b.json", "--allow-contended"]).unwrap(); + assert!(o.update_baseline && o.allow_contended); + assert_eq!(o.from, [PathBuf::from("a.json"), PathBuf::from("b.json")]); + assert!(parse_opts(&["--from", "a.json"]).is_err(), "--from needs --update-baseline"); + assert!(parse_opts(&["--update-baseline", "--from"]).is_err()); } } diff --git a/xtask/src/scorecard.rs b/xtask/src/scorecard.rs index 5c9985c945..69352ea0ff 100644 --- a/xtask/src/scorecard.rs +++ b/xtask/src/scorecard.rs @@ -17,7 +17,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use serde::Deserialize; -use serde_json::Value; +use serde_json::{Value, json}; use crate::perf; @@ -591,12 +591,14 @@ here supersede estimates elsewhere.\n\n## Summary\n\n| Area | Done | Partial | M // Performance. s.push_str("\n## Performance\n\n"); + let class = inp.baseline.as_ref().and_then(|b| b.get("machine_class")).and_then(Value::as_str).unwrap_or("none"); s.push_str(&format!( "Budgets: `perf/budgets.toml` (targets from #209, #210, #211). Numbers: the committed baseline \ (`perf/baseline.json`, full run), updated only by `cargo xtask perf --update-baseline`. The nightly \ `perf-nightly` workflow runs `cargo xtask perf` on a fixed macOS runner and fails on a broken enforced \ -budget or a p50 regression over {:.0} % against a baseline from the same machine class. \"Over budget\" \ -rows are targets the code doesn't meet yet: they are reported, and only their regressions fail.\n\n", +budget. Its p50 regression check (over {:.0} %, against the baseline's highest p50 when it was built from \ +several runs) runs only on machine class `{class}`, the baseline's. \"Over budget\" rows are targets the \ +code doesn't meet yet: they are reported, and only their regressions fail.\n\n", inp.budgets.settings.regression_pct )); match (&base_date, full) { @@ -604,12 +606,22 @@ rows are targets the code doesn't meet yet: they are reported, and only their re let load = perf::fmt_load(f.get("load_avg_start")); let commit = f.get("commit").and_then(Value::as_str).map_or_else(|| "unknown".into(), |c| c.get(..10).unwrap_or(c).to_string()); let ram = machine.and_then(|m| m.get("ram_bytes")).and_then(Value::as_u64).map_or_else(|| "?".into(), |b| format!("{} GB", b >> 30)); + let runs = f.get("runs").and_then(Value::as_u64).unwrap_or(1); + let runs = if runs == 1 { "1 run".to_string() } else { format!("{runs} runs (median p50; the latest run's date and commit)") }; s.push_str(&format!( - "Baseline: {d}, commit `{commit}`, {} ({ram}), GPU {}, {}; load average {load} (1/5/15 min) at the start of the run.\n\n", + "Baseline: {d}, {runs}, commit `{commit}`, {} ({ram}), GPU {}, {}; load average {load} (1/5/15 min) at the start of the run.\n\n", ms("cpu"), ms("gpu_adapter"), ms("os_version") )); + let cores = f.get("cores").or_else(|| machine.and_then(|m| m.get("cores"))); + let contended = f.get("contended").and_then(Value::as_bool) == Some(true) + || perf::run_contended(f.get("load_avg_start"), Some(&json!({"cores": cores})), inp.budgets.settings.max_load_per_core); + if contended { + let one = f.get("load_avg_start").and_then(|l| l.get(0)).and_then(Value::as_f64).map_or_else(|| "?".into(), |x| format!("{x:.2}")); + let n = cores.and_then(Value::as_u64).map_or_else(|| "?".into(), |c| c.to_string()); + s.push_str(&format!("**contended baseline** (load {one} on {n} cores): these numbers measure machine load, not the code.\n\n")); + } } _ => s.push_str("Baseline: **not run** (no `perf/baseline.json` full run yet).\n\n"), } @@ -891,6 +903,29 @@ cc c.psd assert_eq!(anchor("File compatibility"), "file-compatibility"); } + #[test] + fn scorecard_labels_a_contended_baseline() { + let mut inp = gather(&crate::root()).unwrap_or_else(|e| panic!("{e}")); + let base = |load: f64, extra: Value| { + let mut full = json!({"date": "2026-10-05T00:00:00Z", "commit": "f5d2bcb54abd", "load_avg_start": [load, 1.0, 1.0], "scenarios": {}}); + if let (Some(f), Some(x)) = (full.as_object_mut(), extra.as_object()) { + f.extend(x.clone()); + } + json!({"machine_class": "mac-m4", "machine": {"cores": 14, "cpu": "Apple M4 Pro"}, "modes": {"full": full}}) + }; + inp.baseline = Some(base(224.9, json!({}))); + let a = render(&inp); + assert!(a.contains("**contended baseline** (load 224.90 on 14 cores)"), "labelled from the load the baseline already has"); + assert!(a.contains("runs only on machine class `mac-m4`")); + assert!(a.contains("2026-10-05, 1 run,")); + inp.baseline = Some(base(2.0, json!({"runs": 5}))); + let a = render(&inp); + assert!(!a.contains("contended baseline")); + assert!(a.contains("5 runs (median p50")); + inp.baseline = Some(base(2.0, json!({"contended": true, "cores": 3}))); + assert!(render(&inp).contains("(load 2.00 on 3 cores)"), "a baseline recorded with --allow-contended"); + } + #[test] fn staleness_check_and_determinism() { let root = crate::root();