Skip to main content

adk_eval/experiments/
config.rs

1//! Experiment configuration: metrics, guardrails, the error budget and the analysis method
2//! (spec 3.5 §7.12, §13 Q8).
3
4use serde::{Deserialize, Serialize};
5
6use crate::error::{EvalError, Result};
7
8/// Default type I error budget of the primary metric's two-sided test (spec 3.5 §7.12).
9pub const DEFAULT_ALPHA: f64 = 0.05;
10
11/// Default error budget shared by all guardrails of an experiment (spec 3.5 §7.12).
12///
13/// A false guardrail stop keeps the control and costs only the experiment, so guardrails get a
14/// larger budget than the primary metric and detect harm sooner.
15pub const DEFAULT_GUARDRAIL_ALPHA: f64 = 0.10;
16
17/// Default planned units per arm, where the sequential boundary is tightest (spec 3.5 §7.12).
18pub const DEFAULT_PLANNED_UNITS_PER_ARM: u64 = 10_000;
19
20/// Default units each arm needs before a metric's test may decide (spec 3.5 §7.12).
21pub const DEFAULT_MIN_UNITS_PER_ARM: u64 = 100;
22
23/// How a metric is measured per unit (spec 3.5 §7.12).
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26#[non_exhaustive]
27pub enum MetricKind {
28    /// The share of units with at least one event: sign-ups, unsubscribes, orders.
29    Proportion,
30    /// The mean of a per-unit value: revenue per visitor, pages per session.
31    Mean,
32}
33
34/// Which way a metric improves (spec 3.5 §7.12).
35///
36/// The charter's KPI direction `Up` maps to [`MetricDirection::HigherIsBetter`] and `Down` to
37/// [`MetricDirection::LowerIsBetter`].
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub enum MetricDirection {
41    /// Larger values are better: sign-ups, revenue.
42    HigherIsBetter,
43    /// Smaller values are better: unsubscribes, refunds, errors.
44    LowerIsBetter,
45}
46
47impl MetricDirection {
48    /// Returns `+1.0` when higher is better and `-1.0` when lower is better.
49    pub(crate) fn sign(self) -> f64 {
50        match self {
51            Self::HigherIsBetter => 1.0,
52            Self::LowerIsBetter => -1.0,
53        }
54    }
55}
56
57/// A metric an experiment measures in both arms (spec 3.5 §7.12).
58///
59/// # Example
60///
61/// ```
62/// use adk_eval::experiments::{MetricDirection, MetricKind, MetricSpec};
63///
64/// let signups = MetricSpec::proportion("signups", MetricDirection::HigherIsBetter);
65/// assert_eq!(signups.kind, MetricKind::Proportion);
66/// ```
67#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase")]
69#[non_exhaustive]
70pub struct MetricSpec {
71    /// The metric's id; each [`Look`](super::Look) carries samples under this id.
72    pub id: String,
73    /// How the metric is measured per unit.
74    pub kind: MetricKind,
75    /// Which way the metric improves.
76    pub direction: MetricDirection,
77}
78
79impl MetricSpec {
80    /// Creates a metric of the given kind.
81    pub fn new(id: impl Into<String>, kind: MetricKind, direction: MetricDirection) -> Self {
82        Self { id: id.into(), kind, direction }
83    }
84
85    /// Creates a proportion metric: the share of units with an event.
86    pub fn proportion(id: impl Into<String>, direction: MetricDirection) -> Self {
87        Self::new(id, MetricKind::Proportion, direction)
88    }
89
90    /// Creates a mean metric: the average of a per-unit value.
91    pub fn mean(id: impl Into<String>, direction: MetricDirection) -> Self {
92        Self::new(id, MetricKind::Mean, direction)
93    }
94}
95
96/// How much worse than the control a guardrail metric may get before it is breached
97/// (spec 3.5 §7.12).
98#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100#[non_exhaustive]
101pub enum Tolerance {
102    /// An absolute margin in the metric's units: `Absolute(0.002)` tolerates 0.2 percentage
103    /// points more unsubscribes. `Absolute(0.0)` breaches on any proven harm.
104    Absolute(f64),
105    /// A margin relative to the control: `Relative(0.1)` tolerates the variant being up to 10%
106    /// worse than the control.
107    Relative(f64),
108}
109
110/// A guardrail: a metric the variant must not make worse beyond a tolerance (spec 3.5 §7.12,
111/// A-I15).
112///
113/// # Example
114///
115/// ```
116/// use adk_eval::experiments::{GuardrailSpec, MetricDirection, MetricSpec, Tolerance};
117///
118/// // Unsubscribes may rise by at most 10% relative to the control.
119/// let guardrail = GuardrailSpec::new(
120///     MetricSpec::proportion("unsubscribes", MetricDirection::LowerIsBetter),
121///     Tolerance::Relative(0.1),
122/// );
123/// assert_eq!(guardrail.metric.id, "unsubscribes");
124/// ```
125#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct GuardrailSpec {
129    /// The guarded metric.
130    pub metric: MetricSpec,
131    /// How much worse than the control the variant may be.
132    pub tolerance: Tolerance,
133}
134
135impl GuardrailSpec {
136    /// Creates a guardrail on `metric` with `tolerance`.
137    pub fn new(metric: MetricSpec, tolerance: Tolerance) -> Self {
138        Self { metric, tolerance }
139    }
140}
141
142/// The fixed type I error budget of an experiment (spec 3.5 §7.12).
143///
144/// `alpha` bounds the probability that the primary test ever declares a difference when there
145/// is none, however many looks are taken. `guardrail_alpha` bounds the probability that any
146/// guardrail is ever breached when the variant is within every tolerance; it is split equally
147/// across the guardrails.
148///
149/// # Example
150///
151/// ```
152/// use adk_eval::experiments::ErrorBudget;
153///
154/// let budget = ErrorBudget::new(0.05, 0.10);
155/// assert_eq!(budget, ErrorBudget::default());
156/// ```
157#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159#[non_exhaustive]
160pub struct ErrorBudget {
161    /// The primary metric's two-sided type I error budget.
162    pub alpha: f64,
163    /// The type I error budget shared by all guardrails.
164    pub guardrail_alpha: f64,
165}
166
167impl ErrorBudget {
168    /// Creates a budget with `alpha` for the primary metric and `guardrail_alpha` shared by the
169    /// guardrails.
170    pub fn new(alpha: f64, guardrail_alpha: f64) -> Self {
171        Self { alpha, guardrail_alpha }
172    }
173}
174
175impl Default for ErrorBudget {
176    fn default() -> Self {
177        Self::new(DEFAULT_ALPHA, DEFAULT_GUARDRAIL_ALPHA)
178    }
179}
180
181/// A Beta prior for proportion metrics in the Bayesian analysis (spec 3.5 §13 Q8).
182///
183/// The default `Beta(1, 1)` is uniform on the rate.
184#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186#[non_exhaustive]
187pub struct BetaPrior {
188    /// Prior pseudo-count of units with an event.
189    pub alpha: f64,
190    /// Prior pseudo-count of units without an event.
191    pub beta: f64,
192}
193
194impl BetaPrior {
195    /// Creates a `Beta(alpha, beta)` prior.
196    pub fn new(alpha: f64, beta: f64) -> Self {
197        Self { alpha, beta }
198    }
199}
200
201impl Default for BetaPrior {
202    fn default() -> Self {
203        Self::new(1.0, 1.0)
204    }
205}
206
207/// Settings of the Bayesian analysis of the primary metric (spec 3.5 §13 Q8).
208///
209/// # Example
210///
211/// ```
212/// use adk_eval::experiments::BayesianConfig;
213///
214/// let config = BayesianConfig::default().with_max_expected_loss(0.001);
215/// assert_eq!(config.decision_probability, 0.95);
216/// ```
217#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
218#[serde(rename_all = "camelCase")]
219#[non_exhaustive]
220pub struct BayesianConfig {
221    /// The prior of each arm's rate for proportion metrics. Mean metrics use a flat prior.
222    pub prior: BetaPrior,
223    /// The posterior probability that one arm is better needed to decide (default 0.95).
224    pub decision_probability: f64,
225    /// When set, a decision also needs the expected loss of the chosen arm, in the metric's
226    /// units, to be at most this value.
227    pub max_expected_loss: Option<f64>,
228    /// The level of the reported credible intervals (default 0.95).
229    pub credible_level: f64,
230}
231
232impl BayesianConfig {
233    /// Sets the prior of each arm's rate for proportion metrics.
234    pub fn with_prior(mut self, prior: BetaPrior) -> Self {
235        self.prior = prior;
236        self
237    }
238
239    /// Sets the posterior probability needed to decide.
240    pub fn with_decision_probability(mut self, probability: f64) -> Self {
241        self.decision_probability = probability;
242        self
243    }
244
245    /// Requires the chosen arm's expected loss to be at most `loss` before deciding.
246    pub fn with_max_expected_loss(mut self, loss: f64) -> Self {
247        self.max_expected_loss = Some(loss);
248        self
249    }
250
251    /// Sets the level of the reported credible intervals.
252    pub fn with_credible_level(mut self, level: f64) -> Self {
253        self.credible_level = level;
254        self
255    }
256}
257
258impl Default for BayesianConfig {
259    fn default() -> Self {
260        Self {
261            prior: BetaPrior::default(),
262            decision_probability: 0.95,
263            max_expected_loss: None,
264            credible_level: 0.95,
265        }
266    }
267}
268
269/// How the primary metric is analysed (spec 3.5 §7.12, §13 Q8).
270///
271/// Guardrails always use the sequential test, whatever the primary metric's method: a breach
272/// is a safety stop and does not depend on a prior.
273#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
274#[serde(rename_all = "camelCase")]
275#[non_exhaustive]
276pub enum AnalysisMethod {
277    /// The always-valid sequential test with a fixed error budget (the default).
278    #[default]
279    Sequential,
280    /// Posterior probabilities, credible intervals and expected loss. It has no type I error
281    /// guarantee when looked at repeatedly.
282    Bayesian(BayesianConfig),
283}
284
285/// The configuration of one experiment: a control, one variant, a primary metric, guardrails,
286/// the error budget and the analysis method (spec 3.5 §7.12).
287///
288/// # Example
289///
290/// ```
291/// use adk_eval::experiments::{
292///     ExperimentConfig, GuardrailSpec, MetricDirection, MetricSpec, Tolerance,
293/// };
294///
295/// let config = ExperimentConfig::new(
296///     "headline",
297///     MetricSpec::proportion("signups", MetricDirection::HigherIsBetter),
298/// )
299/// .with_guardrail(GuardrailSpec::new(
300///     MetricSpec::proportion("unsubscribes", MetricDirection::LowerIsBetter),
301///     Tolerance::Relative(0.1),
302/// ))
303/// .with_planned_units_per_arm(20_000);
304/// assert!(config.validate().is_ok());
305/// ```
306#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308#[non_exhaustive]
309pub struct ExperimentConfig {
310    /// The experiment's id.
311    pub id: String,
312    /// The metric the experiment tries to improve.
313    pub primary: MetricSpec,
314    /// The metrics the variant must not make worse (A-I15).
315    pub guardrails: Vec<GuardrailSpec>,
316    /// The fixed type I error budget.
317    pub budget: ErrorBudget,
318    /// How the primary metric is analysed.
319    pub method: AnalysisMethod,
320    /// The units per arm the experiment expects to reach; the sequential boundary is tightest
321    /// there. It tunes power, not validity.
322    pub planned_units_per_arm: u64,
323    /// The units each arm of a metric needs before that metric's test may decide.
324    pub min_units_per_arm: u64,
325    /// When set, the experiment stops and keeps the control once both arms of the primary
326    /// metric reach this many units without a decision.
327    pub max_units_per_arm: Option<u64>,
328}
329
330impl ExperimentConfig {
331    /// Creates a sequential experiment with no guardrails and the default budget and sizes.
332    pub fn new(id: impl Into<String>, primary: MetricSpec) -> Self {
333        Self {
334            id: id.into(),
335            primary,
336            guardrails: Vec::new(),
337            budget: ErrorBudget::default(),
338            method: AnalysisMethod::default(),
339            planned_units_per_arm: DEFAULT_PLANNED_UNITS_PER_ARM,
340            min_units_per_arm: DEFAULT_MIN_UNITS_PER_ARM,
341            max_units_per_arm: None,
342        }
343    }
344
345    /// Adds a guardrail.
346    pub fn with_guardrail(mut self, guardrail: GuardrailSpec) -> Self {
347        self.guardrails.push(guardrail);
348        self
349    }
350
351    /// Sets the error budget.
352    pub fn with_budget(mut self, budget: ErrorBudget) -> Self {
353        self.budget = budget;
354        self
355    }
356
357    /// Sets the analysis method of the primary metric.
358    pub fn with_method(mut self, method: AnalysisMethod) -> Self {
359        self.method = method;
360        self
361    }
362
363    /// Sets the units per arm the experiment expects to reach.
364    pub fn with_planned_units_per_arm(mut self, units: u64) -> Self {
365        self.planned_units_per_arm = units;
366        self
367    }
368
369    /// Sets the units each arm needs before a metric's test may decide.
370    pub fn with_min_units_per_arm(mut self, units: u64) -> Self {
371        self.min_units_per_arm = units;
372        self
373    }
374
375    /// Stops the experiment, keeping the control, once both arms reach `units` undecided.
376    pub fn with_max_units_per_arm(mut self, units: u64) -> Self {
377        self.max_units_per_arm = Some(units);
378        self
379    }
380
381    /// Checks the configuration.
382    ///
383    /// # Errors
384    ///
385    /// Returns [`EvalError::ConfigError`] naming the first invalid setting: an empty id, a
386    /// repeated metric id, an error budget outside `(0, 0.5]`, a negative or unusable
387    /// tolerance, sizes that are zero or out of order, or Bayesian settings out of range.
388    pub fn validate(&self) -> Result<()> {
389        let invalid = |message: String| Err(EvalError::ConfigError(message));
390        if self.id.trim().is_empty() {
391            return invalid("experiment id is empty; give the experiment a stable id".into());
392        }
393        let mut ids = vec![self.primary.id.as_str()];
394        for guardrail in &self.guardrails {
395            ids.push(guardrail.metric.id.as_str());
396        }
397        for (index, id) in ids.iter().enumerate() {
398            if id.trim().is_empty() {
399                return invalid(format!("experiment '{}' has a metric with an empty id", self.id));
400            }
401            if ids[..index].contains(id) {
402                return invalid(format!(
403                    "experiment '{}' names metric '{id}' twice; the primary metric and each \
404                     guardrail need distinct metric ids",
405                    self.id
406                ));
407            }
408        }
409        for (name, value) in
410            [("alpha", self.budget.alpha), ("guardrail_alpha", self.budget.guardrail_alpha)]
411        {
412            if !(value > 0.0 && value <= 0.5) {
413                return invalid(format!(
414                    "experiment '{}' has {name} = {value}; an error budget must lie in (0, 0.5]",
415                    self.id
416                ));
417            }
418        }
419        for guardrail in &self.guardrails {
420            let metric = &guardrail.metric.id;
421            match guardrail.tolerance {
422                Tolerance::Absolute(margin) => {
423                    if !(margin.is_finite() && margin >= 0.0) {
424                        return invalid(format!(
425                            "guardrail '{metric}' has absolute tolerance {margin}; use a finite \
426                             margin of zero or more"
427                        ));
428                    }
429                    if guardrail.metric.kind == MetricKind::Proportion && margin >= 1.0 {
430                        return invalid(format!(
431                            "guardrail '{metric}' tolerates an absolute change of {margin} in a \
432                             proportion, which can never be breached; use a margin below 1"
433                        ));
434                    }
435                }
436                Tolerance::Relative(share) => {
437                    if !(share.is_finite() && share >= 0.0) {
438                        return invalid(format!(
439                            "guardrail '{metric}' has relative tolerance {share}; use a finite \
440                             share of zero or more"
441                        ));
442                    }
443                    if guardrail.metric.direction == MetricDirection::HigherIsBetter && share >= 1.0
444                    {
445                        return invalid(format!(
446                            "guardrail '{metric}' tolerates a relative drop of {share} in a metric \
447                             where higher is better, which can never be breached; use a share \
448                             below 1"
449                        ));
450                    }
451                }
452            }
453        }
454        if self.min_units_per_arm < 2 {
455            return invalid(format!(
456                "experiment '{}' has min_units_per_arm = {}; at least 2 units per arm are needed \
457                 to estimate a variance",
458                self.id, self.min_units_per_arm
459            ));
460        }
461        if self.planned_units_per_arm < self.min_units_per_arm {
462            return invalid(format!(
463                "experiment '{}' plans {} units per arm, fewer than its minimum of {}",
464                self.id, self.planned_units_per_arm, self.min_units_per_arm
465            ));
466        }
467        if let Some(max) = self.max_units_per_arm
468            && max < self.min_units_per_arm
469        {
470            return invalid(format!(
471                "experiment '{}' stops at {max} units per arm, before its minimum of {} lets any \
472                 test decide",
473                self.id, self.min_units_per_arm
474            ));
475        }
476        match self.method {
477            AnalysisMethod::Sequential => {}
478            AnalysisMethod::Bayesian(bayes) => {
479                let prior = bayes.prior;
480                if !(prior.alpha.is_finite()
481                    && prior.alpha > 0.0
482                    && prior.beta.is_finite()
483                    && prior.beta > 0.0)
484                {
485                    return invalid(format!(
486                        "experiment '{}' has prior Beta({}, {}); both parameters must be finite \
487                         and positive",
488                        self.id, prior.alpha, prior.beta
489                    ));
490                }
491                if !(bayes.decision_probability > 0.5 && bayes.decision_probability < 1.0) {
492                    return invalid(format!(
493                        "experiment '{}' has decision_probability = {}; use a value in (0.5, 1)",
494                        self.id, bayes.decision_probability
495                    ));
496                }
497                if !(bayes.credible_level > 0.0 && bayes.credible_level < 1.0) {
498                    return invalid(format!(
499                        "experiment '{}' has credible_level = {}; use a value in (0, 1)",
500                        self.id, bayes.credible_level
501                    ));
502                }
503                if let Some(loss) = bayes.max_expected_loss
504                    && !(loss.is_finite() && loss >= 0.0)
505                {
506                    return invalid(format!(
507                        "experiment '{}' has max_expected_loss = {loss}; use a finite loss of \
508                         zero or more",
509                        self.id
510                    ));
511                }
512            }
513        }
514        Ok(())
515    }
516
517    /// Returns the per-guardrail error budget: `guardrail_alpha` split equally.
518    pub(crate) fn alpha_per_guardrail(&self) -> f64 {
519        self.budget.guardrail_alpha / self.guardrails.len().max(1) as f64
520    }
521}
522
523#[cfg(test)]
524mod tests {
525    use super::*;
526
527    fn base() -> ExperimentConfig {
528        ExperimentConfig::new(
529            "headline",
530            MetricSpec::proportion("signups", MetricDirection::HigherIsBetter),
531        )
532    }
533
534    fn message(config: &ExperimentConfig) -> String {
535        match config.validate() {
536            Err(EvalError::ConfigError(message)) => message,
537            other => panic!("expected a configuration error, got {other:?}"),
538        }
539    }
540
541    #[test]
542    fn defaults_are_valid() {
543        assert!(base().validate().is_ok());
544        let bayes = base().with_method(AnalysisMethod::Bayesian(BayesianConfig::default()));
545        assert!(bayes.validate().is_ok());
546    }
547
548    #[test]
549    fn repeated_metric_ids_are_refused() {
550        let config = base().with_guardrail(GuardrailSpec::new(
551            MetricSpec::proportion("signups", MetricDirection::LowerIsBetter),
552            Tolerance::Absolute(0.0),
553        ));
554        assert!(message(&config).contains("names metric 'signups' twice"));
555    }
556
557    #[test]
558    fn budgets_outside_the_open_interval_are_refused() {
559        for alpha in [0.0, -0.1, 0.6, f64::NAN] {
560            let config = base().with_budget(ErrorBudget::new(alpha, 0.1));
561            assert!(message(&config).contains("alpha"), "alpha {alpha}");
562            let config = base().with_budget(ErrorBudget::new(0.05, alpha));
563            assert!(message(&config).contains("guardrail_alpha"), "guardrail alpha {alpha}");
564        }
565    }
566
567    #[test]
568    fn unbreachable_tolerances_are_refused() {
569        let drop = base().with_guardrail(GuardrailSpec::new(
570            MetricSpec::mean("revenue", MetricDirection::HigherIsBetter),
571            Tolerance::Relative(1.0),
572        ));
573        assert!(message(&drop).contains("can never be breached"));
574        let absolute = base().with_guardrail(GuardrailSpec::new(
575            MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
576            Tolerance::Absolute(1.0),
577        ));
578        assert!(message(&absolute).contains("can never be breached"));
579        let negative = base().with_guardrail(GuardrailSpec::new(
580            MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
581            Tolerance::Relative(-0.1),
582        ));
583        assert!(message(&negative).contains("relative tolerance"));
584    }
585
586    #[test]
587    fn sizes_out_of_order_are_refused() {
588        assert!(message(&base().with_min_units_per_arm(1)).contains("at least 2"));
589        assert!(message(&base().with_planned_units_per_arm(50)).contains("plans 50"));
590        assert!(message(&base().with_max_units_per_arm(50)).contains("stops at 50"));
591    }
592
593    #[test]
594    fn bayesian_settings_out_of_range_are_refused() {
595        let with = |bayes: BayesianConfig| base().with_method(AnalysisMethod::Bayesian(bayes));
596        let prior = BayesianConfig::default().with_prior(BetaPrior::new(0.0, 1.0));
597        assert!(message(&with(prior)).contains("prior"));
598        let probability = BayesianConfig::default().with_decision_probability(0.5);
599        assert!(message(&with(probability)).contains("decision_probability"));
600        let level = BayesianConfig::default().with_credible_level(1.0);
601        assert!(message(&with(level)).contains("credible_level"));
602        let loss = BayesianConfig::default().with_max_expected_loss(-1.0);
603        assert!(message(&with(loss)).contains("max_expected_loss"));
604    }
605}