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, Verdict};
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 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#[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 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 pub fn weight(&self) -> f64 {
201 self.weight
202 }
203}
204
205#[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 pub fn empty() -> Self {
226 Self { factories: IndexMap::new() }
227 }
228
229 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 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 pub fn kinds(&self) -> impl Iterator<Item = &str> {
253 self.factories.keys().map(String::as_str)
254 }
255
256 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
279pub 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
287pub fn transform_of(spec: &AssertionSpec) -> Result<Option<JsonPath>, EvalError> {
289 spec.transform.as_deref().map(JsonPath::parse).transpose()
290}
291
292pub(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
306pub(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
328pub(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 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 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}