Skip to main content

adk_eval/experiments/
analyzer.rs

1//! `ExperimentAnalyzer`: the sequential analysis of one experiment, look by look
2//! (spec 3.5 §7.12, A-I15, §13 Q8).
3
4use std::collections::{BTreeMap, BTreeSet};
5
6use serde::{Deserialize, Serialize};
7use tracing::{debug, info};
8
9use super::config::{
10    AnalysisMethod, BayesianConfig, ExperimentConfig, GuardrailSpec, MetricDirection, Tolerance,
11};
12use super::normal;
13use super::report::{
14    Decision, EffectEstimate, Evidence, ExperimentReport, GuardrailAnalysis, Interval,
15    PrimaryAnalysis, StopReason,
16};
17use super::sample::{ArmSamples, Look, Sample};
18use super::sequential::SequentialBoundary;
19use crate::error::{EvalError, Result};
20
21/// The persistent state of an [`ExperimentAnalyzer`] between looks (spec 3.5 §7.12).
22///
23/// The always-valid p-values are running minima over every look, so a process that analyses an
24/// experiment once a day keeps this state and resumes it with
25/// [`ExperimentAnalyzer::resume`]. It serialises to camelCase JSON.
26#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
27#[serde(rename_all = "camelCase")]
28pub struct ExperimentState {
29    experiment_id: String,
30    looks: u32,
31    last: Option<Look>,
32    primary_p_value: f64,
33    guardrail_p_values: BTreeMap<String, f64>,
34    final_report: Option<ExperimentReport>,
35}
36
37impl ExperimentState {
38    /// Returns the experiment's id.
39    pub fn experiment_id(&self) -> &str {
40        &self.experiment_id
41    }
42
43    /// Returns the number of looks analysed.
44    pub fn looks(&self) -> u32 {
45        self.looks
46    }
47
48    /// Returns the report of the look that stopped the experiment, if it has stopped.
49    pub fn final_report(&self) -> Option<&ExperimentReport> {
50        self.final_report.as_ref()
51    }
52}
53
54/// Which way the primary metric's evidence points at a look.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56enum Verdict {
57    Undecided,
58    VariantBetter,
59    VariantWorse,
60}
61
62/// The sequential analysis of a web experiment with one control and one variant
63/// (spec 3.5 §7.12, A-I15, §13 Q8).
64///
65/// Each call to [`observe`](Self::observe) analyses one look at the cumulative data and returns
66/// an [`ExperimentReport`]. Looks may come as often as the caller likes — daily is typical —
67/// without spending more than the [`ErrorBudget`](super::ErrorBudget). Guardrails are checked
68/// first at every look; a breach stops the experiment and keeps the control whatever the
69/// primary metric shows. A final decision is kept: later looks return the same report.
70///
71/// See the [module documentation](super) for the method and its assumptions.
72///
73/// # Example
74///
75/// ```
76/// use adk_eval::experiments::{
77///     Decision, ExperimentAnalyzer, ExperimentConfig, GuardrailSpec, Look, MetricDirection,
78///     MetricSpec, Sample, StopReason, Tolerance,
79/// };
80///
81/// let config = ExperimentConfig::new(
82///     "headline",
83///     MetricSpec::proportion("signups", MetricDirection::HigherIsBetter),
84/// )
85/// .with_guardrail(GuardrailSpec::new(
86///     MetricSpec::proportion("unsubscribes", MetricDirection::LowerIsBetter),
87///     Tolerance::Relative(0.1),
88/// ));
89/// let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
90///
91/// // Each day's look carries the totals so far: B lifts sign-ups from 4% to 5% but doubles
92/// // unsubscribes from 0.5% to 1%.
93/// let mut decision = Decision::Continue;
94/// for day in 1..=28 {
95///     let visitors = 600 * day;
96///     let look = Look::new()
97///         .with_metric(
98///             "signups",
99///             Sample::proportion(visitors, 24 * day),
100///             Sample::proportion(visitors, 30 * day),
101///         )
102///         .with_metric(
103///             "unsubscribes",
104///             Sample::proportion(visitors, 3 * day),
105///             Sample::proportion(visitors, 6 * day),
106///         );
107///     let report = analyzer.observe(&look).unwrap();
108///     decision = report.decision;
109///     if decision.is_final() {
110///         break;
111///     }
112/// }
113/// assert_eq!(
114///     decision,
115///     Decision::KeepControl {
116///         reason: StopReason::GuardrailBreach { guardrails: vec!["unsubscribes".into()] }
117///     }
118/// );
119/// ```
120#[derive(Debug, Clone)]
121pub struct ExperimentAnalyzer {
122    config: ExperimentConfig,
123    primary_boundary: SequentialBoundary,
124    guardrail_boundary: SequentialBoundary,
125    state: ExperimentState,
126}
127
128impl ExperimentAnalyzer {
129    /// Creates an analyzer for a new experiment.
130    ///
131    /// # Errors
132    ///
133    /// Returns [`EvalError::ConfigError`] when the configuration is invalid; see
134    /// [`ExperimentConfig::validate`].
135    pub fn new(config: ExperimentConfig) -> Result<Self> {
136        config.validate()?;
137        let planned = config.planned_units_per_arm as f64 / 2.0;
138        let primary_boundary = SequentialBoundary::new(config.budget.alpha, planned)?;
139        let guardrail_boundary = SequentialBoundary::new(config.alpha_per_guardrail(), planned)?;
140        let state = ExperimentState {
141            experiment_id: config.id.clone(),
142            looks: 0,
143            last: None,
144            primary_p_value: 1.0,
145            guardrail_p_values: config
146                .guardrails
147                .iter()
148                .map(|guardrail| (guardrail.metric.id.clone(), 1.0))
149                .collect(),
150            final_report: None,
151        };
152        Ok(Self { config, primary_boundary, guardrail_boundary, state })
153    }
154
155    /// Resumes an experiment from its saved state.
156    ///
157    /// # Errors
158    ///
159    /// Returns [`EvalError::ConfigError`] when the configuration is invalid or the state
160    /// belongs to another experiment or another set of guardrails, and
161    /// [`EvalError::StatisticsError`] when a saved p-value is outside `[0, 1]`.
162    pub fn resume(config: ExperimentConfig, state: ExperimentState) -> Result<Self> {
163        let mut analyzer = Self::new(config)?;
164        if state.experiment_id != analyzer.config.id {
165            return Err(EvalError::ConfigError(format!(
166                "state of experiment '{}' cannot resume experiment '{}'",
167                state.experiment_id, analyzer.config.id
168            )));
169        }
170        let saved: BTreeSet<&String> = state.guardrail_p_values.keys().collect();
171        let configured: BTreeSet<&String> =
172            analyzer.config.guardrails.iter().map(|guardrail| &guardrail.metric.id).collect();
173        if saved != configured {
174            return Err(EvalError::ConfigError(format!(
175                "experiment '{}' was saved with guardrails {saved:?} but is configured with \
176                 {configured:?}; guardrails are fixed for an experiment's life",
177                analyzer.config.id
178            )));
179        }
180        let p_values =
181            std::iter::once(&state.primary_p_value).chain(state.guardrail_p_values.values());
182        for p_value in p_values {
183            if !(0.0..=1.0).contains(p_value) {
184                return Err(EvalError::StatisticsError(format!(
185                    "saved state of experiment '{}' has p-value {p_value}; p-values lie in [0, 1]",
186                    analyzer.config.id
187                )));
188            }
189        }
190        analyzer.state = state;
191        Ok(analyzer)
192    }
193
194    /// Returns the configuration.
195    pub fn config(&self) -> &ExperimentConfig {
196        &self.config
197    }
198
199    /// Returns the state to save between looks.
200    pub fn state(&self) -> &ExperimentState {
201        &self.state
202    }
203
204    /// Returns whether the experiment has reached a final decision.
205    pub fn is_stopped(&self) -> bool {
206        self.state.final_report.is_some()
207    }
208
209    /// Analyses one look at the cumulative data and returns the decision with its evidence.
210    ///
211    /// Once a look reaches a final decision, every later look returns that look's report
212    /// unchanged.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`EvalError::StatisticsError`] when the look misses the primary metric or a
217    /// guardrail, carries a sample of the wrong kind or an invalid sample, or has fewer units
218    /// or events than the previous look (looks are cumulative). A refused look leaves the
219    /// state unchanged.
220    pub fn observe(&mut self, look: &Look) -> Result<ExperimentReport> {
221        if let Some(report) = &self.state.final_report {
222            return Ok(report.clone());
223        }
224        let look_number = self.state.looks + 1;
225        self.check_look(look, look_number)?;
226
227        let mut guardrail_p_values = BTreeMap::new();
228        let mut guardrails = Vec::with_capacity(self.config.guardrails.len());
229        for spec in &self.config.guardrails {
230            let arms = Self::arms(look, &spec.metric.id);
231            let previous =
232                self.state.guardrail_p_values.get(&spec.metric.id).copied().unwrap_or(1.0);
233            let analysis = self.guardrail(spec, arms, previous);
234            guardrail_p_values.insert(spec.metric.id.clone(), analysis.p_value);
235            guardrails.push(analysis);
236        }
237
238        let arms = Self::arms(look, &self.config.primary.id);
239        let (primary, primary_p_value, verdict) = match self.config.method {
240            AnalysisMethod::Sequential => self.sequential_primary(arms),
241            AnalysisMethod::Bayesian(bayes) => self.bayesian_primary(arms, bayes),
242        };
243
244        let breached: Vec<String> = guardrails
245            .iter()
246            .filter(|guardrail| guardrail.breached)
247            .map(|guardrail| guardrail.metric.clone())
248            .collect();
249        // Adoption also needs every guardrail measured and, on its estimate, within tolerance:
250        // a harm not yet proven still holds the variant back until a breach or more data.
251        let guardrails_clear =
252            guardrails.iter().all(|guardrail| guardrail.ready && guardrail.harm <= 0.0);
253        let at_limit = self
254            .config
255            .max_units_per_arm
256            .is_some_and(|max| arms.control.units() >= max && arms.variant.units() >= max);
257        // Guardrails come first: a breach keeps the control whatever the primary shows (A-I15).
258        let decision = if !breached.is_empty() {
259            Decision::KeepControl { reason: StopReason::GuardrailBreach { guardrails: breached } }
260        } else {
261            match verdict {
262                Verdict::VariantBetter if guardrails_clear => Decision::AdoptVariant,
263                Verdict::VariantWorse => Decision::KeepControl { reason: StopReason::VariantWorse },
264                Verdict::VariantBetter | Verdict::Undecided if at_limit => {
265                    Decision::KeepControl { reason: StopReason::SampleLimitReached }
266                }
267                Verdict::VariantBetter | Verdict::Undecided => Decision::Continue,
268            }
269        };
270
271        let report = ExperimentReport {
272            experiment_id: self.config.id.clone(),
273            look: look_number,
274            primary,
275            guardrails,
276            decision,
277        };
278        self.state.looks = look_number;
279        self.state.last = Some(look.clone());
280        self.state.primary_p_value = primary_p_value;
281        self.state.guardrail_p_values = guardrail_p_values;
282        if report.decision.is_final() {
283            info!(
284                experiment.id = %self.config.id,
285                experiment.look = look_number,
286                experiment.decision = %report.decision,
287                "experiment stopped"
288            );
289            self.state.final_report = Some(report.clone());
290        } else {
291            debug!(experiment.id = %self.config.id, experiment.look = look_number, "experiment continues");
292        }
293        Ok(report)
294    }
295
296    /// Returns the samples of a metric `check_look` has confirmed are present.
297    fn arms<'a>(look: &'a Look, metric: &str) -> &'a ArmSamples {
298        look.metrics.get(metric).expect("check_look confirms every configured metric is present")
299    }
300
301    /// Checks that the look carries every configured metric, valid and cumulative.
302    fn check_look(&self, look: &Look, look_number: u32) -> Result<()> {
303        let specs = std::iter::once(&self.config.primary)
304            .chain(self.config.guardrails.iter().map(|guardrail| &guardrail.metric));
305        for spec in specs {
306            let id = &spec.id;
307            let Some(arms) = look.metric(id) else {
308                return Err(EvalError::StatisticsError(format!(
309                    "look {look_number} of experiment '{}' has no samples for metric '{id}'; \
310                     every look carries the primary metric and every guardrail",
311                    self.config.id
312                )));
313            };
314            for (arm, sample) in [("control", &arms.control), ("variant", &arms.variant)] {
315                if sample.kind() != spec.kind {
316                    return Err(EvalError::StatisticsError(format!(
317                        "look {look_number} carries a {:?} sample for the {arm} of metric \
318                         '{id}', which is configured as {:?}",
319                        sample.kind(),
320                        spec.kind
321                    )));
322                }
323                sample.check(&format!("look {look_number}, metric '{id}', {arm}"))?;
324            }
325            let Some(previous) = self.state.last.as_ref().and_then(|last| last.metric(id)) else {
326                continue;
327            };
328            for (arm, now, before) in [
329                ("control", &arms.control, &previous.control),
330                ("variant", &arms.variant, &previous.variant),
331            ] {
332                let fewer_events = matches!(
333                    (now, before),
334                    (Sample::Proportion { events: now, .. }, Sample::Proportion { events: before, .. })
335                        if now < before
336                );
337                if now.units() < before.units() || fewer_events {
338                    return Err(EvalError::StatisticsError(format!(
339                        "look {look_number} has fewer units or events for the {arm} of metric \
340                         '{id}' than look {}; looks carry cumulative totals since the start",
341                        self.state.looks
342                    )));
343                }
344            }
345        }
346        Ok(())
347    }
348
349    fn ready(&self, arms: &ArmSamples) -> bool {
350        arms.control.units() >= self.config.min_units_per_arm
351            && arms.variant.units() >= self.config.min_units_per_arm
352    }
353
354    /// Analyses one guardrail with the one-sided sequential test of "harm within tolerance".
355    fn guardrail(
356        &self,
357        spec: &GuardrailSpec,
358        arms: &ArmSamples,
359        previous: f64,
360    ) -> GuardrailAnalysis {
361        let (control, variant) = (arms.control.estimate(), arms.variant.estimate());
362        let (control_var, variant_var) =
363            (arms.control.variance_of_estimate(), arms.variant.variance_of_estimate());
364        // harm = variant − c·control − m (lower is better) or c·control − variant − m (higher
365        // is better), so the guardrail holds while harm ≤ 0.
366        let (scale, margin) = match (spec.metric.direction, spec.tolerance) {
367            (_, Tolerance::Absolute(margin)) => (1.0, margin),
368            (MetricDirection::LowerIsBetter, Tolerance::Relative(share)) => (1.0 + share, 0.0),
369            (MetricDirection::HigherIsBetter, Tolerance::Relative(share)) => (1.0 - share, 0.0),
370        };
371        let harm = match spec.metric.direction {
372            MetricDirection::LowerIsBetter => variant - scale * control - margin,
373            MetricDirection::HigherIsBetter => scale * control - variant - margin,
374        };
375        let se = (variant_var + scale * scale * control_var).sqrt();
376        let units = arms.effective_units();
377        let ready = self.ready(arms);
378        let z = if se > 0.0 { harm / se } else { 0.0 };
379        let look_p = if ready && z > 0.0 { self.guardrail_boundary.p_value(z, units) } else { 1.0 };
380        let p_value = previous.min(look_p);
381        let critical = ready.then(|| self.guardrail_boundary.critical_z(units));
382        GuardrailAnalysis {
383            metric: spec.metric.id.clone(),
384            kind: spec.metric.kind,
385            direction: spec.metric.direction,
386            tolerance: spec.tolerance,
387            control_units: arms.control.units(),
388            variant_units: arms.variant.units(),
389            ready,
390            effect: effect(
391                (control, control_var),
392                (variant, variant_var),
393                critical,
394                1.0 - self.guardrail_boundary.alpha(),
395            ),
396            harm,
397            harm_lower_bound: critical
398                .filter(|critical| critical.is_finite() && se > 0.0)
399                .map(|critical| harm - critical * se),
400            p_value,
401            alpha: self.guardrail_boundary.alpha(),
402            breached: p_value <= self.guardrail_boundary.alpha(),
403        }
404    }
405
406    /// Analyses the primary metric with the two-sided sequential test of "no difference".
407    fn sequential_primary(&self, arms: &ArmSamples) -> (PrimaryAnalysis, f64, Verdict) {
408        let (control, variant) = (arms.control.estimate(), arms.variant.estimate());
409        let (control_var, variant_var) =
410            (arms.control.variance_of_estimate(), arms.variant.variance_of_estimate());
411        let difference = variant - control;
412        let se = (control_var + variant_var).sqrt();
413        let units = arms.effective_units();
414        let ready = self.ready(arms);
415        let z = if se > 0.0 { difference / se } else { 0.0 };
416        let look_p = if ready { self.primary_boundary.p_value(z, units) } else { 1.0 };
417        let p_value = self.state.primary_p_value.min(look_p);
418        let critical = ready.then(|| self.primary_boundary.critical_z(units));
419        let improvement = difference * self.config.primary.direction.sign();
420        let verdict = if p_value > self.primary_boundary.alpha() || improvement == 0.0 {
421            Verdict::Undecided
422        } else if improvement > 0.0 {
423            Verdict::VariantBetter
424        } else {
425            Verdict::VariantWorse
426        };
427        let alpha = self.primary_boundary.alpha();
428        let analysis = self.primary_analysis(
429            arms,
430            ready,
431            effect((control, control_var), (variant, variant_var), critical, 1.0 - alpha),
432            Evidence::Sequential { p_value, z, critical_z: critical, alpha },
433        );
434        (analysis, p_value, verdict)
435    }
436
437    /// Analyses the primary metric by its posterior (spec 3.5 §13 Q8).
438    fn bayesian_primary(
439        &self,
440        arms: &ArmSamples,
441        bayes: BayesianConfig,
442    ) -> (PrimaryAnalysis, f64, Verdict) {
443        let posterior = |sample: &Sample| match *sample {
444            Sample::Proportion { units, events } => {
445                let successes = bayes.prior.alpha + events as f64;
446                let total = bayes.prior.alpha + bayes.prior.beta + units as f64;
447                let mean = successes / total;
448                (mean, mean * (1.0 - mean) / (total + 1.0))
449            }
450            Sample::Mean { units: 0, .. } => (0.0, 0.0),
451            Sample::Mean { units, mean, variance } => (mean, variance / units as f64),
452        };
453        let (control, control_var) = posterior(&arms.control);
454        let (variant, variant_var) = posterior(&arms.variant);
455        let ready = self.ready(arms);
456        // The posterior of the improvement (variant over control, in the better direction) is
457        // approximately normal with mean `gain` and standard deviation `spread`.
458        let gain = (variant - control) * self.config.primary.direction.sign();
459        let spread = (control_var + variant_var).sqrt();
460        let (probability, loss_adopt, loss_keep) = if spread > 0.0 {
461            let ratio = gain / spread;
462            let density = spread * normal::pdf(ratio);
463            (
464                normal::cdf(ratio),
465                density - gain * normal::cdf(-ratio),
466                density + gain * normal::cdf(ratio),
467            )
468        } else {
469            let probability = match gain.partial_cmp(&0.0) {
470                Some(std::cmp::Ordering::Greater) => 1.0,
471                Some(std::cmp::Ordering::Less) => 0.0,
472                Some(std::cmp::Ordering::Equal) | None => 0.5,
473            };
474            (probability, (-gain).max(0.0), gain.max(0.0))
475        };
476        let within_loss = |loss: f64| bayes.max_expected_loss.is_none_or(|max| loss <= max);
477        let verdict = if !ready {
478            Verdict::Undecided
479        } else if probability >= bayes.decision_probability && within_loss(loss_adopt) {
480            Verdict::VariantBetter
481        } else if probability <= 1.0 - bayes.decision_probability && within_loss(loss_keep) {
482            Verdict::VariantWorse
483        } else {
484            Verdict::Undecided
485        };
486        let critical = ready.then(|| normal::quantile(0.5 + bayes.credible_level / 2.0));
487        let analysis = self.primary_analysis(
488            arms,
489            ready,
490            effect((control, control_var), (variant, variant_var), critical, bayes.credible_level),
491            Evidence::Bayesian {
492                probability_variant_better: probability,
493                expected_loss_adopt: loss_adopt,
494                expected_loss_keep: loss_keep,
495                decision_probability: bayes.decision_probability,
496            },
497        );
498        (analysis, self.state.primary_p_value, verdict)
499    }
500
501    fn primary_analysis(
502        &self,
503        arms: &ArmSamples,
504        ready: bool,
505        effect: EffectEstimate,
506        evidence: Evidence,
507    ) -> PrimaryAnalysis {
508        PrimaryAnalysis {
509            metric: self.config.primary.id.clone(),
510            kind: self.config.primary.kind,
511            direction: self.config.primary.direction,
512            control_units: arms.control.units(),
513            variant_units: arms.variant.units(),
514            ready,
515            effect,
516            evidence,
517        }
518    }
519}
520
521/// Builds the effect estimate from each arm's estimate and its variance; `critical` scales the
522/// standard errors into interval half-widths. An estimate with no variance gets no interval:
523/// a normal interval of width zero would claim certainty the data cannot give.
524fn effect(
525    (control, control_var): (f64, f64),
526    (variant, variant_var): (f64, f64),
527    critical: Option<f64>,
528    level: f64,
529) -> EffectEstimate {
530    let difference = variant - control;
531    let critical = critical.filter(|critical| critical.is_finite());
532    let interval = |center: f64, se: f64| {
533        critical.filter(|_| se > 0.0).map(|critical| Interval::around(center, critical * se, level))
534    };
535    let difference_interval = interval(difference, (control_var + variant_var).sqrt());
536    let relative_lift = (control != 0.0).then(|| difference / control);
537    // Delta method for variant/control − 1.
538    let relative_interval = relative_lift.and_then(|lift| {
539        let control_sq = control * control;
540        let se = (variant_var / control_sq
541            + variant * variant * control_var / (control_sq * control_sq))
542            .sqrt();
543        interval(lift, se)
544    });
545    EffectEstimate {
546        control,
547        variant,
548        difference,
549        difference_interval,
550        relative_lift,
551        relative_interval,
552    }
553}
554
555#[cfg(test)]
556mod tests {
557    use super::*;
558    use crate::experiments::{ErrorBudget, MetricSpec};
559
560    fn signups() -> MetricSpec {
561        MetricSpec::proportion("signups", MetricDirection::HigherIsBetter)
562    }
563
564    fn proportions(control: (u64, u64), variant: (u64, u64)) -> Look {
565        Look::new().with_metric(
566            "signups",
567            Sample::proportion(control.0, control.1),
568            Sample::proportion(variant.0, variant.1),
569        )
570    }
571
572    #[test]
573    fn a_single_look_matches_the_two_proportion_z_statistic() {
574        // 200/1000 against 250/1000: unpooled se 0.0186414, z 2.68221 (computed by hand).
575        let mut analyzer = ExperimentAnalyzer::new(ExperimentConfig::new("t", signups())).unwrap();
576        let report = analyzer.observe(&proportions((1000, 200), (1000, 250))).unwrap();
577        let Evidence::Sequential { z, critical_z, p_value, alpha } = report.primary.evidence else {
578            panic!("sequential evidence")
579        };
580        assert!((z - 2.6822089039290997).abs() < 1e-12);
581        assert_eq!(alpha, 0.05);
582        let boundary = SequentialBoundary::new(0.05, 5_000.0).unwrap();
583        assert_eq!(critical_z, Some(boundary.critical_z(500.0)));
584        assert_eq!(p_value, boundary.p_value(z, 500.0));
585        let interval = report.primary.effect.difference_interval.unwrap();
586        let half_width = boundary.critical_z(500.0) * 0.01864135188230725;
587        assert!((interval.lower - (0.05 - half_width)).abs() < 1e-12);
588        assert!((interval.upper - (0.05 + half_width)).abs() < 1e-12);
589        assert_eq!(interval.level, 0.95);
590        assert!((report.primary.effect.relative_lift.unwrap() - 0.25).abs() < 1e-12);
591    }
592
593    #[test]
594    fn nothing_decides_before_the_minimum_units() {
595        let config = ExperimentConfig::new("t", signups()).with_min_units_per_arm(500);
596        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
597        let report = analyzer.observe(&proportions((400, 4), (400, 200))).unwrap();
598        assert_eq!(report.decision, Decision::Continue);
599        assert!(!report.primary.ready);
600        assert_eq!(report.primary.effect.difference_interval, None);
601        let Evidence::Sequential { p_value, critical_z, .. } = report.primary.evidence else {
602            panic!("sequential evidence")
603        };
604        assert_eq!((p_value, critical_z), (1.0, None));
605    }
606
607    #[test]
608    fn a_worse_variant_keeps_the_control() {
609        let mut analyzer = ExperimentAnalyzer::new(ExperimentConfig::new("t", signups())).unwrap();
610        let report = analyzer.observe(&proportions((5000, 1000), (5000, 700))).unwrap();
611        assert_eq!(report.decision, Decision::KeepControl { reason: StopReason::VariantWorse });
612    }
613
614    #[test]
615    fn a_better_variant_is_adopted_and_the_decision_is_final() {
616        let mut analyzer = ExperimentAnalyzer::new(ExperimentConfig::new("t", signups())).unwrap();
617        let report = analyzer.observe(&proportions((5000, 700), (5000, 1000))).unwrap();
618        assert_eq!(report.decision, Decision::AdoptVariant);
619        assert!(analyzer.is_stopped());
620        // A later look, even one that reverses the effect, returns the final report.
621        let later = analyzer.observe(&proportions((9000, 1800), (9000, 1000))).unwrap();
622        assert_eq!(later, report);
623    }
624
625    #[test]
626    fn the_sample_limit_keeps_the_control() {
627        let config = ExperimentConfig::new("t", signups()).with_max_units_per_arm(2000);
628        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
629        let first = analyzer.observe(&proportions((1000, 100), (1000, 101))).unwrap();
630        assert_eq!(first.decision, Decision::Continue);
631        let second = analyzer.observe(&proportions((2000, 200), (2000, 203))).unwrap();
632        assert_eq!(
633            second.decision,
634            Decision::KeepControl { reason: StopReason::SampleLimitReached }
635        );
636    }
637
638    #[test]
639    fn looks_must_be_cumulative_and_complete() {
640        let config = ExperimentConfig::new("t", signups()).with_guardrail(GuardrailSpec::new(
641            MetricSpec::mean("revenue", MetricDirection::HigherIsBetter),
642            Tolerance::Relative(0.05),
643        ));
644        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
645        let missing = analyzer.observe(&proportions((100, 1), (100, 2)));
646        assert!(matches!(missing, Err(EvalError::StatisticsError(m)) if m.contains("'revenue'")));
647        let look = |units: u64, events: u64| {
648            proportions((units, events), (units, events)).with_metric(
649                "revenue",
650                Sample::mean(units, 2.0, 1.0),
651                Sample::mean(units, 2.0, 1.0),
652            )
653        };
654        analyzer.observe(&look(200, 20)).unwrap();
655        let shrunk = analyzer.observe(&look(150, 20));
656        assert!(matches!(shrunk, Err(EvalError::StatisticsError(m)) if m.contains("cumulative")));
657        let fewer_events = analyzer.observe(&look(300, 10));
658        assert!(
659            matches!(fewer_events, Err(EvalError::StatisticsError(m)) if m.contains("cumulative"))
660        );
661        let wrong_kind = look(300, 30).with_metric(
662            "revenue",
663            Sample::proportion(300, 1),
664            Sample::proportion(300, 1),
665        );
666        assert!(analyzer.observe(&wrong_kind).is_err());
667        // Refused looks leave the state unchanged.
668        assert_eq!(analyzer.state().looks(), 1);
669        assert_eq!(analyzer.observe(&look(300, 30)).unwrap().look, 2);
670    }
671
672    #[test]
673    fn guardrails_override_a_winning_primary_metric() {
674        let config = ExperimentConfig::new("t", signups()).with_guardrail(GuardrailSpec::new(
675            MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
676            Tolerance::Absolute(0.0),
677        ));
678        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
679        let look = proportions((5000, 700), (5000, 1000)).with_metric(
680            "refunds",
681            Sample::proportion(5000, 50),
682            Sample::proportion(5000, 150),
683        );
684        let report = analyzer.observe(&look).unwrap();
685        let Evidence::Sequential { p_value, alpha, .. } = report.primary.evidence else {
686            panic!("sequential evidence")
687        };
688        assert!(p_value <= alpha, "the primary metric alone would adopt the variant");
689        assert_eq!(
690            report.decision,
691            Decision::KeepControl {
692                reason: StopReason::GuardrailBreach { guardrails: vec!["refunds".into()] }
693            }
694        );
695    }
696
697    #[test]
698    fn an_unproven_harm_holds_adoption_back() {
699        let config = ExperimentConfig::new("t", signups()).with_guardrail(GuardrailSpec::new(
700            MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
701            Tolerance::Relative(0.1),
702        ));
703        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
704        // Refunds look 20% higher in the variant, beyond the 10% tolerance but far from proven.
705        let first = analyzer
706            .observe(&proportions((5000, 700), (5000, 1000)).with_metric(
707                "refunds",
708                Sample::proportion(5000, 50),
709                Sample::proportion(5000, 60),
710            ))
711            .unwrap();
712        assert!(!first.guardrails[0].breached && first.guardrails[0].harm > 0.0);
713        assert_eq!(first.decision, Decision::Continue);
714        // With more data the refunds estimate falls back within tolerance.
715        let second = analyzer
716            .observe(&proportions((10_000, 1400), (10_000, 2000)).with_metric(
717                "refunds",
718                Sample::proportion(10_000, 100),
719                Sample::proportion(10_000, 105),
720            ))
721            .unwrap();
722        assert!(second.guardrails[0].harm <= 0.0);
723        assert_eq!(second.decision, Decision::AdoptVariant);
724    }
725
726    #[test]
727    fn adoption_waits_for_every_guardrail_to_reach_the_minimum() {
728        let config = ExperimentConfig::new("t", signups()).with_guardrail(GuardrailSpec::new(
729            MetricSpec::proportion("unsubscribes", MetricDirection::LowerIsBetter),
730            Tolerance::Relative(0.1),
731        ));
732        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
733        // The guardrail counts unsubscribes among sign-ups, which lag the visitors.
734        let look = proportions((5000, 700), (5000, 1000)).with_metric(
735            "unsubscribes",
736            Sample::proportion(70, 1),
737            Sample::proportion(90, 1),
738        );
739        let report = analyzer.observe(&look).unwrap();
740        assert!(!report.guardrails[0].ready);
741        assert_eq!(report.decision, Decision::Continue);
742    }
743
744    #[test]
745    fn guardrail_budget_is_split_across_guardrails() {
746        let guardrail = |id: &str| {
747            GuardrailSpec::new(
748                MetricSpec::proportion(id, MetricDirection::LowerIsBetter),
749                Tolerance::Absolute(0.0),
750            )
751        };
752        let config = ExperimentConfig::new("t", signups())
753            .with_budget(ErrorBudget::new(0.05, 0.10))
754            .with_guardrail(guardrail("refunds"))
755            .with_guardrail(guardrail("complaints"));
756        let mut analyzer = ExperimentAnalyzer::new(config).unwrap();
757        let look = proportions((1000, 100), (1000, 100))
758            .with_metric("refunds", Sample::proportion(1000, 10), Sample::proportion(1000, 10))
759            .with_metric("complaints", Sample::proportion(1000, 5), Sample::proportion(1000, 5));
760        let report = analyzer.observe(&look).unwrap();
761        assert!(report.guardrails.iter().all(|guardrail| guardrail.alpha == 0.05));
762    }
763
764    #[test]
765    fn resume_continues_the_running_p_values() {
766        let config = ExperimentConfig::new("t", signups());
767        let mut analyzer = ExperimentAnalyzer::new(config.clone()).unwrap();
768        analyzer.observe(&proportions((1000, 100), (1000, 130))).unwrap();
769        let saved = serde_json::to_string(analyzer.state()).unwrap();
770        let state: ExperimentState = serde_json::from_str(&saved).unwrap();
771        let mut resumed = ExperimentAnalyzer::resume(config.clone(), state).unwrap();
772        let next = proportions((2000, 200), (2000, 230));
773        let (resumed_report, report) =
774            (resumed.observe(&next).unwrap(), analyzer.observe(&next).unwrap());
775        assert_eq!(resumed_report.decision, report.decision);
776        let p_value = |report: &ExperimentReport| match report.primary.evidence {
777            Evidence::Sequential { p_value, .. } => p_value,
778            Evidence::Bayesian { .. } => panic!("sequential evidence"),
779        };
780        // JSON keeps floats to within the last digit.
781        assert!((p_value(&resumed_report) - p_value(&report)).abs() < 1e-12);
782
783        let other = ExperimentConfig::new("other", signups());
784        assert!(ExperimentAnalyzer::resume(other, resumed.state().clone()).is_err());
785        let more_guardrails = config.with_guardrail(GuardrailSpec::new(
786            MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
787            Tolerance::Absolute(0.0),
788        ));
789        assert!(ExperimentAnalyzer::resume(more_guardrails, resumed.state().clone()).is_err());
790    }
791}