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
11/// One run of the target on a case.
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
13#[non_exhaustive]
14pub struct Trial {
15    /// The case's id.
16    pub case_id: String,
17    /// Which run of the case this is, from 1.
18    pub repetition: usize,
19    /// The answer; empty when the target failed.
20    pub output: String,
21    /// The tool calls, in order.
22    pub tool_calls: Vec<ToolCall>,
23    /// The model tokens spent.
24    pub usage: Usage,
25    /// How long the run took.
26    #[serde(rename = "latency_ms", with = "millis")]
27    pub latency: Duration,
28    /// Why the target failed, if it did.
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub error: Option<String>,
31    /// The session the target ran in, when it reports one (an AgentCore
32    /// runtime does): remote evaluators look up the run's traces by it.
33    #[serde(default, skip_serializing_if = "Option::is_none")]
34    pub session_id: Option<String>,
35    /// Each turn of a multi-turn case and its answer, in order; empty for a
36    /// single-turn case. `output` is the answer to the last turn.
37    #[serde(default, skip_serializing_if = "Vec::is_empty")]
38    pub transcript: Vec<Turn>,
39}
40
41impl Trial {
42    /// A successful run of `case_id` that answered `output`, with no tool
43    /// calls, usage or latency: to test an evaluator.
44    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/// A trial and its scores.
60#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
61#[non_exhaustive]
62pub struct TrialResult {
63    /// The run.
64    pub trial: Trial,
65    /// One per evaluator, in the experiment's order.
66    pub scores: Vec<Score>,
67}
68
69impl TrialResult {
70    /// Whether every evaluator passed the run.
71    pub fn passed(&self) -> bool {
72        self.scores
73            .iter()
74            .all(|score| score.passed || score.not_applicable)
75    }
76
77    /// Whether an evaluator did not apply to the run: with no failure, the
78    /// run is reported as skipped in JUnit.
79    fn skipped(&self) -> bool {
80        self.scores.iter().any(|score| score.not_applicable)
81    }
82
83    /// The scores that failed (not the ones not applicable).
84    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/// One evaluator's results over all trials.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct EvaluatorSummary {
95    /// The evaluator.
96    pub evaluator: String,
97    /// The trials scored (not counting the ones not applicable).
98    pub count: usize,
99    /// The trials it passed.
100    pub passed: usize,
101    /// `passed / count`; 0 when no trial was applicable.
102    pub pass_rate: f64,
103    /// The mean score value over the trials scored.
104    pub mean: f64,
105    /// The trials the evaluator did not apply to (N/A): left out of
106    /// `count`, `pass_rate` and `mean`.
107    #[serde(default)]
108    pub not_applicable: usize,
109}
110
111/// Model tokens over all trials.
112#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
113#[non_exhaustive]
114pub struct Tokens {
115    /// Input tokens.
116    pub input: u64,
117    /// Output tokens.
118    pub output: u64,
119    /// The reported totals, or input plus output where none was reported.
120    pub total: u64,
121}
122
123/// Run latencies over all trials.
124#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize, Deserialize)]
125#[non_exhaustive]
126pub struct LatencySummary {
127    /// The median.
128    #[serde(rename = "p50_ms", with = "millis")]
129    pub p50: Duration,
130    /// The 95th percentile.
131    #[serde(rename = "p95_ms", with = "millis")]
132    pub p95: Duration,
133}
134
135/// Whether an evaluator's pass rate reached its threshold.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137#[non_exhaustive]
138pub struct ThresholdResult {
139    /// The evaluator.
140    pub evaluator: String,
141    /// The lowest pass rate that passes: 1 unless the experiment set one.
142    pub min_pass_rate: f64,
143    /// The pass rate reached.
144    pub pass_rate: f64,
145    /// `pass_rate >= min_pass_rate`, or no trial was applicable.
146    pub passed: bool,
147}
148
149/// What an experiment found.
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
151#[non_exhaustive]
152pub struct Report {
153    /// The experiment's name.
154    pub experiment: String,
155    /// How many times each case ran.
156    pub repetitions: usize,
157    /// Every trial, by case then repetition.
158    pub trials: Vec<TrialResult>,
159    /// Per evaluator, in the experiment's order.
160    pub summary: Vec<EvaluatorSummary>,
161    /// Model tokens: the target's and the LLM judges'.
162    pub tokens: Tokens,
163    /// The part of `tokens` that LLM judges spent.
164    #[serde(default)]
165    pub judge_tokens: Tokens,
166    /// Run latencies.
167    pub latency: LatencySummary,
168    /// One per evaluator.
169    pub thresholds: Vec<ThresholdResult>,
170}
171
172impl Report {
173    /// Summarize `trials`, scored by `evaluators` with minimum pass rates
174    /// `thresholds` (1 for the others).
175    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                    // Nothing applicable to fail.
231                    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    /// Whether every evaluator reached its threshold: the exit status for CI.
269    pub fn passed(&self) -> bool {
270        self.thresholds.iter().all(|threshold| threshold.passed)
271    }
272
273    /// An evaluator's pass rate.
274    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    /// The report as pretty-printed JSON.
282    pub fn to_json(&self) -> Result<String, serde_json::Error> {
283        serde_json::to_string_pretty(self)
284    }
285
286    /// The report as JUnit XML: a test case per trial (failing when an
287    /// evaluator failed it) and per threshold.
288    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    /// The report as Markdown: the outcome, a table per evaluator, tokens,
396    /// latency, and the failed trials.
397    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
475/// Add `usage` to `tokens`; a total not reported is input plus output.
476fn 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
486/// The nearest-rank percentile `p` of sorted `values`; zero when empty.
487fn 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
495/// `text` safe in XML text and attributes: markup escaped, and the control
496/// characters XML 1.0 forbids dropped.
497fn 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("&amp;"),
502            '<' => out.push_str("&lt;"),
503            '>' => out.push_str("&gt;"),
504            '"' => out.push_str("&quot;"),
505            '\'' => out.push_str("&apos;"),
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
514/// `text` on one line.
515fn one_line(text: &str) -> String {
516    text.split_whitespace().collect::<Vec<_>>().join(" ")
517}
518
519/// `text` safe in a Markdown table cell.
520fn cell(text: &str) -> String {
521    one_line(text).replace('|', "\\|")
522}
523
524/// A duration as fractional milliseconds.
525mod 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;