1use std::fmt::Write as _;
4use std::time::Duration;
5
6use rig_core::completion::Usage;
7use serde::{Deserialize, Serialize};
8
9use crate::{Score, ToolCall, Turn};
10
11#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13#[non_exhaustive]
14pub struct Trial {
15 pub case_id: String,
17 pub repetition: usize,
19 pub output: String,
21 pub tool_calls: Vec<ToolCall>,
23 pub usage: Usage,
25 #[serde(rename = "latency_ms", with = "millis")]
27 pub latency: Duration,
28 #[serde(default, skip_serializing_if = "Option::is_none")]
30 pub error: Option<String>,
31 #[serde(default, skip_serializing_if = "Option::is_none")]
34 pub session_id: Option<String>,
35 #[serde(default, skip_serializing_if = "Vec::is_empty")]
38 pub transcript: Vec<Turn>,
39}
40
41impl Trial {
42 pub fn new(case_id: impl Into<String>, repetition: usize, output: impl Into<String>) -> Self {
45 Self {
46 case_id: case_id.into(),
47 repetition,
48 output: output.into(),
49 tool_calls: Vec::new(),
50 usage: Usage::default(),
51 latency: Duration::ZERO,
52 error: None,
53 session_id: None,
54 transcript: Vec::new(),
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[non_exhaustive]
62pub struct TrialResult {
63 pub trial: Trial,
65 pub scores: Vec<Score>,
67}
68
69impl TrialResult {
70 pub fn passed(&self) -> bool {
72 self.scores
73 .iter()
74 .all(|score| score.passed || score.not_applicable)
75 }
76
77 fn skipped(&self) -> bool {
80 self.scores.iter().any(|score| score.not_applicable)
81 }
82
83 pub fn failures(&self) -> impl Iterator<Item = &Score> {
85 self.scores
86 .iter()
87 .filter(|score| !score.passed && !score.not_applicable)
88 }
89}
90
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct EvaluatorSummary {
95 pub evaluator: String,
97 pub count: usize,
99 pub passed: usize,
101 pub pass_rate: f64,
103 pub mean: f64,
105 #[serde(default)]
108 pub not_applicable: usize,
109}
110
111#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
113#[non_exhaustive]
114pub struct Tokens {
115 pub input: u64,
117 pub output: u64,
119 pub total: u64,
121}
122
123#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
125#[non_exhaustive]
126pub struct LatencySummary {
127 #[serde(rename = "p50_ms", with = "millis")]
129 pub p50: Duration,
130 #[serde(rename = "p95_ms", with = "millis")]
132 pub p95: Duration,
133}
134
135#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137#[non_exhaustive]
138pub struct ThresholdResult {
139 pub evaluator: String,
141 pub min_pass_rate: f64,
143 pub pass_rate: f64,
145 pub passed: bool,
147}
148
149#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
151#[non_exhaustive]
152pub struct Report {
153 pub experiment: String,
155 pub repetitions: usize,
157 pub trials: Vec<TrialResult>,
159 pub summary: Vec<EvaluatorSummary>,
161 pub tokens: Tokens,
163 #[serde(default)]
165 pub judge_tokens: Tokens,
166 pub latency: LatencySummary,
168 pub thresholds: Vec<ThresholdResult>,
170}
171
172impl Report {
173 pub(crate) fn new(
176 experiment: String,
177 repetitions: usize,
178 trials: Vec<TrialResult>,
179 evaluators: &[String],
180 thresholds: &[(String, f64)],
181 ) -> Self {
182 let summary: Vec<EvaluatorSummary> = evaluators
183 .iter()
184 .map(|evaluator| {
185 let scores = trials
186 .iter()
187 .flat_map(|trial| &trial.scores)
188 .filter(|score| &score.evaluator == evaluator);
189 let (count, passed, sum, not_applicable) =
190 scores.fold((0, 0, 0.0, 0), |(count, passed, sum, na), score| {
191 if score.not_applicable {
192 return (count, passed, sum, na + 1);
193 }
194 (
195 count + 1,
196 passed + usize::from(score.passed),
197 sum + score.value,
198 na,
199 )
200 });
201 let per = |value: f64| {
202 if count == 0 {
203 0.0
204 } else {
205 value / count as f64
206 }
207 };
208 EvaluatorSummary {
209 evaluator: evaluator.clone(),
210 count,
211 passed,
212 pass_rate: per(passed as f64),
213 mean: per(sum),
214 not_applicable,
215 }
216 })
217 .collect();
218 let thresholds = summary
219 .iter()
220 .map(|summary| {
221 let min_pass_rate = thresholds
222 .iter()
223 .rev()
224 .find(|(name, _)| name == &summary.evaluator)
225 .map_or(1.0, |(_, min)| *min);
226 ThresholdResult {
227 evaluator: summary.evaluator.clone(),
228 min_pass_rate,
229 pass_rate: summary.pass_rate,
230 passed: summary.count == 0 || summary.pass_rate >= min_pass_rate,
232 }
233 })
234 .collect();
235 let mut tokens = Tokens::default();
236 for usage in trials.iter().map(|trial| &trial.trial.usage) {
237 add_usage(&mut tokens, usage);
238 }
239 let mut judge_tokens = Tokens::default();
240 for usage in trials
241 .iter()
242 .flat_map(|trial| &trial.scores)
243 .filter_map(|score| score.usage.as_ref())
244 {
245 add_usage(&mut judge_tokens, usage);
246 }
247 tokens.input += judge_tokens.input;
248 tokens.output += judge_tokens.output;
249 tokens.total += judge_tokens.total;
250 let mut latencies: Vec<Duration> = trials.iter().map(|trial| trial.trial.latency).collect();
251 latencies.sort_unstable();
252 let latency = LatencySummary {
253 p50: percentile(&latencies, 0.50),
254 p95: percentile(&latencies, 0.95),
255 };
256 Self {
257 experiment,
258 repetitions,
259 trials,
260 summary,
261 tokens,
262 judge_tokens,
263 latency,
264 thresholds,
265 }
266 }
267
268 pub fn passed(&self) -> bool {
270 self.thresholds.iter().all(|threshold| threshold.passed)
271 }
272
273 pub fn pass_rate(&self, evaluator: &str) -> Option<f64> {
275 self.summary
276 .iter()
277 .find(|summary| summary.evaluator == evaluator)
278 .map(|summary| summary.pass_rate)
279 }
280
281 pub fn to_json(&self) -> Result<String, serde_json::Error> {
283 serde_json::to_string_pretty(self)
284 }
285
286 pub fn to_junit(&self) -> String {
289 let name = escape(&self.experiment);
290 let tests = self.trials.len() + self.thresholds.len();
291 let skipped = self.trials.iter().filter(|trial| trial.skipped()).count();
292 let failures = self.trials.iter().filter(|trial| !trial.passed()).count()
293 + self
294 .thresholds
295 .iter()
296 .filter(|threshold| !threshold.passed)
297 .count();
298 let time: f64 = self
299 .trials
300 .iter()
301 .map(|trial| trial.trial.latency.as_secs_f64())
302 .sum();
303 let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
304 let _ = writeln!(
305 xml,
306 "<testsuites name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" time=\"{time:.3}\">"
307 );
308 let _ = writeln!(
309 xml,
310 " <testsuite name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" errors=\"0\" skipped=\"{skipped}\" time=\"{time:.3}\">"
311 );
312 for result in &self.trials {
313 let trial = &result.trial;
314 let case = if self.repetitions > 1 {
315 format!("{} #{}", trial.case_id, trial.repetition)
316 } else {
317 trial.case_id.clone()
318 };
319 let _ = write!(
320 xml,
321 " <testcase name=\"{}\" classname=\"{name}\" time=\"{:.3}\"",
322 escape(&case),
323 trial.latency.as_secs_f64()
324 );
325 let failed: Vec<&Score> = result.failures().collect();
326 if failed.is_empty() {
327 if result.skipped() {
328 let why: Vec<String> = result
329 .scores
330 .iter()
331 .filter(|score| score.not_applicable)
332 .map(|score| {
333 format!(
334 "{}: {}",
335 score.evaluator,
336 score.explanation.as_deref().unwrap_or("not applicable")
337 )
338 })
339 .collect();
340 let message = format!("not applicable: {}", why.join("; "));
341 let _ = write!(
342 xml,
343 ">\n <skipped message=\"{}\"/>\n </testcase>\n",
344 escape(&message)
345 );
346 } else {
347 xml.push_str("/>\n");
348 }
349 continue;
350 }
351 let names: Vec<&str> = failed
352 .iter()
353 .map(|score| score.evaluator.as_str())
354 .collect();
355 let mut body = String::new();
356 if let Some(error) = &trial.error {
357 let _ = writeln!(body, "target error: {error}");
358 }
359 for score in &failed {
360 let _ = writeln!(
361 body,
362 "{} ({:.2}): {}",
363 score.evaluator,
364 score.value,
365 score.explanation.as_deref().unwrap_or("failed")
366 );
367 }
368 let _ = write!(
369 xml,
370 ">\n <failure message=\"failed: {}\" type=\"evaluation\">{}</failure>\n </testcase>\n",
371 escape(&names.join(", ")),
372 escape(&body)
373 );
374 }
375 for threshold in &self.thresholds {
376 let _ = write!(
377 xml,
378 " <testcase name=\"threshold {}\" classname=\"{name}.thresholds\"",
379 escape(&threshold.evaluator)
380 );
381 if threshold.passed {
382 xml.push_str("/>\n");
383 } else {
384 let _ = write!(
385 xml,
386 ">\n <failure message=\"pass rate {:.2} below {:.2}\" type=\"threshold\"/>\n </testcase>\n",
387 threshold.pass_rate, threshold.min_pass_rate
388 );
389 }
390 }
391 xml.push_str(" </testsuite>\n</testsuites>\n");
392 xml
393 }
394
395 pub fn to_markdown(&self) -> String {
398 let outcome = if self.passed() { "passed" } else { "FAILED" };
399 let mut md = format!(
400 "# {}: {outcome}\n\n{} trials ({} cases × {} repetitions)\n\n",
401 self.experiment,
402 self.trials.len(),
403 self.trials.len() / self.repetitions.max(1),
404 self.repetitions
405 );
406 md.push_str("| Evaluator | Pass rate | Threshold | Mean | Passed | Result |\n|---|---|---|---|---|---|\n");
407 for (summary, threshold) in self.summary.iter().zip(&self.thresholds) {
408 let applicable = summary.count > 0;
409 let (rate, mean) = if applicable {
410 (
411 format!("{:.0}%", summary.pass_rate * 100.0),
412 format!("{:.2}", summary.mean),
413 )
414 } else {
415 ("N/A".to_owned(), "N/A".to_owned())
416 };
417 let not_applicable = if summary.not_applicable > 0 {
418 format!(" ({} N/A)", summary.not_applicable)
419 } else {
420 String::new()
421 };
422 let result = match (applicable, threshold.passed) {
423 (false, _) => "N/A",
424 (true, true) => "pass",
425 (true, false) => "FAIL",
426 };
427 let _ = writeln!(
428 md,
429 "| {} | {rate} | {:.0}% | {mean} | {}/{}{not_applicable} | {result} |",
430 cell(&summary.evaluator),
431 threshold.min_pass_rate * 100.0,
432 summary.passed,
433 summary.count,
434 );
435 }
436 let judges = if self.judge_tokens == Tokens::default() {
437 String::new()
438 } else {
439 format!(
440 " Of which LLM judges: {} input, {} output, {} total.",
441 self.judge_tokens.input, self.judge_tokens.output, self.judge_tokens.total
442 )
443 };
444 let _ = writeln!(
445 md,
446 "\nTokens: {} input, {} output, {} total.{judges} Latency: p50 {:?}, p95 {:?}.",
447 self.tokens.input,
448 self.tokens.output,
449 self.tokens.total,
450 self.latency.p50,
451 self.latency.p95
452 );
453 let failed: Vec<&TrialResult> =
454 self.trials.iter().filter(|trial| !trial.passed()).collect();
455 if !failed.is_empty() {
456 md.push_str("\n## Failures\n\n");
457 for result in failed {
458 let trial = &result.trial;
459 for score in result.failures() {
460 let _ = writeln!(
461 md,
462 "- `{}` #{} {}: {}",
463 trial.case_id,
464 trial.repetition,
465 score.evaluator,
466 one_line(score.explanation.as_deref().unwrap_or("failed"))
467 );
468 }
469 }
470 }
471 md
472 }
473}
474
475fn add_usage(tokens: &mut Tokens, usage: &Usage) {
477 let (input, output) = (
478 usage.input_tokens.unwrap_or(0),
479 usage.output_tokens.unwrap_or(0),
480 );
481 tokens.input += input;
482 tokens.output += output;
483 tokens.total += usage.total_tokens.unwrap_or(input + output);
484}
485
486fn percentile(sorted: &[Duration], p: f64) -> Duration {
488 let rank = (p * sorted.len() as f64).ceil() as usize;
489 sorted
490 .get(rank.saturating_sub(1))
491 .copied()
492 .unwrap_or_default()
493}
494
495fn escape(text: &str) -> String {
498 let mut out = String::with_capacity(text.len());
499 for c in text.chars() {
500 match c {
501 '&' => out.push_str("&"),
502 '<' => out.push_str("<"),
503 '>' => out.push_str(">"),
504 '"' => out.push_str("""),
505 '\'' => out.push_str("'"),
506 '\t' | '\n' | '\r' => out.push(c),
507 c if (c as u32) < 0x20 => {}
508 c => out.push(c),
509 }
510 }
511 out
512}
513
514fn one_line(text: &str) -> String {
516 text.split_whitespace().collect::<Vec<_>>().join(" ")
517}
518
519fn cell(text: &str) -> String {
521 one_line(text).replace('|', "\\|")
522}
523
524mod millis {
526 use std::time::Duration;
527
528 use serde::{Deserialize, Deserializer, Serializer};
529
530 pub(super) fn serialize<S: Serializer>(
531 duration: &Duration,
532 serializer: S,
533 ) -> Result<S::Ok, S::Error> {
534 serializer.serialize_f64(duration.as_secs_f64() * 1000.0)
535 }
536
537 pub(super) fn deserialize<'de, D: Deserializer<'de>>(
538 deserializer: D,
539 ) -> Result<Duration, D::Error> {
540 let millis = f64::deserialize(deserializer)?;
541 Duration::try_from_secs_f64(millis / 1000.0).map_err(serde::de::Error::custom)
542 }
543}
544
545#[cfg(test)]
546mod tests;