Skip to main content

rig_evals/
report.rs

1//! What an experiment found, and its JSON, JUnit and Markdown forms.
2
3use 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/// One run of the target on a case.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18#[non_exhaustive]
19pub struct Trial {
20    /// The case's id.
21    pub case_id: String,
22    /// Which run of the case this is, from 1.
23    pub repetition: usize,
24    /// The answer; empty when the target failed.
25    pub output: String,
26    /// The tool calls, in order.
27    pub tool_calls: Vec<ToolCall>,
28    /// The model tokens spent.
29    pub usage: Usage,
30    /// How long the run took.
31    #[serde(rename = "latency_ms", with = "millis")]
32    pub latency: Duration,
33    /// Why the target failed, if it did.
34    #[serde(default, skip_serializing_if = "Option::is_none")]
35    pub error: Option<String>,
36    /// The session the target ran in, when it reports one (an AgentCore
37    /// runtime does): remote evaluators look up the run's traces by it.
38    #[serde(default, skip_serializing_if = "Option::is_none")]
39    pub session_id: Option<String>,
40    /// Each turn of a multi-turn case and its answer, in order; empty for a
41    /// single-turn case. `output` is the answer to the last turn.
42    #[serde(default, skip_serializing_if = "Vec::is_empty")]
43    pub transcript: Vec<Turn>,
44}
45
46impl Trial {
47    /// A successful run of `case_id` that answered `output`, with no tool
48    /// calls, usage or latency: to test an evaluator.
49    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/// A trial and its scores.
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[non_exhaustive]
67pub struct TrialResult {
68    /// The run.
69    pub trial: Trial,
70    /// One per evaluator, in the experiment's order.
71    pub scores: Vec<Score>,
72}
73
74impl TrialResult {
75    /// Whether every evaluator passed the run.
76    pub fn passed(&self) -> bool {
77        self.scores
78            .iter()
79            .all(|score| score.passed || score.not_applicable)
80    }
81
82    /// Whether an evaluator did not apply to the run: with no failure, the
83    /// run is reported as skipped in JUnit.
84    fn skipped(&self) -> bool {
85        self.scores.iter().any(|score| score.not_applicable)
86    }
87
88    /// The scores that failed (not the ones not applicable).
89    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/// One evaluator's results over all trials.
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
98#[non_exhaustive]
99pub struct EvaluatorSummary {
100    /// The evaluator.
101    pub evaluator: String,
102    /// The trials scored (not counting the ones not applicable).
103    pub count: usize,
104    /// The trials it passed.
105    pub passed: usize,
106    /// `passed / count`; 0 when no trial was applicable.
107    pub pass_rate: f64,
108    /// The mean score value over the trials scored.
109    pub mean: f64,
110    /// The trials the evaluator did not apply to (N/A): left out of
111    /// `count`, `pass_rate` and `mean`.
112    #[serde(default)]
113    pub not_applicable: usize,
114    /// pass@k with k = the repetitions: an estimate of the chance that at
115    /// least one of k trials of a case passed, averaged over the cases with
116    /// at least k applicable trials (`None` when there are none). A case
117    /// with fewer applicable trials (for example, one with N/A trials) is
118    /// left out. Errored trials count as scores, as in `pass_rate`. Equals
119    /// `pass_rate` with one repetition. See [`Report::pass_at_k`].
120    #[serde(default)]
121    pub pass_at_k: Option<f64>,
122    /// pass^k with k = the repetitions: an estimate of the chance that all k
123    /// trials of a case passed, averaged the same way (cases with fewer than
124    /// k applicable trials are left out; errored trials count as scores, as
125    /// in `pass_rate`). See [`Report::pass_hat_k`].
126    #[serde(default)]
127    pub pass_hat_k: Option<f64>,
128    /// The score at or above which the evaluator passes a run, when it has
129    /// one (an [`LlmJudge`](crate::LlmJudge)'s threshold). `None` otherwise;
130    /// left out of the JSON then.
131    #[serde(default, skip_serializing_if = "Option::is_none")]
132    pub pass_cutoff: Option<f64>,
133}
134
135/// Model tokens over all trials.
136#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
137#[non_exhaustive]
138pub struct Tokens {
139    /// Input tokens.
140    pub input: u64,
141    /// Output tokens.
142    pub output: u64,
143    /// The reported totals, or input plus output where none was reported.
144    pub total: u64,
145}
146
147/// Run latencies over all trials.
148#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct LatencySummary {
151    /// The median.
152    #[serde(rename = "p50_ms", with = "millis")]
153    pub p50: Duration,
154    /// The 95th percentile.
155    #[serde(rename = "p95_ms", with = "millis")]
156    pub p95: Duration,
157}
158
159/// Whether an evaluator's pass rate reached its threshold.
160#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
161#[non_exhaustive]
162pub struct ThresholdResult {
163    /// The evaluator.
164    pub evaluator: String,
165    /// The lowest pass rate that passes: 1 unless the experiment set one.
166    pub min_pass_rate: f64,
167    /// The pass rate reached.
168    pub pass_rate: f64,
169    /// `pass_rate >= min_pass_rate`, or no trial was applicable.
170    pub passed: bool,
171}
172
173/// What an experiment found.
174#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
175#[non_exhaustive]
176pub struct Report {
177    /// The experiment's name.
178    pub experiment: String,
179    /// How many times each case ran.
180    pub repetitions: usize,
181    /// Every trial, by case then repetition.
182    pub trials: Vec<TrialResult>,
183    /// Per evaluator, in the experiment's order.
184    pub summary: Vec<EvaluatorSummary>,
185    /// Model tokens: the target's and the LLM judges'.
186    pub tokens: Tokens,
187    /// The part of `tokens` that LLM judges spent.
188    #[serde(default)]
189    pub judge_tokens: Tokens,
190    /// Run latencies.
191    pub latency: LatencySummary,
192    /// One per evaluator.
193    pub thresholds: Vec<ThresholdResult>,
194}
195
196impl Report {
197    /// Summarize `trials`, scored by `evaluators` (each with its pass cutoff,
198    /// if any) with minimum pass rates `thresholds` (1 for the others).
199    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                    // Nothing applicable to fail.
258                    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    /// Whether every evaluator reached its threshold: the exit status for CI.
296    pub fn passed(&self) -> bool {
297        self.thresholds.iter().all(|threshold| threshold.passed)
298    }
299
300    /// An evaluator's pass rate.
301    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    /// An evaluator's pass@k estimate (Chen et al. 2021): per case, the chance
309    /// that at least one of `k` of its trials passed, from its `n` applicable
310    /// trials with `c` passed, as `1 - C(n - c, k) / C(n, k)`; then the mean
311    /// over the cases with `n >= k`. Cases with fewer applicable trials (for
312    /// example, N/A trials) are left out; errored trials count as scores, as in
313    /// `pass_rate`. `None` when `k` is 0 or no case has `k` trials.
314    /// With `k = n` it is the share of cases with any pass.
315    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    /// An evaluator's pass^k (tau-bench): per case, the chance that all `k`
320    /// of its trials passed, as `C(c, k) / C(n, k)`; then the mean over the
321    /// cases with `n >= k`. `None` when `k` is 0 or no case has `k` trials.
322    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    /// The report as pretty-printed JSON.
327    pub fn to_json(&self) -> Result<String, serde_json::Error> {
328        serde_json::to_string_pretty(self)
329    }
330
331    /// The report as JUnit XML: a test case per trial (failing when an
332    /// evaluator failed it) and per threshold.
333    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    /// The report as Markdown: the outcome, a table per evaluator, tokens,
441    /// latency, and the failed trials.
442    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        // pass@k and pass^k only say something beyond the pass rate with repetitions.
452        let multi = self.repetitions > 1;
453        // The pass cutoff is a column only when some evaluator has one.
454        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
552/// The mean of `estimate(n, c, k)` over the cases of `evaluator`, where `n`
553/// is a case's applicable trials and `c` how many passed. Cases the estimate
554/// is undefined for (`n < k`) are left out; `None` when none is left.
555fn 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
583/// Chen et al.'s pass@k for one case: `1 - C(n - c, k) / C(n, k)`.
584fn 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
588/// tau-bench's pass^k for one case: `C(c, k) / C(n, k)`.
589fn pass_hat(n: usize, c: usize, k: usize) -> Option<f64> {
590    ratio(c.min(n), n, k)
591}
592
593/// `C(a, k) / C(n, k)` in product form, so no binomial is computed and
594/// nothing overflows. Zero when `a < k`; `None` when `k` is 0 or above `n`.
595fn 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
605/// Add `usage` to `tokens`; a total not reported is input plus output.
606fn 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
616/// The nearest-rank percentile `p` of sorted `values`; zero when empty.
617fn 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
625/// `text` safe in XML text and attributes: markup escaped, and the control
626/// characters XML 1.0 forbids dropped.
627fn 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("&amp;"),
632            '<' => out.push_str("&lt;"),
633            '>' => out.push_str("&gt;"),
634            '"' => out.push_str("&quot;"),
635            '\'' => out.push_str("&apos;"),
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
644/// `text` on one line.
645fn one_line(text: &str) -> String {
646    text.split_whitespace().collect::<Vec<_>>().join(" ")
647}
648
649/// `text` safe in a Markdown table cell.
650fn cell(text: &str) -> String {
651    one_line(text).replace('|', "\\|")
652}
653
654/// A duration as fractional milliseconds.
655mod 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;