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, Verdict};
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    /// The result as a score label: `unknown` when excluded (it decided
155    /// nothing), else `pass` or `fail`. Offline trace evaluations and online
156    /// scores label results the same way through this.
157    pub fn verdict(&self) -> Verdict {
158        if self.excluded {
159            Verdict::Unknown
160        } else if self.pass {
161            Verdict::Pass
162        } else {
163            Verdict::Fail
164        }
165    }
166}
167
168/// An assertion ready to evaluate, with its reporting settings.
169#[derive(Debug)]
170pub struct PreparedAssertion {
171    kind: String,
172    metric: Option<String>,
173    weight: f64,
174    negated: bool,
175    inner: Box<dyn Assertion>,
176}
177
178impl PreparedAssertion {
179    /// Evaluate and wrap the outcome into a reported result.
180    pub async fn run(&self, ctx: AssertionContext<'_>) -> AssertionResult {
181        let mut outcome = self.inner.evaluate(ctx).await;
182        if self.negated && !outcome.excluded {
183            outcome.pass = !outcome.pass;
184            outcome.score = 1.0 - outcome.score;
185            outcome.reason = format!("negated: {}", outcome.reason);
186        }
187        AssertionResult {
188            kind: self.kind.clone(),
189            metric: self.metric.clone(),
190            pass: outcome.pass,
191            score: outcome.score,
192            weight: self.weight,
193            reason: outcome.reason,
194            excluded: outcome.excluded,
195            judge: outcome.judge,
196        }
197    }
198
199    /// Weight in the test score (`0` = report only).
200    pub fn weight(&self) -> f64 {
201        self.weight
202    }
203}
204
205/// Assertion types by name.
206#[derive(Clone)]
207pub struct AssertionRegistry {
208    factories: IndexMap<String, AssertionFactory>,
209}
210
211impl fmt::Debug for AssertionRegistry {
212    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
213        f.debug_struct("AssertionRegistry").field("types", &self.factories.keys().collect::<Vec<_>>()).finish()
214    }
215}
216
217impl Default for AssertionRegistry {
218    fn default() -> Self {
219        Self::with_builtins()
220    }
221}
222
223impl AssertionRegistry {
224    /// No types at all.
225    pub fn empty() -> Self {
226        Self { factories: IndexMap::new() }
227    }
228
229    /// The built-in deterministic, performance, trajectory, retrieval and
230    /// `verdict` types. `judge` needs a workflow loader: see [`crate::judge::register`].
231    pub fn with_builtins() -> Self {
232        let mut registry = Self::empty();
233        text::register(&mut registry);
234        perf::register(&mut registry);
235        trajectory::register(&mut registry);
236        retrieval::register(&mut registry);
237        verdict::register(&mut registry);
238        registry
239    }
240
241    /// Register (or replace) an assertion type. Names must not start with `not-`.
242    pub fn register(
243        &mut self,
244        kind: impl Into<String>,
245        factory: impl Fn(&AssertionSpec) -> Result<Box<dyn Assertion>, EvalError> + Send + Sync + 'static,
246    ) -> &mut Self {
247        self.factories.insert(kind.into(), Arc::new(factory));
248        self
249    }
250
251    /// Registered type names.
252    pub fn kinds(&self) -> impl Iterator<Item = &str> {
253        self.factories.keys().map(String::as_str)
254    }
255
256    /// Build an assertion from a spec whose values are already rendered.
257    pub fn prepare(&self, spec: &AssertionSpec) -> Result<PreparedAssertion, EvalError> {
258        let (negated, base) = match spec.kind.strip_prefix("not-") {
259            Some(base) => (true, base),
260            None => (false, spec.kind.as_str()),
261        };
262        let factory = self.factories.get(base).ok_or_else(|| {
263            let known: Vec<&str> = self.kinds().collect();
264            EvalError::invalid(format!("unknown assertion type `{}` (known: {})", spec.kind, known.join(", ")))
265        })?;
266        let mut base_spec = spec.clone();
267        base_spec.kind = base.to_owned();
268        let inner = factory(&base_spec).map_err(|e| EvalError::invalid(format!("assertion `{}`: {e}", spec.kind)))?;
269        Ok(PreparedAssertion {
270            kind: spec.kind.clone(),
271            metric: spec.metric.clone(),
272            weight: spec.weight,
273            negated,
274            inner,
275        })
276    }
277}
278
279/// Reject `config` keys other than `allowed` (typos would otherwise be ignored).
280pub fn only_keys(spec: &AssertionSpec, allowed: &[&str]) -> Result<(), EvalError> {
281    match spec.config.keys().find(|k| !allowed.contains(&k.as_str())) {
282        Some(key) => Err(EvalError::invalid(format!("unknown key `{key}`"))),
283        None => Ok(()),
284    }
285}
286
287/// The parsed `transform` path of a spec.
288pub fn transform_of(spec: &AssertionSpec) -> Result<Option<JsonPath>, EvalError> {
289    spec.transform.as_deref().map(JsonPath::parse).transpose()
290}
291
292/// Display a JSON value briefly for reasons.
293pub(crate) fn brief(value: &Json) -> String {
294    let text = match value {
295        Json::String(s) => format!("{s:?}"),
296        other => other.to_string(),
297    };
298    if text.chars().count() > 120 {
299        let cut: String = text.chars().take(117).collect();
300        format!("{cut}...")
301    } else {
302        text
303    }
304}
305
306/// An assertion implemented by a synchronous function.
307pub(crate) struct FnAssertion<F> {
308    name: &'static str,
309    check: F,
310}
311
312impl<F> fmt::Debug for FnAssertion<F> {
313    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
314        f.debug_struct("FnAssertion").field("name", &self.name).finish()
315    }
316}
317
318impl<F> Assertion for FnAssertion<F>
319where
320    F: Fn(AssertionContext<'_>) -> Outcome + Send + Sync,
321{
322    fn evaluate<'a>(&'a self, ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome> {
323        let outcome = (self.check)(ctx);
324        Box::pin(std::future::ready(outcome))
325    }
326}
327
328/// Box a synchronous check as an [`Assertion`].
329pub(crate) fn sync_assertion<F>(name: &'static str, check: F) -> Box<dyn Assertion>
330where
331    F: Fn(AssertionContext<'_>) -> Outcome + Send + Sync + 'static,
332{
333    Box::new(FnAssertion { name, check })
334}
335
336#[cfg(test)]
337pub(crate) mod test_support {
338    #![allow(clippy::unwrap_used, clippy::expect_used)]
339
340    use super::*;
341
342    /// Evaluate a spec (given as JSON) against a capture.
343    pub fn eval(spec: Json, capture: &RunCapture) -> AssertionResult {
344        try_eval(spec, capture).unwrap()
345    }
346
347    pub fn try_eval(spec: Json, capture: &RunCapture) -> Result<AssertionResult, EvalError> {
348        let spec = AssertionSpec::from_json(spec)?;
349        let prepared = AssertionRegistry::with_builtins().prepare(&spec)?;
350        let case = TestCase::new("t", serde_json::Map::new());
351        let ctx = AssertionContext::new(&case, capture);
352        Ok(tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(prepared.run(ctx)))
353    }
354
355    /// A capture whose answer is `answer`.
356    pub fn answered(answer: &str) -> RunCapture {
357        RunCapture { answer: answer.to_owned(), ..RunCapture::default() }
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    #![allow(clippy::unwrap_used)]
364
365    use super::test_support::*;
366    use super::*;
367    use serde_json::json;
368
369    #[test]
370    fn negation_weights_and_metrics() {
371        let capture = answered("hello world");
372        let result = eval(json!({"type": "not-contains", "value": "bye", "weight": 0, "metric": "polite"}), &capture);
373        assert!(result.pass && result.score == 1.0, "{result:?}");
374        assert_eq!(result.weight, 0.0);
375        assert_eq!(result.metric_name(), "polite");
376        assert_eq!(result.kind, "not-contains");
377        let result = eval(json!({"type": "not-contains", "value": "hello"}), &capture);
378        assert!(!result.pass && result.score == 0.0);
379        assert_eq!(result.metric_name(), "not-contains");
380    }
381
382    #[test]
383    fn verdict_labels_excluded_results_unknown() {
384        let mut result = AssertionResult::new("contains", true, 1.0, 1.0, "");
385        assert_eq!(result.verdict(), Verdict::Pass);
386        result.pass = false;
387        assert_eq!(result.verdict(), Verdict::Fail);
388        result.excluded = true;
389        assert_eq!(result.verdict(), Verdict::Unknown);
390        result.pass = true;
391        assert_eq!(result.verdict().as_str(), "unknown", "excluded wins over pass");
392    }
393
394    #[test]
395    fn unknown_types_and_keys_are_rejected() {
396        let capture = answered("x");
397        let err = try_eval(json!({"type": "llm-rubric", "value": "x"}), &capture).unwrap_err().to_string();
398        assert!(err.contains("unknown assertion type `llm-rubric`") && err.contains("equals"), "{err}");
399        let err = try_eval(json!({"type": "contains", "value": "x", "k": 3}), &capture).unwrap_err().to_string();
400        assert!(err.contains("unknown key `k`"), "{err}");
401    }
402
403    #[test]
404    fn custom_types_can_be_registered() {
405        #[derive(Debug)]
406        struct Always;
407        impl Assertion for Always {
408            fn evaluate<'a>(&'a self, _ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome> {
409                Box::pin(async { Outcome::graded(true, 0.75, "judged") })
410            }
411        }
412        let mut registry = AssertionRegistry::with_builtins();
413        registry.register("judge", |_spec| Ok(Box::new(Always) as Box<dyn Assertion>));
414        let prepared = registry.prepare(&AssertionSpec::new("judge", None)).unwrap();
415        let case = TestCase::new("t", serde_json::Map::new());
416        let capture = answered("x");
417        let result = tokio::runtime::Builder::new_current_thread()
418            .build()
419            .unwrap()
420            .block_on(prepared.run(AssertionContext::new(&case, &capture)));
421        assert_eq!(result.score, 0.75);
422    }
423}