Skip to main content

adk_eval/online/
sampling.rs

1//! Which finished runs online evaluation samples, and the trace it scores.
2
3use std::collections::HashMap;
4
5use adk_core::{Content, Event, GovernanceControl};
6use serde::{Deserialize, Serialize};
7
8use crate::error::{EvalError, Result};
9
10/// How a run ended, as online evaluation classifies it from the run's events.
11///
12/// # Example
13///
14/// ```
15/// use adk_core::{Content, Event};
16/// use adk_eval::online::RunOutcome;
17///
18/// let mut answer = Event::new("inv-1");
19/// answer.llm_response.content = Some(Content::new("model").with_text("Sunny."));
20/// assert_eq!(RunOutcome::of(&[answer.clone()], false), RunOutcome::Completed);
21///
22/// answer.llm_response.error_code = Some("model.unavailable".to_string());
23/// assert_eq!(RunOutcome::of(&[answer], false), RunOutcome::Errored);
24/// assert_eq!(RunOutcome::of(&[], false), RunOutcome::Incomplete);
25/// ```
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
27#[serde(rename_all = "snake_case")]
28#[non_exhaustive]
29pub enum RunOutcome {
30    /// The run ended on a final response and no event carried an error.
31    Completed,
32    /// An event carried an error code or message, such as a budget refusal or a model error.
33    Errored,
34    /// The run ended without a final response: a stream error, a held tool call, or an
35    /// interrupt.
36    Incomplete,
37    /// The run was cancelled.
38    Cancelled,
39}
40
41impl RunOutcome {
42    /// Classifies a run from its complete (non-partial) events and whether it was cancelled.
43    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/// A request-metadata condition a run must meet to be sampled.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[non_exhaustive]
64pub struct MetadataFilter {
65    /// The metadata key ([`RunConfig::request_metadata`](adk_core::RunConfig::request_metadata)).
66    pub key: String,
67    /// The value the key must have; `None` accepts any value of a present key.
68    pub value: Option<String>,
69}
70
71/// Which finished runs online evaluation samples.
72///
73/// A run is sampled when its agent, request metadata and outcome pass the filters (an empty
74/// filter passes everything) and its sample point falls under the rate. The sample point is
75/// a deterministic hash of the seed and the run's invocation id, so the same seed samples the
76/// same runs in every process and on every replay, and a different seed samples a different
77/// set of the same size.
78///
79/// # Example
80///
81/// ```
82/// use adk_eval::online::{RunOutcome, SamplingPolicy};
83///
84/// let policy = SamplingPolicy::rate(0.25)?
85///     .with_seed(42)
86///     .agent("support")
87///     .tag("tier", Some("gold"))
88///     .outcome(RunOutcome::Completed);
89/// let sampled = (0..1_000)
90///     .filter(|run| policy.sample_point(&format!("inv-{run}")) < 0.25)
91///     .count();
92/// assert!((200..300).contains(&sampled));
93/// assert_eq!(policy.sample_point("inv-7"), policy.sample_point("inv-7"));
94/// # Ok::<(), adk_eval::EvalError>(())
95/// ```
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[non_exhaustive]
98pub struct SamplingPolicy {
99    /// Fraction of runs to sample, from 0.0 (none) to 1.0 (every run).
100    pub rate: f64,
101    /// Seed of the sample point hash.
102    pub seed: u64,
103    /// Root agents whose runs may be sampled; empty means every agent.
104    pub agents: Vec<String>,
105    /// Request-metadata conditions a run must all meet; empty means any metadata.
106    pub metadata: Vec<MetadataFilter>,
107    /// Outcomes a run must end with; empty means any outcome.
108    pub outcomes: Vec<RunOutcome>,
109}
110
111impl SamplingPolicy {
112    /// Samples `rate` of runs, from 0.0 to 1.0, with seed 0 and no filters.
113    ///
114    /// # Errors
115    ///
116    /// Returns [`EvalError::ConfigError`] when `rate` is not between 0.0 and 1.0.
117    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    /// Sets the seed of the sample point hash.
127    pub fn with_seed(mut self, seed: u64) -> Self {
128        self.seed = seed;
129        self
130    }
131
132    /// Admits runs of the agent named `name` (repeatable).
133    pub fn agent(mut self, name: impl Into<String>) -> Self {
134        self.agents.push(name.into());
135        self
136    }
137
138    /// Requires request metadata `key`, with `value` when one is given (repeatable).
139    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    /// Admits runs that end with `outcome` (repeatable).
145    pub fn outcome(mut self, outcome: RunOutcome) -> Self {
146        self.outcomes.push(outcome);
147        self
148    }
149
150    /// The run's deterministic sample point in `[0, 1)`.
151    pub fn sample_point(&self, invocation_id: &str) -> f64 {
152        // FNV-1a over the seed and the id, then a SplitMix64 finaliser to spread the bits;
153        // both are fixed, unlike `DefaultHasher`, so the point is stable across releases.
154        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        // The top 53 bits make an exactly representable fraction.
163        (hash >> 11) as f64 / (1u64 << 53) as f64
164    }
165
166    /// Whether a run of `agent` with `metadata` and `invocation_id` is sampled, before its
167    /// outcome is known.
168    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    /// Whether a run that ended with `outcome` is evaluated.
185    pub fn admits_outcome(&self, outcome: RunOutcome) -> bool {
186        self.outcomes.is_empty() || self.outcomes.contains(&outcome)
187    }
188
189    /// Whether `trace` is sampled: [`admits_run`](Self::admits_run) and
190    /// [`admits_outcome`](Self::admits_outcome).
191    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/// A finished run as online evaluation scores it.
198///
199/// The [`plugin`](crate::online::OnlineEvaluator::plugin) builds one from each sampled run;
200/// an application that collects runs some other way builds one with [`new`](Self::new) and
201/// passes it to [`submit`](crate::online::OnlineEvaluator::submit).
202#[derive(Debug, Clone)]
203#[non_exhaustive]
204pub struct RunTrace {
205    /// The runner's application name.
206    pub app_name: String,
207    /// The session the run belongs to.
208    pub session_id: String,
209    /// The run's invocation id.
210    pub invocation_id: String,
211    /// The agent the run started.
212    pub agent_name: String,
213    /// The run's request metadata.
214    pub metadata: HashMap<String, String>,
215    /// The user message that started the run.
216    pub user_content: Content,
217    /// The run's complete (non-partial) events, in order.
218    pub events: Vec<Event>,
219    /// How the run ended.
220    pub outcome: RunOutcome,
221    /// The whole session's conversation, for thread-level criteria; empty otherwise.
222    pub thread: Vec<Content>,
223    /// The run's kill switches, checked again before the run is evaluated.
224    pub governance: Vec<GovernanceControl>,
225    /// When the run finished.
226    pub finished_at: chrono::DateTime<chrono::Utc>,
227}
228
229impl RunTrace {
230    /// A trace of a run that has finished now, its outcome classified from `events`
231    /// ([`RunOutcome::of`]).
232    ///
233    /// # Example
234    ///
235    /// ```
236    /// use adk_core::{Content, Event};
237    /// use adk_eval::online::{RunOutcome, RunTrace};
238    ///
239    /// let mut answer = Event::new("inv-1");
240    /// answer.llm_response.content = Some(Content::new("model").with_text("Sunny."));
241    /// let trace = RunTrace::new(
242    ///     "weather-app",
243    ///     "session-1",
244    ///     "inv-1",
245    ///     "weather_agent",
246    ///     Content::new("user").with_text("Weather in Nairobi?"),
247    ///     vec![answer],
248    /// )
249    /// .with_metadata("tier", "gold");
250    /// assert_eq!(trace.outcome, RunOutcome::Completed);
251    /// ```
252    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    /// Adds a request-metadata entry.
278    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    /// Sets how the run ended, overriding the classification from its events.
284    pub fn with_outcome(mut self, outcome: RunOutcome) -> Self {
285        self.outcome = outcome;
286        self
287    }
288
289    /// Sets the whole session's conversation, for thread-level criteria. Without one, they
290    /// score the run's own user message and answer.
291    pub fn with_thread(mut self, thread: Vec<Content>) -> Self {
292        self.thread = thread;
293        self
294    }
295
296    /// Adds a kill switch that stops the run's evaluation while it is frozen.
297    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        // Independent seeds overlap in about rate² of the runs.
325        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}