1use std::fmt;
5
6use serde::{Deserialize, Serialize};
7
8use super::config::{MetricDirection, MetricKind, Tolerance};
9
10#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
15#[serde(rename_all = "camelCase")]
16#[non_exhaustive]
17pub struct Interval {
18 pub lower: f64,
20 pub upper: f64,
22 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 pub fn contains(&self, value: f64) -> bool {
33 self.lower <= value && value <= self.upper
34 }
35}
36
37#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43#[non_exhaustive]
44pub struct EffectEstimate {
45 pub control: f64,
47 pub variant: f64,
49 pub difference: f64,
51 pub difference_interval: Option<Interval>,
53 pub relative_lift: Option<f64>,
55 pub relative_interval: Option<Interval>,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
61#[serde(rename_all = "camelCase", tag = "method")]
62#[non_exhaustive]
63pub enum Evidence {
64 #[serde(rename_all = "camelCase")]
66 Sequential {
67 p_value: f64,
69 z: f64,
71 critical_z: Option<f64>,
73 alpha: f64,
75 },
76 #[serde(rename_all = "camelCase")]
78 Bayesian {
79 probability_variant_better: f64,
81 expected_loss_adopt: f64,
83 expected_loss_keep: f64,
85 decision_probability: f64,
87 },
88}
89
90#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
92#[serde(rename_all = "camelCase")]
93#[non_exhaustive]
94pub struct PrimaryAnalysis {
95 pub metric: String,
97 pub kind: MetricKind,
99 pub direction: MetricDirection,
101 pub control_units: u64,
103 pub variant_units: u64,
105 pub ready: bool,
107 pub effect: EffectEstimate,
109 pub evidence: Evidence,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116#[non_exhaustive]
117pub struct GuardrailAnalysis {
118 pub metric: String,
120 pub kind: MetricKind,
122 pub direction: MetricDirection,
124 pub tolerance: Tolerance,
126 pub control_units: u64,
128 pub variant_units: u64,
130 pub ready: bool,
132 pub effect: EffectEstimate,
134 pub harm: f64,
137 pub harm_lower_bound: Option<f64>,
139 pub p_value: f64,
141 pub alpha: f64,
143 pub breached: bool,
145}
146
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
152#[serde(rename_all = "camelCase", tag = "outcome")]
153#[non_exhaustive]
154pub enum Decision {
155 Continue,
157 AdoptVariant,
160 KeepControl {
162 reason: StopReason,
164 },
165}
166
167impl Decision {
168 pub fn is_final(&self) -> bool {
170 !matches!(self, Self::Continue)
171 }
172
173 pub fn keeps_control(&self) -> bool {
175 matches!(self, Self::KeepControl { .. })
176 }
177}
178
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
181#[serde(rename_all = "camelCase", tag = "kind")]
182#[non_exhaustive]
183pub enum StopReason {
184 #[serde(rename_all = "camelCase")]
186 GuardrailBreach {
187 guardrails: Vec<String>,
189 },
190 VariantWorse,
192 SampleLimitReached,
194}
195
196#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
200#[serde(rename_all = "camelCase")]
201#[non_exhaustive]
202pub struct ExperimentReport {
203 pub experiment_id: String,
205 pub look: u32,
207 pub primary: PrimaryAnalysis,
209 pub guardrails: Vec<GuardrailAnalysis>,
211 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
246fn 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
254fn 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}