1use std::collections::HashMap;
10use std::fmt::Write as _;
11use std::path::Path;
12
13use indexmap::IndexMap;
14use serde::{Deserialize, Serialize};
15use serde_json::Value as Json;
16
17use crate::config::Tolerance;
18use crate::error::EvalError;
19use crate::report::{EvalReport, REPORT_SCHEMA_VERSION, TestStatus};
20
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "snake_case")]
24pub enum Change {
25 Regressed,
26 Improved,
27 Unchanged,
28 New,
30 Missing,
32}
33
34#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
36#[non_exhaustive]
37pub struct Delta {
38 pub name: String,
39 #[serde(default, skip_serializing_if = "Option::is_none")]
40 pub baseline: Option<f64>,
41 #[serde(default, skip_serializing_if = "Option::is_none")]
42 pub current: Option<f64>,
43 pub tolerance: f64,
44 pub change: Change,
45}
46
47#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
49#[non_exhaustive]
50pub struct BaselineComparison {
51 pub path: String,
53 #[serde(default, skip_serializing_if = "String::is_empty")]
55 pub workflow_fingerprint: String,
56 #[serde(default, skip_serializing_if = "Vec::is_empty")]
59 pub judges_changed: Vec<String>,
60 pub regressions: usize,
61 pub improvements: usize,
62 pub metrics: Vec<Delta>,
64 #[serde(default, skip_serializing_if = "Vec::is_empty")]
66 pub tests: Vec<Delta>,
67}
68
69#[derive(Clone, Debug, Default, PartialEq)]
73#[non_exhaustive]
74pub struct Baseline {
75 pub path: String,
77 pub workflow_fingerprint: String,
78 pub metrics: IndexMap<String, f64>,
80 pub pass_rates: IndexMap<String, f64>,
82 pub judges: HashMap<String, String>,
84}
85
86impl Baseline {
87 pub fn load(path: &Path) -> Result<Self, EvalError> {
89 let text = std::fs::read_to_string(path)
90 .map_err(|e| EvalError::Io(format!("cannot read baseline `{}`: {e}", path.display())))?;
91 let report: Json = serde_json::from_str(&text)
92 .map_err(|e| EvalError::invalid(format!("baseline {}: invalid JSON: {e}", path.display())))?;
93 Self::from_json(&path.display().to_string(), &report)
94 .map_err(|why| EvalError::invalid(format!("baseline {}: {why}", path.display())))
95 }
96
97 pub fn from_json(path: &str, report: &Json) -> Result<Self, String> {
99 match report.get("schema_version").and_then(Json::as_u64) {
100 Some(v) if (1..=u64::from(REPORT_SCHEMA_VERSION)).contains(&v) => {}
101 Some(v) => {
102 return Err(format!("report schema version {v} is not supported (1 to {REPORT_SCHEMA_VERSION})"));
103 }
104 None => return Err("not a graphrt eval report (no `schema_version`)".into()),
105 }
106 let text = |v: Option<&Json>| v.and_then(Json::as_str).unwrap_or_default().to_owned();
107 let mut baseline = Self {
108 path: path.to_owned(),
109 workflow_fingerprint: text(report.pointer("/workflow/fingerprint")),
110 ..Self::default()
111 };
112 for (name, m) in report.pointer("/summary/metrics").and_then(Json::as_object).into_iter().flatten() {
113 if m.get("count").and_then(Json::as_u64).unwrap_or_default() > 0 {
114 baseline.metrics.insert(name.clone(), m.get("mean_score").and_then(Json::as_f64).unwrap_or_default());
115 }
116 }
117 let tests = report.get("tests").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default();
118 baseline.pass_rates = pass_rates(tests.iter().map(|t| (text(t.get("id")), text(t.get("status")) == "passed")));
119 for judge in tests.iter().flat_map(|t| t.get("assertions").and_then(Json::as_array).into_iter().flatten()) {
120 if let Some(record) = judge.get("judge") {
121 baseline.judges.insert(text(record.get("workflow")), text(record.get("fingerprint")));
122 }
123 }
124 Ok(baseline)
125 }
126
127 pub fn of(report: &EvalReport, path: &str) -> Self {
129 let tests = &report.tests;
130 Self {
131 path: path.to_owned(),
132 workflow_fingerprint: report.workflow.fingerprint.clone(),
133 metrics: report
134 .summary
135 .metrics
136 .iter()
137 .filter(|(_, m)| m.count > 0)
138 .map(|(k, m)| (k.clone(), m.mean_score))
139 .collect(),
140 pass_rates: pass_rates(tests.iter().map(|t| (t.id.clone(), t.status == TestStatus::Passed))),
141 judges: tests
142 .iter()
143 .flat_map(|t| &t.assertions)
144 .filter_map(|a| a.judge.as_deref())
145 .map(|j| (j.workflow.clone(), j.fingerprint.clone()))
146 .collect(),
147 }
148 }
149}
150
151impl BaselineComparison {
152 pub fn compare(current: &Baseline, baseline: &Baseline, tolerance: &Tolerance) -> Self {
154 let mut judges_changed: Vec<String> = current
155 .judges
156 .iter()
157 .filter(|(path, fingerprint)| baseline.judges.get(*path).is_some_and(|old| old != *fingerprint))
158 .map(|(path, _)| path.clone())
159 .collect();
160 judges_changed.sort();
161 let mut comparison = Self {
162 path: baseline.path.clone(),
163 workflow_fingerprint: baseline.workflow_fingerprint.clone(),
164 judges_changed,
165 metrics: diff(¤t.metrics, &baseline.metrics, |name| tolerance.of(name)),
166 tests: diff(¤t.pass_rates, &baseline.pass_rates, |_| tolerance.test_tolerance),
167 ..Self::default()
168 };
169 comparison.tests.retain(|d| d.change != Change::Unchanged);
170 let count = |change| comparison.metrics.iter().chain(&comparison.tests).filter(|d| d.change == change).count();
171 comparison.regressions = count(Change::Regressed);
172 comparison.improvements = count(Change::Improved);
173 comparison
174 }
175}
176
177impl EvalReport {
178 pub fn apply_baseline(&mut self, baseline: &Baseline, tolerance: &Tolerance) {
181 let comparison = BaselineComparison::compare(&Baseline::of(self, ""), baseline, tolerance);
182 let regressions = comparison.regressions;
183 self.summary.gate.require(regressions == 0, || format!("{regressions} regression(s) vs the baseline"));
184 self.baseline = Some(comparison);
185 }
186}
187
188fn pass_rates(results: impl Iterator<Item = (String, bool)>) -> IndexMap<String, f64> {
190 let mut counts: IndexMap<String, (u32, u32)> = IndexMap::new();
191 for (id, passed) in results {
192 let entry = counts.entry(id).or_default();
193 entry.0 += u32::from(passed);
194 entry.1 += 1;
195 }
196 counts.into_iter().map(|(id, (passed, n))| (id, f64::from(passed) / f64::from(n.max(1)))).collect()
197}
198
199fn diff(
200 current: &IndexMap<String, f64>,
201 baseline: &IndexMap<String, f64>,
202 tolerance: impl Fn(&str) -> f64,
203) -> Vec<Delta> {
204 let mut deltas: Vec<Delta> = current
205 .iter()
206 .map(|(name, &now)| {
207 let tolerance = tolerance(name);
208 let before = baseline.get(name).copied();
209 let change = match before {
210 None => Change::New,
211 Some(before) if now < before - tolerance - 1e-9 => Change::Regressed,
212 Some(before) if now > before + tolerance + 1e-9 => Change::Improved,
213 Some(_) => Change::Unchanged,
214 };
215 Delta { name: name.clone(), baseline: before, current: Some(now), tolerance, change }
216 })
217 .collect();
218 deltas.extend(baseline.iter().filter(|(name, _)| !current.contains_key(*name)).map(|(name, &before)| Delta {
219 name: name.clone(),
220 baseline: Some(before),
221 current: None,
222 tolerance: tolerance(name),
223 change: Change::Missing,
224 }));
225 deltas
226}
227
228pub fn format_baseline(b: &BaselineComparison) -> String {
230 let mut out = String::new();
231 let _ = writeln!(out, "\nbaseline {}: {} regression(s), {} improvement(s)", b.path, b.regressions, b.improvements);
232 for judge in &b.judges_changed {
233 let _ = writeln!(out, " note: judge {judge} changed since the baseline");
234 }
235 let value = |v: Option<f64>| v.map_or_else(|| "-".to_owned(), |v| format!("{v:.3}"));
236 for (kind, deltas) in [("metric", &b.metrics), ("test", &b.tests)] {
237 for d in deltas.iter().filter(|d| matches!(d.change, Change::Regressed | Change::Improved)) {
238 let label = if d.change == Change::Regressed { "REGRESSED" } else { "improved " };
239 let _ = writeln!(
240 out,
241 " {label} {kind} {:<28} {} -> {} (tolerance {:.2})",
242 d.name,
243 value(d.baseline),
244 value(d.current),
245 d.tolerance
246 );
247 }
248 }
249 out
250}
251
252#[cfg(test)]
253mod tests {
254 #![allow(clippy::unwrap_used, clippy::indexing_slicing)]
255
256 use super::*;
257 use crate::assertion::AssertionResult;
258 use crate::judge::JudgeRecord;
259 use crate::report::{RunSummary, Summary, TestResult, WorkflowInfo};
260 use serde_json::Map;
261
262 fn test(id: &str, trial: u32, pass: bool, faithfulness: f64, judge_fingerprint: &str) -> TestResult {
263 let mut judged = AssertionResult::new("judge", faithfulness >= 0.5, faithfulness, 1.0, "");
264 judged.metric = Some("faithfulness".into());
265 judged.judge = Some(Box::new(JudgeRecord {
266 workflow: "judges/faithfulness.yaml".into(),
267 fingerprint: judge_fingerprint.into(),
268 ..JudgeRecord::default()
269 }));
270 TestResult {
271 id: id.into(),
272 description: None,
273 source: "inline".into(),
274 tags: vec![],
275 trial,
276 status: if pass { TestStatus::Passed } else { TestStatus::Failed },
277 pass,
278 score: f64::from(u8::from(pass)),
279 reason: None,
280 vars: Map::new(),
281 expected: None,
282 run: RunSummary::default(),
283 assertions: vec![judged],
284 }
285 }
286
287 fn report(tests: Vec<TestResult>) -> EvalReport {
288 EvalReport {
289 schema_version: REPORT_SCHEMA_VERSION,
290 graphrt_version: "0".into(),
291 suite: "s".into(),
292 description: None,
293 workflow: WorkflowInfo { path: "w".into(), name: String::new(), fingerprint: "f".into() },
294 started_at_ms: 0,
295 summary: Summary::of(&tests, 0.0, 1),
296 cases: vec![],
297 calibration: None,
298 baseline: None,
299 tests,
300 }
301 }
302
303 fn baseline_of(report: &EvalReport) -> Baseline {
305 let json: Json = serde_json::from_str(&report.to_json().unwrap()).unwrap();
306 Baseline::from_json("prev.json", &json).unwrap()
307 }
308
309 #[test]
310 fn reads_baselines_of_every_schema_version() {
311 let mut json: Json =
312 serde_json::from_str(&report(vec![test("a", 0, true, 0.9, "j")]).to_json().unwrap()).unwrap();
313 json["schema_version"] = 1.into();
314 assert_eq!(Baseline::from_json("v1", &json).unwrap().pass_rates["a"], 1.0);
315 json["schema_version"] = 99.into();
316 assert!(Baseline::from_json("v99", &json).unwrap_err().contains("99 is not supported"));
317 assert!(Baseline::from_json("x", &serde_json::json!({})).unwrap_err().contains("not a graphrt eval report"));
318 }
319
320 #[test]
321 fn detects_regressions_beyond_tolerance() {
322 let baseline = report(vec![
323 test("a", 0, true, 1.0, "j1"),
324 test("a", 1, true, 1.0, "j1"),
325 test("b", 0, true, 0.9, "j1"),
326 test("gone", 0, true, 0.8, "j1"),
327 ]);
328 let current = report(vec![
330 test("a", 0, true, 1.0, "j2"),
331 test("a", 1, false, 0.2, "j2"),
332 test("b", 0, true, 0.9, "j2"),
333 test("new", 0, true, 0.7, "j2"),
334 ]);
335 let tolerance = Tolerance::default();
336 let (current, baseline) = (Baseline::of(¤t, ""), baseline_of(&baseline));
337 let c = BaselineComparison::compare(¤t, &baseline, &tolerance);
338 assert_eq!(c.judges_changed, ["judges/faithfulness.yaml"]);
339 let faithfulness = c.metrics.iter().find(|d| d.name == "faithfulness").unwrap();
340 assert_eq!(faithfulness.change, Change::Regressed, "{faithfulness:?}");
341 let changes: Vec<(&str, Change)> = c.tests.iter().map(|d| (d.name.as_str(), d.change)).collect();
342 assert_eq!(changes, [("a", Change::Regressed), ("new", Change::New), ("gone", Change::Missing)]);
343 assert_eq!((c.regressions, c.improvements), (2, 0));
344 let text = format_baseline(&c);
345 assert!(text.contains("REGRESSED metric faithfulness") && text.contains("REGRESSED test a"), "{text}");
346 assert!(text.contains("judge judges/faithfulness.yaml changed"), "{text}");
347
348 let mut loose = Tolerance { test_tolerance: 0.5, ..Tolerance::default() };
350 loose.metrics.insert("faithfulness".into(), 0.3);
351 let c = BaselineComparison::compare(¤t, &baseline, &loose);
352 assert_eq!(c.regressions, 0, "{c:?}");
353 let c = BaselineComparison::compare(&baseline, ¤t, &tolerance);
354 assert_eq!((c.regressions, c.improvements), (0, 2));
355 }
356
357 #[test]
358 fn identical_reports_do_not_change() {
359 let r = report(vec![test("a", 0, true, 0.9, "j")]);
360 let c = BaselineComparison::compare(&Baseline::of(&r, ""), &baseline_of(&r), &Tolerance::default());
361 assert_eq!((c.regressions, c.improvements), (0, 0));
362 assert!(c.tests.is_empty() && c.judges_changed.is_empty());
363 assert!(c.metrics.iter().all(|d| d.change == Change::Unchanged));
364 }
365}