Skip to main content

adk_eval/experiments/
report.rs

1//! The analysis of one look: effect estimates, evidence, guardrails and the decision
2//! (spec 3.5 §7.12, A-I15).
3
4use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use super::config::{MetricDirection, MetricKind, Tolerance};
9
10/// An interval estimate of an effect (spec 3.5 §7.12).
11///
12/// Sequential analyses report a confidence sequence, which covers the true effect at every look
13/// at once with probability `level`; the Bayesian analysis reports a credible interval.
14#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16#[non_exhaustive]
17pub struct Interval {
18    /// The lower end.
19    pub lower: f64,
20    /// The upper end.
21    pub upper: f64,
22    /// The coverage level, such as 0.95.
23    pub level: f64,
24}
25
26impl Interval {
27    pub(crate) fn around(center: f64, half_width: f64, level: f64) -> Self {
28        Self { lower: center - half_width, upper: center + half_width, level }
29    }
30
31    /// Returns whether `value` lies in the interval, ends included.
32    pub fn contains(&self, value: f64) -> bool {
33        self.lower <= value && value <= self.upper
34    }
35}
36
37/// The effect of the variant on one metric (spec 3.5 §7.12).
38///
39/// Differences are variant minus control in the metric's units: a rate for a proportion, a
40/// mean for a mean. Intervals are `None` until both arms reach the minimum units.
41#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct EffectEstimate {
45    /// The control's estimate.
46    pub control: f64,
47    /// The variant's estimate.
48    pub variant: f64,
49    /// Variant minus control.
50    pub difference: f64,
51    /// The interval of the difference.
52    pub difference_interval: Option<Interval>,
53    /// The difference relative to the control; `None` when the control's estimate is zero.
54    pub relative_lift: Option<f64>,
55    /// The interval of the relative lift, by the delta method.
56    pub relative_interval: Option<Interval>,
57}
58
59/// The evidence behind the primary metric's verdict (spec 3.5 §7.12, §13 Q8).
60#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase", tag = "method")]
62#[non_exhaustive]
63pub enum Evidence {
64    /// The always-valid sequential test.
65    #[serde(rename_all = "camelCase")]
66    Sequential {
67        /// The always-valid p-value: the running minimum over every look so far.
68        p_value: f64,
69        /// This look's z statistic.
70        z: f64,
71        /// The |z| this look needs; `None` until both arms reach the minimum units.
72        critical_z: Option<f64>,
73        /// The test's error budget.
74        alpha: f64,
75    },
76    /// The Bayesian analysis.
77    #[serde(rename_all = "camelCase")]
78    Bayesian {
79        /// The posterior probability that the variant is better than the control.
80        probability_variant_better: f64,
81        /// The expected loss, in the metric's units, of adopting the variant.
82        expected_loss_adopt: f64,
83        /// The expected loss, in the metric's units, of keeping the control.
84        expected_loss_keep: f64,
85        /// The probability needed to decide.
86        decision_probability: f64,
87    },
88}
89
90/// The analysis of the primary metric at one look (spec 3.5 §7.12).
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93#[non_exhaustive]
94pub struct PrimaryAnalysis {
95    /// The metric's id.
96    pub metric: String,
97    /// How the metric is measured.
98    pub kind: MetricKind,
99    /// Which way the metric improves.
100    pub direction: MetricDirection,
101    /// Units in the control.
102    pub control_units: u64,
103    /// Units in the variant.
104    pub variant_units: u64,
105    /// Whether both arms reached the minimum units, so the test may decide.
106    pub ready: bool,
107    /// The variant's effect.
108    pub effect: EffectEstimate,
109    /// The evidence for a decision.
110    pub evidence: Evidence,
111}
112
113/// The analysis of one guardrail at one look (spec 3.5 §7.12, A-I15).
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub struct GuardrailAnalysis {
118    /// The metric's id.
119    pub metric: String,
120    /// How the metric is measured.
121    pub kind: MetricKind,
122    /// Which way the metric improves.
123    pub direction: MetricDirection,
124    /// How much worse than the control the variant may be.
125    pub tolerance: Tolerance,
126    /// Units in the control.
127    pub control_units: u64,
128    /// Units in the variant.
129    pub variant_units: u64,
130    /// Whether both arms reached the minimum units, so the guardrail may be breached.
131    pub ready: bool,
132    /// The variant's effect, with intervals at the guardrail's budget.
133    pub effect: EffectEstimate,
134    /// The estimated harm beyond the tolerance, in the metric's units; positive means worse
135    /// than tolerated.
136    pub harm: f64,
137    /// The always-valid lower confidence bound of the harm; `None` until ready.
138    pub harm_lower_bound: Option<f64>,
139    /// The always-valid one-sided p-value of "harm within tolerance": the running minimum.
140    pub p_value: f64,
141    /// This guardrail's share of the guardrail error budget.
142    pub alpha: f64,
143    /// Whether the guardrail is breached.
144    pub breached: bool,
145}
146
147/// What the experiment should do after a look (spec 3.5 §7.12, A-I15).
148///
149/// Every decision other than [`Decision::Continue`] is final: the analyzer returns the same
150/// report for every later look.
151#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase", tag = "outcome")]
153#[non_exhaustive]
154pub enum Decision {
155    /// Keep collecting data.
156    Continue,
157    /// The variant is better on the primary metric, no guardrail is breached, and every
158    /// guardrail's estimated harm is within its tolerance.
159    AdoptVariant,
160    /// Stop and keep the control.
161    KeepControl {
162        /// Why the control is kept.
163        reason: StopReason,
164    },
165}
166
167impl Decision {
168    /// Returns whether the experiment has stopped.
169    pub fn is_final(&self) -> bool {
170        !matches!(self, Self::Continue)
171    }
172
173    /// Returns whether the experiment stopped keeping the control.
174    pub fn keeps_control(&self) -> bool {
175        matches!(self, Self::KeepControl { .. })
176    }
177}
178
179/// Why an experiment kept the control (spec 3.5 §7.12, A-I15).
180#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(rename_all = "camelCase", tag = "kind")]
182#[non_exhaustive]
183pub enum StopReason {
184    /// One or more guardrails were breached; this overrides the primary metric (A-I15).
185    #[serde(rename_all = "camelCase")]
186    GuardrailBreach {
187        /// The breached guardrails' metric ids.
188        guardrails: Vec<String>,
189    },
190    /// The variant is worse on the primary metric.
191    VariantWorse,
192    /// Both arms reached the maximum units without a decision.
193    SampleLimitReached,
194}
195
196/// The analysis of one look at an experiment: the decision and its evidence (spec 3.5 §7.12).
197///
198/// Its [`Display`](fmt::Display) form is the evidence block the weekly review shows.
199#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct ExperimentReport {
203    /// The experiment's id.
204    pub experiment_id: String,
205    /// The look this report analyses, counted from 1.
206    pub look: u32,
207    /// The primary metric.
208    pub primary: PrimaryAnalysis,
209    /// Every guardrail, in configuration order.
210    pub guardrails: Vec<GuardrailAnalysis>,
211    /// What the experiment should do.
212    pub decision: Decision,
213}
214
215impl fmt::Display for Decision {
216    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
217        match self {
218            Self::Continue => f.write_str("continue"),
219            Self::AdoptVariant => f.write_str("adopt the variant"),
220            Self::KeepControl { reason } => write!(f, "keep the control — {reason}"),
221        }
222    }
223}
224
225impl fmt::Display for StopReason {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        match self {
228            Self::GuardrailBreach { guardrails } => {
229                write!(f, "guardrail breached: {}", guardrails.join(", "))
230            }
231            Self::VariantWorse => f.write_str("the variant is worse on the primary metric"),
232            Self::SampleLimitReached => f.write_str("sample limit reached without a decision"),
233        }
234    }
235}
236
237impl fmt::Display for MetricDirection {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        match self {
240            Self::HigherIsBetter => f.write_str("higher is better"),
241            Self::LowerIsBetter => f.write_str("lower is better"),
242        }
243    }
244}
245
246/// Formats a value in the metric's units: a rate as a percentage, a mean as a number.
247fn value(kind: MetricKind, value: f64) -> String {
248    match kind {
249        MetricKind::Proportion => format!("{:.2}%", value * 100.0),
250        MetricKind::Mean => format!("{value:.4}"),
251    }
252}
253
254/// Formats a difference in the metric's units: percentage points for a rate.
255fn difference(kind: MetricKind, value: f64) -> String {
256    match kind {
257        MetricKind::Proportion => format!("{:+.2} pp", value * 100.0),
258        MetricKind::Mean => format!("{value:+.4}"),
259    }
260}
261
262fn level(interval: &Interval) -> String {
263    format!("{}%", (interval.level * 100.0 * 10.0).round() / 10.0)
264}
265
266fn write_effect(
267    f: &mut fmt::Formatter<'_>,
268    kind: MetricKind,
269    effect: &EffectEstimate,
270) -> fmt::Result {
271    write!(f, "  difference {}", difference(kind, effect.difference))?;
272    if let Some(interval) = &effect.difference_interval {
273        write!(
274            f,
275            ", {} interval [{}, {}]",
276            level(interval),
277            difference(kind, interval.lower),
278            difference(kind, interval.upper)
279        )?;
280    }
281    if let Some(lift) = effect.relative_lift {
282        write!(f, "; relative lift {:+.1}%", lift * 100.0)?;
283        if let Some(interval) = &effect.relative_interval {
284            write!(
285                f,
286                ", {} interval [{:+.1}%, {:+.1}%]",
287                level(interval),
288                interval.lower * 100.0,
289                interval.upper * 100.0
290            )?;
291        }
292    }
293    writeln!(f)
294}
295
296impl fmt::Display for ExperimentReport {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        writeln!(f, "Experiment '{}', look {}: {}", self.experiment_id, self.look, self.decision)?;
299        let primary = &self.primary;
300        writeln!(
301            f,
302            "Primary {} ({}): control {} of {}, variant {} of {}",
303            primary.metric,
304            primary.direction,
305            value(primary.kind, primary.effect.control),
306            primary.control_units,
307            value(primary.kind, primary.effect.variant),
308            primary.variant_units
309        )?;
310        write_effect(f, primary.kind, &primary.effect)?;
311        match primary.evidence {
312            Evidence::Sequential { p_value, z, critical_z, alpha } => {
313                write!(f, "  always-valid p {p_value:.4} against alpha {alpha}; z {z:.2}")?;
314                match critical_z {
315                    Some(critical) => writeln!(f, " against {critical:.2}")?,
316                    None => writeln!(f, ", below the minimum units")?,
317                }
318            }
319            Evidence::Bayesian {
320                probability_variant_better,
321                expected_loss_adopt,
322                expected_loss_keep,
323                decision_probability,
324            } => writeln!(
325                f,
326                "  P(variant better) {probability_variant_better:.4} against \
327                 {decision_probability}; expected loss {} adopting, {} keeping",
328                difference(primary.kind, expected_loss_adopt),
329                difference(primary.kind, expected_loss_keep)
330            )?,
331        }
332        for guardrail in &self.guardrails {
333            let tolerance = match guardrail.tolerance {
334                Tolerance::Absolute(margin) => {
335                    format!("{} absolute", difference(guardrail.kind, margin))
336                }
337                Tolerance::Relative(share) => format!("{:.1}% relative", share * 100.0),
338            };
339            writeln!(
340                f,
341                "Guardrail {} ({}, tolerance {tolerance}): control {} of {}, variant {} of {}",
342                guardrail.metric,
343                guardrail.direction,
344                value(guardrail.kind, guardrail.effect.control),
345                guardrail.control_units,
346                value(guardrail.kind, guardrail.effect.variant),
347                guardrail.variant_units
348            )?;
349            write_effect(f, guardrail.kind, &guardrail.effect)?;
350            write!(f, "  harm beyond tolerance {}", difference(guardrail.kind, guardrail.harm))?;
351            if let Some(bound) = guardrail.harm_lower_bound {
352                write!(f, ", lower bound {}", difference(guardrail.kind, bound))?;
353            }
354            writeln!(
355                f,
356                "; always-valid p {:.4} against alpha {:.4}: {}",
357                guardrail.p_value,
358                guardrail.alpha,
359                if guardrail.breached { "breached" } else { "holding" }
360            )?;
361        }
362        Ok(())
363    }
364}