use serde::{Deserialize, Serialize};
use crate::error::{EvalError, Result};
pub const DEFAULT_ALPHA: f64 = 0.05;
pub const DEFAULT_GUARDRAIL_ALPHA: f64 = 0.10;
pub const DEFAULT_PLANNED_UNITS_PER_ARM: u64 = 10_000;
pub const DEFAULT_MIN_UNITS_PER_ARM: u64 = 100;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum MetricKind {
Proportion,
Mean,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum MetricDirection {
HigherIsBetter,
LowerIsBetter,
}
impl MetricDirection {
pub(crate) fn sign(self) -> f64 {
match self {
Self::HigherIsBetter => 1.0,
Self::LowerIsBetter => -1.0,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct MetricSpec {
pub id: String,
pub kind: MetricKind,
pub direction: MetricDirection,
}
impl MetricSpec {
pub fn new(id: impl Into<String>, kind: MetricKind, direction: MetricDirection) -> Self {
Self { id: id.into(), kind, direction }
}
pub fn proportion(id: impl Into<String>, direction: MetricDirection) -> Self {
Self::new(id, MetricKind::Proportion, direction)
}
pub fn mean(id: impl Into<String>, direction: MetricDirection) -> Self {
Self::new(id, MetricKind::Mean, direction)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum Tolerance {
Absolute(f64),
Relative(f64),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct GuardrailSpec {
pub metric: MetricSpec,
pub tolerance: Tolerance,
}
impl GuardrailSpec {
pub fn new(metric: MetricSpec, tolerance: Tolerance) -> Self {
Self { metric, tolerance }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ErrorBudget {
pub alpha: f64,
pub guardrail_alpha: f64,
}
impl ErrorBudget {
pub fn new(alpha: f64, guardrail_alpha: f64) -> Self {
Self { alpha, guardrail_alpha }
}
}
impl Default for ErrorBudget {
fn default() -> Self {
Self::new(DEFAULT_ALPHA, DEFAULT_GUARDRAIL_ALPHA)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BetaPrior {
pub alpha: f64,
pub beta: f64,
}
impl BetaPrior {
pub fn new(alpha: f64, beta: f64) -> Self {
Self { alpha, beta }
}
}
impl Default for BetaPrior {
fn default() -> Self {
Self::new(1.0, 1.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct BayesianConfig {
pub prior: BetaPrior,
pub decision_probability: f64,
pub max_expected_loss: Option<f64>,
pub credible_level: f64,
}
impl BayesianConfig {
pub fn with_prior(mut self, prior: BetaPrior) -> Self {
self.prior = prior;
self
}
pub fn with_decision_probability(mut self, probability: f64) -> Self {
self.decision_probability = probability;
self
}
pub fn with_max_expected_loss(mut self, loss: f64) -> Self {
self.max_expected_loss = Some(loss);
self
}
pub fn with_credible_level(mut self, level: f64) -> Self {
self.credible_level = level;
self
}
}
impl Default for BayesianConfig {
fn default() -> Self {
Self {
prior: BetaPrior::default(),
decision_probability: 0.95,
max_expected_loss: None,
credible_level: 0.95,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum AnalysisMethod {
#[default]
Sequential,
Bayesian(BayesianConfig),
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub struct ExperimentConfig {
pub id: String,
pub primary: MetricSpec,
pub guardrails: Vec<GuardrailSpec>,
pub budget: ErrorBudget,
pub method: AnalysisMethod,
pub planned_units_per_arm: u64,
pub min_units_per_arm: u64,
pub max_units_per_arm: Option<u64>,
}
impl ExperimentConfig {
pub fn new(id: impl Into<String>, primary: MetricSpec) -> Self {
Self {
id: id.into(),
primary,
guardrails: Vec::new(),
budget: ErrorBudget::default(),
method: AnalysisMethod::default(),
planned_units_per_arm: DEFAULT_PLANNED_UNITS_PER_ARM,
min_units_per_arm: DEFAULT_MIN_UNITS_PER_ARM,
max_units_per_arm: None,
}
}
pub fn with_guardrail(mut self, guardrail: GuardrailSpec) -> Self {
self.guardrails.push(guardrail);
self
}
pub fn with_budget(mut self, budget: ErrorBudget) -> Self {
self.budget = budget;
self
}
pub fn with_method(mut self, method: AnalysisMethod) -> Self {
self.method = method;
self
}
pub fn with_planned_units_per_arm(mut self, units: u64) -> Self {
self.planned_units_per_arm = units;
self
}
pub fn with_min_units_per_arm(mut self, units: u64) -> Self {
self.min_units_per_arm = units;
self
}
pub fn with_max_units_per_arm(mut self, units: u64) -> Self {
self.max_units_per_arm = Some(units);
self
}
pub fn validate(&self) -> Result<()> {
let invalid = |message: String| Err(EvalError::ConfigError(message));
if self.id.trim().is_empty() {
return invalid("experiment id is empty; give the experiment a stable id".into());
}
let mut ids = vec![self.primary.id.as_str()];
for guardrail in &self.guardrails {
ids.push(guardrail.metric.id.as_str());
}
for (index, id) in ids.iter().enumerate() {
if id.trim().is_empty() {
return invalid(format!("experiment '{}' has a metric with an empty id", self.id));
}
if ids[..index].contains(id) {
return invalid(format!(
"experiment '{}' names metric '{id}' twice; the primary metric and each \
guardrail need distinct metric ids",
self.id
));
}
}
for (name, value) in
[("alpha", self.budget.alpha), ("guardrail_alpha", self.budget.guardrail_alpha)]
{
if !(value > 0.0 && value <= 0.5) {
return invalid(format!(
"experiment '{}' has {name} = {value}; an error budget must lie in (0, 0.5]",
self.id
));
}
}
for guardrail in &self.guardrails {
let metric = &guardrail.metric.id;
match guardrail.tolerance {
Tolerance::Absolute(margin) => {
if !(margin.is_finite() && margin >= 0.0) {
return invalid(format!(
"guardrail '{metric}' has absolute tolerance {margin}; use a finite \
margin of zero or more"
));
}
if guardrail.metric.kind == MetricKind::Proportion && margin >= 1.0 {
return invalid(format!(
"guardrail '{metric}' tolerates an absolute change of {margin} in a \
proportion, which can never be breached; use a margin below 1"
));
}
}
Tolerance::Relative(share) => {
if !(share.is_finite() && share >= 0.0) {
return invalid(format!(
"guardrail '{metric}' has relative tolerance {share}; use a finite \
share of zero or more"
));
}
if guardrail.metric.direction == MetricDirection::HigherIsBetter && share >= 1.0
{
return invalid(format!(
"guardrail '{metric}' tolerates a relative drop of {share} in a metric \
where higher is better, which can never be breached; use a share \
below 1"
));
}
}
}
}
if self.min_units_per_arm < 2 {
return invalid(format!(
"experiment '{}' has min_units_per_arm = {}; at least 2 units per arm are needed \
to estimate a variance",
self.id, self.min_units_per_arm
));
}
if self.planned_units_per_arm < self.min_units_per_arm {
return invalid(format!(
"experiment '{}' plans {} units per arm, fewer than its minimum of {}",
self.id, self.planned_units_per_arm, self.min_units_per_arm
));
}
if let Some(max) = self.max_units_per_arm
&& max < self.min_units_per_arm
{
return invalid(format!(
"experiment '{}' stops at {max} units per arm, before its minimum of {} lets any \
test decide",
self.id, self.min_units_per_arm
));
}
match self.method {
AnalysisMethod::Sequential => {}
AnalysisMethod::Bayesian(bayes) => {
let prior = bayes.prior;
if !(prior.alpha.is_finite()
&& prior.alpha > 0.0
&& prior.beta.is_finite()
&& prior.beta > 0.0)
{
return invalid(format!(
"experiment '{}' has prior Beta({}, {}); both parameters must be finite \
and positive",
self.id, prior.alpha, prior.beta
));
}
if !(bayes.decision_probability > 0.5 && bayes.decision_probability < 1.0) {
return invalid(format!(
"experiment '{}' has decision_probability = {}; use a value in (0.5, 1)",
self.id, bayes.decision_probability
));
}
if !(bayes.credible_level > 0.0 && bayes.credible_level < 1.0) {
return invalid(format!(
"experiment '{}' has credible_level = {}; use a value in (0, 1)",
self.id, bayes.credible_level
));
}
if let Some(loss) = bayes.max_expected_loss
&& !(loss.is_finite() && loss >= 0.0)
{
return invalid(format!(
"experiment '{}' has max_expected_loss = {loss}; use a finite loss of \
zero or more",
self.id
));
}
}
}
Ok(())
}
pub(crate) fn alpha_per_guardrail(&self) -> f64 {
self.budget.guardrail_alpha / self.guardrails.len().max(1) as f64
}
}
#[cfg(test)]
mod tests {
use super::*;
fn base() -> ExperimentConfig {
ExperimentConfig::new(
"headline",
MetricSpec::proportion("signups", MetricDirection::HigherIsBetter),
)
}
fn message(config: &ExperimentConfig) -> String {
match config.validate() {
Err(EvalError::ConfigError(message)) => message,
other => panic!("expected a configuration error, got {other:?}"),
}
}
#[test]
fn defaults_are_valid() {
assert!(base().validate().is_ok());
let bayes = base().with_method(AnalysisMethod::Bayesian(BayesianConfig::default()));
assert!(bayes.validate().is_ok());
}
#[test]
fn repeated_metric_ids_are_refused() {
let config = base().with_guardrail(GuardrailSpec::new(
MetricSpec::proportion("signups", MetricDirection::LowerIsBetter),
Tolerance::Absolute(0.0),
));
assert!(message(&config).contains("names metric 'signups' twice"));
}
#[test]
fn budgets_outside_the_open_interval_are_refused() {
for alpha in [0.0, -0.1, 0.6, f64::NAN] {
let config = base().with_budget(ErrorBudget::new(alpha, 0.1));
assert!(message(&config).contains("alpha"), "alpha {alpha}");
let config = base().with_budget(ErrorBudget::new(0.05, alpha));
assert!(message(&config).contains("guardrail_alpha"), "guardrail alpha {alpha}");
}
}
#[test]
fn unbreachable_tolerances_are_refused() {
let drop = base().with_guardrail(GuardrailSpec::new(
MetricSpec::mean("revenue", MetricDirection::HigherIsBetter),
Tolerance::Relative(1.0),
));
assert!(message(&drop).contains("can never be breached"));
let absolute = base().with_guardrail(GuardrailSpec::new(
MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
Tolerance::Absolute(1.0),
));
assert!(message(&absolute).contains("can never be breached"));
let negative = base().with_guardrail(GuardrailSpec::new(
MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
Tolerance::Relative(-0.1),
));
assert!(message(&negative).contains("relative tolerance"));
}
#[test]
fn sizes_out_of_order_are_refused() {
assert!(message(&base().with_min_units_per_arm(1)).contains("at least 2"));
assert!(message(&base().with_planned_units_per_arm(50)).contains("plans 50"));
assert!(message(&base().with_max_units_per_arm(50)).contains("stops at 50"));
}
#[test]
fn bayesian_settings_out_of_range_are_refused() {
let with = |bayes: BayesianConfig| base().with_method(AnalysisMethod::Bayesian(bayes));
let prior = BayesianConfig::default().with_prior(BetaPrior::new(0.0, 1.0));
assert!(message(&with(prior)).contains("prior"));
let probability = BayesianConfig::default().with_decision_probability(0.5);
assert!(message(&with(probability)).contains("decision_probability"));
let level = BayesianConfig::default().with_credible_level(1.0);
assert!(message(&with(level)).contains("credible_level"));
let loss = BayesianConfig::default().with_max_expected_loss(-1.0);
assert!(message(&with(loss)).contains("max_expected_loss"));
}
}