Skip to main content

rig_evals/
report.rs

1//! What an experiment found, and its JSON, JUnit and Markdown forms.
2
3use 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
11mod compare;
12
13pub use compare::{CaseChange, Comparison, EvaluatorDelta};
14
15/// One run of the target on a case.
16#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
17#[non_exhaustive]
18pub struct Trial {
19    /// The case's id.
20    pub case_id: String,
21    /// Which run of the case this is, from 1.
22    pub repetition: usize,
23    /// The answer; empty when the target failed.
24    pub output: String,
25    /// The tool calls, in order.
26    pub tool_calls: Vec<ToolCall>,
27    /// The model tokens spent.
28    pub usage: Usage,
29    /// How long the run took.
30    #[serde(rename = "latency_ms", with = "millis")]
31    pub latency: Duration,
32    /// Why the target failed, if it did.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub error: Option<String>,
35    /// The session the target ran in, when it reports one (an AgentCore
36    /// runtime does): remote evaluators look up the run's traces by it.
37    #[serde(default, skip_serializing_if = "Option::is_none")]
38    pub session_id: Option<String>,
39    /// Each turn of a multi-turn case and its answer, in order; empty for a
40    /// single-turn case. `output` is the answer to the last turn.
41    #[serde(default, skip_serializing_if = "Vec::is_empty")]
42    pub transcript: Vec<Turn>,
43}
44
45impl Trial {
46    /// A successful run of `case_id` that answered `output`, with no tool
47    /// calls, usage or latency: to test an evaluator.
48    pub fn new(case_id: impl Into<String>, repetition: usize, output: impl Into<String>) -> Self {
49        Self {
50            case_id: case_id.into(),
51            repetition,
52            output: output.into(),
53            tool_calls: Vec::new(),
54            usage: Usage::default(),
55            latency: Duration::ZERO,
56            error: None,
57            session_id: None,
58            transcript: Vec::new(),
59        }
60    }
61}
62
63/// A trial and its scores.
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
65#[non_exhaustive]
66pub struct TrialResult {
67    /// The run.
68    pub trial: Trial,
69    /// One per evaluator, in the experiment's order.
70    pub scores: Vec<Score>,
71}
72
73impl TrialResult {
74    /// Whether every evaluator passed the run.
75    pub fn passed(&self) -> bool {
76        self.scores
77            .iter()
78            .all(|score| score.passed || score.not_applicable)
79    }
80
81    /// Whether an evaluator did not apply to the run: with no failure, the
82    /// run is reported as skipped in JUnit.
83    fn skipped(&self) -> bool {
84        self.scores.iter().any(|score| score.not_applicable)
85    }
86
87    /// The scores that failed (not the ones not applicable).
88    pub fn failures(&self) -> impl Iterator<Item = &Score> {
89        self.scores
90            .iter()
91            .filter(|score| !score.passed && !score.not_applicable)
92    }
93}
94
95/// One evaluator's results over all trials.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[non_exhaustive]
98pub struct EvaluatorSummary {
99    /// The evaluator.
100    pub evaluator: String,
101    /// The trials scored (not counting the ones not applicable).
102    pub count: usize,
103    /// The trials it passed.
104    pub passed: usize,
105    /// `passed / count`; 0 when no trial was applicable.
106    pub pass_rate: f64,
107    /// The mean score value over the trials scored.
108    pub mean: f64,
109    /// The trials the evaluator did not apply to (N/A): left out of
110    /// `count`, `pass_rate` and `mean`.
111    #[serde(default)]
112    pub not_applicable: usize,
113}
114
115/// Model tokens over all trials.
116#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
117#[non_exhaustive]
118pub struct Tokens {
119    /// Input tokens.
120    pub input: u64,
121    /// Output tokens.
122    pub output: u64,
123    /// The reported totals, or input plus output where none was reported.
124    pub total: u64,
125}
126
127/// Run latencies over all trials.
128#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
129#[non_exhaustive]
130pub struct LatencySummary {
131    /// The median.
132    #[serde(rename = "p50_ms", with = "millis")]
133    pub p50: Duration,
134    /// The 95th percentile.
135    #[serde(rename = "p95_ms", with = "millis")]
136    pub p95: Duration,
137}
138
139/// Whether an evaluator's pass rate reached its threshold.
140#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
141#[non_exhaustive]
142pub struct ThresholdResult {
143    /// The evaluator.
144    pub evaluator: String,
145    /// The lowest pass rate that passes: 1 unless the experiment set one.
146    pub min_pass_rate: f64,
147    /// The pass rate reached.
148    pub pass_rate: f64,
149    /// `pass_rate >= min_pass_rate`, or no trial was applicable.
150    pub passed: bool,
151}
152
153/// What an experiment found.
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155#[non_exhaustive]
156pub struct Report {
157    /// The experiment's name.
158    pub experiment: String,
159    /// How many times each case ran.
160    pub repetitions: usize,
161    /// Every trial, by case then repetition.
162    pub trials: Vec<TrialResult>,
163    /// Per evaluator, in the experiment's order.
164    pub summary: Vec<EvaluatorSummary>,
165    /// Model tokens: the target's and the LLM judges'.
166    pub tokens: Tokens,
167    /// The part of `tokens` that LLM judges spent.
168    #[serde(default)]
169    pub judge_tokens: Tokens,
170    /// Run latencies.
171    pub latency: LatencySummary,
172    /// One per evaluator.
173    pub thresholds: Vec<ThresholdResult>,
174}
175
176impl Report {
177    /// Summarize `trials`, scored by `evaluators` with minimum pass rates
178    /// `thresholds` (1 for the others).
179    pub(crate) fn new(
180        experiment: String,
181        repetitions: usize,
182        trials: Vec<TrialResult>,
183        evaluators: &[String],
184        thresholds: &[(String, f64)],
185    ) -> Self {
186        let summary: Vec<EvaluatorSummary> = evaluators
187            .iter()
188            .map(|evaluator| {
189                let scores = trials
190                    .iter()
191                    .flat_map(|trial| &trial.scores)
192                    .filter(|score| &score.evaluator == evaluator);
193                let (count, passed, sum, not_applicable) =
194                    scores.fold((0, 0, 0.0, 0), |(count, passed, sum, na), score| {
195                        if score.not_applicable {
196                            return (count, passed, sum, na + 1);
197                        }
198                        (
199                            count + 1,
200                            passed + usize::from(score.passed),
201                            sum + score.value,
202                            na,
203                        )
204                    });
205                let per = |value: f64| {
206                    if count == 0 {
207                        0.0
208                    } else {
209                        value / count as f64
210                    }
211                };
212                EvaluatorSummary {
213                    evaluator: evaluator.clone(),
214                    count,
215                    passed,
216                    pass_rate: per(passed as f64),
217                    mean: per(sum),
218                    not_applicable,
219                }
220            })
221            .collect();
222        let thresholds = summary
223            .iter()
224            .map(|summary| {
225                let min_pass_rate = thresholds
226                    .iter()
227                    .rev()
228                    .find(|(name, _)| name == &summary.evaluator)
229                    .map_or(1.0, |(_, min)| *min);
230                ThresholdResult {
231                    evaluator: summary.evaluator.clone(),
232                    min_pass_rate,
233                    pass_rate: summary.pass_rate,
234                    // Nothing applicable to fail.
235                    passed: summary.count == 0 || summary.pass_rate >= min_pass_rate,
236                }
237            })
238            .collect();
239        let mut tokens = Tokens::default();
240        for usage in trials.iter().map(|trial| &trial.trial.usage) {
241            add_usage(&mut tokens, usage);
242        }
243        let mut judge_tokens = Tokens::default();
244        for usage in trials
245            .iter()
246            .flat_map(|trial| &trial.scores)
247            .filter_map(|score| score.usage.as_ref())
248        {
249            add_usage(&mut judge_tokens, usage);
250        }
251        tokens.input += judge_tokens.input;
252        tokens.output += judge_tokens.output;
253        tokens.total += judge_tokens.total;
254        let mut latencies: Vec<Duration> = trials.iter().map(|trial| trial.trial.latency).collect();
255        latencies.sort_unstable();
256        let latency = LatencySummary {
257            p50: percentile(&latencies, 0.50),
258            p95: percentile(&latencies, 0.95),
259        };
260        Self {
261            experiment,
262            repetitions,
263            trials,
264            summary,
265            tokens,
266            judge_tokens,
267            latency,
268            thresholds,
269        }
270    }
271
272    /// Whether every evaluator reached its threshold: the exit status for CI.
273    pub fn passed(&self) -> bool {
274        self.thresholds.iter().all(|threshold| threshold.passed)
275    }
276
277    /// An evaluator's pass rate.
278    pub fn pass_rate(&self, evaluator: &str) -> Option<f64> {
279        self.summary
280            .iter()
281            .find(|summary| summary.evaluator == evaluator)
282            .map(|summary| summary.pass_rate)
283    }
284
285    /// The report as pretty-printed JSON.
286    pub fn to_json(&self) -> Result<String, serde_json::Error> {
287        serde_json::to_string_pretty(self)
288    }
289
290    /// The report as JUnit XML: a test case per trial (failing when an
291    /// evaluator failed it) and per threshold.
292    pub fn to_junit(&self) -> String {
293        let name = escape(&self.experiment);
294        let tests = self.trials.len() + self.thresholds.len();
295        let skipped = self.trials.iter().filter(|trial| trial.skipped()).count();
296        let failures = self.trials.iter().filter(|trial| !trial.passed()).count()
297            + self
298                .thresholds
299                .iter()
300                .filter(|threshold| !threshold.passed)
301                .count();
302        let time: f64 = self
303            .trials
304            .iter()
305            .map(|trial| trial.trial.latency.as_secs_f64())
306            .sum();
307        let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
308        let _ = writeln!(
309            xml,
310            "<testsuites name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" time=\"{time:.3}\">"
311        );
312        let _ = writeln!(
313            xml,
314            "  <testsuite name=\"{name}\" tests=\"{tests}\" failures=\"{failures}\" errors=\"0\" skipped=\"{skipped}\" time=\"{time:.3}\">"
315        );
316        for result in &self.trials {
317            let trial = &result.trial;
318            let case = if self.repetitions > 1 {
319                format!("{} #{}", trial.case_id, trial.repetition)
320            } else {
321                trial.case_id.clone()
322            };
323            let _ = write!(
324                xml,
325                "    <testcase name=\"{}\" classname=\"{name}\" time=\"{:.3}\"",
326                escape(&case),
327                trial.latency.as_secs_f64()
328            );
329            let failed: Vec<&Score> = result.failures().collect();
330            if failed.is_empty() {
331                if result.skipped() {
332                    let why: Vec<String> = result
333                        .scores
334                        .iter()
335                        .filter(|score| score.not_applicable)
336                        .map(|score| {
337                            format!(
338                                "{}: {}",
339                                score.evaluator,
340                                score.explanation.as_deref().unwrap_or("not applicable")
341                            )
342                        })
343                        .collect();
344                    let message = format!("not applicable: {}", why.join("; "));
345                    let _ = write!(
346                        xml,
347                        ">\n      <skipped message=\"{}\"/>\n    </testcase>\n",
348                        escape(&message)
349                    );
350                } else {
351                    xml.push_str("/>\n");
352                }
353                continue;
354            }
355            let names: Vec<&str> = failed
356                .iter()
357                .map(|score| score.evaluator.as_str())
358                .collect();
359            let mut body = String::new();
360            if let Some(error) = &trial.error {
361                let _ = writeln!(body, "target error: {error}");
362            }
363            for score in &failed {
364                let _ = writeln!(
365                    body,
366                    "{} ({:.2}): {}",
367                    score.evaluator,
368                    score.value,
369                    score.explanation.as_deref().unwrap_or("failed")
370                );
371            }
372            let _ = write!(
373                xml,
374                ">\n      <failure message=\"failed: {}\" type=\"evaluation\">{}</failure>\n    </testcase>\n",
375                escape(&names.join(", ")),
376                escape(&body)
377            );
378        }
379        for threshold in &self.thresholds {
380            let _ = write!(
381                xml,
382                "    <testcase name=\"threshold {}\" classname=\"{name}.thresholds\"",
383                escape(&threshold.evaluator)
384            );
385            if threshold.passed {
386                xml.push_str("/>\n");
387            } else {
388                let _ = write!(
389                    xml,
390                    ">\n      <failure message=\"pass rate {:.2} below {:.2}\" type=\"threshold\"/>\n    </testcase>\n",
391                    threshold.pass_rate, threshold.min_pass_rate
392                );
393            }
394        }
395        xml.push_str("  </testsuite>\n</testsuites>\n");
396        xml
397    }
398
399    /// The report as Markdown: the outcome, a table per evaluator, tokens,
400    /// latency, and the failed trials.
401    pub fn to_markdown(&self) -> String {
402        let outcome = if self.passed() { "passed" } else { "FAILED" };
403        let mut md = format!(
404            "# {}: {outcome}\n\n{} trials ({} cases × {} repetitions)\n\n",
405            self.experiment,
406            self.trials.len(),
407            self.trials.len() / self.repetitions.max(1),
408            self.repetitions
409        );
410        md.push_str("| Evaluator | Pass rate | Threshold | Mean | Passed | Result |\n|---|---|---|---|---|---|\n");
411        for (summary, threshold) in self.summary.iter().zip(&self.thresholds) {
412            let applicable = summary.count > 0;
413            let (rate, mean) = if applicable {
414                (
415                    format!("{:.0}%", summary.pass_rate * 100.0),
416                    format!("{:.2}", summary.mean),
417                )
418            } else {
419                ("N/A".to_owned(), "N/A".to_owned())
420            };
421            let not_applicable = if summary.not_applicable > 0 {
422                format!(" ({} N/A)", summary.not_applicable)
423            } else {
424                String::new()
425            };
426            let result = match (applicable, threshold.passed) {
427                (false, _) => "N/A",
428                (true, true) => "pass",
429                (true, false) => "FAIL",
430            };
431            let _ = writeln!(
432                md,
433                "| {} | {rate} | {:.0}% | {mean} | {}/{}{not_applicable} | {result} |",
434                cell(&summary.evaluator),
435                threshold.min_pass_rate * 100.0,
436                summary.passed,
437                summary.count,
438            );
439        }
440        let judges = if self.judge_tokens == Tokens::default() {
441            String::new()
442        } else {
443            format!(
444                " Of which LLM judges: {} input, {} output, {} total.",
445                self.judge_tokens.input, self.judge_tokens.output, self.judge_tokens.total
446            )
447        };
448        let _ = writeln!(
449            md,
450            "\nTokens: {} input, {} output, {} total.{judges} Latency: p50 {:?}, p95 {:?}.",
451            self.tokens.input,
452            self.tokens.output,
453            self.tokens.total,
454            self.latency.p50,
455            self.latency.p95
456        );
457        let failed: Vec<&TrialResult> =
458            self.trials.iter().filter(|trial| !trial.passed()).collect();
459        if !failed.is_empty() {
460            md.push_str("\n## Failures\n\n");
461            for result in failed {
462                let trial = &result.trial;
463                for score in result.failures() {
464                    let _ = writeln!(
465                        md,
466                        "- `{}` #{} {}: {}",
467                        trial.case_id,
468                        trial.repetition,
469                        score.evaluator,
470                        one_line(score.explanation.as_deref().unwrap_or("failed"))
471                    );
472                }
473            }
474        }
475        md
476    }
477}
478
479/// Add `usage` to `tokens`; a total not reported is input plus output.
480fn add_usage(tokens: &mut Tokens, usage: &Usage) {
481    let (input, output) = (
482        usage.input_tokens.unwrap_or(0),
483        usage.output_tokens.unwrap_or(0),
484    );
485    tokens.input += input;
486    tokens.output += output;
487    tokens.total += usage.total_tokens.unwrap_or(input + output);
488}
489
490/// The nearest-rank percentile `p` of sorted `values`; zero when empty.
491fn percentile(sorted: &[Duration], p: f64) -> Duration {
492    let rank = (p * sorted.len() as f64).ceil() as usize;
493    sorted
494        .get(rank.saturating_sub(1))
495        .copied()
496        .unwrap_or_default()
497}
498
499/// `text` safe in XML text and attributes: markup escaped, and the control
500/// characters XML 1.0 forbids dropped.
501fn escape(text: &str) -> String {
502    let mut out = String::with_capacity(text.len());
503    for c in text.chars() {
504        match c {
505            '&' => out.push_str("&amp;"),
506            '<' => out.push_str("&lt;"),
507            '>' => out.push_str("&gt;"),
508            '"' => out.push_str("&quot;"),
509            '\'' => out.push_str("&apos;"),
510            '\t' | '\n' | '\r' => out.push(c),
511            c if (c as u32) < 0x20 => {}
512            c => out.push(c),
513        }
514    }
515    out
516}
517
518/// `text` on one line.
519fn one_line(text: &str) -> String {
520    text.split_whitespace().collect::<Vec<_>>().join(" ")
521}
522
523/// `text` safe in a Markdown table cell.
524fn cell(text: &str) -> String {
525    one_line(text).replace('|', "\\|")
526}
527
528/// A duration as fractional milliseconds.
529mod millis {
530    use std::time::Duration;
531
532    use serde::{Deserialize, Deserializer, Serializer};
533
534    pub(super) fn serialize<S: Serializer>(
535        duration: &Duration,
536        serializer: S,
537    ) -> Result<S::Ok, S::Error> {
538        serializer.serialize_f64(duration.as_secs_f64() * 1000.0)
539    }
540
541    pub(super) fn deserialize<'de, D: Deserializer<'de>>(
542        deserializer: D,
543    ) -> Result<Duration, D::Error> {
544        let millis = f64::deserialize(deserializer)?;
545        Duration::try_from_secs_f64(millis / 1000.0).map_err(serde::de::Error::custom)
546    }
547}
548
549#[cfg(test)]
550mod tests;