1mod 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#[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 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#[derive(Clone, Debug, PartialEq)]
58#[non_exhaustive]
59pub struct Outcome {
60 pub pass: bool,
61 pub score: f64,
63 pub reason: String,
64 pub excluded: bool,
67 pub judge: Option<Box<JudgeRecord>>,
69}
70
71impl Outcome {
72 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 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 pub fn excluded(reason: impl Into<String>) -> Self {
85 Self { excluded: true, ..Self::check(false, reason) }
86 }
87
88 pub fn with_judge(mut self, record: JudgeRecord) -> Self {
90 self.judge = Some(Box::new(record));
91 self
92 }
93}
94
95pub trait Assertion: Send + Sync + fmt::Debug {
97 fn evaluate<'a>(&'a self, ctx: AssertionContext<'a>) -> BoxFuture<'a, Outcome>;
99}
100
101pub type AssertionFactory = Arc<dyn Fn(&AssertionSpec) -> Result<Box<dyn Assertion>, EvalError> + Send + Sync>;
103
104#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
106#[non_exhaustive]
107pub struct AssertionResult {
108 #[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 #[serde(default, skip_serializing_if = "is_false")]
119 pub excluded: bool,
120 #[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 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 pub fn gates(&self) -> bool {
146 self.weight > 0.0 && !self.excluded
147 }
148
149 pub fn metric_name(&self) -> &str {
151 self.metric.as_deref().unwrap_or(&self.kind)
152 }
153}
154
155#[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 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 pub fn weight(&self) -> f64 {
188 self.weight
189 }
190}
191
192#[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 pub fn empty() -> Self {
213 Self { factories: IndexMap::new() }
214 }
215
216 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 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 pub fn kinds(&self) -> impl Iterator<Item = &str> {
240 self.factories.keys().map(String::as_str)
241 }
242
243 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
266pub 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
274pub fn transform_of(spec: &AssertionSpec) -> Result<Option<JsonPath>, EvalError> {
276 spec.transform.as_deref().map(JsonPath::parse).transpose()
277}
278
279pub(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
293pub(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
315pub(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 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 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}