Skip to main content

adk_eval/
multi_run.rs

1//! Repeated runs of an eval set: per-case pass rate, score statistics and flakiness.
2//!
3//! An agent backed by a sampling model can pass a case once and fail it the next time. One
4//! run cannot tell a reliable case from a lucky one, so
5//! [`Evaluator::evaluate_test_file_runs`](crate::Evaluator::evaluate_test_file_runs) runs the
6//! whole eval set `num_runs` times, each case in a fresh session every time, and
7//! [`MultiRunReport`] summarises the runs per case:
8//!
9//! | Field | Meaning |
10//! |-------|---------|
11//! | [`pass_rate`](CaseRunSummary::pass_rate) | Runs in which the case passed, divided by the runs completed |
12//! | [`scores`](CaseRunSummary::scores) | Mean, sample variance, standard deviation, minimum and maximum of each criterion's score |
13//! | [`flaky`](CaseRunSummary::flaky) | The case passed in some runs and failed in others |
14//! | [`passed`](CaseRunSummary::passed) | The pass rate reached [`MultiRunConfig::min_pass_rate`] |
15//!
16//! [`MultiRunReport::baseline_metrics`] gives the mean score of every criterion and the
17//! [`PASS_RATE_METRIC`] per case, so a [`BaselineStore`](crate::BaselineStore) regression check
18//! catches a case that became flaky as well as one whose scores dropped.
19//!
20//! # Example
21//!
22//! ```rust,no_run
23//! use std::sync::Arc;
24//!
25//! use adk_core::Agent;
26//! use adk_eval::{EvaluationConfig, EvaluationCriteria, Evaluator, MultiRunConfig, TestFile};
27//!
28//! async fn check(agent: Arc<dyn Agent>) -> adk_eval::Result<()> {
29//!     let evaluator = Evaluator::new(EvaluationConfig::with_criteria(
30//!         EvaluationCriteria::exact_tools(),
31//!     ));
32//!     let test_file = TestFile::load("tests/weather.test.json")?;
33//!     let config = MultiRunConfig::new(5)?.with_min_pass_rate(0.8)?;
34//!     let report = evaluator.evaluate_test_file_runs(agent, &test_file, &config).await?;
35//!     for case in report.flaky_cases() {
36//!         eprintln!("{} passed {} of {} runs", case.eval_id, case.passed_runs, case.runs);
37//!     }
38//!     assert!(report.all_passed(), "{}", report.format_summary());
39//!     Ok(())
40//! }
41//! ```
42
43use std::collections::{BTreeMap, HashMap};
44use std::time::Duration;
45
46use serde::{Deserialize, Serialize};
47use serde_json::Value;
48
49use crate::error::{EvalError, Result};
50use crate::report::{EvaluationReport, EvaluationResult, Failure};
51
52/// The baseline metric that holds a case's pass rate across runs.
53pub const PASS_RATE_METRIC: &str = "pass_rate";
54
55/// How many times to run an eval set, and how often a case must pass.
56///
57/// # Example
58///
59/// ```
60/// use adk_eval::MultiRunConfig;
61///
62/// let config = MultiRunConfig::new(3)?.with_min_pass_rate(2.0 / 3.0)?;
63/// assert_eq!(config.num_runs, 3);
64/// assert!(MultiRunConfig::new(0).is_err());
65/// # Ok::<(), adk_eval::EvalError>(())
66/// ```
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[non_exhaustive]
69pub struct MultiRunConfig {
70    /// Runs of the whole eval set, at least 1.
71    pub num_runs: usize,
72    /// Fraction of runs, from 0.0 to 1.0, a case must pass to pass overall. The default,
73    /// 1.0, requires every run to pass.
74    pub min_pass_rate: f64,
75}
76
77impl MultiRunConfig {
78    /// Runs the eval set `num_runs` times, requiring every run of a case to pass.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`EvalError::ConfigError`] when `num_runs` is 0.
83    pub fn new(num_runs: usize) -> Result<Self> {
84        if num_runs == 0 {
85            return Err(EvalError::ConfigError(
86                "num_runs must be at least 1; one run is a plain evaluation".to_string(),
87            ));
88        }
89        Ok(Self { num_runs, min_pass_rate: 1.0 })
90    }
91
92    /// Sets the fraction of runs a case must pass.
93    ///
94    /// # Errors
95    ///
96    /// Returns [`EvalError::ConfigError`] when `min_pass_rate` is not between 0.0 and 1.0.
97    pub fn with_min_pass_rate(mut self, min_pass_rate: f64) -> Result<Self> {
98        if !(0.0..=1.0).contains(&min_pass_rate) {
99            return Err(EvalError::ConfigError(format!(
100                "min_pass_rate must be between 0.0 and 1.0, got {min_pass_rate}"
101            )));
102        }
103        self.min_pass_rate = min_pass_rate;
104        Ok(self)
105    }
106}
107
108/// Statistics of one criterion's score across runs.
109///
110/// # Example
111///
112/// ```
113/// use adk_eval::ScoreStats;
114///
115/// let stats = ScoreStats::from_scores(&[1.0, 0.5, 0.0]).unwrap();
116/// assert_eq!(stats.mean, 0.5);
117/// assert_eq!(stats.variance, 0.25); // sample variance, n - 1 in the denominator
118/// assert_eq!(stats.std_dev, 0.5);
119/// assert!(ScoreStats::from_scores(&[]).is_none());
120/// ```
121#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
122#[non_exhaustive]
123pub struct ScoreStats {
124    /// Runs in which the criterion was scored.
125    pub count: usize,
126    /// Arithmetic mean.
127    pub mean: f64,
128    /// Sample variance, with `count - 1` in the denominator; 0.0 for a single score.
129    pub variance: f64,
130    /// Square root of the variance.
131    pub std_dev: f64,
132    /// Lowest score.
133    pub min: f64,
134    /// Highest score.
135    pub max: f64,
136}
137
138impl ScoreStats {
139    /// Computes the statistics of `scores`, or `None` when there are none.
140    pub fn from_scores(scores: &[f64]) -> Option<Self> {
141        if scores.is_empty() {
142            return None;
143        }
144        let count = scores.len();
145        let mean = scores.iter().sum::<f64>() / count as f64;
146        let variance = if count > 1 {
147            scores.iter().map(|score| (score - mean).powi(2)).sum::<f64>() / (count - 1) as f64
148        } else {
149            0.0
150        };
151        Some(Self {
152            count,
153            mean,
154            variance,
155            std_dev: variance.sqrt(),
156            min: scores.iter().copied().fold(f64::INFINITY, f64::min),
157            max: scores.iter().copied().fold(f64::NEG_INFINITY, f64::max),
158        })
159    }
160}
161
162/// One case across every completed run.
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
164#[non_exhaustive]
165pub struct CaseRunSummary {
166    /// The case's `eval_id`.
167    pub eval_id: String,
168    /// Runs in which the case ran.
169    pub runs: usize,
170    /// Runs in which the case passed.
171    pub passed_runs: usize,
172    /// `passed_runs / runs`.
173    pub pass_rate: f64,
174    /// `true` when the case passed in some runs and failed in others.
175    pub flaky: bool,
176    /// `true` when the pass rate reached the report's minimum.
177    pub passed: bool,
178    /// Statistics of each criterion's score, by criterion name.
179    pub scores: BTreeMap<String, ScoreStats>,
180    /// Runs in which each criterion failed, by criterion name.
181    pub failed_criteria: BTreeMap<String, usize>,
182}
183
184/// The result of running an eval set several times.
185#[derive(Debug, Clone, Serialize, Deserialize)]
186#[non_exhaustive]
187pub struct MultiRunReport {
188    /// The eval set's id.
189    pub eval_set_id: String,
190    /// Runs requested.
191    pub requested_runs: usize,
192    /// Fraction of runs a case must pass.
193    pub min_pass_rate: f64,
194    /// One summary per case, in the order the cases first appeared.
195    pub cases: Vec<CaseRunSummary>,
196    /// The report of every completed run, in order.
197    pub runs: Vec<EvaluationReport>,
198    /// Why the runs stopped before `requested_runs` completed: a budget, spend cap or kill
199    /// switch refusal. The run it interrupted is not counted.
200    pub stopped: Option<String>,
201    /// When the first run started.
202    pub started_at: chrono::DateTime<chrono::Utc>,
203    /// Wall time of every completed run.
204    pub duration: Duration,
205}
206
207impl MultiRunReport {
208    /// Summarises the reports of completed runs of one eval set.
209    ///
210    /// A case passes when it passed in at least `min_pass_rate` of the runs it ran in. A
211    /// case that errored in a run counts as failing that run.
212    ///
213    /// # Example
214    ///
215    /// ```
216    /// use std::collections::HashMap;
217    /// use std::time::Duration;
218    ///
219    /// use adk_eval::{EvaluationReport, EvaluationResult, MultiRunReport};
220    ///
221    /// let run = |passed: bool| {
222    ///     let scores = HashMap::from([("response_similarity".to_string(), if passed { 1.0 } else { 0.4 })]);
223    ///     let result = if passed {
224    ///         EvaluationResult::passed("weather", scores, Duration::ZERO)
225    ///     } else {
226    ///         EvaluationResult::failed("weather", scores, vec![], Duration::ZERO)
227    ///     };
228    ///     EvaluationReport::new("run", vec![result], chrono::Utc::now())
229    /// };
230    /// let report = MultiRunReport::from_runs("weather", 3, 1.0, vec![run(true), run(false), run(true)]);
231    /// let case = &report.cases[0];
232    /// assert_eq!((case.passed_runs, case.runs, case.flaky, case.passed), (2, 3, true, false));
233    /// assert!(!report.all_passed());
234    /// ```
235    pub fn from_runs(
236        eval_set_id: &str,
237        requested_runs: usize,
238        min_pass_rate: f64,
239        runs: Vec<EvaluationReport>,
240    ) -> Self {
241        let mut order: Vec<String> = Vec::new();
242        let mut by_case: HashMap<String, Vec<&EvaluationResult>> = HashMap::new();
243        for result in runs.iter().flat_map(|run| &run.results) {
244            by_case
245                .entry(result.eval_id.clone())
246                .or_insert_with(|| {
247                    order.push(result.eval_id.clone());
248                    Vec::new()
249                })
250                .push(result);
251        }
252
253        let cases = order
254            .into_iter()
255            .map(|eval_id| {
256                let results = &by_case[&eval_id];
257                summarise_case(eval_id, results, min_pass_rate)
258            })
259            .collect();
260
261        Self {
262            eval_set_id: eval_set_id.to_string(),
263            requested_runs,
264            min_pass_rate,
265            cases,
266            started_at: runs.first().map_or_else(chrono::Utc::now, |run| run.started_at),
267            duration: runs.iter().map(|run| run.duration).sum(),
268            runs,
269            stopped: None,
270        }
271    }
272
273    /// Records why the runs stopped early.
274    pub fn with_stopped(mut self, reason: impl Into<String>) -> Self {
275        self.stopped = Some(reason.into());
276        self
277    }
278
279    /// Runs that completed.
280    pub fn completed_runs(&self) -> usize {
281        self.runs.len()
282    }
283
284    /// `true` when every requested run completed and every case reached the minimum pass
285    /// rate.
286    pub fn all_passed(&self) -> bool {
287        self.stopped.is_none()
288            && self.completed_runs() == self.requested_runs
289            && !self.cases.is_empty()
290            && self.cases.iter().all(|case| case.passed)
291    }
292
293    /// The cases that passed in some runs and failed in others.
294    pub fn flaky_cases(&self) -> impl Iterator<Item = &CaseRunSummary> {
295        self.cases.iter().filter(|case| case.flaky)
296    }
297
298    /// Metric name → case id → value, the shape [`BaselineStore`](crate::BaselineStore)
299    /// stores: the mean score of every criterion and the case's [`PASS_RATE_METRIC`].
300    pub fn baseline_metrics(&self) -> HashMap<String, HashMap<String, f64>> {
301        let mut metrics: HashMap<String, HashMap<String, f64>> = HashMap::new();
302        for case in &self.cases {
303            for (criterion, stats) in &case.scores {
304                metrics
305                    .entry(criterion.clone())
306                    .or_default()
307                    .insert(case.eval_id.clone(), stats.mean);
308            }
309            metrics
310                .entry(PASS_RATE_METRIC.to_string())
311                .or_default()
312                .insert(case.eval_id.clone(), case.pass_rate);
313        }
314        metrics
315    }
316
317    /// One result per case for reporters that take an [`EvaluationReport`], such as the
318    /// JUnit reporter: it passes when the case reached the minimum pass rate, carries the
319    /// mean scores and the pass rate, and fails with a `pass_rate` failure otherwise.
320    pub fn case_results(&self) -> Vec<EvaluationResult> {
321        self.cases
322            .iter()
323            .map(|case| {
324                let mut scores: HashMap<String, f64> =
325                    case.scores.iter().map(|(name, stats)| (name.clone(), stats.mean)).collect();
326                scores.insert(PASS_RATE_METRIC.to_string(), case.pass_rate);
327                let duration = self
328                    .runs
329                    .iter()
330                    .flat_map(|run| &run.results)
331                    .filter(|result| result.eval_id == case.eval_id)
332                    .map(|result| result.duration)
333                    .sum();
334                if case.passed {
335                    return EvaluationResult::passed(&case.eval_id, scores, duration);
336                }
337                let failing = case
338                    .failed_criteria
339                    .iter()
340                    .map(|(criterion, runs)| format!("{criterion} in {runs}"))
341                    .collect::<Vec<_>>()
342                    .join(", ");
343                let failure = Failure::new(
344                    PASS_RATE_METRIC,
345                    number(self.min_pass_rate),
346                    number(case.pass_rate),
347                    case.pass_rate,
348                    self.min_pass_rate,
349                )
350                .with_details(&format!(
351                    "passed {} of {} runs{}; failed criteria: {failing}",
352                    case.passed_runs,
353                    case.runs,
354                    if case.flaky { " (flaky)" } else { "" }
355                ));
356                EvaluationResult::failed(&case.eval_id, scores, vec![failure], duration)
357            })
358            .collect()
359    }
360
361    /// A human-readable summary: one line per case with its pass rate, then the score
362    /// statistics of each criterion.
363    pub fn format_summary(&self) -> String {
364        use std::fmt::Write;
365
366        let passed = self.cases.iter().filter(|case| case.passed).count();
367        let flaky = self.flaky_cases().count();
368        let mut out = String::new();
369        let _ = writeln!(
370            out,
371            "Runs: {}/{}  Cases: {}  Passed: {passed}  Failed: {}  Flaky: {flaky}  Min pass rate: {:.2}",
372            self.completed_runs(),
373            self.requested_runs,
374            self.cases.len(),
375            self.cases.len() - passed,
376            self.min_pass_rate
377        );
378        if let Some(reason) = &self.stopped {
379            let _ = writeln!(out, "Stopped early: {reason}");
380        }
381        let _ = writeln!(out, "\n{:<28} {:>10} {:>9}  Verdict", "Case", "Passed", "Rate");
382        for case in &self.cases {
383            let verdict = match (case.passed, case.flaky) {
384                (true, false) => "PASS",
385                (true, true) => "PASS (flaky)",
386                (false, true) => "FAIL (flaky)",
387                (false, false) => "FAIL",
388            };
389            let _ = writeln!(
390                out,
391                "{:<28} {:>10} {:>9.2}  {verdict}",
392                case.eval_id,
393                format!("{}/{}", case.passed_runs, case.runs),
394                case.pass_rate
395            );
396        }
397
398        let mut by_criterion: BTreeMap<&str, Vec<f64>> = BTreeMap::new();
399        for result in self.runs.iter().flat_map(|run| &run.results) {
400            for (criterion, &score) in &result.scores {
401                by_criterion.entry(criterion.as_str()).or_default().push(score);
402            }
403        }
404        if !by_criterion.is_empty() {
405            let _ = writeln!(
406                out,
407                "\n{:<28} {:>8} {:>8} {:>8} {:>8}",
408                "Criterion", "Mean", "Std", "Min", "Max"
409            );
410            for (criterion, scores) in by_criterion {
411                if let Some(stats) = ScoreStats::from_scores(&scores) {
412                    let _ = writeln!(
413                        out,
414                        "{criterion:<28} {:>8.3} {:>8.3} {:>8.3} {:>8.3}",
415                        stats.mean, stats.std_dev, stats.min, stats.max
416                    );
417                }
418            }
419        }
420        let _ = writeln!(out, "\nDuration: {:.2}s", self.duration.as_secs_f64());
421        out
422    }
423
424    /// Serializes the report as pretty-printed JSON.
425    ///
426    /// # Errors
427    ///
428    /// Returns an error when a score cannot be serialized.
429    pub fn to_json(&self) -> std::result::Result<String, serde_json::Error> {
430        serde_json::to_string_pretty(self)
431    }
432}
433
434fn summarise_case(
435    eval_id: String,
436    results: &[&EvaluationResult],
437    min_pass_rate: f64,
438) -> CaseRunSummary {
439    let runs = results.len();
440    let passed_runs = results.iter().filter(|result| result.passed).count();
441    let pass_rate = if runs == 0 { 0.0 } else { passed_runs as f64 / runs as f64 };
442
443    let mut per_criterion: BTreeMap<String, Vec<f64>> = BTreeMap::new();
444    let mut failed_criteria: BTreeMap<String, usize> = BTreeMap::new();
445    for result in results {
446        for (criterion, &score) in &result.scores {
447            per_criterion.entry(criterion.clone()).or_default().push(score);
448        }
449        let mut failed: Vec<&str> =
450            result.failures.iter().map(|failure| failure.criterion.as_str()).collect();
451        failed.sort_unstable();
452        failed.dedup();
453        for criterion in failed {
454            *failed_criteria.entry(criterion.to_string()).or_default() += 1;
455        }
456    }
457
458    CaseRunSummary {
459        eval_id,
460        runs,
461        passed_runs,
462        pass_rate,
463        flaky: passed_runs > 0 && passed_runs < runs,
464        // Compared in whole runs, so 2 of 3 meets a minimum of 2/3 despite rounding.
465        passed: runs > 0 && passed_runs as f64 + 1e-9 >= min_pass_rate * runs as f64,
466        scores: per_criterion
467            .into_iter()
468            .filter_map(|(criterion, scores)| {
469                ScoreStats::from_scores(&scores).map(|stats| (criterion, stats))
470            })
471            .collect(),
472        failed_criteria,
473    }
474}
475
476fn number(value: f64) -> Value {
477    serde_json::Number::from_f64(value).map_or(Value::Null, Value::Number)
478}
479
480#[cfg(test)]
481mod tests {
482    use super::*;
483
484    fn result(eval_id: &str, passed: bool, score: f64) -> EvaluationResult {
485        let scores = HashMap::from([("tool_trajectory".to_string(), score)]);
486        if passed {
487            EvaluationResult::passed(eval_id, scores, Duration::from_millis(10))
488        } else {
489            let failure = Failure::new("tool_trajectory", Value::Null, Value::Null, score, 1.0);
490            EvaluationResult::failed(eval_id, scores, vec![failure], Duration::from_millis(10))
491        }
492    }
493
494    fn run(results: Vec<EvaluationResult>) -> EvaluationReport {
495        EvaluationReport::new("run", results, chrono::Utc::now())
496    }
497
498    #[test]
499    fn pass_rates_count_runs_per_case() {
500        let report = MultiRunReport::from_runs(
501            "set",
502            3,
503            1.0,
504            vec![
505                run(vec![result("steady", true, 1.0), result("flaky", true, 1.0)]),
506                run(vec![result("steady", true, 1.0), result("flaky", false, 0.0)]),
507                run(vec![result("steady", true, 1.0), result("flaky", true, 1.0)]),
508            ],
509        );
510
511        let steady = &report.cases[0];
512        assert_eq!(
513            (steady.eval_id.as_str(), steady.passed_runs, steady.runs, steady.flaky, steady.passed),
514            ("steady", 3, 3, false, true)
515        );
516        let flaky = &report.cases[1];
517        assert_eq!((flaky.passed_runs, flaky.runs, flaky.flaky, flaky.passed), (2, 3, true, false));
518        assert!((flaky.pass_rate - 2.0 / 3.0).abs() < 1e-12);
519        assert_eq!(flaky.failed_criteria, BTreeMap::from([("tool_trajectory".to_string(), 1)]));
520        let stats = &flaky.scores["tool_trajectory"];
521        assert!((stats.mean - 2.0 / 3.0).abs() < 1e-12);
522        assert!((stats.variance - 1.0 / 3.0).abs() < 1e-12);
523        assert_eq!((stats.min, stats.max, stats.count), (0.0, 1.0, 3));
524        assert_eq!(
525            report.flaky_cases().map(|case| case.eval_id.as_str()).collect::<Vec<_>>(),
526            ["flaky"]
527        );
528        assert!(!report.all_passed());
529    }
530
531    #[test]
532    fn a_minimum_pass_rate_admits_flaky_cases_in_whole_runs() {
533        let runs = || {
534            vec![
535                run(vec![result("flaky", true, 1.0)]),
536                run(vec![result("flaky", false, 0.0)]),
537                run(vec![result("flaky", true, 1.0)]),
538            ]
539        };
540        assert!(MultiRunReport::from_runs("set", 3, 2.0 / 3.0, runs()).all_passed());
541        assert!(!MultiRunReport::from_runs("set", 3, 0.7, runs()).all_passed());
542    }
543
544    #[test]
545    fn baselines_hold_mean_scores_and_pass_rates() {
546        let report = MultiRunReport::from_runs(
547            "set",
548            2,
549            1.0,
550            vec![run(vec![result("case", true, 1.0)]), run(vec![result("case", false, 0.5)])],
551        );
552        let metrics = report.baseline_metrics();
553        assert_eq!(
554            metrics,
555            HashMap::from([
556                ("tool_trajectory".to_string(), HashMap::from([("case".to_string(), 0.75)])),
557                (PASS_RATE_METRIC.to_string(), HashMap::from([("case".to_string(), 0.5)])),
558            ])
559        );
560    }
561
562    #[test]
563    fn a_report_that_stopped_early_or_ran_nothing_does_not_pass() {
564        let complete = || vec![run(vec![result("case", true, 1.0)])];
565        assert!(MultiRunReport::from_runs("set", 1, 1.0, complete()).all_passed());
566        assert!(!MultiRunReport::from_runs("set", 2, 1.0, complete()).all_passed());
567        assert!(
568            !MultiRunReport::from_runs("set", 1, 1.0, complete())
569                .with_stopped("budget spent")
570                .all_passed()
571        );
572        assert!(!MultiRunReport::from_runs("set", 1, 1.0, Vec::new()).all_passed());
573    }
574
575    #[test]
576    fn case_results_fail_below_the_minimum_with_the_pass_rate() {
577        let report = MultiRunReport::from_runs(
578            "set",
579            2,
580            1.0,
581            vec![run(vec![result("case", true, 1.0)]), run(vec![result("case", false, 0.0)])],
582        );
583        let results = report.case_results();
584        assert_eq!(results.len(), 1);
585        assert!(!results[0].passed);
586        assert_eq!(results[0].scores[PASS_RATE_METRIC], 0.5);
587        assert_eq!(results[0].failures[0].criterion, PASS_RATE_METRIC);
588        assert!(
589            results[0].failures[0]
590                .details
591                .as_deref()
592                .is_some_and(|details| details.contains("passed 1 of 2 runs (flaky)"))
593        );
594    }
595
596    #[test]
597    fn configs_reject_impossible_values() {
598        assert!(MultiRunConfig::new(0).is_err());
599        let config = MultiRunConfig::new(2).unwrap();
600        assert!(config.clone().with_min_pass_rate(1.5).is_err());
601        assert!(config.clone().with_min_pass_rate(f64::NAN).is_err());
602        assert_eq!(config.with_min_pass_rate(0.5).unwrap().min_pass_rate, 0.5);
603    }
604}