The platform for continuously improving AI agents.
//! Span-level evaluation processor, matching `overbae/innermind/span_processor.py`
//! and `overbae/innermind/evals.py`.
use std::collections::{BTreeMap, HashMap, HashSet};
use futures::future::join_all;
use serde_json::{Map, Value};
use trace_types::SpanRecord;
use crate::{
checks, evidence,
jev::{ChoiceQuestion, DecisionBackend, DecisionError, judge_expectation},
model::{
EvalMatrixRow, EvalRowType, MAX_ATTEMPTS, MAX_EXPECTATIONS, Metric, SpanEvalState,
SpanMetric, answers_for_capability, mean_of,
},
};
pub fn matches_row(row: &EvalMatrixRow, span: &SpanRecord) -> bool {
if let Some(cap) = row.capability_id.as_deref().filter(|s| !s.is_empty())
&& evidence::capability_id(span).as_deref() != Some(cap)
{
return false;
}
if !row.span_type.is_empty() && row.span_type != evidence::classify_span_type(span) {
return false;
}
if !row.span_name.is_empty() && row.span_name != span.name {
return false;
}
true
}
pub fn expectation_rows(project_id: &str, span: &SpanRecord) -> Vec<EvalMatrixRow> {
let mut seen = HashSet::new();
let mut rows = Vec::new();
for exp in evidence::read_expectations(span)
.into_iter()
.chain(evidence::declared_constraints(span))
{
if seen.insert(exp.clone()) {
rows.push(EvalMatrixRow::llm(project_id, exp.clone(), exp));
if rows.len() >= MAX_EXPECTATIONS {
break;
}
}
}
rows
}
fn takes_unscoped_expectations(span: &SpanRecord, trace: &HashMap<String, SpanRecord>) -> bool {
if evidence::is_tool(span) {
return false;
}
answers_for_capability(span, trace)
}
/// Resolves the ordered list of matrix + span-declared rows applicable to `span`.
pub fn select_rows(
project_id: &str,
span: &SpanRecord,
matrix: &[EvalMatrixRow],
trace: &HashMap<String, SpanRecord>,
) -> Vec<EvalMatrixRow> {
let mut order: Vec<String> = Vec::new();
let mut by_name: HashMap<String, EvalMatrixRow> = HashMap::new();
for row in matrix {
if !row.enabled || !matches_row(row, span) {
continue;
}
if row.row_type == EvalRowType::Llm
&& row.is_unscoped()
&& !takes_unscoped_expectations(span, trace)
{
continue;
}
if !by_name.contains_key(&row.name) {
order.push(row.name.clone());
}
by_name.insert(row.name.clone(), row.clone());
}
for row in expectation_rows(project_id, span) {
if !by_name.contains_key(&row.name) {
order.push(row.name.clone());
by_name.insert(row.name.clone(), row);
}
}
order
.into_iter()
.filter_map(|name| by_name.remove(&name))
.collect()
}
fn dedup_key(row: &EvalMatrixRow) -> String {
let opts = row
.judge_options
.as_ref()
.and_then(|o| serde_json::to_string(o).ok())
.unwrap_or_default();
format!("{}\0{}\0{}", row.row_type.as_str(), row.source, opts)
}
fn llm_evidence(span: &SpanRecord, intent: &str, expectation: &str) -> Map<String, Value> {
let mut state = Map::new();
if !intent.is_empty() {
state.insert("intent".into(), Value::String(intent.to_string()));
}
if !expectation.is_empty() {
state.insert("expectation".into(), Value::String(expectation.to_string()));
}
let input = evidence::read_input(span);
if !input.is_empty() {
state.insert("input".into(), Value::String(input));
}
let output = evidence::read_output(span);
if !output.is_empty() {
state.insert("output".into(), Value::String(output));
}
let reference = evidence::read_expected(span);
if !reference.is_empty() {
state.insert("reference".into(), Value::String(reference));
}
state
}
async fn score_row(
backend: &dyn DecisionBackend,
project_id: &str,
row: &EvalMatrixRow,
span: &SpanRecord,
trace_nodes: &[SpanRecord],
intent: &str,
) -> Result<Metric, DecisionError> {
match row.row_type {
EvalRowType::Deterministic => Ok(checks::evaluate_deterministic(row, span, trace_nodes)),
EvalRowType::Llm => {
let state = llm_evidence(span, intent, &row.source);
if !state.contains_key("output") {
return Ok(Metric::abstained(&row.source, "no output"));
}
if let Some(options) = row.judge_options.as_deref()
&& !options.is_empty()
{
let question = ChoiceQuestion::from_judge_options(options);
let values: HashMap<String, f64> = options
.iter()
.map(|o| (o.label.clone(), o.score))
.collect();
judge_expectation(
backend,
project_id,
&state,
&row.source,
Some(&question),
Some(&values),
)
.await
} else {
judge_expectation(backend, project_id, &state, &row.source, None, None).await
}
}
}
}
pub struct SpanEvalOptions<'a> {
pub project_id: &'a str,
pub fallback_intent: &'a str,
pub judge: bool,
pub last_attempt: bool,
}
/// Evaluates one span against `matrix` and its own expectations.
///
/// Mirrors `overbae/innermind/span_processor.py::SpanProcessor.evaluate`:
/// - Writes `has_score = true` only when the result is final.
/// - Preserves completed row metrics in `state.partial` on transient failures so retries
/// only re-run the failed rows.
/// - Deduplicates identical `(row_type, source, judge_options)` so a shared expectation
/// is judged at most once per span.
pub async fn evaluate_span(
backend: &dyn DecisionBackend,
span: &SpanRecord,
matrix: &[EvalMatrixRow],
trace: &HashMap<String, SpanRecord>,
previous: Option<SpanEvalState>,
opts: SpanEvalOptions<'_>,
) -> Result<SpanEvalState, (SpanEvalState, DecisionError)> {
let mut state = previous.unwrap_or_else(|| SpanEvalState::empty(&span.span_id, &span.trace_id));
let intent_resolved = evidence::read_intent(span, trace, opts.fallback_intent);
let intent = if intent_resolved.is_empty() {
opts.fallback_intent.to_string()
} else {
intent_resolved
};
state.intent = intent.clone();
let rows = select_rows(opts.project_id, span, matrix, trace);
let trace_nodes: Vec<SpanRecord> = trace.values().cloned().collect();
let mut done: BTreeMap<String, SpanMetric> = state.partial.clone();
let mut distinct_keys: Vec<(String, EvalMatrixRow)> = Vec::new();
if opts.judge {
let mut seen_keys = HashSet::new();
for row in &rows {
if done.contains_key(&row.name) {
continue;
}
let key = dedup_key(row);
if seen_keys.insert(key.clone()) {
distinct_keys.push((key, row.clone()));
}
}
}
let futures = distinct_keys.iter().map(|(_, row)| {
score_row(
backend,
opts.project_id,
row,
span,
&trace_nodes,
&intent,
)
});
let outcomes = join_all(futures).await;
let mut by_source: HashMap<String, Metric> = HashMap::new();
let mut first_error: Option<DecisionError> = None;
for ((key, _), outcome) in distinct_keys.into_iter().zip(outcomes) {
match outcome {
Ok(metric) => {
by_source.insert(key, metric);
}
Err(err) => {
if first_error.is_none() {
first_error = Some(err);
}
}
}
}
for row in &rows {
if done.contains_key(&row.name) {
continue;
}
let key = dedup_key(row);
if let Some(metric) = by_source.get(&key) {
done.insert(row.name.clone(), metric.clone().into_span_metric(row.row_type));
}
}
if let Some(err) = first_error
&& !opts.last_attempt
{
state.partial = done;
state.error = format!("DecisionError: {}", err.reason);
return Err((state, err));
}
let mut metrics = BTreeMap::new();
for row in &rows {
let metric = done.remove(&row.name).unwrap_or_else(|| {
Metric::errored(
&row.name,
format!("scoring failed after {MAX_ATTEMPTS} attempts"),
)
.into_span_metric(row.row_type)
});
metrics.insert(row.name.clone(), metric);
}
let aggregate = mean_of(metrics.values().map(|m| m.score));
state.version += 1;
state.intent = intent;
state.fingerprint = evidence::fingerprint(span);
state.has_score = true;
state.score = aggregate;
state.metrics = metrics;
state.partial.clear();
state.error.clear();
Ok(state)
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use serde_json::json;
use trace_types::SpanUsage;
use super::*;
use crate::jev::{BoxFuture, ChoiceAnswer};
struct CountingFakeBackend {
calls: AtomicUsize,
fail_transient: bool,
score_choice: &'static str,
}
impl DecisionBackend for CountingFakeBackend {
fn decide<'a>(
&'a self,
_project_id: &'a str,
_workload: &'a str,
_contract: &'a str,
_state: &'a Value,
_question: &'a ChoiceQuestion,
) -> BoxFuture<'a, Result<ChoiceAnswer, DecisionError>> {
self.calls.fetch_add(1, Ordering::SeqCst);
let fail = self.fail_transient;
let choice = self.score_choice;
Box::pin(async move {
if fail {
return Err(DecisionError::retryable("provider_timeout"));
}
let probs = match choice {
"yes" => BTreeMap::from([
("yes".into(), 0.9),
("partial".into(), 0.1),
("no".into(), 0.0),
]),
_ => BTreeMap::from([
("yes".into(), 0.0),
("partial".into(), 0.2),
("no".into(), 0.8),
]),
};
Ok(ChoiceAnswer {
kind: "choice".into(),
choice: choice.into(),
confidence: *probs.get(choice).unwrap(),
probabilities: probs,
})
})
}
fn explain<'a>(&'a self, _prompt: &'a str) -> BoxFuture<'a, Result<String, String>> {
Box::pin(async { Ok("Missing required order confirmation.".to_string()) })
}
}
fn make_span(id: &str, parent: Option<&str>, span_type: &str, output: &str) -> SpanRecord {
SpanRecord {
span_id: id.into(),
trace_id: "t1".into(),
parent_span_id: parent.map(ToString::to_string),
name: id.into(),
kind: 1,
start_time_ns: 0,
end_time_ns: 1_000_000,
duration_ns: 1_000_000,
status_code: 1,
status_message: String::new(),
service_name: "svc".into(),
resource_attrs: json!({}),
scope_name: String::new(),
scope_version: String::new(),
attributes: json!({
"overmind.span.type": span_type,
"overmind.input": "find flights",
"overmind.output": output,
}),
events: json!([]),
links: json!([]),
usage: SpanUsage::default(),
received_at_ms: 1_000,
}
}
#[tokio::test]
async fn deduplicates_identical_llm_expectations_and_skips_unscoped_on_tools() {
let root = make_span("root", None, "workflow", r#"{"ok": true}"#);
let tool = make_span("tool1", Some("root"), "tool_call", r#"{"ok": true}"#);
let trace = HashMap::from([
(root.span_id.clone(), root.clone()),
(tool.span_id.clone(), tool.clone()),
]);
let matrix = vec![
EvalMatrixRow::deterministic("p1", "output_is_valid_json"),
EvalMatrixRow::llm("p1", "helpful_a", "Answer is helpful."),
EvalMatrixRow::llm("p1", "helpful_b", "Answer is helpful."),
];
let backend = CountingFakeBackend {
calls: AtomicUsize::new(0),
fail_transient: false,
score_choice: "yes",
};
let res = evaluate_span(
&backend,
&root,
&matrix,
&trace,
None,
SpanEvalOptions {
project_id: "p1",
fallback_intent: "",
judge: true,
last_attempt: false,
},
)
.await
.unwrap();
assert!(res.has_score);
// Both LLM rows share the same source, so Jev was called only once!
assert_eq!(backend.calls.load(Ordering::SeqCst), 1);
assert_eq!(res.metrics.len(), 3);
assert!(res.score.unwrap() > 0.9);
// Unscoped LLM rows must not run on tool_call spans.
let tool_res = evaluate_span(
&backend,
&tool,
&matrix,
&trace,
None,
SpanEvalOptions {
project_id: "p1",
fallback_intent: "",
judge: true,
last_attempt: false,
},
)
.await
.unwrap();
assert_eq!(backend.calls.load(Ordering::SeqCst), 1);
assert_eq!(tool_res.metrics.len(), 1);
assert!(tool_res.metrics.contains_key("output_is_valid_json"));
}
#[tokio::test]
async fn preserves_partial_results_across_transient_failure_and_explains_low_scores() {
let root = make_span("root", None, "llm_call", r#"{"ok": true}"#);
let trace = HashMap::from([(root.span_id.clone(), root.clone())]);
let matrix = vec![
EvalMatrixRow::deterministic("p1", "output_is_valid_json"),
EvalMatrixRow::llm("p1", "complete", "Includes confirmation."),
];
let failing = CountingFakeBackend {
calls: AtomicUsize::new(0),
fail_transient: true,
score_choice: "no",
};
let (partial_state, err) = evaluate_span(
&failing,
&root,
&matrix,
&trace,
None,
SpanEvalOptions {
project_id: "p1",
fallback_intent: "",
judge: true,
last_attempt: false,
},
)
.await
.unwrap_err();
assert!(err.is_retryable());
assert!(!partial_state.has_score);
assert!(partial_state.partial.contains_key("output_is_valid_json"));
// Second pass succeeds and gets explanation for low score (< 0.75).
let succeeding = CountingFakeBackend {
calls: AtomicUsize::new(0),
fail_transient: false,
score_choice: "no",
};
let final_state = evaluate_span(
&succeeding,
&root,
&matrix,
&trace,
Some(partial_state),
SpanEvalOptions {
project_id: "p1",
fallback_intent: "",
judge: true,
last_attempt: true,
},
)
.await
.unwrap();
assert!(final_state.has_score);
assert_eq!(
final_state.metrics["complete"].reason,
"Missing required order confirmation."
);
// Mean of 1.0 (json) and 0.1 (0.2*0.5) = 0.55
assert!((final_state.score.unwrap() - 0.55).abs() < 1e-9);
}
}