Skip to main content

trusty_code/bakeoff/
compare.rs

1//! Candidate-versus-baseline comparison (#5441).
2//!
3//! Why: #5441's gate contract asks for two different verdicts from one diff.
4//! A correctness or completion regression — a verifier check that used to pass
5//! and no longer does, a level that used to finish and now times out, a level
6//! that is simply absent — blocks milestone closure outright. A cost, token,
7//! turn, or duration change outside an explicit tolerance does not block, but
8//! it does require a documented disposition; the first qualification attempt
9//! stalled precisely because L3's +27% wall-clock and +50% turns had none.
10//! What: [`compare_against_baseline`] walks every level the baseline covered,
11//! blocks on missing deliverables, pass-rate drops, and status regressions, and
12//! for each of the four performance metrics either records the delta as a note
13//! (inside tolerance, or dispositioned) or blocks on it.
14//! Test: `bakeoff::tests::a_pass_rate_drop_blocks_closure`,
15//! `bakeoff::tests::a_documented_disposition_clears_a_performance_change`.
16
17use std::collections::BTreeMap;
18
19use crate::bakeoff::metadata::LevelMetadata;
20use crate::bakeoff::{Bundle, CLEAN_STATUS, DISPOSITIONS_FILE, GateReport, Rule, Violation};
21
22/// Default percentage change a metric may move before it needs a disposition.
23///
24/// Why: run-to-run variance on a real model is real; blocking on every
25/// percentage point would make the gate noise. 20% is wide enough to absorb
26/// that variance and narrow enough that the L3 change which triggered this
27/// ticket (+27% wall-clock, +50% turns, +22% cost) would have been caught.
28/// What: a percentage, overridable per invocation.
29/// Test: `bakeoff::tests::a_small_change_stays_inside_the_default_tolerance`.
30pub const DEFAULT_TOLERANCE_PCT: f64 = 20.0;
31
32/// A previously accepted bundle to measure the candidate against.
33///
34/// Why: naming the type makes the argument order at the call site unambiguous —
35/// a candidate and a baseline are the same shape, and swapping them silently
36/// inverts every verdict.
37/// What: a newtype over the loaded baseline bundle.
38/// Test: `bakeoff::tests::a_pass_rate_drop_blocks_closure`.
39#[derive(Debug, Clone)]
40pub struct Baseline(pub Bundle);
41
42/// Everything the comparison stage needs beyond the two bundles.
43///
44/// Why: tolerance and dispositions arrive from different places (a flag and a
45/// file in the candidate bundle) and both are optional; bundling them keeps
46/// [`compare_against_baseline`] to three arguments.
47/// What: the tolerance percentage and the disposition map read from
48/// [`DISPOSITIONS_FILE`].
49/// Test: `bakeoff::tests::a_documented_disposition_clears_a_performance_change`.
50#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct ComparisonInputs {
53    /// Percentage change allowed before a metric needs a disposition.
54    pub tolerance_pct: f64,
55    /// Metric key (`L3.turns`) to the operator's written acceptance.
56    pub dispositions: BTreeMap<String, String>,
57}
58
59impl Default for ComparisonInputs {
60    fn default() -> Self {
61        Self {
62            tolerance_pct: DEFAULT_TOLERANCE_PCT,
63            dispositions: BTreeMap::new(),
64        }
65    }
66}
67
68impl ComparisonInputs {
69    /// Load `<bundle>/dispositions.json`, treating an absent file as none.
70    ///
71    /// Why: most bundles have no accepted regression, so requiring the file
72    /// would be ceremony. A file that exists but does not parse is an error,
73    /// not silently-none: an operator who wrote a disposition and typoed the
74    /// JSON must not be told their regression is undispositioned.
75    /// What: returns the parsed map, an empty map when the file is absent, or
76    /// the parse error.
77    /// Test: `bakeoff::tests::a_documented_disposition_clears_a_performance_change`,
78    /// `bakeoff::tests::a_malformed_dispositions_file_is_an_error`.
79    pub fn load(bundle: &Bundle, tolerance_pct: f64) -> Result<Self, String> {
80        let path = bundle.root.join(DISPOSITIONS_FILE);
81        let dispositions = match std::fs::read_to_string(&path) {
82            Ok(raw) => serde_json::from_str(&raw)
83                .map_err(|e| format!("{} is not valid: {e}", path.display()))?,
84            Err(e) if e.kind() == std::io::ErrorKind::NotFound => BTreeMap::new(),
85            Err(e) => return Err(format!("{} unreadable: {e}", path.display())),
86        };
87        Ok(Self {
88            tolerance_pct,
89            dispositions,
90        })
91    }
92}
93
94/// One comparable scalar, named the way its disposition key is written.
95///
96/// Why: four metrics compared by four near-identical code paths is where a
97/// copy-paste bug lives. One table, one loop.
98/// What: the metric's key suffix and its value for a given level.
99/// Test: `bakeoff::tests::token_regression_beyond_tolerance_needs_a_disposition`.
100fn metrics(meta: &LevelMetadata) -> [(&'static str, f64); 4] {
101    [
102        ("turns", meta.run.turns as f64),
103        ("duration_secs", meta.run.duration_secs),
104        ("tokens", meta.run.tokens.total() as f64),
105        ("cost_usd", meta.run.cost_usd.unwrap_or(0.0)),
106    ]
107}
108
109/// Diff a candidate bundle against the previously accepted baseline.
110///
111/// Why: #5441 closes a milestone on "no unexplained regression against the
112/// previous accepted milestone baseline", which is a comparison, not a
113/// threshold — a level that has always taken 40 minutes is fine; one that
114/// suddenly takes 40 is the finding.
115/// What: for every level the baseline covers, blocks when the candidate omits
116/// it, when its verifier pass rate falls, or when its terminal status stops
117/// being [`CLEAN_STATUS`]; then measures the four `metrics` and blocks on a
118/// change beyond `tolerance_pct` unless the candidate carries a disposition for
119/// that metric key. Levels the candidate adds are noted, never blocked.
120/// Test: `bakeoff::tests::a_pass_rate_drop_blocks_closure`,
121/// `bakeoff::tests::a_status_regression_blocks_closure`,
122/// `bakeoff::tests::a_missing_candidate_level_is_a_missing_deliverable`.
123pub fn compare_against_baseline(
124    candidate: &Bundle,
125    baseline: &Baseline,
126    inputs: &ComparisonInputs,
127) -> GateReport {
128    let mut report = GateReport::default();
129    report.notes.push(format!(
130        "compared against baseline {}",
131        baseline.0.root.display()
132    ));
133
134    for (&level, base) in &baseline.0.levels {
135        let Some(cand) = candidate.levels.get(&level) else {
136            report.violations.push(Violation::level(
137                Rule::MissingDeliverable,
138                level,
139                "covered by the baseline but absent from the candidate".to_string(),
140            ));
141            continue;
142        };
143
144        let base_meta = &base.metadata;
145        let cand_meta = &cand.metadata;
146
147        if cand_meta.verifier.checks_passed < base_meta.verifier.checks_passed {
148            report.violations.push(Violation::level(
149                Rule::CorrectnessRegression,
150                level,
151                format!(
152                    "verifier passed {}/{} against the baseline's {}/{}",
153                    cand_meta.verifier.checks_passed,
154                    cand_meta.verifier.checks_total,
155                    base_meta.verifier.checks_passed,
156                    base_meta.verifier.checks_total
157                ),
158            ));
159        }
160
161        if base_meta.run.status == CLEAN_STATUS && cand_meta.run.status != CLEAN_STATUS {
162            report.violations.push(Violation::level(
163                Rule::CorrectnessRegression,
164                level,
165                format!(
166                    "terminal status is {} against the baseline's {CLEAN_STATUS}",
167                    cand_meta.run.status
168                ),
169            ));
170        }
171
172        compare_metrics(level, base_meta, cand_meta, inputs, &mut report);
173    }
174
175    for &level in candidate.levels.keys() {
176        if !baseline.0.levels.contains_key(&level) {
177            report
178                .notes
179                .push(format!("L{level} has no baseline to compare against"));
180        }
181    }
182
183    report
184}
185
186/// Measure one level's four performance metrics against the baseline's.
187///
188/// Why: the tolerance/disposition rule is identical for all four, and #5441
189/// wants the accepted ones recorded rather than silently dropped — a note is
190/// how the next milestone learns that this delta was already looked at.
191/// What: computes the signed percentage change, ignores an improvement or a
192/// change inside tolerance (noting the latter), records a dispositioned
193/// regression as a note, and blocks on an undispositioned one.
194/// Test: `bakeoff::tests::token_regression_beyond_tolerance_needs_a_disposition`,
195/// `bakeoff::tests::an_improvement_never_needs_a_disposition`.
196fn compare_metrics(
197    level: u8,
198    base: &LevelMetadata,
199    cand: &LevelMetadata,
200    inputs: &ComparisonInputs,
201    report: &mut GateReport,
202) {
203    for ((name, base_value), (_, cand_value)) in metrics(base).into_iter().zip(metrics(cand)) {
204        let Some(delta_pct) = percent_change(base_value, cand_value) else {
205            continue;
206        };
207        if delta_pct <= inputs.tolerance_pct {
208            if delta_pct.abs() >= 1.0 {
209                report.notes.push(format!(
210                    "L{level} {name}: {base_value:.3} -> {cand_value:.3} ({delta_pct:+.1}%), within tolerance"
211                ));
212            }
213            continue;
214        }
215
216        let key = format!("L{level}.{name}");
217        match inputs.dispositions.get(&key) {
218            Some(disposition) => report.notes.push(format!(
219                "L{level} {name}: {base_value:.3} -> {cand_value:.3} ({delta_pct:+.1}%), dispositioned: {disposition}"
220            )),
221            None => report.violations.push(Violation::level(
222                Rule::UndispositionedChange,
223                level,
224                format!(
225                    "{name} moved {base_value:.3} -> {cand_value:.3} ({delta_pct:+.1}%), beyond the {:.1}% tolerance; record an accepted disposition under \"{key}\" in {DISPOSITIONS_FILE}",
226                    inputs.tolerance_pct
227                ),
228            )),
229        }
230    }
231}
232
233/// Signed percentage change from `base` to `cand`, when one is meaningful.
234///
235/// Why: a baseline of zero has no percentage change (every increase is
236/// infinite), and a metric that is zero in both runs has not moved. Returning
237/// `None` for those keeps the caller from emitting `inf%` findings on a level
238/// whose cost was simply never priced.
239/// What: `None` when `base` is zero or either value is not finite; otherwise
240/// `(cand - base) / base * 100`. A negative result is an improvement.
241/// Test: `bakeoff::tests::an_unpriced_baseline_metric_reports_no_change`.
242fn percent_change(base: f64, cand: f64) -> Option<f64> {
243    if !base.is_finite() || !cand.is_finite() || base == 0.0 {
244        return None;
245    }
246    Some((cand - base) / base * 100.0)
247}