1use std::path::{Path, PathBuf};
31
32use indexmap::IndexMap;
33use serde_json::{Map, Value as Json};
34
35use crate::assertion::{AssertionContext, AssertionRegistry, AssertionResult, PreparedAssertion};
36use crate::capture::{RunCapture, RunStatus};
37use crate::config::{AssertionSpec, TestCase, parse_structured};
38use crate::error::EvalError;
39use crate::path::render;
40
41pub const DEFAULT_CONCURRENCY: usize = 2;
43pub const DEFAULT_QUEUE: usize = 256;
45const MAX_CONCURRENCY: usize = 256;
47const MAX_QUEUE: usize = 100_000;
48
49pub const ONLINE_TYPES: &[&str] = &[
52 "judge",
53 "regex",
54 "contains",
55 "icontains",
56 "contains-any",
57 "icontains-any",
58 "contains-all",
59 "icontains-all",
60 "starts-with",
61 "is-json",
62 "json-schema",
63 "latency",
64 "tokens",
65 "trajectory:tool-used",
66 "trajectory:tool-sequence",
67 "trajectory:tool-args-match",
68 "trajectory:step-count",
69];
70
71#[derive(Clone, Debug, PartialEq)]
73#[non_exhaustive]
74pub struct OnlineConfig {
75 pub path: PathBuf,
77 pub concurrency: usize,
78 pub queue: usize,
79 pub evaluators: Vec<EvaluatorSpec>,
80}
81
82#[derive(Clone, Debug, PartialEq)]
84#[non_exhaustive]
85pub struct EvaluatorSpec {
86 pub name: String,
88 pub workflows: Vec<String>,
90 pub sample: f64,
92 pub status: Vec<RunStatus>,
93 pub tags: Vec<String>,
95 pub metadata: IndexMap<String, String>,
97 pub assertion: AssertionSpec,
98}
99
100#[derive(Clone, Copy, Debug)]
102#[non_exhaustive]
103pub struct RunInfo<'a> {
104 pub run_id: &'a str,
105 pub workflow: &'a str,
106 pub status: RunStatus,
107 pub tags: &'a [String],
108 pub metadata: &'a IndexMap<String, String>,
109}
110
111impl<'a> RunInfo<'a> {
112 pub fn new(
113 run_id: &'a str,
114 workflow: &'a str,
115 status: RunStatus,
116 tags: &'a [String],
117 metadata: &'a IndexMap<String, String>,
118 ) -> Self {
119 Self { run_id, workflow, status, tags, metadata }
120 }
121}
122
123type Object = Map<String, Json>;
126
127fn known_keys(object: &Object, allowed: &[&str]) -> Result<(), EvalError> {
129 match object.keys().find(|k| !allowed.contains(&k.as_str())) {
130 Some(key) => Err(EvalError::invalid(format!("unknown field `{key}`, expected one of {}", allowed.join(", ")))),
131 None => Ok(()),
132 }
133}
134
135fn count_field(object: &Object, key: &str, default: usize) -> Result<usize, EvalError> {
136 match object.get(key) {
137 None | Some(Json::Null) => Ok(default),
138 Some(value) => value
139 .as_u64()
140 .and_then(|n| usize::try_from(n).ok())
141 .ok_or_else(|| EvalError::invalid(format!("`{key}` must be a positive integer"))),
142 }
143}
144
145fn strings_field(object: &Object, key: &str) -> Result<Vec<String>, EvalError> {
146 let list = match object.get(key) {
147 None | Some(Json::Null) => return Ok(Vec::new()),
148 Some(Json::Array(items)) => items,
149 Some(_) => return Err(EvalError::invalid(format!("`{key}` must be a list of strings"))),
150 };
151 list.iter()
152 .map(|item| {
153 item.as_str()
154 .map(str::to_owned)
155 .ok_or_else(|| EvalError::invalid(format!("`{key}` must be a list of strings")))
156 })
157 .collect()
158}
159
160fn status_of(name: &str) -> Option<RunStatus> {
161 match name {
162 "succeeded" => Some(RunStatus::Succeeded),
163 "failed" => Some(RunStatus::Failed),
164 "aborted" => Some(RunStatus::Aborted),
165 "paused" => Some(RunStatus::Paused),
166 _ => None,
167 }
168}
169
170impl OnlineConfig {
171 pub fn load(path: &Path) -> Result<Self, EvalError> {
175 let text = std::fs::read_to_string(path)
176 .map_err(|e| EvalError::Io(format!("cannot read evaluator config `{}`: {e}", path.display())))?;
177 Self::parse(&text)
178 .map(|mut config| {
179 config.path = path.to_path_buf();
180 config
181 })
182 .map_err(|e| match e {
183 EvalError::Invalid(m) => EvalError::Invalid(format!("{}: {m}", path.display())),
184 other => other,
185 })
186 }
187
188 pub fn parse(text: &str) -> Result<Self, EvalError> {
193 let Json::Object(raw) = parse_structured(text)? else {
194 return Err(EvalError::invalid("an evaluator config must be a mapping with `evaluators`"));
195 };
196 known_keys(&raw, &["concurrency", "queue", "evaluators"])?;
197 let concurrency = count_field(&raw, "concurrency", DEFAULT_CONCURRENCY)?;
198 if !(1..=MAX_CONCURRENCY).contains(&concurrency) {
199 return Err(EvalError::invalid(format!("`concurrency` must be 1-{MAX_CONCURRENCY}")));
200 }
201 let queue = count_field(&raw, "queue", DEFAULT_QUEUE)?;
202 if !(1..=MAX_QUEUE).contains(&queue) {
203 return Err(EvalError::invalid(format!("`queue` must be 1-{MAX_QUEUE}")));
204 }
205 let list = match raw.get("evaluators") {
206 Some(Json::Array(list)) if !list.is_empty() => list,
207 Some(Json::Array(_)) => return Err(EvalError::invalid("`evaluators` is empty")),
208 _ => return Err(EvalError::invalid("`evaluators` (a list) is required")),
209 };
210 let mut evaluators = Vec::with_capacity(list.len());
211 for (index, evaluator) in list.iter().enumerate() {
212 let Json::Object(evaluator) = evaluator else {
213 return Err(EvalError::invalid(format!("evaluator {}: must be a mapping", index + 1)));
214 };
215 let name = evaluator.get("name").and_then(Json::as_str).unwrap_or_default().to_owned();
216 let spec = evaluator_spec(evaluator).map_err(|e| {
217 let label = if name.is_empty() { format!("{}", index + 1) } else { format!("`{name}`") };
218 EvalError::invalid(format!("evaluator {label}: {e}"))
219 })?;
220 if evaluators.iter().any(|e: &EvaluatorSpec| e.name == spec.name) {
221 return Err(EvalError::invalid(format!("duplicate evaluator name `{}`", spec.name)));
222 }
223 evaluators.push(spec);
224 }
225 Ok(Self { path: PathBuf::new(), concurrency, queue, evaluators })
226 }
227
228 pub fn base_dir(&self) -> PathBuf {
230 self.path.parent().map(Path::to_path_buf).unwrap_or_default()
231 }
232
233 pub fn unmatched_workflows<'a>(&'a self, served: &[&str]) -> Vec<&'a str> {
235 self.evaluators
236 .iter()
237 .flat_map(|e| e.workflows.iter())
238 .filter(|pattern| !served.iter().any(|name| crate::glob::matches(pattern, name)))
239 .map(String::as_str)
240 .collect()
241 }
242}
243
244fn evaluator_spec(raw: &Object) -> Result<EvaluatorSpec, EvalError> {
245 known_keys(raw, &["name", "workflows", "sample", "status", "tags", "metadata", "assert"])?;
246 let name = raw.get("name").and_then(Json::as_str).unwrap_or_default().trim().to_owned();
247 if name.is_empty() || name.len() > 200 {
248 return Err(EvalError::invalid("`name` must be 1-200 characters"));
249 }
250 let sample = match raw.get("sample") {
251 None | Some(Json::Null) => 1.0,
252 Some(value) => value.as_f64().ok_or_else(|| EvalError::invalid("`sample` must be a number"))?,
253 };
254 if !(0.0..=1.0).contains(&sample) {
255 return Err(EvalError::invalid("`sample` must be between 0 and 1"));
256 }
257 let status = match raw.get("status") {
258 None | Some(Json::Null) => vec![RunStatus::Succeeded, RunStatus::Failed],
259 Some(_) => strings_field(raw, "status")?
260 .iter()
261 .map(|s| {
262 status_of(s).ok_or_else(|| {
263 EvalError::invalid(format!("unknown status `{s}` (expected succeeded, failed or aborted)"))
264 })
265 })
266 .collect::<Result<_, _>>()?,
267 };
268 if status.contains(&RunStatus::Paused) {
269 return Err(EvalError::invalid("`status` cannot include `paused`: paused runs have not finished"));
270 }
271 if status.is_empty() {
272 return Err(EvalError::invalid("`status` is empty"));
273 }
274 let metadata = match raw.get("metadata") {
275 None | Some(Json::Null) => IndexMap::new(),
276 Some(Json::Object(map)) => map
277 .iter()
278 .map(|(k, v)| match v {
279 Json::String(text) => Ok((k.clone(), text.clone())),
280 _ => Err(EvalError::invalid(format!("`metadata.{k}` must be a string"))),
281 })
282 .collect::<Result<_, _>>()?,
283 Some(_) => return Err(EvalError::invalid("`metadata` must be a mapping of strings")),
284 };
285 let assertion = raw.get("assert").cloned().ok_or_else(|| EvalError::invalid("`assert` is required"))?;
286 let assertion = AssertionSpec::from_json(assertion)?;
287 check_online(&assertion)?;
288 Ok(EvaluatorSpec {
289 name,
290 workflows: strings_field(raw, "workflows")?,
291 sample,
292 status,
293 tags: strings_field(raw, "tags")?,
294 metadata,
295 assertion,
296 })
297}
298
299fn check_online(spec: &AssertionSpec) -> Result<(), EvalError> {
301 let base = spec.kind.strip_prefix("not-").unwrap_or(&spec.kind);
302 if !ONLINE_TYPES.contains(&base) {
303 return Err(EvalError::invalid(format!(
304 "assertion type `{}` needs an expected answer or labels and cannot run online (online types: {})",
305 spec.kind,
306 ONLINE_TYPES.join(", ")
307 )));
308 }
309 let values = spec.value.iter().chain(spec.config.values());
310 if values.into_iter().any(mentions_expected) {
311 return Err(EvalError::invalid(
312 "`{{expected}}` is not available online: production runs have no expected answer",
313 ));
314 }
315 Ok(())
316}
317
318fn mentions_expected(value: &Json) -> bool {
319 match value {
320 Json::String(text) => text.split("{{").skip(1).any(|rest| rest.trim_start().starts_with("expected")),
321 Json::Array(items) => items.iter().any(mentions_expected),
322 Json::Object(map) => map.values().any(mentions_expected),
323 _ => false,
324 }
325}
326
327fn has_template(spec: &AssertionSpec) -> bool {
328 fn walk(value: &Json) -> bool {
329 match value {
330 Json::String(text) => text.contains("{{"),
331 Json::Array(items) => items.iter().any(walk),
332 Json::Object(map) => map.values().any(walk),
333 _ => false,
334 }
335 }
336 spec.value.iter().chain(spec.config.values()).any(walk)
337}
338
339impl EvaluatorSpec {
340 pub fn matches(&self, run: &RunInfo<'_>) -> bool {
342 self.status.contains(&run.status)
343 && (self.workflows.is_empty() || self.workflows.iter().any(|p| crate::glob::matches(p, run.workflow)))
344 && (self.tags.is_empty() || self.tags.iter().any(|t| run.tags.contains(t)))
345 && self.metadata.iter().all(|(k, v)| run.metadata.get(k) == Some(v))
346 }
347
348 pub fn sampled(&self, run_id: &str) -> bool {
350 sample_point(run_id, &self.name) < self.sample
351 }
352}
353
354pub fn sample_point(run_id: &str, name: &str) -> f64 {
357 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
358 for byte in run_id.bytes().chain(std::iter::once(0)).chain(name.bytes()) {
359 hash ^= u64::from(byte);
360 hash = hash.wrapping_mul(0x0100_0000_01b3);
361 }
362 hash ^= hash >> 30;
364 hash = hash.wrapping_mul(0xbf58_476d_1ce4_e5b9);
365 hash ^= hash >> 27;
366 hash = hash.wrapping_mul(0x94d0_49bb_1331_11eb);
367 hash ^= hash >> 31;
368 #[allow(clippy::cast_precision_loss)]
369 let point = (hash >> 11) as f64 / (1u64 << 53) as f64;
370 point
371}
372
373#[derive(Debug)]
375pub struct Evaluator {
376 pub spec: EvaluatorSpec,
377 prepared: Option<PreparedAssertion>,
380}
381
382#[derive(Debug)]
384pub struct OnlineEvaluators {
385 evaluators: Vec<Evaluator>,
386 registry: AssertionRegistry,
387}
388
389impl OnlineEvaluators {
390 pub fn new(config: &OnlineConfig, registry: AssertionRegistry) -> Result<Self, EvalError> {
395 let mut evaluators = Vec::with_capacity(config.evaluators.len());
396 for spec in &config.evaluators {
397 let context = |e: EvalError| EvalError::invalid(format!("evaluator `{}`: {e}", spec.name));
398 let prepared = if has_template(&spec.assertion) {
399 let mut probe = spec.assertion.clone();
401 probe.value = None;
402 if spec.assertion.kind.trim_start_matches("not-") == "judge" {
403 registry.prepare(&probe).map_err(context)?;
404 }
405 None
406 } else {
407 Some(registry.prepare(&spec.assertion).map_err(context)?)
408 };
409 evaluators.push(Evaluator { spec: spec.clone(), prepared });
410 }
411 Ok(Self { evaluators, registry })
412 }
413
414 pub fn evaluators(&self) -> &[Evaluator] {
415 &self.evaluators
416 }
417
418 pub fn select(&self, run: &RunInfo<'_>) -> Vec<usize> {
420 self.evaluators
421 .iter()
422 .enumerate()
423 .filter(|(_, e)| e.spec.matches(run) && e.spec.sampled(run.run_id))
424 .map(|(index, _)| index)
425 .collect()
426 }
427
428 pub fn covers(&self, workflow: &str) -> bool {
431 self.evaluators.iter().any(|e| {
432 e.spec.sample > 0.0
433 && (e.spec.workflows.is_empty() || e.spec.workflows.iter().any(|p| crate::glob::matches(p, workflow)))
434 })
435 }
436
437 pub async fn evaluate(
439 &self,
440 index: usize,
441 run: &RunInfo<'_>,
442 vars: Map<String, Json>,
443 capture: &RunCapture,
444 ) -> Option<AssertionResult> {
445 let evaluator = self.evaluators.get(index)?;
446 let mut case = TestCase::new(run.run_id, vars);
447 case.tags = run.tags.to_vec();
448 case.metadata = run.metadata.iter().map(|(k, v)| (k.clone(), Json::String(v.clone()))).collect();
449 let ctx = AssertionContext::new(&case, capture);
450 let result = match &evaluator.prepared {
451 Some(prepared) => prepared.run(ctx).await,
452 None => match self.prepare_for(&evaluator.spec.assertion, &case) {
453 Ok(prepared) => prepared.run(ctx).await,
454 Err(e) => AssertionResult::new(&evaluator.spec.assertion.kind, false, 0.0, 1.0, e.to_string()),
455 },
456 };
457 Some(result)
458 }
459
460 fn prepare_for(&self, spec: &AssertionSpec, case: &TestCase) -> Result<PreparedAssertion, EvalError> {
461 let mut context = case.vars.clone();
462 context.insert("vars".into(), Json::Object(case.vars.clone()));
463 context.insert("metadata".into(), Json::Object(case.metadata.clone()));
464 context.insert("id".into(), Json::String(case.id.clone()));
465 context.insert("tags".into(), Json::from(case.tags.clone()));
466 let context = Json::Object(context);
467 let mut rendered = spec.clone();
468 rendered.value = spec.value.as_ref().map(|v| render(v, &context)).transpose()?;
469 for value in rendered.config.values_mut() {
470 *value = render(value, &context)?;
471 }
472 self.registry.prepare(&rendered)
473 }
474}
475
476#[cfg(test)]
477mod tests {
478 use super::*;
479 use crate::assertion::test_support::answered;
480
481 const CONFIG: &str = r#"
482concurrency: 3
483queue: 10
484evaluators:
485 - name: polite
486 workflows: [chat, "support-*"]
487 sample: 0.5
488 tags: [prod]
489 metadata: { tier: gold }
490 assert: { type: not-icontains, value: "as an ai" }
491 - name: fast
492 status: [succeeded]
493 assert: { type: latency, threshold: 100 }
494"#;
495
496 fn meta(pairs: &[(&str, &str)]) -> IndexMap<String, String> {
497 pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
498 }
499
500 #[test]
501 fn parses_filters_and_defaults() {
502 let config = OnlineConfig::parse(CONFIG).unwrap();
503 assert_eq!((config.concurrency, config.queue), (3, 10));
504 let polite = &config.evaluators[0];
505 let gold = meta(&[("tier", "gold")]);
506 let tags = vec!["prod".to_owned()];
507 assert!(polite.matches(&RunInfo::new("r", "support-eu", RunStatus::Failed, &tags, &gold)));
508 assert!(!polite.matches(&RunInfo::new("r", "other", RunStatus::Succeeded, &tags, &gold)));
509 assert!(!polite.matches(&RunInfo::new("r", "chat", RunStatus::Succeeded, &[], &gold)));
510 assert!(!polite.matches(&RunInfo::new("r", "chat", RunStatus::Succeeded, &tags, &meta(&[("tier", "free")]))));
511 assert!(!polite.matches(&RunInfo::new("r", "chat", RunStatus::Aborted, &tags, &gold)), "default statuses");
512 let fast = &config.evaluators[1];
513 assert_eq!(fast.sample, 1.0);
514 assert!(fast.matches(&RunInfo::new("r", "anything", RunStatus::Succeeded, &[], &IndexMap::new())));
515 assert!(!fast.matches(&RunInfo::new("r", "anything", RunStatus::Failed, &[], &IndexMap::new())));
516 assert_eq!(config.unmatched_workflows(&["chat"]), vec!["support-*"]);
517 }
518
519 #[test]
520 fn sampling_is_deterministic_and_close_to_the_rate() {
521 let config = OnlineConfig::parse(CONFIG).unwrap();
522 let polite = &config.evaluators[0];
523 let ids: Vec<String> = (0..10_000).map(|i| format!("run-18a2b{i:x}-{i:x}")).collect();
524 let first: Vec<bool> = ids.iter().map(|id| polite.sampled(id)).collect();
525 let again: Vec<bool> = ids.iter().map(|id| polite.sampled(id)).collect();
526 assert_eq!(first, again, "same run id, same decision");
527 let rate = first.iter().filter(|s| **s).count() as f64 / ids.len() as f64;
528 assert!((rate - 0.5).abs() < 0.03, "rate {rate}");
529 assert_eq!(sample_point("run-1", "polite"), sample_point("run-1", "polite"));
530 assert_ne!(sample_point("run-1", "polite"), sample_point("run-1", "fast"), "independent per evaluator");
531 assert!(ids.iter().all(|id| (0.0..1.0).contains(&sample_point(id, "x"))));
532 let mut never = polite.clone();
533 never.sample = 0.0;
534 assert!(!ids.iter().any(|id| never.sampled(id)));
535 let mut always = polite.clone();
536 always.sample = 1.0;
537 assert!(ids.iter().all(|id| always.sampled(id)));
538 }
539
540 #[test]
541 fn rejects_offline_only_assertions_and_bad_settings() {
542 let bad = |text: &str| OnlineConfig::parse(text).unwrap_err().to_string();
543 let one = |assert: &str| format!("evaluators: [{{name: e, assert: {assert}}}]");
544 assert!(bad(&one("{type: equals, value: x}")).contains("cannot run online"));
545 assert!(bad(&one("{type: retrieval:mrr, value: [d]}")).contains("cannot run online"));
546 assert!(bad(&one("{type: verdict, value: pass}")).contains("cannot run online"));
547 assert!(bad(&one("{type: contains, value: \"{{ expected }}\"}")).contains("expected"));
548 assert!(
549 bad(&one("{type: judge, workflow: j.yaml, inputs: {ref: \"{{expected.answer}}\"}}")).contains("expected")
550 );
551 assert!(OnlineConfig::parse(&one("{type: not-regex, value: \"^sorry\"}")).is_ok());
552 assert!(bad("evaluators: [{name: e, sample: 2, assert: {type: latency, threshold: 1}}]").contains("sample"));
553 assert!(
554 bad("evaluators: [{name: e, status: [paused], assert: {type: latency, threshold: 1}}]").contains("paused")
555 );
556 assert!(bad("evaluators: []").contains("empty"));
557 assert!(bad("queue: 0\nevaluators: [{name: e, assert: {type: latency, threshold: 1}}]").contains("queue"));
558 assert!(bad("evaluators: [{name: e, assert: {type: latency, threshold: 1}}, {name: e, assert: {type: latency, threshold: 2}}]").contains("duplicate"));
559 assert!(bad("evaluators: [{name: e, sampel: 1, assert: {type: latency, threshold: 1}}]").contains("sampel"));
560 }
561
562 #[tokio::test]
563 async fn evaluates_a_capture_with_run_references() {
564 let config = OnlineConfig::parse(
565 r#"
566evaluators:
567 - name: mentions-user
568 assert: { type: icontains, value: "{{name}}" }
569 - name: budget
570 assert: { type: latency, threshold: 100 }
571"#,
572 )
573 .unwrap();
574 let evaluators = OnlineEvaluators::new(&config, AssertionRegistry::with_builtins()).unwrap();
575 let metadata = IndexMap::new();
576 let run = RunInfo::new("run-1", "chat", RunStatus::Succeeded, &[], &metadata);
577 assert_eq!(evaluators.select(&run), vec![0, 1]);
578 assert!(evaluators.covers("chat"));
579 let mut capture = answered("Hello, Ada.");
580 capture.latency_ms = 500;
581 let vars: Map<String, Json> = serde_json::from_str(r#"{"name": "ada"}"#).unwrap();
582 let mentions = evaluators.evaluate(0, &run, vars.clone(), &capture).await.unwrap();
583 assert!(mentions.pass, "{mentions:?}");
584 let budget = evaluators.evaluate(1, &run, vars, &capture).await.unwrap();
585 assert!(!budget.pass && budget.score < 1.0, "{budget:?}");
586 let missing = evaluators.evaluate(0, &run, Map::new(), &capture).await.unwrap();
587 assert!(!missing.pass && missing.reason.contains("name"), "{missing:?}");
588 assert!(evaluators.evaluate(9, &run, Map::new(), &capture).await.is_none());
589 }
590}