Skip to main content

graphrt_eval/
runner.rs

1//! Running a suite: the [`Target`] under test, concurrency, trials, filters,
2//! scoring, trial statistics, calibration and the gate.
3
4use std::sync::Arc;
5use std::time::{Instant, SystemTime, UNIX_EPOCH};
6
7use futures::StreamExt;
8use futures::future::BoxFuture;
9use graphrt_core::response::ResponseAssembler;
10use graphrt_core::{Engine, RunInput, Value};
11use indexmap::IndexMap;
12use serde_json::Value as Json;
13
14use crate::assertion::{AssertionContext, AssertionRegistry, AssertionResult, PreparedAssertion};
15use crate::capture::{RunCapture, RunStatus};
16use crate::config::{AssertionSpec, EvalSuite, TestCase, inputs_of};
17use crate::error::EvalError;
18use crate::path::render;
19use crate::report::{
20    EvalReport, REPORT_SCHEMA_VERSION, RunSummary, Summary, TestResult, TestStatus, WorkflowInfo, case_summaries,
21    trial_summary,
22};
23
24/// The system under test: runs one test case and reports what happened.
25///
26/// [`EngineTarget`] runs a compiled graphrt workflow in-process; other
27/// implementations can call a server or a fake.
28pub trait Target: Send + Sync {
29    /// Run `case` once. Return `Err` only when the run could not be attempted;
30    /// a failed run is a capture with [`RunStatus::Failed`].
31    fn run<'a>(&'a self, case: &'a TestCase) -> BoxFuture<'a, Result<RunCapture, EvalError>>;
32
33    /// Describes the workflow for the report.
34    fn workflow(&self) -> WorkflowInfo {
35        WorkflowInfo::default()
36    }
37
38    /// The start variables and their input types (`paragraph`, `json`...),
39    /// used to shape judge inputs. Empty when unknown.
40    fn start_variables(&self) -> Vec<(String, String)> {
41        Vec::new()
42    }
43}
44
45/// Runs test cases on an [`Engine`] (one compiled graph, shared by every test).
46///
47/// Set a [`graphrt_core::node::Clock`] with timers on the engine (e.g.
48/// `TokioClock`) for `Limits::max_duration_ms` to act as a per-test timeout.
49#[derive(Clone, Debug)]
50pub struct EngineTarget {
51    engine: Engine,
52    env: IndexMap<String, Value>,
53    path: String,
54}
55
56impl EngineTarget {
57    pub fn new(engine: Engine) -> Self {
58        Self { engine, env: IndexMap::new(), path: String::new() }
59    }
60
61    /// Values for the workflow's declared `env.*` variables.
62    pub fn with_env(mut self, env: IndexMap<String, Value>) -> Self {
63        self.env = env;
64        self
65    }
66
67    /// The workflow file path shown in the report.
68    pub fn with_path(mut self, path: impl Into<String>) -> Self {
69        self.path = path.into();
70        self
71    }
72
73    /// The engine test cases run on (for hosts that drive runs themselves, e.g. to trace them).
74    pub fn engine(&self) -> &Engine {
75        &self.engine
76    }
77
78    /// The values of the workflow's `env.*` variables.
79    pub fn env(&self) -> &IndexMap<String, Value> {
80        &self.env
81    }
82
83    async fn run_case(&self, case: &TestCase) -> RunCapture {
84        let mut input = RunInput::new();
85        input.inputs = inputs_of(&case.vars);
86        input.env.clone_from(&self.env);
87        let started = Instant::now();
88        let mut assembler = ResponseAssembler::new(self.engine.graph());
89        let mut events = Vec::new();
90        let mut stream = self.engine.run(input);
91        while let Some(event) = stream.next().await {
92            let _chunks = assembler.push(&event);
93            events.push(event);
94        }
95        let latency_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
96        RunCapture::from_events(events, assembler.text_so_far().to_owned(), latency_ms)
97    }
98}
99
100impl Target for EngineTarget {
101    fn run<'a>(&'a self, case: &'a TestCase) -> BoxFuture<'a, Result<RunCapture, EvalError>> {
102        Box::pin(async move { Ok(self.run_case(case).await) })
103    }
104
105    fn workflow(&self) -> WorkflowInfo {
106        let graph = self.engine.graph();
107        WorkflowInfo {
108            path: self.path.clone(),
109            name: graph.workflow().name.clone().unwrap_or_default(),
110            fingerprint: graph.fingerprint().to_owned(),
111        }
112    }
113
114    fn start_variables(&self) -> Vec<(String, String)> {
115        let nodes = &self.engine.graph().workflow().graph.nodes;
116        let Some(start) = nodes.iter().find(|n| n.kind == "start" && n.parent.is_none()) else { return Vec::new() };
117        let declared = start.config.get("variables").and_then(Json::as_array).into_iter().flatten();
118        declared
119            .filter_map(|v| {
120                let name = v.get("variable")?.as_str()?;
121                let kind = v.get("type").and_then(Json::as_str).unwrap_or("text-input");
122                Some((name.to_owned(), kind.to_owned()))
123            })
124            .collect()
125    }
126}
127
128/// How to run a suite.
129#[derive(Clone, Debug)]
130#[non_exhaustive]
131pub struct RunnerOptions {
132    /// Tests running at the same time (at least 1).
133    pub concurrency: usize,
134    /// Trials per test case (at least 1); each trial is a separate result, and
135    /// with more than one the report adds pass@k and pass^k per case.
136    pub trials: u32,
137    /// Keep only cases whose id or a tag matches one of these (`*` wildcards).
138    pub filters: Vec<String>,
139    /// Override the suite's `gate.pass_rate`.
140    pub pass_rate: Option<f64>,
141    /// Include the run events in the results.
142    pub keep_events: bool,
143}
144
145impl Default for RunnerOptions {
146    fn default() -> Self {
147        Self { concurrency: 4, trials: 1, filters: Vec::new(), pass_rate: None, keep_events: false }
148    }
149}
150
151/// Runs suites against a [`Target`].
152#[derive(Clone, Debug, Default)]
153pub struct Runner {
154    registry: AssertionRegistry,
155    options: RunnerOptions,
156}
157
158/// A selected test case with its assertions built.
159type PreparedCase = (Arc<TestCase>, Arc<Vec<PreparedAssertion>>);
160
161struct Job {
162    index: usize,
163    trial: u32,
164    case: Arc<TestCase>,
165    assertions: Arc<Vec<PreparedAssertion>>,
166}
167
168impl Runner {
169    /// A runner with the built-in assertion types.
170    pub fn new(options: RunnerOptions) -> Self {
171        Self { registry: AssertionRegistry::with_builtins(), options }
172    }
173
174    /// Use these assertion types (e.g. built-ins plus custom ones).
175    pub fn with_registry(mut self, registry: AssertionRegistry) -> Self {
176        self.registry = registry;
177        self
178    }
179
180    /// The cases selected by the filters, with their assertions built.
181    /// Fails before anything runs if an assertion is invalid.
182    fn prepare(&self, suite: &EvalSuite) -> Result<Vec<PreparedCase>, EvalError> {
183        let filters = &self.options.filters;
184        let mut prepared = Vec::new();
185        for case in suite.cases.iter().filter(|c| filters.is_empty() || filters.iter().any(|f| c.matches(f))) {
186            let context = template_context(case);
187            let mut assertions = Vec::with_capacity(case.assertions.len());
188            for spec in &case.assertions {
189                let rendered = render_spec(spec, &context)
190                    .and_then(|spec| self.registry.prepare(&spec))
191                    .map_err(|e| EvalError::invalid(format!("test `{}`: {e}", case.id)))?;
192                assertions.push(rendered);
193            }
194            prepared.push((Arc::new(case.clone()), Arc::new(assertions)));
195        }
196        Ok(prepared)
197    }
198
199    /// Run `suite` against `target`, calling `on_result` as each test finishes
200    /// (in completion order). The report lists results in suite order.
201    pub async fn run<T>(
202        &self,
203        suite: &EvalSuite,
204        target: &T,
205        mut on_result: impl FnMut(&TestResult),
206    ) -> Result<EvalReport, EvalError>
207    where
208        T: Target + ?Sized,
209    {
210        let prepared = self.prepare(suite)?;
211        let started_at_ms = SystemTime::now()
212            .duration_since(UNIX_EPOCH)
213            .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
214            .unwrap_or_default();
215        let started = Instant::now();
216        let trials = self.options.trials.max(1);
217        let jobs: Vec<Job> = prepared
218            .iter()
219            .enumerate()
220            .flat_map(|(index, (case, assertions))| {
221                (0..trials).map(move |trial| Job {
222                    index,
223                    trial,
224                    case: Arc::clone(case),
225                    assertions: Arc::clone(assertions),
226                })
227            })
228            .collect();
229        let keep_events = self.options.keep_events;
230        let mut results: Vec<(usize, TestResult)> = Vec::with_capacity(jobs.len());
231        let mut pending = futures::stream::iter(jobs)
232            .map(|job| async move {
233                let result = run_job(target, &job, keep_events).await;
234                result.map(|r| (job.index, r))
235            })
236            .buffer_unordered(self.options.concurrency.max(1));
237        while let Some(finished) = pending.next().await {
238            let (index, result) = finished?;
239            on_result(&result);
240            results.push((index, result));
241        }
242        drop(pending);
243        results.sort_by_key(|(index, result)| (*index, result.trial));
244        let tests: Vec<TestResult> = results.into_iter().map(|(_, r)| r).collect();
245        let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
246        let pass_rate = self.options.pass_rate.unwrap_or(suite.gate.pass_rate);
247        let mut workflow = target.workflow();
248        if workflow.path.is_empty() {
249            workflow.path = suite.workflow.display().to_string();
250        }
251        let mut summary = Summary::of(&tests, pass_rate, duration_ms);
252        let gate = &suite.gate;
253        let cases = if trials > 1 || gate.pass_hat_k.is_some() {
254            let k = gate.k.unwrap_or(trials).clamp(1, trials);
255            let cases = case_summaries(&tests, k);
256            let stats = trial_summary(&cases, k);
257            if let Some(required) = gate.pass_hat_k {
258                summary.gate.pass_hat_k = Some(required);
259                let actual = stats.pass_hat_k;
260                summary.gate.require(actual + 1e-9 >= required, || format!("pass^{k} {actual:.3} < {required:.3}"));
261            }
262            summary.trials = Some(stats);
263            cases
264        } else {
265            Vec::new()
266        };
267        let calibration = suite.calibration.as_ref().map(|config| {
268            let calibration = crate::calibration::calibrate(&tests, config);
269            crate::calibration::gate(&calibration, config, &mut summary.gate);
270            calibration
271        });
272        Ok(EvalReport {
273            schema_version: REPORT_SCHEMA_VERSION,
274            graphrt_version: env!("CARGO_PKG_VERSION").to_owned(),
275            suite: suite.path.display().to_string(),
276            description: suite.description.clone(),
277            workflow,
278            started_at_ms,
279            summary,
280            cases,
281            calibration,
282            baseline: None,
283            tests,
284        })
285    }
286}
287
288/// Values `{{...}}` references in assertions can use: the test's vars (also at
289/// the top level, as in Promptfoo), `expected`, `metadata`, `id` and `tags`.
290fn template_context(case: &TestCase) -> Json {
291    let mut context = case.vars.clone();
292    context.insert("vars".into(), Json::Object(case.vars.clone()));
293    context.insert("expected".into(), case.expected.clone().unwrap_or(Json::Null));
294    context.insert("metadata".into(), Json::Object(case.metadata.clone()));
295    context.insert("id".into(), Json::String(case.id.clone()));
296    context.insert("tags".into(), Json::from(case.tags.clone()));
297    Json::Object(context)
298}
299
300fn render_spec(spec: &AssertionSpec, context: &Json) -> Result<AssertionSpec, EvalError> {
301    let mut rendered = spec.clone();
302    rendered.value = spec.value.as_ref().map(|v| render(v, context)).transpose()?;
303    for value in rendered.config.values_mut() {
304        *value = render(value, context)?;
305    }
306    Ok(rendered)
307}
308
309async fn run_job<T: Target + ?Sized>(target: &T, job: &Job, keep_events: bool) -> Result<TestResult, EvalError> {
310    let case = &job.case;
311    let capture = target.run(case).await?;
312    let ctx = AssertionContext::new(case, &capture);
313    let mut assertions = Vec::with_capacity(job.assertions.len());
314    for assertion in job.assertions.iter() {
315        assertions.push(assertion.run(ctx).await);
316    }
317    let (pass, score) = verdict(&assertions, case.threshold);
318    let status = match (capture.status, pass) {
319        (RunStatus::Succeeded, true) => TestStatus::Passed,
320        (RunStatus::Succeeded, false) => TestStatus::Failed,
321        _ => TestStatus::Error,
322    };
323    let reason = match status {
324        TestStatus::Passed => None,
325        TestStatus::Error => Some(format!(
326            "run {}: {}",
327            serde_json::to_value(capture.status).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
328            capture.error.as_deref().unwrap_or("no details")
329        )),
330        TestStatus::Failed => {
331            let failed: Vec<String> = assertions
332                .iter()
333                .filter(|a| !a.pass && a.gates())
334                .map(|a| format!("{}: {}", a.kind, a.reason))
335                .collect();
336            Some(if failed.is_empty() {
337                format!("score {score:.2} below threshold {:.2}", case.threshold.unwrap_or(1.0))
338            } else {
339                failed.join("; ")
340            })
341        }
342    };
343    let tool_calls = capture.tool_calls();
344    let retrieval = capture.retrieval_hits();
345    let output = capture.output();
346    let RunCapture { run_id, status: run_status, error, error_type, outputs, answer, usage, latency_ms, events } =
347        capture;
348    Ok(TestResult {
349        id: case.id.clone(),
350        description: case.description.clone(),
351        source: case.source.clone(),
352        tags: case.tags.clone(),
353        trial: job.trial,
354        status,
355        pass: status == TestStatus::Passed,
356        score,
357        reason,
358        vars: case.vars.clone(),
359        expected: case.expected.clone(),
360        run: RunSummary {
361            run_id,
362            status: run_status,
363            error,
364            error_type,
365            latency_ms,
366            usage,
367            output,
368            outputs,
369            answer,
370            tool_calls,
371            retrieval,
372            events: keep_events.then_some(events),
373        },
374        assertions,
375    })
376}
377
378/// Promptfoo scoring: the score is the weighted mean of the assertion scores
379/// (weight 0 = report only). Without a threshold every gating assertion must
380/// pass; with one, the score must reach it. Excluded results (a judge's
381/// `unknown` with `unknown: exclude`) take no part; a test whose results are
382/// all excluded passes with score 1.
383pub fn verdict(assertions: &[AssertionResult], threshold: Option<f64>) -> (bool, f64) {
384    let counted = || assertions.iter().filter(|a| !a.excluded);
385    let total_weight: f64 = counted().map(|a| a.weight).sum();
386    let count = counted().count();
387    let score = if total_weight > 0.0 {
388        counted().map(|a| a.weight * a.score).sum::<f64>() / total_weight
389    } else if count == 0 {
390        1.0
391    } else {
392        counted().map(|a| a.score).sum::<f64>() / count as f64
393    };
394    let pass = match threshold {
395        Some(t) => score + 1e-9 >= t,
396        None => counted().filter(|a| a.weight > 0.0).all(|a| a.pass),
397    };
398    (pass, score)
399}
400
401#[cfg(test)]
402mod tests {
403    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
404
405    use super::*;
406    use serde_json::json;
407
408    fn result(pass: bool, score: f64, weight: f64) -> AssertionResult {
409        AssertionResult::new("x", pass, score, weight, "")
410    }
411
412    #[test]
413    fn scoring_follows_promptfoo() {
414        let mixed = [result(true, 1.0, 1.0), result(false, 0.0, 0.0)];
415        assert_eq!(verdict(&mixed, None), (true, 1.0), "weight 0 is report only");
416        let weighted = [result(true, 1.0, 3.0), result(false, 0.0, 1.0)];
417        assert_eq!(verdict(&weighted, None), (false, 0.75));
418        assert_eq!(verdict(&weighted, Some(0.7)), (true, 0.75));
419        assert_eq!(verdict(&weighted, Some(0.8)), (false, 0.75));
420        assert!(verdict(&[result(false, 0.5, 0.0)], None).0);
421        let mut unknown = result(false, 0.0, 1.0);
422        unknown.excluded = true;
423        assert_eq!(verdict(&[result(true, 0.8, 1.0), unknown.clone()], None), (true, 0.8), "excluded is ignored");
424        assert_eq!(verdict(&[unknown], None), (true, 1.0));
425    }
426
427    /// A fake target answering `Hello, <name>.`, failing for `name: fail`.
428    #[derive(Debug)]
429    struct Greeter;
430    impl Target for Greeter {
431        fn run<'a>(&'a self, case: &'a TestCase) -> BoxFuture<'a, Result<RunCapture, EvalError>> {
432            Box::pin(async move {
433                let name = case.vars.get("name").and_then(Json::as_str).unwrap_or_default();
434                let mut capture = RunCapture { latency_ms: 3, ..RunCapture::default() };
435                if name == "fail" {
436                    capture.status = RunStatus::Failed;
437                    capture.error = Some("boom".into());
438                } else {
439                    capture.outputs.insert("greeting".into(), json!(format!("Hello, {name}.")));
440                }
441                Ok(capture)
442            })
443        }
444    }
445
446    fn suite() -> EvalSuite {
447        EvalSuite::parse(
448            r#"
449workflow: w.yaml
450gate: { pass_rate: 0.5 }
451defaultTest:
452  assert: [{ type: latency, threshold: 1000 }]
453tests:
454  - id: ada
455    tags: [smoke]
456    vars: { name: Ada }
457    assert: [{ type: equals, value: "Hello, {{name}}." }]
458  - id: bob
459    vars: { name: Bob }
460    assert: [{ type: contains, value: Alice }]
461  - id: broken
462    vars: { name: fail }
463    assert: [{ type: contains, value: x }]
464"#,
465            std::path::Path::new(""),
466        )
467        .unwrap()
468    }
469
470    fn run(options: RunnerOptions) -> (EvalReport, Vec<String>) {
471        let mut seen = Vec::new();
472        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
473        let report = rt.block_on(Runner::new(options).run(&suite(), &Greeter, |r| seen.push(r.display_id()))).unwrap();
474        (report, seen)
475    }
476
477    #[test]
478    fn runs_scores_and_gates() {
479        let (report, seen) = run(RunnerOptions::default());
480        assert_eq!(seen.len(), 3);
481        let ids: Vec<&str> = report.tests.iter().map(|t| t.id.as_str()).collect();
482        assert_eq!(ids, ["ada", "bob", "broken"], "suite order");
483        assert_eq!(report.tests[0].status, TestStatus::Passed);
484        assert_eq!(report.tests[0].assertions.len(), 2);
485        assert_eq!(report.tests[1].status, TestStatus::Failed);
486        assert!(report.tests[1].reason.as_deref().unwrap().contains("Alice"));
487        assert_eq!(report.tests[2].status, TestStatus::Error);
488        assert!(report.tests[2].reason.as_deref().unwrap().contains("boom"));
489        assert_eq!(report.summary.passed, 1);
490        assert!(!report.gate_passed(), "1/3 < 0.5");
491
492        let mut options = RunnerOptions { pass_rate: Some(0.3), ..RunnerOptions::default() };
493        assert!(run(options.clone()).0.gate_passed());
494        options.filters = vec!["smoke".into()];
495        options.trials = 3;
496        options.concurrency = 2;
497        let (report, seen) = run(options);
498        assert_eq!(report.tests.len(), 3);
499        assert!(report.tests.iter().all(|t| t.id == "ada"));
500        assert_eq!(report.tests.iter().map(|t| t.trial).collect::<Vec<_>>(), [0, 1, 2]);
501        assert!(seen.contains(&"ada#2".to_owned()));
502        assert!(report.gate_passed());
503        assert_eq!(report.cases.len(), 1);
504        let trials = report.summary.trials.as_ref().unwrap();
505        assert_eq!((trials.trials, trials.k, trials.pass_hat_k), (3, 3, 1.0));
506    }
507
508    #[test]
509    fn trials_report_pass_at_k_and_gate_on_pass_hat_k() {
510        let mut suite = suite();
511        suite.gate.pass_rate = 0.0;
512        suite.gate.pass_hat_k = Some(0.5);
513        suite.gate.k = Some(2);
514        let options = RunnerOptions { trials: 4, concurrency: 3, ..RunnerOptions::default() };
515        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
516        let report = rt.block_on(Runner::new(options).run(&suite, &Greeter, |_| {})).unwrap();
517        assert_eq!(report.tests.len(), 12);
518        let ids: Vec<&str> = report.cases.iter().map(|c| c.id.as_str()).collect();
519        assert_eq!(ids, ["ada", "bob", "broken"]);
520        assert_eq!((report.cases[0].passed, report.cases[0].pass_hat_k), (4, 1.0));
521        assert_eq!((report.cases[1].passed, report.cases[1].pass_at_k), (0, 0.0));
522        let trials = report.summary.trials.as_ref().unwrap();
523        assert!((trials.pass_hat_k - 1.0 / 3.0).abs() < 1e-12, "{trials:?}");
524        assert!(!report.gate_passed());
525        assert_eq!(report.summary.gate.failures, ["pass^2 0.333 < 0.500"]);
526        let text = crate::report::format_summary(&report);
527        assert!(text.contains("pass@2 0.333, pass^2 0.333 over 3 case(s)"), "{text}");
528        assert!(text.contains("gate: FAILED (pass^2 0.333 < 0.500)"), "{text}");
529    }
530
531    #[test]
532    fn invalid_assertions_fail_before_running() {
533        let mut suite = suite();
534        suite.cases[1].assertions.push(AssertionSpec::new("regex", Some(json!("("))));
535        let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
536        let err = rt.block_on(Runner::default().run(&suite, &Greeter, |_| {})).unwrap_err().to_string();
537        assert!(err.contains("test `bob`") && err.contains("regex"), "{err}");
538    }
539}