Skip to main content

graphrt_eval/assertion/
mod.rs

1//! Assertions: the [`Assertion`] trait, the registry of assertion types and the
2//! built-in deterministic types.
3//!
4//! An assertion type is a factory turning an [`AssertionSpec`] (one `assert`
5//! entry, with `{{var}}` references already rendered) into an [`Assertion`].
6//! Evaluation is asynchronous so types that call models or run workflows (an
7//! LLM judge) fit the same interface as the string checks.
8//!
9//! Every type can be negated with a `not-` prefix (`not-contains`,
10//! `not-trajectory:tool-used`): the pass flag flips and the score becomes
11//! `1 - score`.
12
13mod perf;
14mod retrieval;
15mod text;
16mod trajectory;
17mod verdict;
18
19use std::fmt;
20use std::sync::Arc;
21
22use futures::future::BoxFuture;
23use indexmap::IndexMap;
24use serde::{Deserialize, Serialize};
25use serde_json::Value as Json;
26
27use crate::capture::RunCapture;
28use crate::config::{AssertionSpec, TestCase};
29use crate::error::EvalError;
30use crate::judge::JudgeRecord;
31use crate::path::JsonPath;
32
33/// What an assertion sees: the test case and the run it produced.
34#[derive(Clone, Copy, Debug)]
35#[non_exhaustive]
36pub struct AssertionContext<'a> {
37    pub case: &'a TestCase,
38    pub capture: &'a RunCapture,
39}
40
41impl<'a> AssertionContext<'a> {
42    pub fn new(case: &'a TestCase, capture: &'a RunCapture) -> Self {
43        Self { case, capture }
44    }
45
46    /// The value under test: the run's [`RunCapture::output`], or the value at
47    /// `transform` (resolved against [`RunCapture::subject_root`]).
48    pub fn subject(&self, transform: Option<&JsonPath>) -> Option<Json> {
49        match transform {
50            None => Some(self.capture.output()),
51            Some(path) => path.get(&self.capture.subject_root(&self.case.vars)),
52        }
53    }
54}
55
56/// The verdict of one assertion.
57#[derive(Clone, Debug, PartialEq)]
58#[non_exhaustive]
59pub struct Outcome {
60    pub pass: bool,
61    /// In `0..=1`.
62    pub score: f64,
63    pub reason: String,
64    /// Leave the result out of the test score, the gate and the metric means
65    /// (a judge's `unknown` verdict with `unknown: exclude`).
66    pub excluded: bool,
67    /// What a judge workflow decided (judge assertions only).
68    pub judge: Option<Box<JudgeRecord>>,
69}
70
71impl Outcome {
72    /// A binary verdict (score 1 or 0).
73    pub fn check(pass: bool, reason: impl Into<String>) -> Self {
74        Self::graded(pass, if pass { 1.0 } else { 0.0 }, reason)
75    }
76
77    /// A graded verdict; `score` is clamped to `0..=1` (NaN becomes 0).
78    pub fn graded(pass: bool, score: f64, reason: impl Into<String>) -> Self {
79        let score = if score.is_nan() { 0.0 } else { score.clamp(0.0, 1.0) };
80        Self { pass, score, reason: reason.into(), excluded: false, judge: None }
81    }
82
83    /// A result that is reported but neither scored nor gated.
84    pub fn excluded(reason: impl Into<String>) -> Self {
85        Self { excluded: true, ..Self::check(false, reason) }
86    }
87
88    /// Attach the judge's details.
89    pub fn with_judge(mut self, record: JudgeRecord) -> Self {
90        self.judge = Some(Box::new(record));
91        self
92    }
93}
94
95/// A check of one aspect of a run.
96pub trait Assertion: Send + Sync + fmt::Debug {
97    /// Evaluate against a finished run.
98    fn evaluate<'a>(&'a self, ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome>;
99}
100
101/// Builds an assertion from its spec (the `not-` prefix already removed).
102pub type AssertionFactory = Arc<dyn Fn(&AssertionSpec) -> Result<Box<dyn Assertion>, EvalError> + Send + Sync>;
103
104/// The result of one assertion, as reported.
105#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
106#[non_exhaustive]
107pub struct AssertionResult {
108    /// The assertion type as written (with any `not-` prefix).
109    #[serde(rename = "type")]
110    pub kind: String,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub metric: Option<String>,
113    pub pass: bool,
114    pub score: f64,
115    pub weight: f64,
116    pub reason: String,
117    /// Reported only: not part of the test score, the gate or the metric means.
118    #[serde(default, skip_serializing_if = "is_false")]
119    pub excluded: bool,
120    /// The judge workflow (path and fingerprint) and its verdict.
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub judge: Option<Box<JudgeRecord>>,
123}
124
125fn is_false(flag: &bool) -> bool {
126    !*flag
127}
128
129impl AssertionResult {
130    /// A result with no judge record, not excluded.
131    pub fn new(kind: impl Into<String>, pass: bool, score: f64, weight: f64, reason: impl Into<String>) -> Self {
132        Self {
133            kind: kind.into(),
134            metric: None,
135            pass,
136            score,
137            weight,
138            reason: reason.into(),
139            excluded: false,
140            judge: None,
141        }
142    }
143
144    /// Whether this result counts towards the test verdict.
145    pub fn gates(&self) -> bool {
146        self.weight > 0.0 && !self.excluded
147    }
148
149    /// The name the summary aggregates this result under: `metric`, else the type.
150    pub fn metric_name(&self) -> &str {
151        self.metric.as_deref().unwrap_or(&self.kind)
152    }
153}
154
155/// An assertion ready to evaluate, with its reporting settings.
156#[derive(Debug)]
157pub struct PreparedAssertion {
158    kind: String,
159    metric: Option<String>,
160    weight: f64,
161    negated: bool,
162    inner: Box<dyn Assertion>,
163}
164
165impl PreparedAssertion {
166    /// Evaluate and wrap the outcome into a reported result.
167    pub async fn run(&self, ctx: AssertionContext<'_>) -> AssertionResult {
168        let mut outcome = self.inner.evaluate(ctx).await;
169        if self.negated && !outcome.excluded {
170            outcome.pass = !outcome.pass;
171            outcome.score = 1.0 - outcome.score;
172            outcome.reason = format!("negated: {}", outcome.reason);
173        }
174        AssertionResult {
175            kind: self.kind.clone(),
176            metric: self.metric.clone(),
177            pass: outcome.pass,
178            score: outcome.score,
179            weight: self.weight,
180            reason: outcome.reason,
181            excluded: outcome.excluded,
182            judge: outcome.judge,
183        }
184    }
185
186    /// Weight in the test score (`0` = report only).
187    pub fn weight(&self) -> f64 {
188        self.weight
189    }
190}
191
192/// Assertion types by name.
193#[derive(Clone)]
194pub struct AssertionRegistry {
195    factories: IndexMap<String, AssertionFactory>,
196}
197
198impl fmt::Debug for AssertionRegistry {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        f.debug_struct("AssertionRegistry").field("types", &self.factories.keys().collect::<Vec<_>>()).finish()
201    }
202}
203
204impl Default for AssertionRegistry {
205    fn default() -> Self {
206        Self::with_builtins()
207    }
208}
209
210impl AssertionRegistry {
211    /// No types at all.
212    pub fn empty() -> Self {
213        Self { factories: IndexMap::new() }
214    }
215
216    /// The built-in deterministic, performance, trajectory, retrieval and
217    /// `verdict` types. `judge` needs a workflow loader: see [`crate::judge::register`].
218    pub fn with_builtins() -> Self {
219        let mut registry = Self::empty();
220        text::register(&mut registry);
221        perf::register(&mut registry);
222        trajectory::register(&mut registry);
223        retrieval::register(&mut registry);
224        verdict::register(&mut registry);
225        registry
226    }
227
228    /// Register (or replace) an assertion type. Names must not start with `not-`.
229    pub fn register(
230        &mut self,
231        kind: impl Into<String>,
232        factory: impl Fn(&AssertionSpec) -> Result<Box<dyn Assertion>, EvalError> + Send + Sync + 'static,
233    ) -> &mut Self {
234        self.factories.insert(kind.into(), Arc::new(factory));
235        self
236    }
237
238    /// Registered type names.
239    pub fn kinds(&self) -> impl Iterator<Item = &str> {
240        self.factories.keys().map(String::as_str)
241    }
242
243    /// Build an assertion from a spec whose values are already rendered.
244    pub fn prepare(&self, spec: &AssertionSpec) -> Result<PreparedAssertion, EvalError> {
245        let (negated, base) = match spec.kind.strip_prefix("not-") {
246            Some(base) => (true, base),
247            None => (false, spec.kind.as_str()),
248        };
249        let factory = self.factories.get(base).ok_or_else(|| {
250            let known: Vec<&str> = self.kinds().collect();
251            EvalError::invalid(format!("unknown assertion type `{}` (known: {})", spec.kind, known.join(", ")))
252        })?;
253        let mut base_spec = spec.clone();
254        base_spec.kind = base.to_owned();
255        let inner = factory(&base_spec).map_err(|e| EvalError::invalid(format!("assertion `{}`: {e}", spec.kind)))?;
256        Ok(PreparedAssertion {
257            kind: spec.kind.clone(),
258            metric: spec.metric.clone(),
259            weight: spec.weight,
260            negated,
261            inner,
262        })
263    }
264}
265
266/// Reject `config` keys other than `allowed` (typos would otherwise be ignored).
267pub fn only_keys(spec: &AssertionSpec, allowed: &[&str]) -> Result<(), EvalError> {
268    match spec.config.keys().find(|k| !allowed.contains(&k.as_str())) {
269        Some(key) => Err(EvalError::invalid(format!("unknown key `{key}`"))),
270        None => Ok(()),
271    }
272}
273
274/// The parsed `transform` path of a spec.
275pub fn transform_of(spec: &AssertionSpec) -> Result<Option<JsonPath>, EvalError> {
276    spec.transform.as_deref().map(JsonPath::parse).transpose()
277}
278
279/// Display a JSON value briefly for reasons.
280pub(crate) fn brief(value: &Json) -> String {
281    let text = match value {
282        Json::String(s) => format!("{s:?}"),
283        other => other.to_string(),
284    };
285    if text.chars().count() > 120 {
286        let cut: String = text.chars().take(117).collect();
287        format!("{cut}...")
288    } else {
289        text
290    }
291}
292
293/// An assertion implemented by a synchronous function.
294pub(crate) struct FnAssertion<F> {
295    name: &'static str,
296    check: F,
297}
298
299impl<F> fmt::Debug for FnAssertion<F> {
300    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
301        f.debug_struct("FnAssertion").field("name", &self.name).finish()
302    }
303}
304
305impl<F> Assertion for FnAssertion<F>
306where
307    F: Fn(AssertionContext<'_>) -> Outcome + Send + Sync,
308{
309    fn evaluate<'a>(&'a self, ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome> {
310        let outcome = (self.check)(ctx);
311        Box::pin(std::future::ready(outcome))
312    }
313}
314
315/// Box a synchronous check as an [`Assertion`].
316pub(crate) fn sync_assertion<F>(name: &'static str, check: F) -> Box<dyn Assertion>
317where
318    F: Fn(AssertionContext<'_>) -> Outcome + Send + Sync + 'static,
319{
320    Box::new(FnAssertion { name, check })
321}
322
323#[cfg(test)]
324pub(crate) mod test_support {
325    #![allow(clippy::unwrap_used, clippy::expect_used)]
326
327    use super::*;
328
329    /// Evaluate a spec (given as JSON) against a capture.
330    pub fn eval(spec: Json, capture: &RunCapture) -> AssertionResult {
331        try_eval(spec, capture).unwrap()
332    }
333
334    pub fn try_eval(spec: Json, capture: &RunCapture) -> Result<AssertionResult, EvalError> {
335        let spec = AssertionSpec::from_json(spec)?;
336        let prepared = AssertionRegistry::with_builtins().prepare(&spec)?;
337        let case = TestCase::new("t", serde_json::Map::new());
338        let ctx = AssertionContext::new(&case, capture);
339        Ok(tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(prepared.run(ctx)))
340    }
341
342    /// A capture whose answer is `answer`.
343    pub fn answered(answer: &str) -> RunCapture {
344        RunCapture { answer: answer.to_owned(), ..RunCapture::default() }
345    }
346}
347
348#[cfg(test)]
349mod tests {
350    #![allow(clippy::unwrap_used)]
351
352    use super::test_support::*;
353    use super::*;
354    use serde_json::json;
355
356    #[test]
357    fn negation_weights_and_metrics() {
358        let capture = answered("hello world");
359        let result = eval(json!({"type": "not-contains", "value": "bye", "weight": 0, "metric": "polite"}), &capture);
360        assert!(result.pass && result.score == 1.0, "{result:?}");
361        assert_eq!(result.weight, 0.0);
362        assert_eq!(result.metric_name(), "polite");
363        assert_eq!(result.kind, "not-contains");
364        let result = eval(json!({"type": "not-contains", "value": "hello"}), &capture);
365        assert!(!result.pass && result.score == 0.0);
366        assert_eq!(result.metric_name(), "not-contains");
367    }
368
369    #[test]
370    fn unknown_types_and_keys_are_rejected() {
371        let capture = answered("x");
372        let err = try_eval(json!({"type": "llm-rubric", "value": "x"}), &capture).unwrap_err().to_string();
373        assert!(err.contains("unknown assertion type `llm-rubric`") && err.contains("equals"), "{err}");
374        let err = try_eval(json!({"type": "contains", "value": "x", "k": 3}), &capture).unwrap_err().to_string();
375        assert!(err.contains("unknown key `k`"), "{err}");
376    }
377
378    #[test]
379    fn custom_types_can_be_registered() {
380        #[derive(Debug)]
381        struct Always;
382        impl Assertion for Always {
383            fn evaluate<'a>(&'a self, _ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome> {
384                Box::pin(async { Outcome::graded(true, 0.75, "judged") })
385            }
386        }
387        let mut registry = AssertionRegistry::with_builtins();
388        registry.register("judge", |_spec| Ok(Box::new(Always) as Box<dyn Assertion>));
389        let prepared = registry.prepare(&AssertionSpec::new("judge", None)).unwrap();
390        let case = TestCase::new("t", serde_json::Map::new());
391        let capture = answered("x");
392        let result = tokio::runtime::Builder::new_current_thread()
393            .build()
394            .unwrap()
395            .block_on(prepared.run(AssertionContext::new(&case, &capture)));
396        assert_eq!(result.score, 0.75);
397    }
398}