1use serde::{Deserialize, Serialize};
5
6use crate::error::{EvalError, Result};
7
8pub const DEFAULT_ALPHA: f64 = 0.05;
10
11pub const DEFAULT_GUARDRAIL_ALPHA: f64 = 0.10;
16
17pub const DEFAULT_PLANNED_UNITS_PER_ARM: u64 = 10_000;
19
20pub const DEFAULT_MIN_UNITS_PER_ARM: u64 = 100;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "camelCase")]
26#[non_exhaustive]
27pub enum MetricKind {
28 Proportion,
30 Mean,
32}
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "camelCase")]
40pub enum MetricDirection {
41 HigherIsBetter,
43 LowerIsBetter,
45}
46
47impl MetricDirection {
48 pub(crate) fn sign(self) -> f64 {
50 match self {
51 Self::HigherIsBetter => 1.0,
52 Self::LowerIsBetter => -1.0,
53 }
54 }
55}
56
57#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase")]
69#[non_exhaustive]
70pub struct MetricSpec {
71 pub id: String,
73 pub kind: MetricKind,
75 pub direction: MetricDirection,
77}
78
79impl MetricSpec {
80 pub fn new(id: impl Into<String>, kind: MetricKind, direction: MetricDirection) -> Self {
82 Self { id: id.into(), kind, direction }
83 }
84
85 pub fn proportion(id: impl Into<String>, direction: MetricDirection) -> Self {
87 Self::new(id, MetricKind::Proportion, direction)
88 }
89
90 pub fn mean(id: impl Into<String>, direction: MetricDirection) -> Self {
92 Self::new(id, MetricKind::Mean, direction)
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100#[non_exhaustive]
101pub enum Tolerance {
102 Absolute(f64),
105 Relative(f64),
108}
109
110#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
126#[serde(rename_all = "camelCase")]
127#[non_exhaustive]
128pub struct GuardrailSpec {
129 pub metric: MetricSpec,
131 pub tolerance: Tolerance,
133}
134
135impl GuardrailSpec {
136 pub fn new(metric: MetricSpec, tolerance: Tolerance) -> Self {
138 Self { metric, tolerance }
139 }
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
158#[serde(rename_all = "camelCase")]
159#[non_exhaustive]
160pub struct ErrorBudget {
161 pub alpha: f64,
163 pub guardrail_alpha: f64,
165}
166
167impl ErrorBudget {
168 pub fn new(alpha: f64, guardrail_alpha: f64) -> Self {
171 Self { alpha, guardrail_alpha }
172 }
173}
174
175impl Default for ErrorBudget {
176 fn default() -> Self {
177 Self::new(DEFAULT_ALPHA, DEFAULT_GUARDRAIL_ALPHA)
178 }
179}
180
181#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186#[non_exhaustive]
187pub struct BetaPrior {
188 pub alpha: f64,
190 pub beta: f64,
192}
193
194impl BetaPrior {
195 pub fn new(alpha: f64, beta: f64) -> Self {
197 Self { alpha, beta }
198 }
199}
200
201impl Default for BetaPrior {
202 fn default() -> Self {
203 Self::new(1.0, 1.0)
204 }
205}
206
207#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
218#[serde(rename_all = "camelCase")]
219#[non_exhaustive]
220pub struct BayesianConfig {
221 pub prior: BetaPrior,
223 pub decision_probability: f64,
225 pub max_expected_loss: Option<f64>,
228 pub credible_level: f64,
230}
231
232impl BayesianConfig {
233 pub fn with_prior(mut self, prior: BetaPrior) -> Self {
235 self.prior = prior;
236 self
237 }
238
239 pub fn with_decision_probability(mut self, probability: f64) -> Self {
241 self.decision_probability = probability;
242 self
243 }
244
245 pub fn with_max_expected_loss(mut self, loss: f64) -> Self {
247 self.max_expected_loss = Some(loss);
248 self
249 }
250
251 pub fn with_credible_level(mut self, level: f64) -> Self {
253 self.credible_level = level;
254 self
255 }
256}
257
258impl Default for BayesianConfig {
259 fn default() -> Self {
260 Self {
261 prior: BetaPrior::default(),
262 decision_probability: 0.95,
263 max_expected_loss: None,
264 credible_level: 0.95,
265 }
266 }
267}
268
269#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
274#[serde(rename_all = "camelCase")]
275#[non_exhaustive]
276pub enum AnalysisMethod {
277 #[default]
279 Sequential,
280 Bayesian(BayesianConfig),
283}
284
285#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308#[non_exhaustive]
309pub struct ExperimentConfig {
310 pub id: String,
312 pub primary: MetricSpec,
314 pub guardrails: Vec<GuardrailSpec>,
316 pub budget: ErrorBudget,
318 pub method: AnalysisMethod,
320 pub planned_units_per_arm: u64,
323 pub min_units_per_arm: u64,
325 pub max_units_per_arm: Option<u64>,
328}
329
330impl ExperimentConfig {
331 pub fn new(id: impl Into<String>, primary: MetricSpec) -> Self {
333 Self {
334 id: id.into(),
335 primary,
336 guardrails: Vec::new(),
337 budget: ErrorBudget::default(),
338 method: AnalysisMethod::default(),
339 planned_units_per_arm: DEFAULT_PLANNED_UNITS_PER_ARM,
340 min_units_per_arm: DEFAULT_MIN_UNITS_PER_ARM,
341 max_units_per_arm: None,
342 }
343 }
344
345 pub fn with_guardrail(mut self, guardrail: GuardrailSpec) -> Self {
347 self.guardrails.push(guardrail);
348 self
349 }
350
351 pub fn with_budget(mut self, budget: ErrorBudget) -> Self {
353 self.budget = budget;
354 self
355 }
356
357 pub fn with_method(mut self, method: AnalysisMethod) -> Self {
359 self.method = method;
360 self
361 }
362
363 pub fn with_planned_units_per_arm(mut self, units: u64) -> Self {
365 self.planned_units_per_arm = units;
366 self
367 }
368
369 pub fn with_min_units_per_arm(mut self, units: u64) -> Self {
371 self.min_units_per_arm = units;
372 self
373 }
374
375 pub fn with_max_units_per_arm(mut self, units: u64) -> Self {
377 self.max_units_per_arm = Some(units);
378 self
379 }
380
381 pub fn validate(&self) -> Result<()> {
389 let invalid = |message: String| Err(EvalError::ConfigError(message));
390 if self.id.trim().is_empty() {
391 return invalid("experiment id is empty; give the experiment a stable id".into());
392 }
393 let mut ids = vec![self.primary.id.as_str()];
394 for guardrail in &self.guardrails {
395 ids.push(guardrail.metric.id.as_str());
396 }
397 for (index, id) in ids.iter().enumerate() {
398 if id.trim().is_empty() {
399 return invalid(format!("experiment '{}' has a metric with an empty id", self.id));
400 }
401 if ids[..index].contains(id) {
402 return invalid(format!(
403 "experiment '{}' names metric '{id}' twice; the primary metric and each \
404 guardrail need distinct metric ids",
405 self.id
406 ));
407 }
408 }
409 for (name, value) in
410 [("alpha", self.budget.alpha), ("guardrail_alpha", self.budget.guardrail_alpha)]
411 {
412 if !(value > 0.0 && value <= 0.5) {
413 return invalid(format!(
414 "experiment '{}' has {name} = {value}; an error budget must lie in (0, 0.5]",
415 self.id
416 ));
417 }
418 }
419 for guardrail in &self.guardrails {
420 let metric = &guardrail.metric.id;
421 match guardrail.tolerance {
422 Tolerance::Absolute(margin) => {
423 if !(margin.is_finite() && margin >= 0.0) {
424 return invalid(format!(
425 "guardrail '{metric}' has absolute tolerance {margin}; use a finite \
426 margin of zero or more"
427 ));
428 }
429 if guardrail.metric.kind == MetricKind::Proportion && margin >= 1.0 {
430 return invalid(format!(
431 "guardrail '{metric}' tolerates an absolute change of {margin} in a \
432 proportion, which can never be breached; use a margin below 1"
433 ));
434 }
435 }
436 Tolerance::Relative(share) => {
437 if !(share.is_finite() && share >= 0.0) {
438 return invalid(format!(
439 "guardrail '{metric}' has relative tolerance {share}; use a finite \
440 share of zero or more"
441 ));
442 }
443 if guardrail.metric.direction == MetricDirection::HigherIsBetter && share >= 1.0
444 {
445 return invalid(format!(
446 "guardrail '{metric}' tolerates a relative drop of {share} in a metric \
447 where higher is better, which can never be breached; use a share \
448 below 1"
449 ));
450 }
451 }
452 }
453 }
454 if self.min_units_per_arm < 2 {
455 return invalid(format!(
456 "experiment '{}' has min_units_per_arm = {}; at least 2 units per arm are needed \
457 to estimate a variance",
458 self.id, self.min_units_per_arm
459 ));
460 }
461 if self.planned_units_per_arm < self.min_units_per_arm {
462 return invalid(format!(
463 "experiment '{}' plans {} units per arm, fewer than its minimum of {}",
464 self.id, self.planned_units_per_arm, self.min_units_per_arm
465 ));
466 }
467 if let Some(max) = self.max_units_per_arm
468 && max < self.min_units_per_arm
469 {
470 return invalid(format!(
471 "experiment '{}' stops at {max} units per arm, before its minimum of {} lets any \
472 test decide",
473 self.id, self.min_units_per_arm
474 ));
475 }
476 match self.method {
477 AnalysisMethod::Sequential => {}
478 AnalysisMethod::Bayesian(bayes) => {
479 let prior = bayes.prior;
480 if !(prior.alpha.is_finite()
481 && prior.alpha > 0.0
482 && prior.beta.is_finite()
483 && prior.beta > 0.0)
484 {
485 return invalid(format!(
486 "experiment '{}' has prior Beta({}, {}); both parameters must be finite \
487 and positive",
488 self.id, prior.alpha, prior.beta
489 ));
490 }
491 if !(bayes.decision_probability > 0.5 && bayes.decision_probability < 1.0) {
492 return invalid(format!(
493 "experiment '{}' has decision_probability = {}; use a value in (0.5, 1)",
494 self.id, bayes.decision_probability
495 ));
496 }
497 if !(bayes.credible_level > 0.0 && bayes.credible_level < 1.0) {
498 return invalid(format!(
499 "experiment '{}' has credible_level = {}; use a value in (0, 1)",
500 self.id, bayes.credible_level
501 ));
502 }
503 if let Some(loss) = bayes.max_expected_loss
504 && !(loss.is_finite() && loss >= 0.0)
505 {
506 return invalid(format!(
507 "experiment '{}' has max_expected_loss = {loss}; use a finite loss of \
508 zero or more",
509 self.id
510 ));
511 }
512 }
513 }
514 Ok(())
515 }
516
517 pub(crate) fn alpha_per_guardrail(&self) -> f64 {
519 self.budget.guardrail_alpha / self.guardrails.len().max(1) as f64
520 }
521}
522
523#[cfg(test)]
524mod tests {
525 use super::*;
526
527 fn base() -> ExperimentConfig {
528 ExperimentConfig::new(
529 "headline",
530 MetricSpec::proportion("signups", MetricDirection::HigherIsBetter),
531 )
532 }
533
534 fn message(config: &ExperimentConfig) -> String {
535 match config.validate() {
536 Err(EvalError::ConfigError(message)) => message,
537 other => panic!("expected a configuration error, got {other:?}"),
538 }
539 }
540
541 #[test]
542 fn defaults_are_valid() {
543 assert!(base().validate().is_ok());
544 let bayes = base().with_method(AnalysisMethod::Bayesian(BayesianConfig::default()));
545 assert!(bayes.validate().is_ok());
546 }
547
548 #[test]
549 fn repeated_metric_ids_are_refused() {
550 let config = base().with_guardrail(GuardrailSpec::new(
551 MetricSpec::proportion("signups", MetricDirection::LowerIsBetter),
552 Tolerance::Absolute(0.0),
553 ));
554 assert!(message(&config).contains("names metric 'signups' twice"));
555 }
556
557 #[test]
558 fn budgets_outside_the_open_interval_are_refused() {
559 for alpha in [0.0, -0.1, 0.6, f64::NAN] {
560 let config = base().with_budget(ErrorBudget::new(alpha, 0.1));
561 assert!(message(&config).contains("alpha"), "alpha {alpha}");
562 let config = base().with_budget(ErrorBudget::new(0.05, alpha));
563 assert!(message(&config).contains("guardrail_alpha"), "guardrail alpha {alpha}");
564 }
565 }
566
567 #[test]
568 fn unbreachable_tolerances_are_refused() {
569 let drop = base().with_guardrail(GuardrailSpec::new(
570 MetricSpec::mean("revenue", MetricDirection::HigherIsBetter),
571 Tolerance::Relative(1.0),
572 ));
573 assert!(message(&drop).contains("can never be breached"));
574 let absolute = base().with_guardrail(GuardrailSpec::new(
575 MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
576 Tolerance::Absolute(1.0),
577 ));
578 assert!(message(&absolute).contains("can never be breached"));
579 let negative = base().with_guardrail(GuardrailSpec::new(
580 MetricSpec::proportion("refunds", MetricDirection::LowerIsBetter),
581 Tolerance::Relative(-0.1),
582 ));
583 assert!(message(&negative).contains("relative tolerance"));
584 }
585
586 #[test]
587 fn sizes_out_of_order_are_refused() {
588 assert!(message(&base().with_min_units_per_arm(1)).contains("at least 2"));
589 assert!(message(&base().with_planned_units_per_arm(50)).contains("plans 50"));
590 assert!(message(&base().with_max_units_per_arm(50)).contains("stops at 50"));
591 }
592
593 #[test]
594 fn bayesian_settings_out_of_range_are_refused() {
595 let with = |bayes: BayesianConfig| base().with_method(AnalysisMethod::Bayesian(bayes));
596 let prior = BayesianConfig::default().with_prior(BetaPrior::new(0.0, 1.0));
597 assert!(message(&with(prior)).contains("prior"));
598 let probability = BayesianConfig::default().with_decision_probability(0.5);
599 assert!(message(&with(probability)).contains("decision_probability"));
600 let level = BayesianConfig::default().with_credible_level(1.0);
601 assert!(message(&with(level)).contains("credible_level"));
602 let loss = BayesianConfig::default().with_max_expected_loss(-1.0);
603 assert!(message(&with(loss)).contains("max_expected_loss"));
604 }
605}