use std::fmt;
use serde::{Deserialize, Serialize};
use super::config::{MetricDirection, MetricKind, Tolerance};
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct Interval {
pub lower: f64,
pub upper: f64,
pub level: f64,
}
impl Interval {
pub(crate) fn around(center: f64, half_width: f64, level: f64) -> Self {
Self { lower: center - half_width, upper: center + half_width, level }
}
pub fn contains(&self, value: f64) -> bool {
self.lower <= value && value <= self.upper
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct EffectEstimate {
pub control: f64,
pub variant: f64,
pub difference: f64,
pub difference_interval: Option<Interval>,
pub relative_lift: Option<f64>,
pub relative_interval: Option<Interval>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "method")]
#[non_exhaustive]
pub enum Evidence {
#[serde(rename_all = "camelCase")]
Sequential {
p_value: f64,
z: f64,
critical_z: Option<f64>,
alpha: f64,
},
#[serde(rename_all = "camelCase")]
Bayesian {
probability_variant_better: f64,
expected_loss_adopt: f64,
expected_loss_keep: f64,
decision_probability: f64,
},
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct PrimaryAnalysis {
pub metric: String,
pub kind: MetricKind,
pub direction: MetricDirection,
pub control_units: u64,
pub variant_units: u64,
pub ready: bool,
pub effect: EffectEstimate,
pub evidence: Evidence,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct GuardrailAnalysis {
pub metric: String,
pub kind: MetricKind,
pub direction: MetricDirection,
pub tolerance: Tolerance,
pub control_units: u64,
pub variant_units: u64,
pub ready: bool,
pub effect: EffectEstimate,
pub harm: f64,
pub harm_lower_bound: Option<f64>,
pub p_value: f64,
pub alpha: f64,
pub breached: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "outcome")]
#[non_exhaustive]
pub enum Decision {
Continue,
AdoptVariant,
KeepControl {
reason: StopReason,
},
}
impl Decision {
pub fn is_final(&self) -> bool {
!matches!(self, Self::Continue)
}
pub fn keeps_control(&self) -> bool {
matches!(self, Self::KeepControl { .. })
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", tag = "kind")]
#[non_exhaustive]
pub enum StopReason {
#[serde(rename_all = "camelCase")]
GuardrailBreach {
guardrails: Vec<String>,
},
VariantWorse,
SampleLimitReached,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ExperimentReport {
pub experiment_id: String,
pub look: u32,
pub primary: PrimaryAnalysis,
pub guardrails: Vec<GuardrailAnalysis>,
pub decision: Decision,
}
impl fmt::Display for Decision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Continue => f.write_str("continue"),
Self::AdoptVariant => f.write_str("adopt the variant"),
Self::KeepControl { reason } => write!(f, "keep the control — {reason}"),
}
}
}
impl fmt::Display for StopReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::GuardrailBreach { guardrails } => {
write!(f, "guardrail breached: {}", guardrails.join(", "))
}
Self::VariantWorse => f.write_str("the variant is worse on the primary metric"),
Self::SampleLimitReached => f.write_str("sample limit reached without a decision"),
}
}
}
impl fmt::Display for MetricDirection {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::HigherIsBetter => f.write_str("higher is better"),
Self::LowerIsBetter => f.write_str("lower is better"),
}
}
}
fn value(kind: MetricKind, value: f64) -> String {
match kind {
MetricKind::Proportion => format!("{:.2}%", value * 100.0),
MetricKind::Mean => format!("{value:.4}"),
}
}
fn difference(kind: MetricKind, value: f64) -> String {
match kind {
MetricKind::Proportion => format!("{:+.2} pp", value * 100.0),
MetricKind::Mean => format!("{value:+.4}"),
}
}
fn level(interval: &Interval) -> String {
format!("{}%", (interval.level * 100.0 * 10.0).round() / 10.0)
}
fn write_effect(
f: &mut fmt::Formatter<'_>,
kind: MetricKind,
effect: &EffectEstimate,
) -> fmt::Result {
write!(f, " difference {}", difference(kind, effect.difference))?;
if let Some(interval) = &effect.difference_interval {
write!(
f,
", {} interval [{}, {}]",
level(interval),
difference(kind, interval.lower),
difference(kind, interval.upper)
)?;
}
if let Some(lift) = effect.relative_lift {
write!(f, "; relative lift {:+.1}%", lift * 100.0)?;
if let Some(interval) = &effect.relative_interval {
write!(
f,
", {} interval [{:+.1}%, {:+.1}%]",
level(interval),
interval.lower * 100.0,
interval.upper * 100.0
)?;
}
}
writeln!(f)
}
impl fmt::Display for ExperimentReport {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "Experiment '{}', look {}: {}", self.experiment_id, self.look, self.decision)?;
let primary = &self.primary;
writeln!(
f,
"Primary {} ({}): control {} of {}, variant {} of {}",
primary.metric,
primary.direction,
value(primary.kind, primary.effect.control),
primary.control_units,
value(primary.kind, primary.effect.variant),
primary.variant_units
)?;
write_effect(f, primary.kind, &primary.effect)?;
match primary.evidence {
Evidence::Sequential { p_value, z, critical_z, alpha } => {
write!(f, " always-valid p {p_value:.4} against alpha {alpha}; z {z:.2}")?;
match critical_z {
Some(critical) => writeln!(f, " against {critical:.2}")?,
None => writeln!(f, ", below the minimum units")?,
}
}
Evidence::Bayesian {
probability_variant_better,
expected_loss_adopt,
expected_loss_keep,
decision_probability,
} => writeln!(
f,
" P(variant better) {probability_variant_better:.4} against \
{decision_probability}; expected loss {} adopting, {} keeping",
difference(primary.kind, expected_loss_adopt),
difference(primary.kind, expected_loss_keep)
)?,
}
for guardrail in &self.guardrails {
let tolerance = match guardrail.tolerance {
Tolerance::Absolute(margin) => {
format!("{} absolute", difference(guardrail.kind, margin))
}
Tolerance::Relative(share) => format!("{:.1}% relative", share * 100.0),
};
writeln!(
f,
"Guardrail {} ({}, tolerance {tolerance}): control {} of {}, variant {} of {}",
guardrail.metric,
guardrail.direction,
value(guardrail.kind, guardrail.effect.control),
guardrail.control_units,
value(guardrail.kind, guardrail.effect.variant),
guardrail.variant_units
)?;
write_effect(f, guardrail.kind, &guardrail.effect)?;
write!(f, " harm beyond tolerance {}", difference(guardrail.kind, guardrail.harm))?;
if let Some(bound) = guardrail.harm_lower_bound {
write!(f, ", lower bound {}", difference(guardrail.kind, bound))?;
}
writeln!(
f,
"; always-valid p {:.4} against alpha {:.4}: {}",
guardrail.p_value,
guardrail.alpha,
if guardrail.breached { "breached" } else { "holding" }
)?;
}
Ok(())
}
}