1use std::collections::BTreeMap;
4use std::fmt::Write as _;
5use std::time::Duration;
6
7use rig_core::completion::Usage;
8use serde::{Deserialize, Serialize};
9
10use crate::{Score, ToolCall, Turn};
11
12mod compare;
13
14pub use compare::{CaseChange, Comparison, EvaluatorDelta};
15
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[non_exhaustive]
19pub struct Trial {
20 pub case_id: String,
22 pub repetition: usize,
24 pub output: String,
26 pub tool_calls: Vec<ToolCall>,
28 pub usage: Usage,
30 #[serde(rename = "latency_ms", with = "millis")]
32 pub latency: Duration,
33 #[serde(default, skip_serializing_if = "Option::is_none")]
35 pub error: Option<String>,
36 #[serde(default, skip_serializing_if = "Option::is_none")]
39 pub session_id: Option<String>,
40 #[serde(default, skip_serializing_if = "Vec::is_empty")]
43 pub transcript: Vec<Turn>,
44}
45
46impl Trial {
47 pub fn new(case_id: impl Into<String>, repetition: usize, output: impl Into<String>) -> Self {
50 Self {
51 case_id: case_id.into(),
52 repetition,
53 output: output.into(),
54 tool_calls: Vec::new(),
55 usage: Usage::default(),
56 latency: Duration::ZERO,
57 error: None,
58 session_id: None,
59 transcript: Vec::new(),
60 }
61 }
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[non_exhaustive]
67pub struct TrialResult {
68 pub trial: Trial,
70 pub scores: Vec<Score>,
72}
73
74impl TrialResult {
75 pub fn passed(&self) -> bool {
77 self.scores
78 .iter()
79 .all(|score| score.passed || score.not_applicable)
80 }
81
82 fn skipped(&self) -> bool {
85 self.scores.iter().any(|score| score.not_applicable)
86 }
87
88 pub fn failures(&self) -> impl Iterator<Item = &Score> {
90 self.scores
91 .iter()
92 .filter(|score| !score.passed && !score.not_applicable)
93 }
94}
95
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98#[non_exhaustive]
99pub struct EvaluatorSummary {
100 pub evaluator: String,
102 pub count: usize,
104 pub passed: usize,
106 pub pass_rate: f64,
108 pub mean: f64,
110 #[serde(default)]
113 pub not_applicable: usize,
114 #[serde(default)]
121 pub pass_at_k: Option<f64>,
122 #[serde(default)]
127 pub pass_hat_k: Option<f64>,
128 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub pass_cutoff: Option<f64>,
133}
134
135#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
137#[non_exhaustive]
138pub struct Tokens {
139 pub input: u64,
141 pub output: u64,
143 pub total: u64,
145}
146
147#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct LatencySummary {
151 #[serde(rename = "p50_ms", with = "millis")]
153 pub p50: Duration,
154 #[serde(rename = "p95_ms", with = "millis")]
156 pub p95: Duration,
157}
158
159#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161#[non_exhaustive]
162pub struct ThresholdResult {
163 pub evaluator: String,
165 pub min_pass_rate: f64,
167 pub pass_rate: f64,
169 pub passed: bool,
171}
172
173#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
175#[non_exhaustive]
176pub struct Report {
177 pub experiment: String,
179 pub repetitions: usize,
181 pub trials: Vec<TrialResult>,
183 pub summary: Vec<EvaluatorSummary>,
185 pub tokens: Tokens,
187 #[serde(default)]
189 pub judge_tokens: Tokens,
190 pub latency: LatencySummary,
192 pub thresholds: Vec<ThresholdResult>,
194}
195
196impl Report {
197 pub(crate) fn new(
200 experiment: String,
201 repetitions: usize,
202 trials: Vec<TrialResult>,
203 evaluators: &[(String, Option<f64>)],
204 thresholds: &[(String, f64)],
205 ) -> Self {
206 let summary: Vec<EvaluatorSummary> = evaluators
207 .iter()
208 .map(|(evaluator, pass_cutoff)| {
209 let scores = trials
210 .iter()
211 .flat_map(|trial| &trial.scores)
212 .filter(|score| &score.evaluator == evaluator);
213 let (count, passed, sum, not_applicable) =
214 scores.fold((0, 0, 0.0, 0), |(count, passed, sum, na), score| {
215 if score.not_applicable {
216 return (count, passed, sum, na + 1);
217 }
218 (
219 count + 1,
220 passed + usize::from(score.passed),
221 sum + score.value,
222 na,
223 )
224 });
225 let per = |value: f64| {
226 if count == 0 {
227 0.0
228 } else {
229 value / count as f64
230 }
231 };
232 EvaluatorSummary {
233 evaluator: evaluator.clone(),
234 count,
235 passed,
236 pass_rate: per(passed as f64),
237 mean: per(sum),
238 not_applicable,
239 pass_at_k: mean_over_cases(&trials, evaluator, repetitions, pass_at),
240 pass_hat_k: mean_over_cases(&trials, evaluator, repetitions, pass_hat),
241 pass_cutoff: *pass_cutoff,
242 }
243 })
244 .collect();
245 let thresholds = summary
246 .iter()
247 .map(|summary| {
248 let min_pass_rate = thresholds
249 .iter()
250 .rev()
251 .find(|(name, _)| name == &summary.evaluator)
252 .map_or(1.0, |(_, min)| *min);
253 ThresholdResult {
254 evaluator: summary.evaluator.clone(),
255 min_pass_rate,
256 pass_rate: summary.pass_rate,
257 passed: summary.count == 0 || summary.pass_rate >= min_pass_rate,
259 }
260 })
261 .collect();
262 let mut tokens = Tokens::default();
263 for usage in trials.iter().map(|trial| &trial.trial.usage) {
264 add_usage(&mut tokens, usage);
265 }
266 let mut judge_tokens = Tokens::default();
267 for usage in trials
268 .iter()
269 .flat_map(|trial| &trial.scores)
270 .filter_map(|score| score.usage.as_ref())
271 {
272 add_usage(&mut judge_tokens, usage);
273 }
274 tokens.input += judge_tokens.input;
275 tokens.output += judge_tokens.output;
276 tokens.total += judge_tokens.total;
277 let mut latencies: Vec<Duration> = trials.iter().map(|trial| trial.trial.latency).collect();
278 latencies.sort_unstable();
279 let latency = LatencySummary {
280 p50: percentile(&latencies, 0.50),
281 p95: percentile(&latencies, 0.95),
282 };
283 Self {
284 experiment,
285 repetitions,
286 trials,
287 summary,
288 tokens,
289 judge_tokens,
290 latency,
291 thresholds,
292 }
293 }
294
295 pub fn passed(&self) -> bool {
297 self.thresholds.iter().all(|threshold| threshold.passed)
298 }
299
300 pub fn pass_rate(&self, evaluator: &str) -> Option<f64> {
302 self.summary
303 .iter()
304 .find(|summary| summary.evaluator == evaluator)
305 .map(|summary| summary.pass_rate)
306 }
307
308 pub fn pass_at_k(&self, evaluator: &str, k: usize) -> Option<f64> {
316 mean_over_cases(&self.trials, evaluator, k, pass_at)
317 }
318
319 pub fn pass_hat_k(&self, evaluator: &str, k: usize) -> Option<f64> {
323 mean_over_cases(&self.trials, evaluator, k, pass_hat)
324 }
325
326 pub fn to_json(&self) -> Result<String, serde_json::Error> {
328 serde_json::to_string_pretty(self)
329 }
330
331 pub fn to_junit(&self) -> String {
334 let name = escape(&self.experiment);
335 let tests = self.trials.len() + self.thresholds.len();
336 let skipped = self.trials.iter().filter(|trial| trial.skipped()).count();
337 let failures = self.trials.iter().filter(|trial| !trial.passed()).count()
338 + self
339 .thresholds
340 .iter()
341 .filter(|threshold| !threshold.passed)
342 .count();
343 let time: f64 = self
344 .trials
345 .iter()
346 .map(|trial| trial.trial.latency.as_secs_f64())
347 .sum();
348 let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
349 let _ = writeln!(
350 xml,
351 "<testsuites name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" time=\"{time:.3}\">"
352 );
353 let _ = writeln!(
354 xml,
355 " <testsuite name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" errors=\"0\" skipped=\"{skipped}\" time=\"{time:.3}\">"
356 );
357 for result in &self.trials {
358 let trial = &result.trial;
359 let case = if self.repetitions > 1 {
360 format!("{} #{}", trial.case_id, trial.repetition)
361 } else {
362 trial.case_id.clone()
363 };
364 let _ = write!(
365 xml,
366 " <testcase name=\"{}\" classname=\"{name}\" time=\"{:.3}\"",
367 escape(&case),
368 trial.latency.as_secs_f64()
369 );
370 let failed: Vec<&Score> = result.failures().collect();
371 if failed.is_empty() {
372 if result.skipped() {
373 let why: Vec<String> = result
374 .scores
375 .iter()
376 .filter(|score| score.not_applicable)
377 .map(|score| {
378 format!(
379 "{}: {}",
380 score.evaluator,
381 score.explanation.as_deref().unwrap_or("not applicable")
382 )
383 })
384 .collect();
385 let message = format!("not applicable: {}", why.join("; "));
386 let _ = write!(
387 xml,
388 ">\n <skipped message=\"{}\"/>\n </testcase>\n",
389 escape(&message)
390 );
391 } else {
392 xml.push_str("/>\n");
393 }
394 continue;
395 }
396 let names: Vec<&str> = failed
397 .iter()
398 .map(|score| score.evaluator.as_str())
399 .collect();
400 let mut body = String::new();
401 if let Some(error) = &trial.error {
402 let _ = writeln!(body, "target error: {error}");
403 }
404 for score in &failed {
405 let _ = writeln!(
406 body,
407 "{} ({:.2}): {}",
408 score.evaluator,
409 score.value,
410 score.explanation.as_deref().unwrap_or("failed")
411 );
412 }
413 let _ = write!(
414 xml,
415 ">\n <failure message=\"failed: {}\" type=\"evaluation\">{}</failure>\n </testcase>\n",
416 escape(&names.join(", ")),
417 escape(&body)
418 );
419 }
420 for threshold in &self.thresholds {
421 let _ = write!(
422 xml,
423 " <testcase name=\"threshold {}\" classname=\"{name}.thresholds\"",
424 escape(&threshold.evaluator)
425 );
426 if threshold.passed {
427 xml.push_str("/>\n");
428 } else {
429 let _ = write!(
430 xml,
431 ">\n <failure message=\"pass rate {:.2} below {:.2}\" type=\"threshold\"/>\n </testcase>\n",
432 threshold.pass_rate, threshold.min_pass_rate
433 );
434 }
435 }
436 xml.push_str(" </testsuite>\n</testsuites>\n");
437 xml
438 }
439
440 pub fn to_markdown(&self) -> String {
443 let outcome = if self.passed() { "passed" } else { "FAILED" };
444 let mut md = format!(
445 "# {}: {outcome}\n\n{} trials ({} cases × {} repetitions)\n\n",
446 self.experiment,
447 self.trials.len(),
448 self.trials.len() / self.repetitions.max(1),
449 self.repetitions
450 );
451 let multi = self.repetitions > 1;
453 let cutoffs = self
455 .summary
456 .iter()
457 .any(|summary| summary.pass_cutoff.is_some());
458 let mut header = vec!["Evaluator", "Pass rate"];
459 if multi {
460 header.extend(["pass@k", "pass^k"]);
461 }
462 header.push("Min pass rate");
463 if cutoffs {
464 header.push("Pass cutoff");
465 }
466 header.extend(["Mean", "Passed", "Result"]);
467 let _ = writeln!(md, "| {} |", header.join(" | "));
468 let _ = writeln!(md, "|{}", "---|".repeat(header.len()));
469 for (summary, threshold) in self.summary.iter().zip(&self.thresholds) {
470 let applicable = summary.count > 0;
471 let (rate, mean) = if applicable {
472 (
473 format!("{:.0}%", summary.pass_rate * 100.0),
474 format!("{:.2}", summary.mean),
475 )
476 } else {
477 ("N/A".to_owned(), "N/A".to_owned())
478 };
479 let not_applicable = if summary.not_applicable > 0 {
480 format!(" ({} N/A)", summary.not_applicable)
481 } else {
482 String::new()
483 };
484 let result = match (applicable, threshold.passed) {
485 (false, _) => "N/A",
486 (true, true) => "pass",
487 (true, false) => "FAIL",
488 };
489 let mut cells = vec![cell(&summary.evaluator), rate];
490 if multi {
491 let percent = |value: Option<f64>| {
492 value.map_or("N/A".to_owned(), |v| format!("{:.0}%", v * 100.0))
493 };
494 cells.push(percent(summary.pass_at_k));
495 cells.push(percent(summary.pass_hat_k));
496 }
497 cells.push(format!("{:.0}%", threshold.min_pass_rate * 100.0));
498 if cutoffs {
499 cells.push(
500 summary
501 .pass_cutoff
502 .map_or("-".to_owned(), |cutoff| format!("{cutoff}")),
503 );
504 }
505 cells.push(mean);
506 cells.push(format!(
507 "{}/{}{not_applicable}",
508 summary.passed, summary.count
509 ));
510 cells.push(result.to_owned());
511 let _ = writeln!(md, "| {} |", cells.join(" | "));
512 }
513 let judges = if self.judge_tokens == Tokens::default() {
514 String::new()
515 } else {
516 format!(
517 " Of which LLM judges: {} input, {} output, {} total.",
518 self.judge_tokens.input, self.judge_tokens.output, self.judge_tokens.total
519 )
520 };
521 let _ = writeln!(
522 md,
523 "\nTokens: {} input, {} output, {} total.{judges} Latency: p50 {:?}, p95 {:?}.",
524 self.tokens.input,
525 self.tokens.output,
526 self.tokens.total,
527 self.latency.p50,
528 self.latency.p95
529 );
530 let failed: Vec<&TrialResult> =
531 self.trials.iter().filter(|trial| !trial.passed()).collect();
532 if !failed.is_empty() {
533 md.push_str("\n## Failures\n\n");
534 for result in failed {
535 let trial = &result.trial;
536 for score in result.failures() {
537 let _ = writeln!(
538 md,
539 "- `{}` #{} {}: {}",
540 trial.case_id,
541 trial.repetition,
542 score.evaluator,
543 one_line(score.explanation.as_deref().unwrap_or("failed"))
544 );
545 }
546 }
547 }
548 md
549 }
550}
551
552fn mean_over_cases(
556 trials: &[TrialResult],
557 evaluator: &str,
558 k: usize,
559 estimate: fn(usize, usize, usize) -> Option<f64>,
560) -> Option<f64> {
561 let mut per_case: BTreeMap<&str, (usize, usize)> = BTreeMap::new();
562 for result in trials {
563 let scores = result
564 .scores
565 .iter()
566 .filter(|score| score.evaluator == evaluator && !score.not_applicable);
567 for score in scores {
568 let (n, c) = per_case.entry(result.trial.case_id.as_str()).or_default();
569 *n += 1;
570 *c += usize::from(score.passed);
571 }
572 }
573 let values: Vec<f64> = per_case
574 .values()
575 .filter_map(|&(n, c)| estimate(n, c, k))
576 .collect();
577 if values.is_empty() {
578 return None;
579 }
580 Some(values.iter().sum::<f64>() / values.len() as f64)
581}
582
583fn pass_at(n: usize, c: usize, k: usize) -> Option<f64> {
585 ratio(n - c.min(n), n, k).map(|miss| 1.0 - miss)
586}
587
588fn pass_hat(n: usize, c: usize, k: usize) -> Option<f64> {
590 ratio(c.min(n), n, k)
591}
592
593fn ratio(a: usize, n: usize, k: usize) -> Option<f64> {
596 if k == 0 || k > n {
597 return None;
598 }
599 let product = (0..k).fold(1.0, |acc, i| {
600 acc * (a.saturating_sub(i) as f64) / ((n - i) as f64)
601 });
602 Some(product)
603}
604
605fn add_usage(tokens: &mut Tokens, usage: &Usage) {
607 let (input, output) = (
608 usage.input_tokens.unwrap_or(0),
609 usage.output_tokens.unwrap_or(0),
610 );
611 tokens.input += input;
612 tokens.output += output;
613 tokens.total += usage.total_tokens.unwrap_or(input + output);
614}
615
616fn percentile(sorted: &[Duration], p: f64) -> Duration {
618 let rank = (p * sorted.len() as f64).ceil() as usize;
619 sorted
620 .get(rank.saturating_sub(1))
621 .copied()
622 .unwrap_or_default()
623}
624
625fn escape(text: &str) -> String {
628 let mut out = String::with_capacity(text.len());
629 for c in text.chars() {
630 match c {
631 '&' => out.push_str("&"),
632 '<' => out.push_str("<"),
633 '>' => out.push_str(">"),
634 '"' => out.push_str("""),
635 '\'' => out.push_str("'"),
636 '\t' | '\n' | '\r' => out.push(c),
637 c if (c as u32) < 0x20 => {}
638 c => out.push(c),
639 }
640 }
641 out
642}
643
644fn one_line(text: &str) -> String {
646 text.split_whitespace().collect::<Vec<_>>().join(" ")
647}
648
649fn cell(text: &str) -> String {
651 one_line(text).replace('|', "\\|")
652}
653
654mod millis {
656 use std::time::Duration;
657
658 use serde::{Deserialize, Deserializer, Serializer};
659
660 pub(super) fn serialize<S: Serializer>(
661 duration: &Duration,
662 serializer: S,
663 ) -> Result<S::Ok, S::Error> {
664 serializer.serialize_f64(duration.as_secs_f64() * 1000.0)
665 }
666
667 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
668 deserializer: D,
669 ) -> Result<Duration, D::Error> {
670 let millis = f64::deserialize(deserializer)?;
671 Duration::try_from_secs_f64(millis / 1000.0).map_err(serde::de::Error::custom)
672 }
673}
674
675#[cfg(test)]
676mod tests;