use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::time::Duration;
use rig_core::completion::Usage;
use serde::{Deserialize, Serialize};
use crate::{Score, ToolCall, Turn};
mod compare;
pub use compare::{CaseChange, Comparison, EvaluatorDelta};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Trial {
pub case_id: String,
pub repetition: usize,
pub output: String,
pub tool_calls: Vec<ToolCall>,
pub usage: Usage,
#[serde(rename = "latency_ms", with = "millis")]
pub latency: Duration,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub session_id: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub transcript: Vec<Turn>,
}
impl Trial {
pub fn new(case_id: impl Into<String>, repetition: usize, output: impl Into<String>) -> Self {
Self {
case_id: case_id.into(),
repetition,
output: output.into(),
tool_calls: Vec::new(),
usage: Usage::default(),
latency: Duration::ZERO,
error: None,
session_id: None,
transcript: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TrialResult {
pub trial: Trial,
pub scores: Vec<Score>,
}
impl TrialResult {
pub fn passed(&self) -> bool {
self.scores
.iter()
.all(|score| score.passed || score.not_applicable)
}
fn skipped(&self) -> bool {
self.scores.iter().any(|score| score.not_applicable)
}
pub fn failures(&self) -> impl Iterator<Item = &Score> {
self.scores
.iter()
.filter(|score| !score.passed && !score.not_applicable)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EvaluatorSummary {
pub evaluator: String,
pub count: usize,
pub passed: usize,
pub pass_rate: f64,
pub mean: f64,
#[serde(default)]
pub not_applicable: usize,
#[serde(default)]
pub pass_at_k: Option<f64>,
#[serde(default)]
pub pass_hat_k: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pass_cutoff: Option<f64>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Tokens {
pub input: u64,
pub output: u64,
pub total: u64,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct LatencySummary {
#[serde(rename = "p50_ms", with = "millis")]
pub p50: Duration,
#[serde(rename = "p95_ms", with = "millis")]
pub p95: Duration,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ThresholdResult {
pub evaluator: String,
pub min_pass_rate: f64,
pub pass_rate: f64,
pub passed: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Report {
pub experiment: String,
pub repetitions: usize,
pub trials: Vec<TrialResult>,
pub summary: Vec<EvaluatorSummary>,
pub tokens: Tokens,
#[serde(default)]
pub judge_tokens: Tokens,
pub latency: LatencySummary,
pub thresholds: Vec<ThresholdResult>,
}
impl Report {
pub(crate) fn new(
experiment: String,
repetitions: usize,
trials: Vec<TrialResult>,
evaluators: &[(String, Option<f64>)],
thresholds: &[(String, f64)],
) -> Self {
let summary: Vec<EvaluatorSummary> = evaluators
.iter()
.map(|(evaluator, pass_cutoff)| {
let scores = trials
.iter()
.flat_map(|trial| &trial.scores)
.filter(|score| &score.evaluator == evaluator);
let (count, passed, sum, not_applicable) =
scores.fold((0, 0, 0.0, 0), |(count, passed, sum, na), score| {
if score.not_applicable {
return (count, passed, sum, na + 1);
}
(
count + 1,
passed + usize::from(score.passed),
sum + score.value,
na,
)
});
let per = |value: f64| {
if count == 0 {
0.0
} else {
value / count as f64
}
};
EvaluatorSummary {
evaluator: evaluator.clone(),
count,
passed,
pass_rate: per(passed as f64),
mean: per(sum),
not_applicable,
pass_at_k: mean_over_cases(&trials, evaluator, repetitions, pass_at),
pass_hat_k: mean_over_cases(&trials, evaluator, repetitions, pass_hat),
pass_cutoff: *pass_cutoff,
}
})
.collect();
let thresholds = summary
.iter()
.map(|summary| {
let min_pass_rate = thresholds
.iter()
.rev()
.find(|(name, _)| name == &summary.evaluator)
.map_or(1.0, |(_, min)| *min);
ThresholdResult {
evaluator: summary.evaluator.clone(),
min_pass_rate,
pass_rate: summary.pass_rate,
passed: summary.count == 0 || summary.pass_rate >= min_pass_rate,
}
})
.collect();
let mut tokens = Tokens::default();
for usage in trials.iter().map(|trial| &trial.trial.usage) {
add_usage(&mut tokens, usage);
}
let mut judge_tokens = Tokens::default();
for usage in trials
.iter()
.flat_map(|trial| &trial.scores)
.filter_map(|score| score.usage.as_ref())
{
add_usage(&mut judge_tokens, usage);
}
tokens.input += judge_tokens.input;
tokens.output += judge_tokens.output;
tokens.total += judge_tokens.total;
let mut latencies: Vec<Duration> = trials.iter().map(|trial| trial.trial.latency).collect();
latencies.sort_unstable();
let latency = LatencySummary {
p50: percentile(&latencies, 0.50),
p95: percentile(&latencies, 0.95),
};
Self {
experiment,
repetitions,
trials,
summary,
tokens,
judge_tokens,
latency,
thresholds,
}
}
pub fn passed(&self) -> bool {
self.thresholds.iter().all(|threshold| threshold.passed)
}
pub fn pass_rate(&self, evaluator: &str) -> Option<f64> {
self.summary
.iter()
.find(|summary| summary.evaluator == evaluator)
.map(|summary| summary.pass_rate)
}
pub fn pass_at_k(&self, evaluator: &str, k: usize) -> Option<f64> {
mean_over_cases(&self.trials, evaluator, k, pass_at)
}
pub fn pass_hat_k(&self, evaluator: &str, k: usize) -> Option<f64> {
mean_over_cases(&self.trials, evaluator, k, pass_hat)
}
pub fn to_json(&self) -> Result<String, serde_json::Error> {
serde_json::to_string_pretty(self)
}
pub fn to_junit(&self) -> String {
let name = escape(&self.experiment);
let tests = self.trials.len() + self.thresholds.len();
let skipped = self.trials.iter().filter(|trial| trial.skipped()).count();
let failures = self.trials.iter().filter(|trial| !trial.passed()).count()
+ self
.thresholds
.iter()
.filter(|threshold| !threshold.passed)
.count();
let time: f64 = self
.trials
.iter()
.map(|trial| trial.trial.latency.as_secs_f64())
.sum();
let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
let _ = writeln!(
xml,
"<testsuites name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" time=\"{time:.3}\">"
);
let _ = writeln!(
xml,
" <testsuite name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" errors=\"0\" skipped=\"{skipped}\" time=\"{time:.3}\">"
);
for result in &self.trials {
let trial = &result.trial;
let case = if self.repetitions > 1 {
format!("{} #{}", trial.case_id, trial.repetition)
} else {
trial.case_id.clone()
};
let _ = write!(
xml,
" <testcase name=\"{}\" classname=\"{name}\" time=\"{:.3}\"",
escape(&case),
trial.latency.as_secs_f64()
);
let failed: Vec<&Score> = result.failures().collect();
if failed.is_empty() {
if result.skipped() {
let why: Vec<String> = result
.scores
.iter()
.filter(|score| score.not_applicable)
.map(|score| {
format!(
"{}: {}",
score.evaluator,
score.explanation.as_deref().unwrap_or("not applicable")
)
})
.collect();
let message = format!("not applicable: {}", why.join("; "));
let _ = write!(
xml,
">\n <skipped message=\"{}\"/>\n </testcase>\n",
escape(&message)
);
} else {
xml.push_str("/>\n");
}
continue;
}
let names: Vec<&str> = failed
.iter()
.map(|score| score.evaluator.as_str())
.collect();
let mut body = String::new();
if let Some(error) = &trial.error {
let _ = writeln!(body, "target error: {error}");
}
for score in &failed {
let _ = writeln!(
body,
"{} ({:.2}): {}",
score.evaluator,
score.value,
score.explanation.as_deref().unwrap_or("failed")
);
}
let _ = write!(
xml,
">\n <failure message=\"failed: {}\" type=\"evaluation\">{}</failure>\n </testcase>\n",
escape(&names.join(", ")),
escape(&body)
);
}
for threshold in &self.thresholds {
let _ = write!(
xml,
" <testcase name=\"threshold {}\" classname=\"{name}.thresholds\"",
escape(&threshold.evaluator)
);
if threshold.passed {
xml.push_str("/>\n");
} else {
let _ = write!(
xml,
">\n <failure message=\"pass rate {:.2} below {:.2}\" type=\"threshold\"/>\n </testcase>\n",
threshold.pass_rate, threshold.min_pass_rate
);
}
}
xml.push_str(" </testsuite>\n</testsuites>\n");
xml
}
pub fn to_markdown(&self) -> String {
let outcome = if self.passed() { "passed" } else { "FAILED" };
let mut md = format!(
"# {}: {outcome}\n\n{} trials ({} cases × {} repetitions)\n\n",
self.experiment,
self.trials.len(),
self.trials.len() / self.repetitions.max(1),
self.repetitions
);
let multi = self.repetitions > 1;
let cutoffs = self
.summary
.iter()
.any(|summary| summary.pass_cutoff.is_some());
let mut header = vec!["Evaluator", "Pass rate"];
if multi {
header.extend(["pass@k", "pass^k"]);
}
header.push("Min pass rate");
if cutoffs {
header.push("Pass cutoff");
}
header.extend(["Mean", "Passed", "Result"]);
let _ = writeln!(md, "| {} |", header.join(" | "));
let _ = writeln!(md, "|{}", "---|".repeat(header.len()));
for (summary, threshold) in self.summary.iter().zip(&self.thresholds) {
let applicable = summary.count > 0;
let (rate, mean) = if applicable {
(
format!("{:.0}%", summary.pass_rate * 100.0),
format!("{:.2}", summary.mean),
)
} else {
("N/A".to_owned(), "N/A".to_owned())
};
let not_applicable = if summary.not_applicable > 0 {
format!(" ({} N/A)", summary.not_applicable)
} else {
String::new()
};
let result = match (applicable, threshold.passed) {
(false, _) => "N/A",
(true, true) => "pass",
(true, false) => "FAIL",
};
let mut cells = vec![cell(&summary.evaluator), rate];
if multi {
let percent = |value: Option<f64>| {
value.map_or("N/A".to_owned(), |v| format!("{:.0}%", v * 100.0))
};
cells.push(percent(summary.pass_at_k));
cells.push(percent(summary.pass_hat_k));
}
cells.push(format!("{:.0}%", threshold.min_pass_rate * 100.0));
if cutoffs {
cells.push(
summary
.pass_cutoff
.map_or("-".to_owned(), |cutoff| format!("{cutoff}")),
);
}
cells.push(mean);
cells.push(format!(
"{}/{}{not_applicable}",
summary.passed, summary.count
));
cells.push(result.to_owned());
let _ = writeln!(md, "| {} |", cells.join(" | "));
}
let judges = if self.judge_tokens == Tokens::default() {
String::new()
} else {
format!(
" Of which LLM judges: {} input, {} output, {} total.",
self.judge_tokens.input, self.judge_tokens.output, self.judge_tokens.total
)
};
let _ = writeln!(
md,
"\nTokens: {} input, {} output, {} total.{judges} Latency: p50 {:?}, p95 {:?}.",
self.tokens.input,
self.tokens.output,
self.tokens.total,
self.latency.p50,
self.latency.p95
);
let failed: Vec<&TrialResult> =
self.trials.iter().filter(|trial| !trial.passed()).collect();
if !failed.is_empty() {
md.push_str("\n## Failures\n\n");
for result in failed {
let trial = &result.trial;
for score in result.failures() {
let _ = writeln!(
md,
"- `{}` #{} {}: {}",
trial.case_id,
trial.repetition,
score.evaluator,
one_line(score.explanation.as_deref().unwrap_or("failed"))
);
}
}
}
md
}
}
fn mean_over_cases(
trials: &[TrialResult],
evaluator: &str,
k: usize,
estimate: fn(usize, usize, usize) -> Option<f64>,
) -> Option<f64> {
let mut per_case: BTreeMap<&str, (usize, usize)> = BTreeMap::new();
for result in trials {
let scores = result
.scores
.iter()
.filter(|score| score.evaluator == evaluator && !score.not_applicable);
for score in scores {
let (n, c) = per_case.entry(result.trial.case_id.as_str()).or_default();
*n += 1;
*c += usize::from(score.passed);
}
}
let values: Vec<f64> = per_case
.values()
.filter_map(|&(n, c)| estimate(n, c, k))
.collect();
if values.is_empty() {
return None;
}
Some(values.iter().sum::<f64>() / values.len() as f64)
}
fn pass_at(n: usize, c: usize, k: usize) -> Option<f64> {
ratio(n - c.min(n), n, k).map(|miss| 1.0 - miss)
}
fn pass_hat(n: usize, c: usize, k: usize) -> Option<f64> {
ratio(c.min(n), n, k)
}
fn ratio(a: usize, n: usize, k: usize) -> Option<f64> {
if k == 0 || k > n {
return None;
}
let product = (0..k).fold(1.0, |acc, i| {
acc * (a.saturating_sub(i) as f64) / ((n - i) as f64)
});
Some(product)
}
fn add_usage(tokens: &mut Tokens, usage: &Usage) {
let (input, output) = (
usage.input_tokens.unwrap_or(0),
usage.output_tokens.unwrap_or(0),
);
tokens.input += input;
tokens.output += output;
tokens.total += usage.total_tokens.unwrap_or(input + output);
}
fn percentile(sorted: &[Duration], p: f64) -> Duration {
let rank = (p * sorted.len() as f64).ceil() as usize;
sorted
.get(rank.saturating_sub(1))
.copied()
.unwrap_or_default()
}
fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len());
for c in text.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
'\t' | '\n' | '\r' => out.push(c),
c if (c as u32) < 0x20 => {}
c => out.push(c),
}
}
out
}
fn one_line(text: &str) -> String {
text.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn cell(text: &str) -> String {
one_line(text).replace('|', "\\|")
}
mod millis {
use std::time::Duration;
use serde::{Deserialize, Deserializer, Serializer};
pub(super) fn serialize<S: Serializer>(
duration: &Duration,
serializer: S,
) -> Result<S::Ok, S::Error> {
serializer.serialize_f64(duration.as_secs_f64() * 1000.0)
}
pub(super) fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<Duration, D::Error> {
let millis = f64::deserialize(deserializer)?;
Duration::try_from_secs_f64(millis / 1000.0).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod tests;