Skip to main content

graphrt_eval/
config.rs

1//! The eval file format (`*.eval.yaml`) and JSONL datasets.
2//!
3//! The shape follows Promptfoo (`tests: [{vars, assert: [{type, value,
4//! threshold, weight, metric}]}]`, `defaultTest`) so test cases move between
5//! the two tools. Keys starting with `x-` are ignored at the file and test level.
6//!
7//! ```yaml
8//! workflow: ../hello.yaml
9//! providers: providers.replay.yaml   # optional
10//! dataset: cases.jsonl               # optional: {id, vars, expected?, tags?, metadata?} per line
11//! defaultTest:
12//!   assert: [{ type: latency, threshold: 2000 }]
13//! tests:
14//!   - id: ada
15//!     vars: { name: Ada }
16//!     assert:
17//!       - { type: equals, value: "Hello, Ada." }
18//! gate: { pass_rate: 1.0 }
19//! ```
20//!
21//! With `calibration:` the workflow under test is a judge and each test's
22//! `expected` is a human label (`pass` / `fail`): the report adds agreement,
23//! TPR, TNR and Cohen's kappa.
24
25use std::path::{Path, PathBuf};
26
27use indexmap::IndexMap;
28use serde::Deserialize;
29use serde_json::{Map, Value as Json};
30
31use crate::error::EvalError;
32
33/// A parsed eval file, with relative paths resolved against its directory.
34#[derive(Clone, Debug, Default)]
35#[non_exhaustive]
36pub struct EvalSuite {
37    /// Where the suite was loaded from (empty for in-memory suites).
38    pub path: PathBuf,
39    pub description: Option<String>,
40    /// The workflow under test.
41    pub workflow: PathBuf,
42    /// Model providers file layered over the environment providers.
43    pub providers: Option<PathBuf>,
44    /// Knowledge base config for knowledge-retrieval nodes.
45    pub knowledge: Option<PathBuf>,
46    /// MCP servers file.
47    pub mcp: Option<PathBuf>,
48    /// Plugin directories.
49    pub plugins: Vec<PathBuf>,
50    /// Every test case: inline tests first, then dataset rows, with `defaultTest` merged in.
51    pub cases: Vec<TestCase>,
52    pub gate: Gate,
53    /// Judge calibration mode (the workflow is a judge, `expected` are labels).
54    pub calibration: Option<Calibration>,
55}
56
57/// The CI gate.
58#[derive(Clone, Debug, Deserialize, PartialEq)]
59#[serde(deny_unknown_fields)]
60#[non_exhaustive]
61pub struct Gate {
62    /// Minimum fraction of passing test runs (0..=1, every trial counts).
63    /// Default 1.0: every test must pass.
64    #[serde(default = "one")]
65    pub pass_rate: f64,
66    /// Minimum mean pass^k over the test cases (with `--trials`).
67    #[serde(default)]
68    pub pass_hat_k: Option<f64>,
69    /// `k` of pass@k and pass^k (default: the number of trials).
70    #[serde(default)]
71    pub k: Option<u32>,
72    /// Tolerances when comparing against `--baseline`.
73    #[serde(default)]
74    pub baseline: Tolerance,
75}
76
77impl Default for Gate {
78    fn default() -> Self {
79        Self { pass_rate: 1.0, pass_hat_k: None, k: None, baseline: Tolerance::default() }
80    }
81}
82
83/// How far results may fall below the baseline before it is a regression.
84#[derive(Clone, Debug, Deserialize, PartialEq)]
85#[serde(deny_unknown_fields)]
86#[non_exhaustive]
87pub struct Tolerance {
88    /// Largest allowed drop of a metric's mean score (default 0.05: LLM metrics are noisy).
89    #[serde(default = "five_percent")]
90    pub tolerance: f64,
91    /// Largest allowed drop of a test's pass rate across its trials (default 0:
92    /// a test that passed and now fails is a regression).
93    #[serde(default)]
94    pub test_tolerance: f64,
95    /// Per-metric tolerances, overriding `tolerance`.
96    #[serde(default)]
97    pub metrics: IndexMap<String, f64>,
98}
99
100impl Default for Tolerance {
101    fn default() -> Self {
102        Self { tolerance: 0.05, test_tolerance: 0.0, metrics: IndexMap::new() }
103    }
104}
105
106impl Tolerance {
107    /// The tolerance of `metric`.
108    pub fn of(&self, metric: &str) -> f64 {
109        self.metrics.get(metric).copied().unwrap_or(self.tolerance)
110    }
111}
112
113/// Judge calibration settings (`calibration:` in the eval file).
114#[derive(Clone, Debug, Deserialize, PartialEq)]
115#[serde(deny_unknown_fields)]
116#[non_exhaustive]
117pub struct Calibration {
118    /// `unknown` verdicts: `exclude` (default: counted apart, outside the
119    /// confusion matrix) or `fail` (counted as the judge saying fail).
120    #[serde(default = "exclude")]
121    pub unknown: crate::judge::UnknownPolicy,
122    /// Score at which a judge that returns only a `score` says pass (default 0.5).
123    #[serde(default)]
124    pub threshold: Option<f64>,
125    /// Gate: minimum Cohen's kappa.
126    #[serde(default)]
127    pub min_kappa: Option<f64>,
128    /// Gate: minimum true positive rate.
129    #[serde(default)]
130    pub min_tpr: Option<f64>,
131    /// Gate: minimum true negative rate.
132    #[serde(default)]
133    pub min_tnr: Option<f64>,
134}
135
136impl Default for Calibration {
137    fn default() -> Self {
138        Self { unknown: exclude(), threshold: None, min_kappa: None, min_tpr: None, min_tnr: None }
139    }
140}
141
142fn one() -> f64 {
143    1.0
144}
145
146fn five_percent() -> f64 {
147    0.05
148}
149
150fn exclude() -> crate::judge::UnknownPolicy {
151    crate::judge::UnknownPolicy::Exclude
152}
153
154/// One assertion as written in the file.
155///
156/// `config` holds every key other than the common ones (`type`, `value`,
157/// `threshold`, `weight`, `metric`, `transform`), e.g. `k` for retrieval
158/// metrics. Assertion factories validate it.
159#[derive(Clone, Debug, PartialEq)]
160#[non_exhaustive]
161pub struct AssertionSpec {
162    /// The assertion type, including any `not-` prefix.
163    pub kind: String,
164    pub value: Option<Json>,
165    pub threshold: Option<f64>,
166    /// Contribution to the test score; `0` reports the result without gating the test.
167    pub weight: f64,
168    /// Name to aggregate the score under in the summary.
169    pub metric: Option<String>,
170    /// Path selecting the value under test (`output.field`, `outputs.text`...).
171    pub transform: Option<String>,
172    pub config: Map<String, Json>,
173}
174
175impl AssertionSpec {
176    /// An assertion of `kind` with `value`.
177    pub fn new(kind: impl Into<String>, value: Option<Json>) -> Self {
178        Self {
179            kind: kind.into(),
180            value,
181            threshold: None,
182            weight: 1.0,
183            metric: None,
184            transform: None,
185            config: Map::new(),
186        }
187    }
188
189    /// Parse one `assert` entry.
190    pub fn from_json(raw: Json) -> Result<Self, EvalError> {
191        let Json::Object(mut map) = raw else {
192            return Err(EvalError::invalid("an assertion must be a mapping with a `type`"));
193        };
194        let kind = match map.remove("type") {
195            Some(Json::String(kind)) if !kind.trim().is_empty() => kind,
196            _ => return Err(EvalError::invalid("an assertion needs a `type` string")),
197        };
198        let number = |map: &mut Map<String, Json>, key: &str| -> Result<Option<f64>, EvalError> {
199            match map.remove(key) {
200                None | Some(Json::Null) => Ok(None),
201                Some(v) => v
202                    .as_f64()
203                    .filter(|n| n.is_finite())
204                    .map(Some)
205                    .ok_or_else(|| EvalError::invalid(format!("assertion `{kind}`: `{key}` must be a number"))),
206            }
207        };
208        let threshold = number(&mut map, "threshold")?;
209        let weight = number(&mut map, "weight")?.unwrap_or(1.0);
210        if weight < 0.0 {
211            return Err(EvalError::invalid(format!("assertion `{kind}`: `weight` must not be negative")));
212        }
213        let text = |map: &mut Map<String, Json>, key: &str| -> Result<Option<String>, EvalError> {
214            match map.remove(key) {
215                None | Some(Json::Null) => Ok(None),
216                Some(Json::String(s)) => Ok(Some(s)),
217                Some(_) => Err(EvalError::invalid(format!("assertion `{kind}`: `{key}` must be a string"))),
218            }
219        };
220        let metric = text(&mut map, "metric")?;
221        let transform = text(&mut map, "transform")?;
222        let value = map.remove("value");
223        Ok(Self { kind, value, threshold, weight, metric, transform, config: map })
224    }
225}
226
227/// A test case ready to run.
228#[derive(Clone, Debug, Default, PartialEq)]
229#[non_exhaustive]
230pub struct TestCase {
231    /// Unique within the suite.
232    pub id: String,
233    pub description: Option<String>,
234    /// Start inputs of the workflow.
235    pub vars: Map<String, Json>,
236    /// Expected answer (dataset rows); available to assertion values as `{{expected}}`.
237    pub expected: Option<Json>,
238    pub tags: Vec<String>,
239    pub metadata: Map<String, Json>,
240    pub assertions: Vec<AssertionSpec>,
241    /// Pass when the weighted score reaches this, instead of requiring every gating assertion.
242    pub threshold: Option<f64>,
243    /// `inline` or `<dataset file>:<line>`.
244    pub source: String,
245}
246
247impl TestCase {
248    /// A test case with `id` and start inputs.
249    pub fn new(id: impl Into<String>, vars: Map<String, Json>) -> Self {
250        Self { id: id.into(), vars, source: "inline".into(), ..Self::default() }
251    }
252
253    /// Whether `filter` matches the id or one of the tags (`*` wildcards allowed).
254    pub fn matches(&self, filter: &str) -> bool {
255        crate::glob::matches(filter, &self.id) || self.tags.iter().any(|t| crate::glob::matches(filter, t))
256    }
257}
258
259#[derive(Deserialize)]
260#[serde(deny_unknown_fields)]
261struct RawFile {
262    #[serde(default)]
263    description: Option<String>,
264    workflow: PathBuf,
265    #[serde(default)]
266    providers: Option<PathBuf>,
267    #[serde(default)]
268    knowledge: Option<PathBuf>,
269    #[serde(default)]
270    mcp: Option<PathBuf>,
271    #[serde(default)]
272    plugins: Vec<PathBuf>,
273    #[serde(default)]
274    dataset: Option<PathBuf>,
275    #[serde(default, rename = "defaultTest")]
276    default_test: Option<RawTest>,
277    #[serde(default)]
278    tests: Vec<RawTest>,
279    #[serde(default)]
280    gate: Gate,
281    #[serde(default)]
282    calibration: Option<Calibration>,
283}
284
285#[derive(Default, Deserialize)]
286#[serde(deny_unknown_fields)]
287struct RawTest {
288    #[serde(default)]
289    id: Option<String>,
290    #[serde(default)]
291    description: Option<String>,
292    #[serde(default)]
293    vars: Map<String, Json>,
294    #[serde(default)]
295    expected: Option<Json>,
296    #[serde(default)]
297    tags: Vec<String>,
298    #[serde(default)]
299    metadata: Map<String, Json>,
300    #[serde(default)]
301    assert: Vec<Json>,
302    #[serde(default)]
303    threshold: Option<f64>,
304}
305
306impl EvalSuite {
307    /// Load an eval file (YAML or JSON) and its dataset.
308    pub fn load(path: &Path) -> Result<Self, EvalError> {
309        let text = std::fs::read_to_string(path)
310            .map_err(|e| EvalError::Io(format!("cannot read eval file `{}`: {e}", path.display())))?;
311        let base = path.parent().unwrap_or_else(|| Path::new(""));
312        Self::parse(&text, base)
313            .map(|mut suite| {
314                suite.path = path.to_path_buf();
315                suite
316            })
317            .map_err(|e| match e {
318                EvalError::Invalid(m) => EvalError::Invalid(format!("{}: {m}", path.display())),
319                other => other,
320            })
321    }
322
323    /// Parse eval file text; relative paths are resolved against `base`.
324    pub fn parse(text: &str, base: &Path) -> Result<Self, EvalError> {
325        let mut value = parse_structured(text)?;
326        strip_extensions(&mut value);
327        if let Some(Json::Array(tests)) = value.get_mut("tests") {
328            tests.iter_mut().for_each(strip_extensions);
329        }
330        let raw: RawFile = serde_json::from_value(value).map_err(|e| EvalError::invalid(e.to_string()))?;
331        validate_gate(&raw.gate, raw.calibration.as_ref())?;
332        let resolve = |p: PathBuf| if p.is_relative() { base.join(p) } else { p };
333        let default_test = raw.default_test.unwrap_or_default();
334        if default_test.id.is_some() || default_test.expected.is_some() {
335            return Err(EvalError::invalid("`defaultTest` cannot set `id` or `expected`"));
336        }
337        let mut cases = Vec::new();
338        let implicit = if raw.calibration.is_some() { "verdict" } else { "equals" };
339        for (index, test) in raw.tests.into_iter().enumerate() {
340            let id = test.id.clone().unwrap_or_else(|| format!("test-{}", index + 1));
341            cases.push(build_case(test, &default_test, id, "inline".into(), implicit)?);
342        }
343        if let Some(dataset) = raw.dataset {
344            let path = resolve(dataset);
345            for row in read_dataset(&path)? {
346                cases.push(build_case(row.test, &default_test, row.id, row.source, implicit)?);
347            }
348        }
349        let mut seen = std::collections::HashSet::new();
350        for case in &cases {
351            if !seen.insert(case.id.as_str()) {
352                return Err(EvalError::invalid(format!("duplicate test id `{}`", case.id)));
353            }
354        }
355        Ok(Self {
356            path: PathBuf::new(),
357            description: raw.description,
358            workflow: resolve(raw.workflow),
359            providers: raw.providers.map(resolve),
360            knowledge: raw.knowledge.map(resolve),
361            mcp: raw.mcp.map(resolve),
362            plugins: raw.plugins.into_iter().map(resolve).collect(),
363            cases,
364            gate: raw.gate,
365            calibration: raw.calibration,
366        })
367    }
368}
369
370fn validate_gate(gate: &Gate, calibration: Option<&Calibration>) -> Result<(), EvalError> {
371    let fraction = |name: &str, value: Option<f64>| match value {
372        Some(v) if !(0.0..=1.0).contains(&v) => Err(EvalError::invalid(format!("`{name}` must be between 0 and 1"))),
373        _ => Ok(()),
374    };
375    fraction("gate.pass_rate", Some(gate.pass_rate))?;
376    fraction("gate.pass_hat_k", gate.pass_hat_k)?;
377    fraction("gate.baseline.tolerance", Some(gate.baseline.tolerance))?;
378    fraction("gate.baseline.test_tolerance", Some(gate.baseline.test_tolerance))?;
379    for (metric, tolerance) in &gate.baseline.metrics {
380        fraction(&format!("gate.baseline.metrics.{metric}"), Some(*tolerance))?;
381    }
382    if gate.k == Some(0) {
383        return Err(EvalError::invalid("`gate.k` must be at least 1"));
384    }
385    if let Some(c) = calibration {
386        fraction("calibration.threshold", c.threshold)?;
387        fraction("calibration.min_tpr", c.min_tpr)?;
388        fraction("calibration.min_tnr", c.min_tnr)?;
389        if c.min_kappa.is_some_and(|k| !(-1.0..=1.0).contains(&k)) {
390            return Err(EvalError::invalid("`calibration.min_kappa` must be between -1 and 1"));
391        }
392    }
393    Ok(())
394}
395
396fn build_case(
397    test: RawTest,
398    defaults: &RawTest,
399    id: String,
400    source: String,
401    implicit: &str,
402) -> Result<TestCase, EvalError> {
403    let context = |e: EvalError| EvalError::invalid(format!("test `{id}`: {e}"));
404    let mut vars = defaults.vars.clone();
405    vars.extend(test.vars);
406    let mut metadata = defaults.metadata.clone();
407    metadata.extend(test.metadata);
408    let mut tags = defaults.tags.clone();
409    tags.extend(test.tags.into_iter().filter(|t| !defaults.tags.contains(t)));
410    let own_assertions = !test.assert.is_empty();
411    let mut assertions = Vec::with_capacity(defaults.assert.len() + test.assert.len() + 1);
412    for raw in defaults.assert.iter().cloned().chain(test.assert) {
413        assertions.push(AssertionSpec::from_json(raw).map_err(context)?);
414    }
415    // Promptfoo's `__expected` convention: an expected value on a test without its
416    // own assertions means `equals` (after the `defaultTest` assertions). In
417    // calibration suites the expected value is a label the judge's verdict must match.
418    if !own_assertions && let Some(expected) = &test.expected {
419        assertions.push(AssertionSpec::new(implicit, Some(expected.clone())));
420    }
421    if assertions.is_empty() {
422        return Err(EvalError::invalid(format!("test `{id}` has no assertions (and no `expected` value)")));
423    }
424    let threshold = test.threshold.or(defaults.threshold);
425    if threshold.is_some_and(|t| !(0.0..=1.0).contains(&t)) {
426        return Err(EvalError::invalid(format!("test `{id}`: `threshold` must be between 0 and 1")));
427    }
428    Ok(TestCase {
429        description: test.description.or_else(|| defaults.description.clone()),
430        vars,
431        expected: test.expected,
432        tags,
433        metadata,
434        assertions,
435        threshold,
436        source,
437        id,
438    })
439}
440
441struct DatasetRow {
442    id: String,
443    source: String,
444    test: RawTest,
445}
446
447/// Read a JSONL dataset: one `{id?, vars, expected?, tags?, metadata?, assert?}`
448/// object per line; blank lines and lines starting with `//` are skipped.
449fn read_dataset(path: &Path) -> Result<Vec<DatasetRow>, EvalError> {
450    let text = std::fs::read_to_string(path)
451        .map_err(|e| EvalError::Io(format!("cannot read dataset `{}`: {e}", path.display())))?;
452    let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "dataset".into());
453    let name = path.file_name().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
454    let mut rows = Vec::new();
455    for (index, line) in text.lines().enumerate() {
456        let line_no = index + 1;
457        let trimmed = line.trim();
458        if trimmed.is_empty() || trimmed.starts_with("//") {
459            continue;
460        }
461        let mut value: Json = serde_json::from_str(trimmed)
462            .map_err(|e| EvalError::invalid(format!("{}:{line_no}: invalid JSON: {e}", path.display())))?;
463        strip_extensions(&mut value);
464        let test: RawTest = serde_json::from_value(value)
465            .map_err(|e| EvalError::invalid(format!("{}:{line_no}: {e}", path.display())))?;
466        let id = test.id.clone().unwrap_or_else(|| format!("{stem}:{line_no}"));
467        rows.push(DatasetRow { id, source: format!("{name}:{line_no}"), test });
468    }
469    Ok(rows)
470}
471
472/// Drop `x-` keys of a mapping (tool-specific extensions).
473fn strip_extensions(value: &mut Json) {
474    if let Json::Object(map) = value {
475        map.retain(|k, _| !k.starts_with("x-"));
476    }
477}
478
479/// YAML or JSON text to JSON (YAML 1.2 booleans).
480pub fn parse_structured(text: &str) -> Result<Json, EvalError> {
481    if text.trim_start().starts_with(['{', '[']) {
482        return serde_json::from_str(text).map_err(|e| EvalError::invalid(format!("invalid JSON: {e}")));
483    }
484    graphrt_core::yaml::to_value(text, true).map_err(|e| EvalError::invalid(format!("invalid YAML: {e}")))
485}
486
487/// Start inputs for the engine.
488pub fn inputs_of(vars: &Map<String, Json>) -> IndexMap<String, graphrt_core::Value> {
489    vars.iter().map(|(k, v)| (k.clone(), graphrt_core::Value::from_json(v.clone()))).collect()
490}
491
492#[cfg(test)]
493mod tests {
494    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::indexing_slicing)]
495
496    use super::*;
497
498    #[test]
499    fn parses_tests_defaults_and_resolves_paths() {
500        let suite = EvalSuite::parse(
501            r#"
502workflow: ../wf.yaml
503providers: p.yaml
504x-owner: me
505defaultTest:
506  vars: { lang: en }
507  tags: [smoke]
508  assert: [{ type: latency, threshold: 100, weight: 0 }]
509tests:
510  - vars: { name: Ada }
511    assert: [{ type: equals, value: "Hi", metric: exact }]
512  - id: named
513    tags: [slow]
514    x-note: ignored
515    vars: { name: Bob, lang: id }
516    threshold: 0.5
517    assert: [{ type: retrieval:recall-at-k, value: [d1], k: 3 }]
518gate: { pass_rate: 0.9 }
519"#,
520            Path::new("/evals"),
521        )
522        .unwrap();
523        assert_eq!(suite.workflow, PathBuf::from("/evals/../wf.yaml"));
524        assert_eq!(suite.providers, Some(PathBuf::from("/evals/p.yaml")));
525        assert_eq!(suite.gate.pass_rate, 0.9);
526        assert_eq!(suite.cases.len(), 2);
527        let first = &suite.cases[0];
528        assert_eq!(first.id, "test-1");
529        assert_eq!(first.vars["lang"], "en");
530        assert_eq!(first.assertions.len(), 2, "defaultTest assertions come first");
531        assert_eq!(first.assertions[0].weight, 0.0);
532        assert_eq!(first.assertions[1].metric.as_deref(), Some("exact"));
533        let second = &suite.cases[1];
534        assert_eq!(second.vars["lang"], "id");
535        assert_eq!(second.tags, ["smoke", "slow"]);
536        assert_eq!(second.assertions[1].config["k"], 3);
537        assert!(second.matches("slow") && second.matches("nam*") && !second.matches("other"));
538    }
539
540    #[test]
541    fn rejects_bad_files() {
542        let bad = |text: &str| EvalSuite::parse(text, Path::new("")).unwrap_err().to_string();
543        assert!(bad("tests: []").contains("workflow"));
544        assert!(bad("workflow: w.yaml\ntestz: []").contains("testz"));
545        assert!(bad("workflow: w.yaml\ntests: [{vars: {}}]").contains("no assertions"));
546        assert!(bad("workflow: w.yaml\ntests: [{assert: [{value: 1}]}]").contains("type"));
547        assert!(bad("workflow: w.yaml\ntests: [{assert: [{type: equals, weight: -1}]}]").contains("weight"));
548        assert!(bad("workflow: w.yaml\ngate: {pass_rate: 2}").contains("pass_rate"));
549        assert!(
550            bad("workflow: w.yaml\ntests: [{id: a, assert: [{type: equals}]}, {id: a, assert: [{type: equals}]}]")
551                .contains("duplicate")
552        );
553    }
554
555    #[test]
556    fn reads_jsonl_datasets() {
557        let dir = std::env::temp_dir().join(format!("graphrt-eval-dataset-{}", std::process::id()));
558        std::fs::create_dir_all(&dir).unwrap();
559        std::fs::write(
560            dir.join("cases.jsonl"),
561            "{\"id\": \"one\", \"vars\": {\"q\": \"a\"}, \"expected\": \"A\", \"tags\": [\"t\"]}\n\n// comment\n{\"vars\": {\"q\": \"b\"}, \"expected\": \"B\", \"metadata\": {\"expected_docs\": [\"d\"]}}\n",
562        )
563        .unwrap();
564        let suite = EvalSuite::parse("workflow: w.yaml\ndataset: cases.jsonl\n", &dir).unwrap();
565        assert_eq!(suite.cases.len(), 2);
566        assert_eq!(suite.cases[0].id, "one");
567        assert_eq!(suite.cases[0].assertions[0].kind, "equals", "bare expected means equals");
568        assert_eq!(suite.cases[1].id, "cases:4");
569        assert_eq!(suite.cases[1].source, "cases.jsonl:4");
570        std::fs::write(dir.join("bad.jsonl"), "{\"vars\": {}, \"nope\": 1}\n").unwrap();
571        let err = EvalSuite::parse("workflow: w.yaml\ndataset: bad.jsonl\n", &dir).unwrap_err().to_string();
572        assert!(err.contains("bad.jsonl:1") && err.contains("nope"), "{err}");
573        let _cleanup = std::fs::remove_dir_all(&dir);
574    }
575}