1use std::fmt::Write as _;
11
12use graphrt_core::Event;
13use graphrt_core::event::Usage;
14use indexmap::IndexMap;
15use serde::{Deserialize, Serialize};
16use serde_json::{Map, Value as Json};
17
18use crate::assertion::AssertionResult;
19use crate::baseline::BaselineComparison;
20use crate::calibration::CalibrationSummary;
21use crate::capture::{RetrievalHit, RunStatus, ToolCallRecord};
22use crate::stats::{pass_at_k, pass_hat_k};
23
24pub const REPORT_SCHEMA_VERSION: u32 = 2;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30pub enum TestStatus {
31 Passed,
33 Failed,
35 Error,
37}
38
39#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
41#[non_exhaustive]
42pub struct RunSummary {
43 pub run_id: String,
44 pub status: RunStatus,
45 #[serde(default, skip_serializing_if = "Option::is_none")]
46 pub error: Option<String>,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub error_type: Option<String>,
49 pub latency_ms: u64,
50 pub usage: Usage,
51 pub output: Json,
53 pub outputs: Map<String, Json>,
54 #[serde(default, skip_serializing_if = "String::is_empty")]
55 pub answer: String,
56 #[serde(default, skip_serializing_if = "Vec::is_empty")]
57 pub tool_calls: Vec<ToolCallRecord>,
58 #[serde(default, skip_serializing_if = "Vec::is_empty")]
59 pub retrieval: Vec<RetrievalHit>,
60 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub events: Option<Vec<Event>>,
63}
64
65#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
67#[non_exhaustive]
68pub struct TestResult {
69 pub id: String,
70 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub description: Option<String>,
72 pub source: String,
74 #[serde(default, skip_serializing_if = "Vec::is_empty")]
75 pub tags: Vec<String>,
76 #[serde(alias = "repeat")]
78 pub trial: u32,
79 pub status: TestStatus,
80 pub pass: bool,
81 pub score: f64,
83 #[serde(default, skip_serializing_if = "Option::is_none")]
85 pub reason: Option<String>,
86 pub vars: Map<String, Json>,
87 #[serde(default, skip_serializing_if = "Option::is_none")]
88 pub expected: Option<Json>,
89 pub run: RunSummary,
90 pub assertions: Vec<AssertionResult>,
91}
92
93impl TestResult {
94 pub fn display_id(&self) -> String {
96 if self.trial == 0 { self.id.clone() } else { format!("{}#{}", self.id, self.trial) }
97 }
98}
99
100#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
102#[non_exhaustive]
103pub struct MetricSummary {
104 pub count: usize,
106 pub passed: usize,
107 pub mean_score: f64,
108 #[serde(default, skip_serializing_if = "is_zero")]
110 pub excluded: usize,
111}
112
113fn no_tokens(usage: &Usage) -> bool {
114 usage.total_tokens == 0
115}
116
117fn is_zero(n: &usize) -> bool {
118 *n == 0
119}
120
121#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
123#[non_exhaustive]
124pub struct LatencySummary {
125 pub mean: f64,
126 pub p50: u64,
127 pub p95: u64,
128 pub max: u64,
129}
130
131#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
133#[non_exhaustive]
134pub struct GateResult {
135 pub pass_rate: f64,
137 #[serde(default, skip_serializing_if = "Option::is_none")]
139 pub pass_hat_k: Option<f64>,
140 pub passed: bool,
141 #[serde(default, skip_serializing_if = "Vec::is_empty")]
143 pub failures: Vec<String>,
144}
145
146impl GateResult {
147 pub fn require(&mut self, ok: bool, failure: impl FnOnce() -> String) {
149 if !ok {
150 self.passed = false;
151 self.failures.push(failure());
152 }
153 }
154}
155
156#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
158#[non_exhaustive]
159pub struct TrialSummary {
160 pub trials: u32,
162 pub k: u32,
163 pub pass_at_k: f64,
165 pub pass_hat_k: f64,
167}
168
169#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
171#[non_exhaustive]
172pub struct CaseSummary {
173 pub id: String,
174 pub trials: u32,
175 pub passed: u32,
176 pub pass_rate: f64,
178 pub pass_at_k: f64,
180 pub pass_hat_k: f64,
182 pub mean_score: f64,
183}
184
185pub fn case_summaries(tests: &[TestResult], k: u32) -> Vec<CaseSummary> {
187 let mut cases: IndexMap<&str, CaseSummary> = IndexMap::new();
188 for test in tests {
189 let case =
190 cases.entry(&test.id).or_insert_with(|| CaseSummary { id: test.id.clone(), ..CaseSummary::default() });
191 case.trials += 1;
192 case.passed += u32::from(test.status == TestStatus::Passed);
193 case.mean_score += test.score;
194 }
195 cases
196 .into_values()
197 .map(|mut case| {
198 let n = case.trials.max(1);
199 case.pass_rate = f64::from(case.passed) / f64::from(n);
200 case.mean_score /= f64::from(n);
201 case.pass_at_k = pass_at_k(case.trials, case.passed, k);
202 case.pass_hat_k = pass_hat_k(case.trials, case.passed, k);
203 case
204 })
205 .collect()
206}
207
208pub fn trial_summary(cases: &[CaseSummary], k: u32) -> TrialSummary {
210 let n = cases.len().max(1) as f64;
211 TrialSummary {
212 trials: cases.iter().map(|c| c.trials).max().unwrap_or_default(),
213 k,
214 pass_at_k: cases.iter().map(|c| c.pass_at_k).sum::<f64>() / n,
215 pass_hat_k: cases.iter().map(|c| c.pass_hat_k).sum::<f64>() / n,
216 }
217}
218
219#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
221#[non_exhaustive]
222pub struct Summary {
223 pub total: usize,
224 pub passed: usize,
225 pub failed: usize,
226 pub errors: usize,
227 pub pass_rate: f64,
229 pub duration_ms: u64,
231 pub usage: Usage,
232 #[serde(default, skip_serializing_if = "no_tokens")]
234 pub judge_usage: Usage,
235 pub latency_ms: LatencySummary,
236 pub metrics: IndexMap<String, MetricSummary>,
237 #[serde(default, skip_serializing_if = "Option::is_none")]
239 pub trials: Option<TrialSummary>,
240 pub gate: GateResult,
241}
242
243impl Summary {
244 pub fn of(tests: &[TestResult], required_pass_rate: f64, duration_ms: u64) -> Self {
246 let total = tests.len();
247 let passed = tests.iter().filter(|t| t.status == TestStatus::Passed).count();
248 let errors = tests.iter().filter(|t| t.status == TestStatus::Error).count();
249 let pass_rate = if total == 0 { 1.0 } else { passed as f64 / total as f64 };
250 let mut usage = Usage::default();
251 for test in tests {
252 usage.add(&test.run.usage);
253 }
254 let mut judge_usage = Usage::default();
255 let mut metrics: IndexMap<String, MetricSummary> = IndexMap::new();
256 for result in tests.iter().flat_map(|t| &t.assertions) {
257 if let Some(judge) = &result.judge {
258 judge_usage.add(&judge.usage);
259 }
260 let entry = metrics.entry(result.metric_name().to_owned()).or_default();
261 if result.excluded {
262 entry.excluded += 1;
263 continue;
264 }
265 entry.count += 1;
266 entry.passed += usize::from(result.pass);
267 entry.mean_score += result.score;
268 }
269 for metric in metrics.values_mut() {
270 metric.mean_score /= metric.count.max(1) as f64;
271 }
272 Self {
273 total,
274 passed,
275 failed: total - passed - errors,
276 errors,
277 pass_rate,
278 duration_ms,
279 usage,
280 judge_usage,
281 latency_ms: latency_summary(tests),
282 metrics,
283 trials: None,
284 gate: {
285 let mut gate =
286 GateResult { pass_rate: required_pass_rate, pass_hat_k: None, passed: true, failures: Vec::new() };
287 gate.require(pass_rate + 1e-9 >= required_pass_rate, || {
288 format!("pass rate {pass_rate:.3} < {required_pass_rate:.3}")
289 });
290 gate
291 },
292 }
293 }
294}
295
296fn latency_summary(tests: &[TestResult]) -> LatencySummary {
297 let mut latencies: Vec<u64> = tests.iter().map(|t| t.run.latency_ms).collect();
298 if latencies.is_empty() {
299 return LatencySummary::default();
300 }
301 latencies.sort_unstable();
302 let percentile = |p: f64| {
303 let rank = ((p * latencies.len() as f64).ceil() as usize).clamp(1, latencies.len());
304 latencies.get(rank - 1).copied().unwrap_or_default()
305 };
306 LatencySummary {
307 mean: latencies.iter().sum::<u64>() as f64 / latencies.len() as f64,
308 p50: percentile(0.5),
309 p95: percentile(0.95),
310 max: latencies.last().copied().unwrap_or_default(),
311 }
312}
313
314#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
316#[non_exhaustive]
317pub struct WorkflowInfo {
318 pub path: String,
319 #[serde(default, skip_serializing_if = "String::is_empty")]
320 pub name: String,
321 #[serde(default, skip_serializing_if = "String::is_empty")]
323 pub fingerprint: String,
324}
325
326#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
328#[non_exhaustive]
329pub struct EvalReport {
330 pub schema_version: u32,
331 pub graphrt_version: String,
333 pub suite: String,
335 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub description: Option<String>,
337 pub workflow: WorkflowInfo,
338 pub started_at_ms: u64,
340 pub summary: Summary,
341 #[serde(default, skip_serializing_if = "Vec::is_empty")]
343 pub cases: Vec<CaseSummary>,
344 #[serde(default, skip_serializing_if = "Option::is_none")]
346 pub calibration: Option<CalibrationSummary>,
347 #[serde(default, skip_serializing_if = "Option::is_none")]
349 pub baseline: Option<BaselineComparison>,
350 pub tests: Vec<TestResult>,
352}
353
354impl EvalReport {
355 pub fn gate_passed(&self) -> bool {
357 self.summary.gate.passed
358 }
359
360 pub fn to_json(&self) -> Result<String, serde_json::Error> {
362 let mut text = serde_json::to_string_pretty(self)?;
363 text.push('\n');
364 Ok(text)
365 }
366
367 pub fn to_junit(&self) -> String {
370 let suite_name = if self.workflow.name.is_empty() { &self.suite } else { &self.workflow.name };
371 let summary = &self.summary;
372 let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
373 let _ = writeln!(
374 xml,
375 "<testsuites name=\"graphrt eval\" tests=\"{}\" failures=\"{}\" errors=\"{}\" time=\"{}\">",
376 summary.total,
377 summary.failed,
378 summary.errors,
379 seconds(summary.duration_ms)
380 );
381 let _ = writeln!(
382 xml,
383 " <testsuite name=\"{}\" tests=\"{}\" failures=\"{}\" errors=\"{}\" time=\"{}\">",
384 xml_escape(suite_name),
385 summary.total,
386 summary.failed,
387 summary.errors,
388 seconds(summary.duration_ms)
389 );
390 for test in &self.tests {
391 let _ = write!(
392 xml,
393 " <testcase name=\"{}\" classname=\"{}\" time=\"{}\"",
394 xml_escape(&test.display_id()),
395 xml_escape(suite_name),
396 seconds(test.run.latency_ms)
397 );
398 let details = failure_details(test);
399 match test.status {
400 TestStatus::Passed => xml.push_str(" />\n"),
401 TestStatus::Failed | TestStatus::Error => {
402 let tag = if test.status == TestStatus::Error { "error" } else { "failure" };
403 let message = test.reason.as_deref().unwrap_or("failed");
404 let _ = writeln!(
405 xml,
406 ">\n <{tag} message=\"{}\" type=\"{}\">{}</{tag}>\n </testcase>",
407 xml_escape(message),
408 if tag == "error" { test.run.error_type.as_deref().unwrap_or("error") } else { "assertion" },
409 xml_escape(&details)
410 );
411 }
412 }
413 }
414 xml.push_str(" </testsuite>\n</testsuites>\n");
415 xml
416 }
417}
418
419fn seconds(ms: u64) -> String {
420 format!("{:.3}", ms as f64 / 1000.0)
421}
422
423fn failure_details(test: &TestResult) -> String {
424 let mut lines = Vec::new();
425 if let Some(error) = &test.run.error {
426 lines.push(format!("run {}: {error}", status_word(test.run.status)));
427 }
428 for a in test.assertions.iter().filter(|a| !a.pass && !a.excluded) {
429 let note = if a.weight == 0.0 { " (report only)" } else { "" };
430 lines.push(format!("{}{note}: {}", a.kind, a.reason));
431 }
432 lines.join("\n")
433}
434
435fn status_word(status: RunStatus) -> &'static str {
436 match status {
437 RunStatus::Succeeded => "succeeded",
438 RunStatus::Failed => "failed",
439 RunStatus::Aborted => "aborted",
440 RunStatus::Paused => "paused",
441 }
442}
443
444pub fn xml_escape(text: &str) -> String {
447 let mut out = String::with_capacity(text.len());
448 for c in text.chars() {
449 match c {
450 '&' => out.push_str("&"),
451 '<' => out.push_str("<"),
452 '>' => out.push_str(">"),
453 '"' => out.push_str("""),
454 '\'' => out.push_str("'"),
455 '\t' | '\n' | '\r' => out.push(c),
456 c if c.is_control() => {}
457 c => out.push(c),
458 }
459 }
460 out
461}
462
463pub fn format_result_line(test: &TestResult) -> String {
465 let label = match test.status {
466 TestStatus::Passed => "PASS ",
467 TestStatus::Failed => "FAIL ",
468 TestStatus::Error => "ERROR",
469 };
470 let mut line =
471 format!(" {label} {:<28} {:>7} ms score {:.2}", test.display_id(), test.run.latency_ms, test.score);
472 if let Some(reason) = &test.reason {
473 let _ = write!(line, " {reason}");
474 }
475 line
476}
477
478pub fn format_summary(report: &EvalReport) -> String {
481 let s = &report.summary;
482 let mut out = String::new();
483 if !s.metrics.is_empty() {
484 out.push_str("\n metric pass mean\n");
485 for (name, m) in &s.metrics {
486 let _ = write!(out, " {name:<30} {:>3}/{:<3} {:>6.3}", m.passed, m.count, m.mean_score);
487 if m.excluded > 0 {
488 let _ = write!(out, " ({} excluded)", m.excluded);
489 }
490 out.push('\n');
491 }
492 }
493 if let Some(t) = &s.trials {
494 let _ = writeln!(out, "\n test case passed pass@{0} pass^{0}", t.k);
495 for c in &report.cases {
496 let _ = writeln!(
497 out,
498 " {:<30} {:>3}/{:<3} {:>6.3} {:>6.3}",
499 c.id, c.passed, c.trials, c.pass_at_k, c.pass_hat_k
500 );
501 }
502 let _ = writeln!(
503 out,
504 "pass@{0} {1:.3}, pass^{0} {2:.3} over {3} case(s), up to {4} trial(s) each",
505 t.k,
506 t.pass_at_k,
507 t.pass_hat_k,
508 report.cases.len(),
509 t.trials
510 );
511 }
512 if let Some(c) = &report.calibration {
513 out.push_str(&crate::calibration::format_calibration(c));
514 }
515 if let Some(b) = &report.baseline {
516 out.push_str(&crate::baseline::format_baseline(b));
517 }
518 let _ = write!(
519 out,
520 "\n{} test(s): {} passed, {} failed, {} error(s); pass rate {:.1}% (gate {:.1}%) in {} ms, {} tokens",
521 s.total,
522 s.passed,
523 s.failed,
524 s.errors,
525 s.pass_rate * 100.0,
526 s.gate.pass_rate * 100.0,
527 s.duration_ms,
528 s.usage.total_tokens
529 );
530 if s.judge_usage.total_tokens > 0 {
531 let _ = write!(out, " (+{} judge tokens)", s.judge_usage.total_tokens);
532 }
533 out.push('\n');
534 if s.gate.passed {
535 out.push_str("gate: PASSED\n");
536 } else {
537 let _ = writeln!(out, "gate: FAILED ({})", s.gate.failures.join("; "));
538 }
539 out
540}
541
542#[cfg(test)]
543mod tests {
544 #![allow(clippy::unwrap_used, clippy::indexing_slicing)]
545
546 use super::*;
547
548 pub(crate) fn result(id: &str, status: TestStatus, latency_ms: u64) -> TestResult {
549 TestResult {
550 id: id.into(),
551 description: None,
552 source: "inline".into(),
553 tags: vec![],
554 trial: 0,
555 status,
556 pass: status == TestStatus::Passed,
557 score: if status == TestStatus::Passed { 1.0 } else { 0.0 },
558 reason: (status != TestStatus::Passed).then(|| "contains: \"x\" not found <in> & out".to_owned()),
559 vars: Map::new(),
560 expected: None,
561 run: RunSummary { latency_ms, ..RunSummary::default() },
562 assertions: vec![AssertionResult::new(
563 "contains",
564 status == TestStatus::Passed,
565 if status == TestStatus::Passed { 1.0 } else { 0.0 },
566 1.0,
567 "r",
568 )],
569 }
570 }
571
572 fn report() -> EvalReport {
573 let tests = vec![
574 result("a", TestStatus::Passed, 10),
575 result("b", TestStatus::Failed, 30),
576 result("c", TestStatus::Error, 20),
577 ];
578 EvalReport {
579 schema_version: REPORT_SCHEMA_VERSION,
580 graphrt_version: "0".into(),
581 suite: "s.eval.yaml".into(),
582 description: None,
583 workflow: WorkflowInfo { path: "w.yaml".into(), name: "wf".into(), fingerprint: "f".into() },
584 started_at_ms: 0,
585 summary: Summary::of(&tests, 0.5, 60),
586 cases: Vec::new(),
587 calibration: None,
588 baseline: None,
589 tests,
590 }
591 }
592
593 #[test]
594 fn summary_and_gate() {
595 let r = report();
596 let s = &r.summary;
597 assert_eq!((s.total, s.passed, s.failed, s.errors), (3, 1, 1, 1));
598 assert!((s.pass_rate - 1.0 / 3.0).abs() < 1e-9);
599 assert!(!s.gate.passed);
600 assert_eq!((s.latency_ms.p50, s.latency_ms.max), (20, 30));
601 assert_eq!(s.metrics["contains"].count, 3);
602 assert!(Summary::of(&r.tests[..1], 1.0, 1).gate.passed);
603 assert!(Summary::of(&[], 1.0, 1).gate.passed);
604 let text = format_summary(&r);
605 assert!(text.contains("1 passed, 1 failed, 1 error(s)") && text.contains("gate: FAILED"), "{text}");
606 assert!(format_result_line(&r.tests[1]).starts_with(" FAIL b"));
607 }
608
609 #[test]
610 fn json_round_trips() {
611 let r = report();
612 let text = r.to_json().unwrap();
613 let back: EvalReport = serde_json::from_str(&text).unwrap();
614 assert_eq!(back, r);
615 let value: Json = serde_json::from_str(&text).unwrap();
616 assert_eq!(value["schema_version"], 2);
617 assert_eq!(value["tests"][1]["status"], "failed");
618 assert_eq!(value["tests"][0]["assertions"][0]["type"], "contains");
619 }
620
621 #[test]
622 fn junit_is_escaped_and_counts_failures() {
623 let xml = report().to_junit();
624 assert!(xml.starts_with("<?xml"));
625 assert!(xml.contains("<testsuite name=\"wf\" tests=\"3\" failures=\"1\" errors=\"1\""), "{xml}");
626 assert!(xml.contains("<testcase name=\"a\" classname=\"wf\" time=\"0.010\" />"), "{xml}");
627 assert!(xml.contains("<failure message=\"contains: "x" not found <in> & out\""), "{xml}");
628 assert!(xml.contains("<error message="), "{xml}");
629 assert_eq!(xml_escape("a\u{1}b<"), "ab<");
630 assert_eq!(xml.matches("<testcase").count(), 3);
631 }
632}