use std::collections::HashMap;
use adk_core::{Content, Event, GovernanceControl};
use serde::{Deserialize, Serialize};
use crate::error::{EvalError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum RunOutcome {
Completed,
Errored,
Incomplete,
Cancelled,
}
impl RunOutcome {
pub fn of(events: &[Event], cancelled: bool) -> Self {
if cancelled {
return Self::Cancelled;
}
let complete: Vec<&Event> =
events.iter().filter(|event| !event.llm_response.partial).collect();
if complete.iter().any(|event| {
event.llm_response.error_code.is_some() || event.llm_response.error_message.is_some()
}) {
return Self::Errored;
}
match complete.last() {
Some(last) if last.is_final_response() => Self::Completed,
_ => Self::Incomplete,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MetadataFilter {
pub key: String,
pub value: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct SamplingPolicy {
pub rate: f64,
pub seed: u64,
pub agents: Vec<String>,
pub metadata: Vec<MetadataFilter>,
pub outcomes: Vec<RunOutcome>,
}
impl SamplingPolicy {
pub fn rate(rate: f64) -> Result<Self> {
if !(0.0..=1.0).contains(&rate) {
return Err(EvalError::ConfigError(format!(
"the online evaluation sample rate must be between 0.0 and 1.0, got {rate}"
)));
}
Ok(Self { rate, seed: 0, agents: Vec::new(), metadata: Vec::new(), outcomes: Vec::new() })
}
pub fn with_seed(mut self, seed: u64) -> Self {
self.seed = seed;
self
}
pub fn agent(mut self, name: impl Into<String>) -> Self {
self.agents.push(name.into());
self
}
pub fn tag(mut self, key: impl Into<String>, value: Option<&str>) -> Self {
self.metadata.push(MetadataFilter { key: key.into(), value: value.map(str::to_string) });
self
}
pub fn outcome(mut self, outcome: RunOutcome) -> Self {
self.outcomes.push(outcome);
self
}
pub fn sample_point(&self, invocation_id: &str) -> f64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in self.seed.to_le_bytes().iter().chain(invocation_id.as_bytes()) {
hash ^= u64::from(*byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash = (hash ^ (hash >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
hash = (hash ^ (hash >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
hash ^= hash >> 31;
(hash >> 11) as f64 / (1u64 << 53) as f64
}
pub fn admits_run(
&self,
agent: &str,
metadata: &HashMap<String, String>,
invocation_id: &str,
) -> bool {
self.rate > 0.0
&& (self.agents.is_empty() || self.agents.iter().any(|name| name == agent))
&& self.metadata.iter().all(|filter| match (metadata.get(&filter.key), &filter.value) {
(Some(actual), Some(expected)) => actual == expected,
(Some(_), None) => true,
(None, _) => false,
})
&& self.sample_point(invocation_id) < self.rate
}
pub fn admits_outcome(&self, outcome: RunOutcome) -> bool {
self.outcomes.is_empty() || self.outcomes.contains(&outcome)
}
pub fn admits(&self, trace: &RunTrace) -> bool {
self.admits_run(&trace.agent_name, &trace.metadata, &trace.invocation_id)
&& self.admits_outcome(trace.outcome)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct RunTrace {
pub app_name: String,
pub session_id: String,
pub invocation_id: String,
pub agent_name: String,
pub metadata: HashMap<String, String>,
pub user_content: Content,
pub events: Vec<Event>,
pub outcome: RunOutcome,
pub thread: Vec<Content>,
pub governance: Vec<GovernanceControl>,
pub finished_at: chrono::DateTime<chrono::Utc>,
}
impl RunTrace {
pub fn new(
app_name: impl Into<String>,
session_id: impl Into<String>,
invocation_id: impl Into<String>,
agent_name: impl Into<String>,
user_content: Content,
events: Vec<Event>,
) -> Self {
let events: Vec<Event> =
events.into_iter().filter(|event| !event.llm_response.partial).collect();
Self {
app_name: app_name.into(),
session_id: session_id.into(),
invocation_id: invocation_id.into(),
agent_name: agent_name.into(),
metadata: HashMap::new(),
user_content,
outcome: RunOutcome::of(&events, false),
events,
thread: Vec::new(),
governance: Vec::new(),
finished_at: chrono::Utc::now(),
}
}
pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.metadata.insert(key.into(), value.into());
self
}
pub fn with_outcome(mut self, outcome: RunOutcome) -> Self {
self.outcome = outcome;
self
}
pub fn with_thread(mut self, thread: Vec<Content>) -> Self {
self.thread = thread;
self
}
pub fn with_governance(mut self, control: GovernanceControl) -> Self {
self.governance.push(control);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sample_points_are_deterministic_per_seed_and_uniform() {
let policy = SamplingPolicy::rate(0.3).unwrap().with_seed(11);
let ids: Vec<String> = (0..20_000).map(|run| format!("e-{run:08x}")).collect();
let sampled: Vec<&String> =
ids.iter().filter(|id| policy.admits_run("a", &HashMap::new(), id)).collect();
let again: Vec<&String> =
ids.iter().filter(|id| policy.admits_run("a", &HashMap::new(), id)).collect();
assert_eq!(sampled, again);
let share = sampled.len() as f64 / ids.len() as f64;
assert!((share - 0.3).abs() < 0.015, "sampled {share}");
let reseeded = policy.clone().with_seed(12);
let other: Vec<&String> =
ids.iter().filter(|id| reseeded.admits_run("a", &HashMap::new(), id)).collect();
assert_ne!(sampled, other);
let overlap = sampled.iter().filter(|id| other.contains(id)).count() as f64;
assert!((overlap / ids.len() as f64 - 0.09).abs() < 0.015, "overlap {overlap}");
}
#[test]
fn a_rate_of_zero_samples_nothing_and_one_samples_everything() {
let none = SamplingPolicy::rate(0.0).unwrap();
let all = SamplingPolicy::rate(1.0).unwrap();
for run in 0..1_000 {
let id = format!("inv-{run}");
assert!(!none.admits_run("a", &HashMap::new(), &id));
assert!(all.admits_run("a", &HashMap::new(), &id));
}
assert!(SamplingPolicy::rate(1.01).is_err());
assert!(SamplingPolicy::rate(-0.1).is_err());
assert!(SamplingPolicy::rate(f64::NAN).is_err());
}
#[test]
fn filters_select_agents_metadata_and_outcomes() {
let policy = SamplingPolicy::rate(1.0)
.unwrap()
.agent("support")
.tag("tier", Some("gold"))
.tag("channel", None)
.outcome(RunOutcome::Completed)
.outcome(RunOutcome::Errored);
let metadata = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
};
let gold = metadata(&[("tier", "gold"), ("channel", "web")]);
assert!(policy.admits_run("support", &gold, "inv"));
assert!(!policy.admits_run("billing", &gold, "inv"));
assert!(!policy.admits_run(
"support",
&metadata(&[("tier", "silver"), ("channel", "web")]),
"inv"
));
assert!(!policy.admits_run("support", &metadata(&[("tier", "gold")]), "inv"));
assert!(policy.admits_outcome(RunOutcome::Errored));
assert!(!policy.admits_outcome(RunOutcome::Incomplete));
assert!(SamplingPolicy::rate(1.0).unwrap().admits_outcome(RunOutcome::Cancelled));
}
#[test]
fn outcomes_follow_the_events() {
let mut call = Event::new("inv");
let mut content = Content::new("model");
content.parts.push(adk_core::Part::FunctionCall {
name: "lookup".to_string(),
args: serde_json::json!({}),
id: None,
thought_signature: None,
});
call.llm_response.content = Some(content);
let mut answer = Event::new("inv");
answer.llm_response.content = Some(Content::new("model").with_text("done"));
assert_eq!(RunOutcome::of(&[call.clone()], false), RunOutcome::Incomplete);
assert_eq!(RunOutcome::of(&[call, answer.clone()], false), RunOutcome::Completed);
assert_eq!(RunOutcome::of(&[answer], true), RunOutcome::Cancelled);
}
}