use std::collections::{BTreeMap, VecDeque};
use std::path::PathBuf;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::io::AsyncWriteExt;
use tokio::sync::Mutex;
use super::sampling::RunOutcome;
use crate::conversation_scorer::ConversationMetrics;
use crate::error::{EvalError, Result};
use crate::report::Failure;
use crate::trace_analyzer::TraceAnalysis;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[non_exhaustive]
pub struct OnlineEvalRecord {
pub id: String,
pub evaluated_at: chrono::DateTime<chrono::Utc>,
pub finished_at: chrono::DateTime<chrono::Utc>,
pub app_name: String,
pub session_id: String,
pub invocation_id: String,
pub agent_name: String,
pub outcome: RunOutcome,
pub passed: bool,
pub scores: BTreeMap<String, f64>,
pub failures: Vec<Failure>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub trace_analysis: Option<TraceAnalysis>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub thread: Option<ConversationMetrics>,
pub judge_model_calls: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct OnlineEvalQuery {
pub agent: Option<String>,
pub since: Option<chrono::DateTime<chrono::Utc>>,
pub failed_only: bool,
pub limit: Option<usize>,
}
impl OnlineEvalQuery {
pub fn agent(mut self, agent: impl Into<String>) -> Self {
self.agent = Some(agent.into());
self
}
pub fn since(mut self, since: chrono::DateTime<chrono::Utc>) -> Self {
self.since = Some(since);
self
}
pub fn failed_only(mut self) -> Self {
self.failed_only = true;
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
fn matches(&self, record: &OnlineEvalRecord) -> bool {
self.agent.as_ref().is_none_or(|agent| &record.agent_name == agent)
&& self.since.is_none_or(|since| record.evaluated_at >= since)
&& (!self.failed_only || !record.passed)
}
fn select(&self, records: impl Iterator<Item = OnlineEvalRecord>) -> Vec<OnlineEvalRecord> {
let mut selected: Vec<OnlineEvalRecord> =
records.filter(|record| self.matches(record)).collect();
selected.sort_by(|a, b| b.evaluated_at.cmp(&a.evaluated_at).then_with(|| b.id.cmp(&a.id)));
if let Some(limit) = self.limit {
selected.truncate(limit);
}
selected
}
}
#[async_trait]
pub trait OnlineEvalStore: Send + Sync {
async fn append(&self, record: &OnlineEvalRecord) -> Result<()>;
async fn list(&self, query: &OnlineEvalQuery) -> Result<Vec<OnlineEvalRecord>>;
}
#[derive(Debug)]
pub struct InMemoryOnlineEvalStore {
capacity: usize,
records: Mutex<VecDeque<OnlineEvalRecord>>,
}
impl InMemoryOnlineEvalStore {
pub fn new(capacity: usize) -> Self {
Self { capacity: capacity.max(1), records: Mutex::new(VecDeque::new()) }
}
}
#[async_trait]
impl OnlineEvalStore for InMemoryOnlineEvalStore {
async fn append(&self, record: &OnlineEvalRecord) -> Result<()> {
let mut records = self.records.lock().await;
if records.len() == self.capacity {
records.pop_front();
}
records.push_back(record.clone());
Ok(())
}
async fn list(&self, query: &OnlineEvalQuery) -> Result<Vec<OnlineEvalRecord>> {
let records = self.records.lock().await;
Ok(query.select(records.iter().cloned()))
}
}
#[derive(Debug)]
pub struct JsonlOnlineEvalStore {
path: PathBuf,
write: Mutex<()>,
}
impl JsonlOnlineEvalStore {
pub fn new(path: impl Into<PathBuf>) -> Self {
Self { path: path.into(), write: Mutex::new(()) }
}
}
#[async_trait]
impl OnlineEvalStore for JsonlOnlineEvalStore {
async fn append(&self, record: &OnlineEvalRecord) -> Result<()> {
let mut line = serde_json::to_string(record)?;
line.push('\n');
let _guard = self.write.lock().await;
let mut file = tokio::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&self.path)
.await
.map_err(|e| store_error(&self.path, "open", &e))?;
file.write_all(line.as_bytes()).await.map_err(|e| store_error(&self.path, "write", &e))?;
file.flush().await.map_err(|e| store_error(&self.path, "write", &e))
}
async fn list(&self, query: &OnlineEvalQuery) -> Result<Vec<OnlineEvalRecord>> {
let contents = match tokio::fs::read_to_string(&self.path).await {
Ok(contents) => contents,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(e) => return Err(store_error(&self.path, "read", &e)),
};
let records = contents
.lines()
.filter(|line| !line.trim().is_empty())
.enumerate()
.map(|(index, line)| {
serde_json::from_str::<OnlineEvalRecord>(line).map_err(|e| {
EvalError::ParseError(format!(
"line {} of {} is not an online evaluation record: {e}",
index + 1,
self.path.display()
))
})
})
.collect::<Result<Vec<_>>>()?;
Ok(query.select(records.into_iter()))
}
}
fn store_error(path: &std::path::Path, action: &str, error: &std::io::Error) -> EvalError {
EvalError::ExecutionError(format!(
"cannot {action} the online evaluation store {}: {error}",
path.display()
))
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct CriterionSummary {
pub evaluated: usize,
pub failed: usize,
pub mean_score: f64,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct OnlineEvalSummary {
pub evaluated: usize,
pub passed: usize,
pub pass_rate: f64,
pub criteria: BTreeMap<String, CriterionSummary>,
}
impl OnlineEvalSummary {
pub fn from_records(records: &[OnlineEvalRecord]) -> Self {
let passed = records.iter().filter(|record| record.passed).count();
let mut sums: BTreeMap<String, (usize, usize, f64)> = BTreeMap::new();
for record in records {
for (criterion, score) in &record.scores {
let entry = sums.entry(criterion.clone()).or_default();
entry.0 += 1;
entry.2 += score;
}
let mut failed: Vec<&str> =
record.failures.iter().map(|failure| failure.criterion.as_str()).collect();
failed.sort_unstable();
failed.dedup();
for criterion in failed {
sums.entry(criterion.to_string()).or_default().1 += 1;
}
}
Self {
evaluated: records.len(),
passed,
pass_rate: if records.is_empty() { 0.0 } else { passed as f64 / records.len() as f64 },
criteria: sums
.into_iter()
.map(|(criterion, (evaluated, failed, total))| {
let mean_score = if evaluated == 0 { 0.0 } else { total / evaluated as f64 };
(criterion, CriterionSummary { evaluated, failed, mean_score })
})
.collect(),
}
}
}