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