1use std::collections::HashMap;
4
5use adk_core::{Content, Event, GovernanceControl};
6use serde::{Deserialize, Serialize};
7
8use crate::error::{EvalError, Result};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28#[non_exhaustive]
29pub enum RunOutcome {
30 Completed,
32 Errored,
34 Incomplete,
37 Cancelled,
39}
40
41impl RunOutcome {
42 pub fn of(events: &[Event], cancelled: bool) -> Self {
44 if cancelled {
45 return Self::Cancelled;
46 }
47 let complete: Vec<&Event> =
48 events.iter().filter(|event| !event.llm_response.partial).collect();
49 if complete.iter().any(|event| {
50 event.llm_response.error_code.is_some() || event.llm_response.error_message.is_some()
51 }) {
52 return Self::Errored;
53 }
54 match complete.last() {
55 Some(last) if last.is_final_response() => Self::Completed,
56 _ => Self::Incomplete,
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[non_exhaustive]
64pub struct MetadataFilter {
65 pub key: String,
67 pub value: Option<String>,
69}
70
71#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[non_exhaustive]
98pub struct SamplingPolicy {
99 pub rate: f64,
101 pub seed: u64,
103 pub agents: Vec<String>,
105 pub metadata: Vec<MetadataFilter>,
107 pub outcomes: Vec<RunOutcome>,
109}
110
111impl SamplingPolicy {
112 pub fn rate(rate: f64) -> Result<Self> {
118 if !(0.0..=1.0).contains(&rate) {
119 return Err(EvalError::ConfigError(format!(
120 "the online evaluation sample rate must be between 0.0 and 1.0, got {rate}"
121 )));
122 }
123 Ok(Self { rate, seed: 0, agents: Vec::new(), metadata: Vec::new(), outcomes: Vec::new() })
124 }
125
126 pub fn with_seed(mut self, seed: u64) -> Self {
128 self.seed = seed;
129 self
130 }
131
132 pub fn agent(mut self, name: impl Into<String>) -> Self {
134 self.agents.push(name.into());
135 self
136 }
137
138 pub fn tag(mut self, key: impl Into<String>, value: Option<&str>) -> Self {
140 self.metadata.push(MetadataFilter { key: key.into(), value: value.map(str::to_string) });
141 self
142 }
143
144 pub fn outcome(mut self, outcome: RunOutcome) -> Self {
146 self.outcomes.push(outcome);
147 self
148 }
149
150 pub fn sample_point(&self, invocation_id: &str) -> f64 {
152 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
155 for byte in self.seed.to_le_bytes().iter().chain(invocation_id.as_bytes()) {
156 hash ^= u64::from(*byte);
157 hash = hash.wrapping_mul(0x0100_0000_01b3);
158 }
159 hash = (hash ^ (hash >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
160 hash = (hash ^ (hash >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
161 hash ^= hash >> 31;
162 (hash >> 11) as f64 / (1u64 << 53) as f64
164 }
165
166 pub fn admits_run(
169 &self,
170 agent: &str,
171 metadata: &HashMap<String, String>,
172 invocation_id: &str,
173 ) -> bool {
174 self.rate > 0.0
175 && (self.agents.is_empty() || self.agents.iter().any(|name| name == agent))
176 && self.metadata.iter().all(|filter| match (metadata.get(&filter.key), &filter.value) {
177 (Some(actual), Some(expected)) => actual == expected,
178 (Some(_), None) => true,
179 (None, _) => false,
180 })
181 && self.sample_point(invocation_id) < self.rate
182 }
183
184 pub fn admits_outcome(&self, outcome: RunOutcome) -> bool {
186 self.outcomes.is_empty() || self.outcomes.contains(&outcome)
187 }
188
189 pub fn admits(&self, trace: &RunTrace) -> bool {
192 self.admits_run(&trace.agent_name, &trace.metadata, &trace.invocation_id)
193 && self.admits_outcome(trace.outcome)
194 }
195}
196
197#[derive(Debug, Clone)]
203#[non_exhaustive]
204pub struct RunTrace {
205 pub app_name: String,
207 pub session_id: String,
209 pub invocation_id: String,
211 pub agent_name: String,
213 pub metadata: HashMap<String, String>,
215 pub user_content: Content,
217 pub events: Vec<Event>,
219 pub outcome: RunOutcome,
221 pub thread: Vec<Content>,
223 pub governance: Vec<GovernanceControl>,
225 pub finished_at: chrono::DateTime<chrono::Utc>,
227}
228
229impl RunTrace {
230 pub fn new(
253 app_name: impl Into<String>,
254 session_id: impl Into<String>,
255 invocation_id: impl Into<String>,
256 agent_name: impl Into<String>,
257 user_content: Content,
258 events: Vec<Event>,
259 ) -> Self {
260 let events: Vec<Event> =
261 events.into_iter().filter(|event| !event.llm_response.partial).collect();
262 Self {
263 app_name: app_name.into(),
264 session_id: session_id.into(),
265 invocation_id: invocation_id.into(),
266 agent_name: agent_name.into(),
267 metadata: HashMap::new(),
268 user_content,
269 outcome: RunOutcome::of(&events, false),
270 events,
271 thread: Vec::new(),
272 governance: Vec::new(),
273 finished_at: chrono::Utc::now(),
274 }
275 }
276
277 pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
279 self.metadata.insert(key.into(), value.into());
280 self
281 }
282
283 pub fn with_outcome(mut self, outcome: RunOutcome) -> Self {
285 self.outcome = outcome;
286 self
287 }
288
289 pub fn with_thread(mut self, thread: Vec<Content>) -> Self {
292 self.thread = thread;
293 self
294 }
295
296 pub fn with_governance(mut self, control: GovernanceControl) -> Self {
298 self.governance.push(control);
299 self
300 }
301}
302
303#[cfg(test)]
304mod tests {
305 use super::*;
306
307 #[test]
308 fn sample_points_are_deterministic_per_seed_and_uniform() {
309 let policy = SamplingPolicy::rate(0.3).unwrap().with_seed(11);
310 let ids: Vec<String> = (0..20_000).map(|run| format!("e-{run:08x}")).collect();
311 let sampled: Vec<&String> =
312 ids.iter().filter(|id| policy.admits_run("a", &HashMap::new(), id)).collect();
313 let again: Vec<&String> =
314 ids.iter().filter(|id| policy.admits_run("a", &HashMap::new(), id)).collect();
315 assert_eq!(sampled, again);
316 let share = sampled.len() as f64 / ids.len() as f64;
317 assert!((share - 0.3).abs() < 0.015, "sampled {share}");
318
319 let reseeded = policy.clone().with_seed(12);
320 let other: Vec<&String> =
321 ids.iter().filter(|id| reseeded.admits_run("a", &HashMap::new(), id)).collect();
322 assert_ne!(sampled, other);
323 let overlap = sampled.iter().filter(|id| other.contains(id)).count() as f64;
324 assert!((overlap / ids.len() as f64 - 0.09).abs() < 0.015, "overlap {overlap}");
326 }
327
328 #[test]
329 fn a_rate_of_zero_samples_nothing_and_one_samples_everything() {
330 let none = SamplingPolicy::rate(0.0).unwrap();
331 let all = SamplingPolicy::rate(1.0).unwrap();
332 for run in 0..1_000 {
333 let id = format!("inv-{run}");
334 assert!(!none.admits_run("a", &HashMap::new(), &id));
335 assert!(all.admits_run("a", &HashMap::new(), &id));
336 }
337 assert!(SamplingPolicy::rate(1.01).is_err());
338 assert!(SamplingPolicy::rate(-0.1).is_err());
339 assert!(SamplingPolicy::rate(f64::NAN).is_err());
340 }
341
342 #[test]
343 fn filters_select_agents_metadata_and_outcomes() {
344 let policy = SamplingPolicy::rate(1.0)
345 .unwrap()
346 .agent("support")
347 .tag("tier", Some("gold"))
348 .tag("channel", None)
349 .outcome(RunOutcome::Completed)
350 .outcome(RunOutcome::Errored);
351 let metadata = |pairs: &[(&str, &str)]| -> HashMap<String, String> {
352 pairs.iter().map(|(k, v)| (k.to_string(), v.to_string())).collect()
353 };
354 let gold = metadata(&[("tier", "gold"), ("channel", "web")]);
355
356 assert!(policy.admits_run("support", &gold, "inv"));
357 assert!(!policy.admits_run("billing", &gold, "inv"));
358 assert!(!policy.admits_run(
359 "support",
360 &metadata(&[("tier", "silver"), ("channel", "web")]),
361 "inv"
362 ));
363 assert!(!policy.admits_run("support", &metadata(&[("tier", "gold")]), "inv"));
364 assert!(policy.admits_outcome(RunOutcome::Errored));
365 assert!(!policy.admits_outcome(RunOutcome::Incomplete));
366 assert!(SamplingPolicy::rate(1.0).unwrap().admits_outcome(RunOutcome::Cancelled));
367 }
368
369 #[test]
370 fn outcomes_follow_the_events() {
371 let mut call = Event::new("inv");
372 let mut content = Content::new("model");
373 content.parts.push(adk_core::Part::FunctionCall {
374 name: "lookup".to_string(),
375 args: serde_json::json!({}),
376 id: None,
377 thought_signature: None,
378 });
379 call.llm_response.content = Some(content);
380 let mut answer = Event::new("inv");
381 answer.llm_response.content = Some(Content::new("model").with_text("done"));
382
383 assert_eq!(RunOutcome::of(&[call.clone()], false), RunOutcome::Incomplete);
384 assert_eq!(RunOutcome::of(&[call, answer.clone()], false), RunOutcome::Completed);
385 assert_eq!(RunOutcome::of(&[answer], true), RunOutcome::Cancelled);
386 }
387}