One primary metric, several guardrails
Decide what counts as winning and what must not get worse, and analyze ratio metrics at the unit you randomized.
What runs in CodeSplash
- A/B test analysis — SRM check, lifts, CUPED, guardrails and a Bayesian view Verified in Python and R
You will be able to
- Pick one primary metric tied to the decision
- Add guardrails that would stop a launch
- Explain why a ratio metric needs the delta method
Read first
What would change your decision?
ReadA good primary metric is one where a clear result would change what you do. Sensitive, tied to value, and hard to game.
Everything you care about but aren't trying to move becomes a guardrailGuardrail metricA metric that must not get worse, such as page load time, checked alongside the metric you hope to move.: page load time, refunds, complaints. A guardrail doesn't need to improve. It needs to not get worse.
In the studio's Design step you give each metric a role. That choice is what you pre-register.
Sort the metrics
CheckpointCheck yourself
You're testing a new recommendation carousel to raise purchases. Which is the best guardrail?
Show the answer
Answer: b
Purchases are the primary metric. Carousel clicks will rise almost by construction, so they tell you little. Load time is something you must not harm while chasing the win.
Check yourself
You test 20 unrelated metrics at the 5% level with no real effects. About how many look significant?
Show the answer
Answer: b
Five percent of 20 is one. Without a named primary metric, something will nearly always look like a win.
Ratio metrics need care
ReadClicks per session looks simple, but users are randomized while sessions are counted. A user with 50 sessions contributes 50 correlated values.
Treat sessions as independent and the interval comes out too narrow. The delta methodRatio metricA metric like clicks per session, whose unit of analysis differs from the unit of randomization; needs the delta method. works at the user level: each user contributes a numerator and a denominator, and the variance accounts for how they move together.
See a guardrail hold
In the apprevenue: treatment vs control lift 19.12% [-2.53%, 40.76%], adjusted p = 0.0295.
- SRM p
- .164
- Lift (revenue)
- 19.1%
- Adjusted p
- .029
Plots
View data
| Lift (%) | Role | High | Metric | Low |
|---|---|---|---|---|
| 19.117 | primary | 40.760 | revenue | −2.525 |
| 15.172 | secondary | 34.199 | converted | −3.854 |
| 3.121 | guardrail | 5.901 | sessions | 0.3407 |
View data
| Arm | Density | revenue |
|---|---|---|
| treatment − control | 0.0001 | −2.364 |
| treatment − control | 0.0001 | −2.319 |
| treatment − control | 0.0002 | −2.274 |
| treatment − control | 0.0002 | −2.229 |
| treatment − control | 0.0002 | −2.184 |
| treatment − control | 0.0003 | −2.139 |
| treatment − control | 0.0003 | −2.094 |
| treatment − control | 0.0004 | −2.049 |
| treatment − control | 0.0004 | −2.004 |
| treatment − control | 0.0005 | −1.959 |
| treatment − control | 0.0006 | −1.914 |
| treatment − control | 0.0006 | −1.869 |
| treatment − control | 0.0007 | −1.824 |
| treatment − control | 0.0008 | −1.779 |
| treatment − control | 0.0010 | −1.734 |
| treatment − control | 0.0011 | −1.689 |
| treatment − control | 0.0013 | −1.644 |
| treatment − control | 0.0015 | −1.599 |
| treatment − control | 0.0017 | −1.554 |
| treatment − control | 0.0019 | −1.509 |
| treatment − control | 0.0022 | −1.464 |
| treatment − control | 0.0024 | −1.419 |
| treatment − control | 0.0028 | −1.374 |
| treatment − control | 0.0031 | −1.328 |
| treatment − control | 0.0036 | −1.283 |
| treatment − control | 0.0040 | −1.238 |
| treatment − control | 0.0045 | −1.193 |
| treatment − control | 0.0051 | −1.148 |
| treatment − control | 0.0057 | −1.103 |
| treatment − control | 0.0064 | −1.058 |
| treatment − control | 0.0072 | −1.013 |
| treatment − control | 0.0080 | −0.9683 |
| treatment − control | 0.0090 | −0.9232 |
| treatment − control | 0.0100 | −0.8782 |
| treatment − control | 0.0111 | −0.8332 |
| treatment − control | 0.0124 | −0.7882 |
| treatment − control | 0.0137 | −0.7431 |
| treatment − control | 0.0152 | −0.6981 |
| treatment − control | 0.0168 | −0.6531 |
| treatment − control | 0.0185 | −0.6081 |
| treatment − control | 0.0204 | −0.5630 |
| treatment − control | 0.0224 | −0.5180 |
| treatment − control | 0.0246 | −0.4730 |
| treatment − control | 0.0270 | −0.4279 |
| treatment − control | 0.0296 | −0.3829 |
| treatment − control | 0.0323 | −0.3379 |
| treatment − control | 0.0353 | −0.2929 |
| treatment − control | 0.0384 | −0.2478 |
| treatment − control | 0.0418 | −0.2028 |
| treatment − control | 0.0454 | −0.1578 |
| treatment − control | 0.0492 | −0.1127 |
| treatment − control | 0.0532 | −0.0677 |
| treatment − control | 0.0575 | −0.0227 |
| treatment − control | 0.0621 | 0.0223 |
| treatment − control | 0.0669 | 0.0674 |
| treatment − control | 0.0719 | 0.1124 |
| treatment − control | 0.0772 | 0.1574 |
| treatment − control | 0.0828 | 0.2024 |
| treatment − control | 0.0886 | 0.2475 |
| treatment − control | 0.0946 | 0.2925 |
First 60 of 200 rows.
View data
| Arm | Loss if not shipped | Loss if shipped |
|---|---|---|
| treatment | 2.129 | 0.0127 |
Assumptions
- Sample ratio matches the plan — χ²(1) = 1.94, p = 0.164
Sample ratio
| Arm | Units | Expected | Share |
|---|---|---|---|
| control | 1,956 | 2,000 | 48.9% |
| treatment | 2,044 | 2,000 | 51.1% |
Metrics
| Metric | Role | Arm | Control | Treatment | Difference | CI low | CI high | Lift | Lift low | Lift high | p | Adjusted p |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| revenue | primary | treatment | 11.069 | 13.185 | 2.116 | −0.0798 | 4.312 | 19.1% | -2.5% | 40.8% | .029 | .029 |
| converted | secondary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .046 | .046 |
Guardrails (non-inferiority, margin 2.0% of the control)
| Guardrail | Arm | Better | Lift | Non-inferiority p | Status |
|---|---|---|---|---|---|
| sessions | treatment | higher | 3.1% | < .001 | pass |
Bayesian view of revenue
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 97.1% | 0.0127 | 2.129 | −0.0792 | 4.311 |
Decision by significance
| Arm | Decision | Why |
|---|---|---|
| treatment | ship | the difference is significant in the better direction |
- revenue: 3 units with a missing value were left out.
- Differences are treatment − control; lifts are relative to the control mean with delta-method intervals.
- Ratio metrics are Σ numerator / Σ denominator per arm with delta-method variances (z tests).
- CUPED adjusts each metric by its pre-period value with θ pooled over all units.
The exact R script · R R version 4.5.1 (2025-06-13)
# A/B test analysis — SRM check, lifts, CUPED, guardrails and a Bayesian view
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.analyze 1.1.1 · spec 4a0d104874b43bd7
# Dataset: e1_ab (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # A/B comparisons cs_exp_*, cs_p_adjust, cs_dunnett_prob (twins of codesplash)
# %% Data
v <- "variant" # assigned arm
metrics <- c("revenue", "converted") # first = primary
g_up <- c("sessions") # higher is better
g_down <- c() # lower is better
pre_cols <- c("pre revenue")
nums <- c()
dens <- c()
seg <- NULL
tcol <- NULL
bool_cols <- c("converted", NULL)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/e1_ab.parquet", col_select = c("variant", "revenue", "converted", "sessions", "pre revenue")))
n_input <- nrow(df)
df <- df[!is.na(df[[v]]), , drop = FALSE]
df[[v]] <- as.character(df[[v]])
stored <- c("control", "treatment") # stored arm order
arms <- stored[stored %in% df[[v]]]
if (n_input == 0) cs_error("CS_E_NO_ROWS")
if (nrow(df) == 0) cs_error("CS_E_ALL_MISSING", column = v) # no row has an assigned arm
cs_check_finite_columns(df, c("variant", "revenue", "converted", "sessions", "pre revenue")) # infinite values stop the run (registry/errors.yaml)
warnings <- list()
if (n_input > nrow(df)) warnings <- c(warnings, sprintf("%d of %d rows have no assigned arm and were left out.", n_input - nrow(df), n_input))
values_of <- function(col) {
x <- df[[col]]
if (col %in% bool_cols) return(ifelse(is.na(x), NA_real_, as.numeric(as.character(x) == "true")))
as.numeric(x)
}
# %% Inputs
alpha <- 0.05
alternative <- "greater"
correction <- "holm"
secondary_correction <- "BH"
control <- NULL
if (is.null(control)) control <- arms[1]
if (!(control %in% arms)) cs_error("CS_E_NOT_A_LEVEL", level = control, column = v) # the control arm has no units
treatments <- setdiff(arms, control)
if (!length(treatments)) cs_error("CS_E_TOO_FEW_GROUPS", column = v, min = 2, k = length(arms)) # needs a treatment arm with units
if (!length(metrics) && !length(nums)) stop("Choose at least one metric or ratio metric.")
if (length(nums) != length(dens)) stop("Give one denominator per ratio-metric numerator.")
arm <- df[[v]]
is_c <- arm == control
cuped_on <- TRUE
pre_index <- as.integer(unlist(c()))
if (!length(pre_index)) pre_index <- seq_along(pre_cols)
pre_for <- list()
for (k in seq_len(min(length(pre_index), length(pre_cols)))) {
i <- pre_index[k]
if (i >= 1 && i <= length(metrics)) pre_for[[metrics[i]]] <- pre_cols[k]
}
ni_margin <- 0.02
z <- stats::qnorm(1 - alpha / 2)
# %% Sample ratio mismatch
counts <- vapply(arms, function(a) sum(arm == a), numeric(1))
shares <- as.numeric(unlist(c()))
if (!length(shares)) shares <- rep(1, length(arms))
if (length(shares) != length(arms)) stop(sprintf("Give one planned share per arm (%d), in stored order: %s.", length(arms), paste(arms, collapse = ", ")))
srm <- cs_exp_srm(counts, shares)
srm_failed <- srm$p < 0.001
srm_blocked <- srm_failed && !FALSE
if (srm_failed && FALSE && !nzchar(trimws(""))) warnings <- c(warnings, "The SRM gate was overridden without a reason.")
# %% Metrics
check_arms <- function(name, ok) {
# Every arm needs two or more values of a metric for its variance (control first, then treatments).
for (a in c(control, treatments)) {
k <- sum(ok & arm == a)
if (k < 2) cs_error("CS_E_SMALL_GROUP", min = 2, group = sprintf("%s (%s)", a, name), n = k)
}
}
compare_metric <- function(name, y, x = NULL) {
if (all(is.na(y))) cs_error("CS_E_ALL_MISSING", column = name)
ok <- !is.na(y)
if (!is.null(x)) ok <- ok & !is.na(x)
check_arms(name, ok)
theta <- red <- NULL
yy <- y
if (!is.null(x) && cuped_on) {
cu <- cs_exp_cuped(y[ok], x[ok])
theta <- cu$theta
red <- cu$reduction
yy <- rep(NA_real_, length(y))
yy[ok] <- cu$adj
}
mc <- cs_exp_moments(yy[ok & is_c])
res <- list()
for (a in treatments) {
mt <- cs_exp_moments(yy[ok & arm == a])
r <- cs_exp_welch(mc$n, mc$mean, mc$var, mt$n, mt$mean, mt$var, alpha, alternative)
r$n_c <- mc$n; r$mean_c <- mc$mean; r$var_c <- mc$var / mc$n
r$n_t <- mt$n; r$mean_t <- mt$mean; r$var_t <- mt$var / mt$n
res[[a]] <- r
}
list(res = res, theta = theta, red = red, dropped = sum(!ok))
}
results <- list()
for (mname in metrics) {
x <- if (!is.null(pre_for[[mname]])) values_of(pre_for[[mname]]) else NULL
cm <- compare_metric(mname, values_of(mname), x)
if (cm$dropped > 0) warnings <- c(warnings, sprintf("%s: %d units with a missing value were left out.", mname, cm$dropped))
results[[length(results) + 1]] <- list(name = mname, kind = "metric", res = cm$res, theta = cm$theta, red = cm$red)
}
for (k in seq_along(nums)) {
name <- sprintf("%s / %s", nums[k], dens[k])
nn <- values_of(nums[k])
dd <- values_of(dens[k])
ok <- !(is.na(nn) | is.na(dd))
check_arms(name, ok)
rcl <- cs_exp_ratio_arm(nn[ok & is_c], dd[ok & is_c])
res <- list()
for (a in treatments) {
sel <- ok & arm == a
rtl <- cs_exp_ratio_arm(nn[sel], dd[sel])
r <- cs_exp_ratio_compare(rcl$ratio, rcl$var, rtl$ratio, rtl$var, alpha, alternative)
r$n_c <- rcl$n; r$mean_c <- rcl$ratio; r$var_c <- rcl$var
r$n_t <- rtl$n; r$mean_t <- rtl$ratio; r$var_t <- rtl$var
res[[a]] <- r
}
results[[length(results) + 1]] <- list(name = name, kind = "ratio", res = res, theta = NULL, red = NULL)
}
if (FALSE && length(nums)) { # the first ratio metric is primary
k <- length(metrics)
results <- c(results[k + 1], results[seq_len(k)], results[-seq_len(k + 1)])
}
primary <- results[[1]]$name
primary_kind <- results[[1]]$kind
# Primary metric across treatment arms.
ps <- vapply(treatments, function(a) results[[1]]$res[[a]]$p, numeric(1))
if (correction == "dunnett" && length(treatments) > 1) {
b <- results[[1]]$res[[treatments[1]]]$var_c
lam <- vapply(treatments, function(a) sqrt(b / (b + results[[1]]$res[[a]]$var_t)), numeric(1))
two <- alternative == "two-sided"
sgn <- if (alternative == "less") -1 else 1
p_adj <- vapply(treatments, function(a) {
st <- results[[1]]$res[[a]]$stat
min(1, max(0, 1 - cs_dunnett_prob(if (two) abs(st) else sgn * st, lam, Inf, two)))
}, numeric(1))
} else {
p_adj <- cs_p_adjust(ps, if (length(treatments) > 1) correction else "none")
}
for (i in seq_along(treatments)) results[[1]]$res[[treatments[i]]]$p_adj <- p_adj[i]
# Secondary metrics: one family.
if (length(results) > 1) {
sec <- do.call(rbind, lapply(2:length(results), function(j) data.frame(j = j, a = treatments, stringsAsFactors = FALSE)))
sp <- vapply(seq_len(nrow(sec)), function(i) results[[sec$j[i]]]$res[[sec$a[i]]]$p, numeric(1))
sq <- cs_p_adjust(sp, secondary_correction)
for (i in seq_len(nrow(sec))) results[[sec$j[i]]]$res[[sec$a[i]]]$p_adj <- sq[i]
}
# %% Guardrails (non-inferiority)
guard <- list()
for (gd in c(lapply(g_up, function(g) c(g, "higher")), lapply(g_down, function(g) c(g, "lower")))) {
cm <- compare_metric(gd[1], values_of(gd[1]))
for (a in treatments) {
r <- cm$res[[a]]
ni <- cs_exp_noninferiority(r$diff, r$se, r$df, r$mean_c, ni_margin, gd[2])
guard[[length(guard) + 1]] <- list(name = gd[1], arm = a, direction = gd[2], r = r, t = ni[1], p = ni[2], pass = ni[2] < alpha)
}
}
# %% Bayesian view of the primary metric
decision_rule <- "frequentist" # frequentist | expected_loss | hdi_rope | prob_to_beat
higher_better <- "higher" != "lower"
prior <- NULL
if ("flat" == "meta") {
# Informed prior: random-effects pooled effect of past experiments, predictive SD (tau included).
prior <- cs_exp_meta_prior(as.numeric(unlist(c())), as.numeric(unlist(c())), "REML")
}
bayes <- list()
if (TRUE || decision_rule != "frequentist" || !is.null(prior)) {
cred <- 1 - alpha
binary <- primary_kind == "metric" && primary %in% bool_cols
yb <- if (binary) values_of(primary) else NULL
for (a in treatments) {
bres <- if (!is.null(prior)) {
cs_exp_normal_posterior(results[[1]]$res[[a]]$diff, results[[1]]$res[[a]]$se, prior$mean, prior$sd, cred)
} else if (binary) {
okc <- is_c & !is.na(yb)
okt <- arm == a & !is.na(yb)
cs_exp_beta_compare(sum(yb[okc]), sum(okc), sum(yb[okt]), sum(okt), 1, 1, cred)
} else {
cs_exp_normal_compare(results[[1]]$res[[a]]$diff, results[[1]]$res[[a]]$se, cred)
}
bayes[[a]] <- bres
}
}
# %% Segments (exploratory)
segs <- list()
if (!is.null(seg) && primary_kind == "metric") {
y <- values_of(primary)
sv <- as.character(df[[seg]])
seg_levels <- c()
seg_levels <- seg_levels[seg_levels %in% sv]
if (!length(seg_levels)) seg_levels <- sort(unique(sv[!is.na(sv)]), method = "radix")
for (lv in seg_levels) for (a in treatments) {
selc <- is_c & !is.na(sv) & sv == lv & !is.na(y)
selt <- arm == a & !is.na(sv) & sv == lv & !is.na(y)
if (sum(selc) < 2 || sum(selt) < 2) next
mc <- cs_exp_moments(y[selc])
mt <- cs_exp_moments(y[selt])
segs[[length(segs) + 1]] <- list(level = lv, arm = a, r = cs_exp_welch(mc$n, mc$mean, mc$var, mt$n, mt$mean, mt$var, alpha, alternative), n = mc$n + mt$n)
}
seg_adj <- if (length(segs)) cs_p_adjust(vapply(segs, function(s) s$r$p, numeric(1)), "BH") else numeric(0)
}
# %% Cumulative lift and always-valid p-values
cum <- list()
avp <- list()
if (!is.null(tcol)) {
t_raw <- df[[tcol]]
temporal <- FALSE
tt <- if (inherits(t_raw, "Date")) as.numeric(t_raw) else if (inherits(t_raw, "POSIXt")) as.numeric(t_raw) / 86400 else as.numeric(t_raw)
cuts <- cs_exp_cut_points(tt[!is.na(tt)])
if (primary_kind == "metric") {
y <- values_of(primary)
} else {
nn <- values_of(nums[1])
dd <- values_of(dens[1])
}
for (a in treatments) {
diffs <- variances <- numeric(0)
for (cut in cuts) {
win <- !is.na(tt) & tt <= cut
if (primary_kind == "metric") {
selc <- win & is_c & !is.na(y)
selt <- win & arm == a & !is.na(y)
if (sum(selc) < 2 || sum(selt) < 2) next
mc <- cs_exp_moments(y[selc])
mt <- cs_exp_moments(y[selt])
if (!(mc$var > 0 || mt$var > 0)) next
r <- cs_exp_welch(mc$n, mc$mean, mc$var, mt$n, mt$mean, mt$var, alpha, alternative)
} else {
okr <- win & !(is.na(nn) | is.na(dd))
if (sum(okr & is_c) < 2 || sum(okr & arm == a) < 2) next
rc <- cs_exp_ratio_arm(nn[okr & is_c], dd[okr & is_c])
rt <- cs_exp_ratio_arm(nn[okr & arm == a], dd[okr & arm == a])
r <- cs_exp_ratio_compare(rc$ratio, rc$var, rt$ratio, rt$var, alpha, alternative)
}
diffs <- c(diffs, r$diff)
variances <- c(variances, r$se^2)
cum[[length(cum) + 1]] <- list(cut = cut, arm = a, r = r)
}
if (length(diffs)) {
tau <- NULL
if (is.null(tau) || tau <= 0) tau <- (z + stats::qnorm(0.8)) * sqrt(variances[length(variances)])
ms <- cs_exp_msprt(diffs, variances, tau, alpha)
n <- length(ms$p)
avp[[a]] <- c(ms$p[n], ms$low[n], ms$high[n], tau)
}
}
}
time_label <- function(cut) if (temporal) format(as.Date(cut, origin = "1970-01-01")) else cut
# %% Result
values <- list(control = control, arms = length(arms), comparisons = length(treatments), srm_chi2 = srm$chi2, srm_p = srm$p,
srm_failed = srm_failed, srm_blocked = srm_blocked, alpha = alpha, primary_metric = primary)
for (i in seq_along(arms)) values[[sprintf("n[%s]", arms[i])]] <- counts[[i]]
for (res in results) {
mname <- res$name
if (!is.null(res$theta)) {
values[[sprintf("cuped_theta[%s]", mname)]] <- res$theta
values[[sprintf("cuped_reduction[%s]", mname)]] <- res$red
}
values[[sprintf("mean[%s|%s]", mname, control)]] <- res$res[[treatments[1]]]$mean_c
for (a in treatments) {
r <- res$res[[a]]
k <- sprintf("%s|%s", mname, a)
values[[sprintf("mean[%s]", k)]] <- r$mean_t
for (key in c("diff", "se", "df", "stat", "p", "p_adj", "ci_low", "ci_high", "lift", "lift_low", "lift_high")) values[[sprintf("%s[%s]", key, k)]] <- r[[key]]
}
}
first <- treatments[1]
pr <- results[[1]]$res[[first]]
values$primary_arm <- first
values$primary_diff <- pr$diff
values$primary_lift <- pr$lift
values$primary_lift_low <- pr$lift_low
values$primary_lift_high <- pr$lift_high
values$primary_p <- pr$p
values$primary_p_adj <- pr$p_adj
values$primary_significant <- pr$p_adj < alpha
for (g in guard) {
k <- sprintf("%s|%s", g$name, g$arm)
values[[sprintf("guard_diff[%s]", k)]] <- g$r$diff
values[[sprintf("guard_lift[%s]", k)]] <- g$r$lift
values[[sprintf("ni_stat[%s]", k)]] <- g$t
values[[sprintf("ni_p[%s]", k)]] <- g$p
values[[sprintf("ni_pass[%s]", k)]] <- g$pass
}
values$guardrails_failed <- sum(vapply(guard, function(g) !g$pass, logical(1)))
for (a in names(bayes)) {
k <- sprintf("%s|%s", primary, a)
for (key in c("prob", "loss_t", "loss_c", "cred_low", "cred_high")) values[[sprintf("bayes_%s[%s]", key, k)]] <- bayes[[a]][[key]]
}
values$prob_beat_primary <- if (length(bayes)) bayes[[1]]$prob else NA
# %% Decision
rule_labels <- c(frequentist = "significance", expected_loss = "expected loss", hdi_rope = "credible interval vs ROPE", prob_to_beat = "probability to beat the control")
decisions <- list()
for (a in treatments) {
r <- results[[1]]$res[[a]]
decisions[[a]] <- if (srm_blocked) c("fix the test", "sample ratio mismatch: check randomization and logging") else
cs_exp_decide(decision_rule, bayes[[a]], r$p_adj < alpha, r$diff, higher_better, 0.001, 0.002, 0.95)
values[[sprintf("decision[%s|%s]", primary, a)]] <- decisions[[a]][1]
}
values$decision_rule <- decision_rule
values$decision_rule_label <- unname(rule_labels[decision_rule])
values$decision_primary <- decisions[[first]][1]
values$decision_reason <- decisions[[first]][2]
values$prior_mean <- if (is.null(prior)) NA else prior$mean
values$prior_sd <- if (is.null(prior)) NA else prior$sd
values$prior_k <- if (is.null(prior)) NA else prior$k
values$prior_tau2 <- if (is.null(prior)) NA else prior$tau2
for (a in names(bayes)) if (!is.null(bayes[[a]]$post_mean)) {
values[[sprintf("post_mean[%s|%s]", primary, a)]] <- bayes[[a]]$post_mean
values[[sprintf("post_sd[%s|%s]", primary, a)]] <- bayes[[a]]$post_sd
}
if (length(segs)) for (i in seq_along(segs)) {
values[[sprintf("seg_lift[%s|%s]", segs[[i]]$level, segs[[i]]$arm)]] <- segs[[i]]$r$lift
values[[sprintf("seg_p_adj[%s|%s]", segs[[i]]$level, segs[[i]]$arm)]] <- seg_adj[i]
}
for (a in names(avp)) {
values[[sprintf("avp[%s]", a)]] <- avp[[a]][1]
values[[sprintf("avp_low[%s]", a)]] <- avp[[a]][2]
values[[sprintf("avp_high[%s]", a)]] <- avp[[a]][3]
values[[sprintf("avp_tau[%s]", a)]] <- avp[[a]][4]
}
tables <- list(list(
key = "srm", title = "Sample ratio",
columns = list(list(key = "arm", label = "Arm", type = "string"), list(key = "n", label = "Units", type = "integer"),
list(key = "expected", label = "Expected", type = "number"), list(key = "share", label = "Share", type = "percent")),
rows = lapply(seq_along(arms), function(i) list(arm = arms[i], n = counts[[i]], expected = srm$expected[i], share = counts[[i]] / sum(counts)))
))
charts <- list()
if (!srm_blocked) {
rows <- list()
for (j in seq_along(results)) for (a in treatments) {
r <- results[[j]]$res[[a]]
rows[[length(rows) + 1]] <- list(metric = results[[j]]$name, role = if (j == 1) "primary" else "secondary", arm = a, control = r$mean_c,
treatment = r$mean_t, diff = r$diff, ci_low = r$ci_low, ci_high = r$ci_high, lift = r$lift,
lift_low = r$lift_low, lift_high = r$lift_high, p = r$p, p_adj = r$p_adj)
}
tables <- c(tables, list(list(
key = "metrics", title = "Metrics",
columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "role", label = "Role", type = "string"),
list(key = "arm", label = "Arm", type = "string"), list(key = "control", label = "Control", type = "number"),
list(key = "treatment", label = "Treatment", type = "number"), list(key = "diff", label = "Difference", type = "number"),
list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number"),
list(key = "lift", label = "Lift", type = "percent"), list(key = "lift_low", label = "Lift low", type = "percent"),
list(key = "lift_high", label = "Lift high", type = "percent"), list(key = "p", label = "p", type = "pvalue"),
list(key = "p_adj", label = "Adjusted p", type = "pvalue")),
rows = rows
)))
if (length(guard)) {
tables <- c(tables, list(list(
key = "guardrails", title = sprintf("Guardrails (non-inferiority, margin %.1f%% of the control)", 100 * ni_margin),
columns = list(list(key = "metric", label = "Guardrail", type = "string"), list(key = "arm", label = "Arm", type = "string"),
list(key = "better", label = "Better", type = "string"), list(key = "lift", label = "Lift", type = "percent"),
list(key = "p", label = "Non-inferiority p", type = "pvalue"), list(key = "status", label = "Status", type = "string")),
rows = lapply(guard, function(g) list(metric = g$name, arm = g$arm, better = g$direction, lift = g$r$lift, p = g$p, status = if (g$pass) "pass" else "fail"))
)))
}
if (length(bayes)) {
tables <- c(tables, list(list(
key = "bayes", title = sprintf("Bayesian view of %s", primary),
columns = list(list(key = "arm", label = "Arm", type = "string"), list(key = "prob", label = "P(better than control)", type = "percent"),
list(key = "loss_t", label = "Expected loss if shipped", type = "number"), list(key = "loss_c", label = "Expected loss if not", type = "number"),
list(key = "cred_low", label = "Credible low", type = "number"), list(key = "cred_high", label = "Credible high", type = "number")),
rows = lapply(names(bayes), function(a) list(arm = a, prob = bayes[[a]]$prob, loss_t = bayes[[a]]$loss_t, loss_c = bayes[[a]]$loss_c,
cred_low = bayes[[a]]$cred_low, cred_high = bayes[[a]]$cred_high))
)))
}
if (length(segs)) {
tables <- c(tables, list(list(
key = "segments", title = sprintf("Segments of %s (exploratory)", seg),
columns = list(list(key = "segment", label = "Segment", type = "string"), list(key = "arm", label = "Arm", type = "string"),
list(key = "n", label = "Units", type = "integer"), list(key = "lift", label = "Lift", type = "percent"),
list(key = "p_adj", label = "BH-adjusted p", type = "pvalue")),
rows = lapply(seq_along(segs), function(i) list(segment = segs[[i]]$level, arm = segs[[i]]$arm, n = segs[[i]]$n, lift = segs[[i]]$r$lift, p_adj = seg_adj[i]))
)))
}
fl <- fg <- character(0)
fe <- flo <- fhi <- numeric(0)
for (j in seq_along(results)) for (a in treatments) {
r <- results[[j]]$res[[a]]
fl <- c(fl, if (length(treatments) == 1) results[[j]]$name else sprintf("%s · %s", results[[j]]$name, a))
fe <- c(fe, 100 * r$lift); flo <- c(flo, 100 * r$lift_low); fhi <- c(fhi, 100 * r$lift_high)
fg <- c(fg, if (j == 1) "primary" else "secondary")
}
for (g in guard) {
fl <- c(fl, if (length(treatments) == 1) g$name else sprintf("%s · %s", g$name, g$arm))
fe <- c(fe, 100 * g$r$lift); flo <- c(flo, 100 * g$r$lift_low); fhi <- c(fhi, 100 * g$r$lift_high); fg <- c(fg, "guardrail")
}
charts <- c(charts, list(cs_chart("lifts", "forest", "Relative lift vs the control (%)",
list(label = cs_col("Metric", fl), estimate = cs_col("Lift (%)", fe), low = cs_col("Low", flo), high = cs_col("High", fhi), group = cs_col("Role", fg)),
controls = list(reference = 0))))
if (length(cum)) {
charts <- c(charts, list(cs_chart("cumulative", "cumulative-lift", sprintf("Cumulative lift of %s (%%)", primary),
list(time = cs_col("Time", vapply(cum, function(cc) as.character(time_label(cc$cut)), character(1)), if (temporal) "temporal" else NULL),
lift = cs_col("Lift (%)", vapply(cum, function(cc) 100 * cc$r$lift, numeric(1))),
low = cs_col("Low", vapply(cum, function(cc) 100 * cc$r$lift_low, numeric(1))),
high = cs_col("High", vapply(cum, function(cc) 100 * cc$r$lift_high, numeric(1))),
metric = cs_col("Arm", vapply(cum, function(cc) cc$arm, character(1)))))))
}
if (length(bayes)) {
a0 <- names(bayes)[1]
b0 <- bayes[[1]]
if (!is.null(b0$post)) {
dg <- cs_exp_beta_density(b0$post, b0$range)
px <- c(dg$x, dg$x)
pdn <- c(dg$densities[[1]], dg$densities[[2]])
pa <- c(rep(control, length(dg$x)), rep(a0, length(dg$x)))
} else {
d0 <- if (!is.null(b0$post_mean)) b0$post_mean else results[[1]]$res[[a0]]$diff
s0 <- if (!is.null(b0$post_mean)) b0$post_sd else results[[1]]$res[[a0]]$se
px <- d0 + s0 * (-4 + 8 * (0:199) / 199)
pdn <- stats::dnorm(px, d0, s0)
pa <- rep(sprintf("%s − %s", a0, control), 200)
}
rope_w <- if (decision_rule == "hdi_rope" && is.null(b0$post)) 0.002 else NULL
charts <- c(charts, list(cs_chart("posterior", "posterior-density", sprintf("Posterior of %s", primary),
list(x = cs_col(primary, px), density = cs_col("Density", pdn), arm = cs_col("Arm", pa)),
controls = list(rope_low = if (is.null(rope_w) || rope_w == 0) NULL else -rope_w, rope_high = if (is.null(rope_w) || rope_w == 0) NULL else rope_w))))
ships <- vapply(names(bayes), function(a) if (higher_better) bayes[[a]]$loss_t else bayes[[a]]$loss_c, numeric(1))
keeps <- vapply(names(bayes), function(a) if (higher_better) bayes[[a]]$loss_c else bayes[[a]]$loss_t, numeric(1))
charts <- c(charts, list(cs_chart("loss", "expected-loss", sprintf("Expected loss of each choice (%s)", primary),
list(arm = cs_col("Arm", names(bayes)), ship = cs_col("Loss if shipped", unname(ships)), keep = cs_col("Loss if not shipped", unname(keeps))),
controls = list(threshold = if (decision_rule == "expected_loss") 0.001 else 0))))
}
tables <- c(tables, list(list(
key = "decision", title = sprintf("Decision by %s", rule_labels[[decision_rule]]),
columns = list(list(key = "arm", label = "Arm", type = "string"), list(key = "decision", label = "Decision", type = "string"),
list(key = "reason", label = "Why", type = "string")),
rows = lapply(treatments, function(a) list(arm = a, decision = decisions[[a]][1], reason = decisions[[a]][2]))
)))
if (!is.null(prior)) tables <- c(tables, list(list(
key = "prior", title = "Prior from past experiments (random-effects meta-analysis)",
columns = list(list(key = "k", label = "Experiments", type = "integer"), list(key = "mean", label = "Pooled effect", type = "number"),
list(key = "se", label = "SE of the pooled effect", type = "number"), list(key = "tau", label = "Between-experiment SD (τ)", type = "number"),
list(key = "sd", label = "Prior SD (predictive)", type = "number")),
rows = list(list(k = prior$k, mean = prior$mean, se = prior$se, tau = sqrt(prior$tau2), sd = prior$sd))
)))
}
summary_text <- if (srm_blocked) sprintf("SRM χ² p = %.3g: results withheld.", srm$p) else
sprintf("%s: %s vs %s lift %.2f%% [%.2f%%, %.2f%%], adjusted p = %.3g.", primary, first, control, 100 * pr$lift, 100 * pr$lift_low, 100 * pr$lift_high, pr$p_adj)
stats_list <- list(list(key = "srm_p", label = "SRM p", value = srm$p, format = "p"))
if (!srm_blocked) stats_list <- c(stats_list, list(
list(key = "primary_lift", label = sprintf("Lift (%s)", primary), value = pr$lift, format = "percent"),
list(key = "primary_p_adj", label = "Adjusted p", value = pr$p_adj, format = "p")))
cs_publish(list(
method = "experiment.analyze",
methodVersion = "1.1.1",
title = "A/B test analysis",
engine = cs_engine_info("stats"),
summary = summary_text,
statistics = stats_list,
assumptions = list(list(key = "srm", label = "Sample ratio matches the plan", status = if (srm_failed) "fail" else "pass",
detail = paste0(sprintf("χ²(%d) = %.2f, p = %.3g", length(arms) - 1, srm$chi2, srm$p), if (srm_blocked) " — results withheld" else ""))),
tables = tables,
charts = charts,
warnings = warnings,
notes = c("Differences are treatment − control; lifts are relative to the control mean with delta-method intervals.",
"Ratio metrics are Σ numerator / Σ denominator per arm with delta-method variances (z tests).",
if (length(pre_for) && cuped_on) "CUPED adjusts each metric by its pre-period value with θ pooled over all units.",
if (length(segs)) "Segment results are exploratory (BH-adjusted); they do not confirm effects.",
if (length(avp)) "Always-valid p-values (mixture SPRT) stay valid however often the cumulative results are checked."),
values = values
))
revenue: treatment vs control lift 19.12% [-2.53%, 40.76%], adjusted p = 0.0295.
- SRM p
- .164
- Lift (revenue)
- 19.1%
- Adjusted p
- .029
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample ratio matches the plan — χ²(1) = 1.94, p = 0.164
Sample ratio
| Arm | Units | Expected | Share |
|---|---|---|---|
| control | 1,956 | 2,000 | 48.9% |
| treatment | 2,044 | 2,000 | 51.1% |
Metrics
| Metric | Role | Arm | Control | Treatment | Difference | CI low | CI high | Lift | Lift low | Lift high | p | Adjusted p |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| revenue | primary | treatment | 11.069 | 13.185 | 2.116 | −0.0798 | 4.312 | 19.1% | -2.5% | 40.8% | .029 | .029 |
| converted | secondary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .046 | .046 |
Guardrails (non-inferiority, margin 2.0% of the control)
| Guardrail | Arm | Better | Lift | Non-inferiority p | Status |
|---|---|---|---|---|---|
| sessions | treatment | higher | 3.1% | < .001 | pass |
Bayesian view of revenue
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 97.1% | 0.0127 | 2.129 | −0.0792 | 4.311 |
Decision by significance
| Arm | Decision | Why |
|---|---|---|
| treatment | ship | the difference is significant in the better direction |
- revenue: 3 units with a missing value were left out.
- Differences are treatment − control; lifts are relative to the control mean with delta-method intervals.
- Ratio metrics are Σ numerator / Σ denominator per arm with delta-method variances (z tests).
- CUPED adjusts each metric by its pre-period value with θ pooled over all units.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# A/B test analysis — SRM check, lifts, CUPED, guardrails and a Bayesian view
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.analyze 1.1.1 · spec 4a0d104874b43bd7
# Dataset: e1_ab (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
from scipy.special import ndtri
import codesplash as cs
from codesplash.experiment import analyze as xa # A/B comparisons (twin of R cs_exp_*)
from codesplash.stats.padjust import p_adjust
from codesplash.stats.posthoc import dunnett_prob
# %% Data
v = "variant" # assigned arm
metrics = ["revenue", "converted"] # first = primary
g_up = ["sessions"] # higher is better
g_down = [] # lower is better
pre_cols = ["pre revenue"]
nums, dens = [], []
seg = None
tcol = None
bool_cols = ["converted", ]
df = pd.read_parquet("tests/parity/fixtures/e1_ab.parquet", columns=["variant", "revenue", "converted", "sessions", "pre revenue"])
n_input = len(df)
df = df[df[v].notna()].reset_index(drop=True)
df[v] = df[v].astype(str)
stored = ["control", "treatment"] # stored arm order
arms = [a for a in stored if (df[v] == a).any()]
if not n_input:
cs.cs_error("CS_E_NO_ROWS")
if not len(df):
cs.cs_error("CS_E_ALL_MISSING", column=v) # no row has an assigned arm
cs.check_finite_columns(df, ["variant", "revenue", "converted", "sessions", "pre revenue"]) # infinite values stop the run (registry/errors.yaml)
warnings = []
if n_input > len(df):
warnings.append(f"{n_input - len(df)} of {n_input} rows have no assigned arm and were left out.")
def values_of(col):
"""A metric as floats: yes/no columns become 0/1, missing stays NaN."""
x = df[col]
if col in bool_cols:
return np.where(x.isna(), np.nan, (x.astype(str) == "true").astype(float))
return x.to_numpy(dtype=float)
# %% Inputs
alpha = 0.05
alternative = "greater"
correction = "holm"
secondary_correction = "BH"
control = None or arms[0]
if control not in arms:
cs.cs_error("CS_E_NOT_A_LEVEL", level=control, column=v) # the control arm has no units
treatments = [a for a in arms if a != control]
if not treatments:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=v, min=2, k=len(arms)) # needs a treatment arm with units
if not metrics and not nums:
raise ValueError("Choose at least one metric or ratio metric.")
if len(nums) != len(dens):
raise ValueError("Give one denominator per ratio-metric numerator.")
arm = df[v].to_numpy()
is_c = arm == control
cuped_on = True
pre_index = [int(i) for i in []] or list(range(1, len(pre_cols) + 1))
pre_for = {metrics[i - 1]: pre_cols[k] for k, i in enumerate(pre_index[: len(pre_cols)]) if 1 <= i <= len(metrics)}
ni_margin = 0.02
z = float(ndtri(1.0 - alpha / 2.0))
# %% Sample ratio mismatch
counts = [int(np.sum(arm == a)) for a in arms]
shares = [float(s) for s in []] or [1.0] * len(arms)
if len(shares) != len(arms):
raise ValueError(f"Give one planned share per arm ({len(arms)}), in stored order: {', '.join(arms)}.")
srm_chi2, srm_p, srm_expected = xa.srm(counts, shares)
srm_failed = srm_p < 0.001
srm_blocked = srm_failed and not False
if srm_failed and False and not "".strip():
warnings.append("The SRM gate was overridden without a reason.")
# %% Metrics
def check_arms(name, ok):
"""Every arm needs two or more values of a metric for its variance (control first, then treatments)."""
for a in [control] + treatments:
k = int(np.sum(ok & (arm == a)))
if k < 2:
cs.cs_error("CS_E_SMALL_GROUP", min=2, group=f"{a} ({name})", n=k)
def compare_metric(name, y, x=None):
if np.all(np.isnan(y)):
cs.cs_error("CS_E_ALL_MISSING", column=name)
ok = ~np.isnan(y)
if x is not None:
ok &= ~np.isnan(x)
check_arms(name, ok)
theta = red = None
yy = y
if x is not None and cuped_on:
adj, theta, red = xa.cuped(y[ok], x[ok])
yy = np.full_like(y, np.nan)
yy[ok] = adj
nc, mc, vc = xa.moments(yy[ok & is_c])
res = {}
for a in treatments:
nt, mt, vt = xa.moments(yy[ok & (arm == a)])
r = xa.welch(nc, mc, vc, nt, mt, vt, alpha, alternative)
r.update(n_c=nc, mean_c=mc, var_c=vc / nc, n_t=nt, mean_t=mt, var_t=vt / nt)
res[a] = r
dropped = int(np.sum(~ok))
return res, theta, red, dropped
results = [] # (metric, kind, {arm: result}, theta, reduction)
for mname in metrics:
x = values_of(pre_for[mname]) if mname in pre_for else None
res, theta, red, dropped = compare_metric(mname, values_of(mname), x)
if dropped:
warnings.append(f"{mname}: {dropped} units with a missing value were left out.")
results.append((mname, "metric", res, theta, red))
for num_c, den_c in zip(nums, dens):
name = f"{num_c} / {den_c}"
nn, dd = values_of(num_c), values_of(den_c)
ok = ~(np.isnan(nn) | np.isnan(dd))
check_arms(name, ok)
nc, rc, vc = xa.ratio_arm(nn[ok & is_c], dd[ok & is_c])
res = {}
for a in treatments:
sel = ok & (arm == a)
nt, rt, vt = xa.ratio_arm(nn[sel], dd[sel])
r = xa.ratio_compare(rc, vc, rt, vt, alpha, alternative)
r.update(n_c=nc, mean_c=rc, var_c=vc, n_t=nt, mean_t=rt, var_t=vt)
res[a] = r
results.append((name, "ratio", res, None, None))
if False and nums: # the first ratio metric is primary
k = len(metrics)
results = [results[k]] + results[:k] + results[k + 1:]
primary, primary_kind, primary_res = results[0][0], results[0][1], results[0][2]
# Primary metric across treatment arms.
ps = [primary_res[a]["p"] for a in treatments]
if correction == "dunnett" and len(treatments) > 1:
b = primary_res[treatments[0]]["var_c"]
lam = [math.sqrt(b / (b + primary_res[a]["var_t"])) for a in treatments]
two = alternative == "two-sided"
sign = -1.0 if alternative == "less" else 1.0
p_adj = [min(1.0, max(0.0, 1.0 - dunnett_prob(abs(primary_res[a]["stat"]) if two else sign * primary_res[a]["stat"], lam, math.inf, two))) for a in treatments]
else:
p_adj = [float(q) for q in p_adjust(ps, correction if len(treatments) > 1 else "none")]
for a, q in zip(treatments, p_adj):
primary_res[a]["p_adj"] = q
# Secondary metrics: one family.
sec = [(r[0], a) for r in results[1:] for a in treatments]
sec_adj = [float(q) for q in p_adjust([dict((x[0], x[2]) for x in results)[m][a]["p"] for m, a in sec], secondary_correction)] if sec else []
by_name = {r[0]: r for r in results}
for (m, a), q in zip(sec, sec_adj):
by_name[m][2][a]["p_adj"] = q
# %% Guardrails (non-inferiority)
guard = []
for gname, direction in [(c, "higher") for c in g_up] + [(c, "lower") for c in g_down]:
res, _, _, _ = compare_metric(gname, values_of(gname))
for a in treatments:
r = res[a]
t_ni, p_ni = xa.noninferiority(r["diff"], r["se"], r["df"], r["mean_c"], ni_margin, direction)
guard.append((gname, a, direction, r, t_ni, p_ni, p_ni < alpha))
# %% Bayesian view of the primary metric
decision_rule = "frequentist" # frequentist | expected_loss | hdi_rope | prob_to_beat
higher_better = "higher" != "lower"
prior = None
if "flat" == "meta":
# Informed prior: random-effects pooled effect of past experiments, predictive SD (τ included).
prior = xa.meta_prior([], [], "REML")
bayes = []
if True or decision_rule != "frequentist" or prior is not None:
cred = 1.0 - alpha
binary = primary_kind == "metric" and primary in bool_cols
yb = values_of(primary) if binary else None
for a in treatments:
if prior is not None:
bres = xa.normal_posterior(primary_res[a]["diff"], primary_res[a]["se"], prior["mean"], prior["sd"], cred)
elif binary:
okc, okt = is_c & ~np.isnan(yb), (arm == a) & ~np.isnan(yb)
bres = xa.beta_compare(float(np.sum(yb[okc])), int(np.sum(okc)), float(np.sum(yb[okt])), int(np.sum(okt)),
1, 1, cred)
else:
bres = xa.normal_compare(primary_res[a]["diff"], primary_res[a]["se"], cred)
bayes.append((a, bres))
# %% Segments (exploratory)
segs = []
if seg is not None and primary_kind == "metric":
y = values_of(primary)
sv = df[seg].astype(str).to_numpy()
seg_levels = [lv for lv in [] if (sv == lv).any()] or sorted(set(sv[df[seg].notna().to_numpy()]))
for lv in seg_levels:
for a in treatments:
selc, selt = is_c & (sv == lv) & ~np.isnan(y), (arm == a) & (sv == lv) & ~np.isnan(y)
if selc.sum() < 2 or selt.sum() < 2:
continue
nc, mc, vc = xa.moments(y[selc])
nt, mt, vt = xa.moments(y[selt])
segs.append((lv, a, xa.welch(nc, mc, vc, nt, mt, vt, alpha, alternative), nc + nt))
seg_adj = p_adjust([s[2]["p"] for s in segs], "BH") if segs else []
# %% Cumulative lift and always-valid p-values
cum = []
avp = {}
if tcol is not None:
t_raw = df[tcol]
temporal = False
if temporal:
ts = pd.to_datetime(t_raw)
if ts.dt.tz is not None:
ts = ts.dt.tz_localize(None)
tt = ((ts - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)).to_numpy(dtype=float)
else:
tt = t_raw.to_numpy(dtype=float)
cuts = xa.cut_points([float(t) for t in tt[~np.isnan(tt)]])
if primary_kind == "metric":
y = values_of(primary)
else:
nn, dd = values_of(nums[0]), values_of(dens[0])
for a in treatments:
diffs, variances = [], []
for c in cuts:
win = ~np.isnan(tt) & (tt <= c)
if primary_kind == "metric":
selc, selt = win & is_c & ~np.isnan(y), win & (arm == a) & ~np.isnan(y)
if selc.sum() < 2 or selt.sum() < 2:
continue
nc, mc, vc = xa.moments(y[selc])
nt, mt, vt = xa.moments(y[selt])
if not (vc > 0 or vt > 0):
continue
r = xa.welch(nc, mc, vc, nt, mt, vt, alpha, alternative)
else:
okr = win & ~(np.isnan(nn) | np.isnan(dd))
if (okr & is_c).sum() < 2 or (okr & (arm == a)).sum() < 2:
continue
_, rc, vc = xa.ratio_arm(nn[okr & is_c], dd[okr & is_c])
_, rt, vt = xa.ratio_arm(nn[okr & (arm == a)], dd[okr & (arm == a)])
r = xa.ratio_compare(rc, vc, rt, vt, alpha, alternative)
diffs.append(r["diff"])
variances.append(r["se"] ** 2)
cum.append((c, a, r))
if diffs:
tau = None or (z + float(ndtri(0.8))) * math.sqrt(variances[-1])
pv, lo, hi = xa.msprt(diffs, variances, tau, alpha)
avp[a] = (pv[-1], lo[-1], hi[-1], tau)
def time_label(c):
return (pd.Timestamp("1970-01-01") + pd.Timedelta(days=c)).date().isoformat() if temporal else c
# %% Result
values = {
"control": control, "arms": len(arms), "comparisons": len(treatments), "srm_chi2": srm_chi2, "srm_p": srm_p,
"srm_failed": bool(srm_failed), "srm_blocked": bool(srm_blocked), "alpha": alpha, "primary_metric": primary,
}
for a, n in zip(arms, counts):
values[f"n[{a}]"] = n
for mname, kind, res, theta, red in results:
if theta is not None:
values[f"cuped_theta[{mname}]"] = theta
values[f"cuped_reduction[{mname}]"] = red
values[f"mean[{mname}|{control}]"] = res[treatments[0]]["mean_c"]
for a in treatments:
r = res[a]
k = f"{mname}|{a}"
values[f"mean[{k}]"] = r["mean_t"]
for key in ("diff", "se", "df", "stat", "p", "p_adj", "ci_low", "ci_high", "lift", "lift_low", "lift_high"):
values[f"{key}[{k}]"] = r[key]
first = treatments[0]
pr = primary_res[first]
values.update({
"primary_arm": first, "primary_diff": pr["diff"], "primary_lift": pr["lift"], "primary_lift_low": pr["lift_low"],
"primary_lift_high": pr["lift_high"], "primary_p": pr["p"], "primary_p_adj": pr["p_adj"],
"primary_significant": bool(pr["p_adj"] < alpha),
})
for gname, a, direction, r, t_ni, p_ni, passed in guard:
k = f"{gname}|{a}"
values[f"guard_diff[{k}]"] = r["diff"]
values[f"guard_lift[{k}]"] = r["lift"]
values[f"ni_stat[{k}]"] = t_ni
values[f"ni_p[{k}]"] = p_ni
values[f"ni_pass[{k}]"] = bool(passed)
values["guardrails_failed"] = sum(1 for g in guard if not g[6])
for a, b in bayes:
k = f"{primary}|{a}"
for key in ("prob", "loss_t", "loss_c", "cred_low", "cred_high"):
values[f"bayes_{key}[{k}]"] = b[key]
values["prob_beat_primary"] = bayes[0][1]["prob"] if bayes else None
# %% Decision
RULE_LABELS = {"frequentist": "significance", "expected_loss": "expected loss", "hdi_rope": "credible interval vs ROPE", "prob_to_beat": "probability to beat the control"}
decisions = {}
bayes_by_arm = dict(bayes)
for a in treatments:
r = primary_res[a]
decisions[a] = (("fix the test", "sample ratio mismatch: check randomization and logging") if srm_blocked else
xa.decide(decision_rule, bayes_by_arm.get(a), significant=bool(r["p_adj"] < alpha), diff=r["diff"],
higher_better=higher_better, loss_threshold=0.001, rope=0.002,
prob_threshold=0.95))
values[f"decision[{primary}|{a}]"] = decisions[a][0]
values.update({"decision_rule": decision_rule, "decision_rule_label": RULE_LABELS[decision_rule],
"decision_primary": decisions[first][0], "decision_reason": decisions[first][1],
"prior_mean": prior["mean"] if prior else None, "prior_sd": prior["sd"] if prior else None,
"prior_k": prior["k"] if prior else None, "prior_tau2": prior["tau2"] if prior else None})
for a, b in bayes:
if "post_mean" in b:
values[f"post_mean[{primary}|{a}]"] = b["post_mean"]
values[f"post_sd[{primary}|{a}]"] = b["post_sd"]
if segs:
for (lv, a, r, _), q in zip(segs, seg_adj):
values[f"seg_lift[{lv}|{a}]"] = r["lift"]
values[f"seg_p_adj[{lv}|{a}]"] = float(q)
for a, (pv_, lo_, hi_, tau) in avp.items():
values[f"avp[{a}]"] = pv_
values[f"avp_low[{a}]"] = lo_
values[f"avp_high[{a}]"] = hi_
values[f"avp_tau[{a}]"] = tau
tables = [{
"key": "srm", "title": "Sample ratio",
"columns": [{"key": "arm", "label": "Arm", "type": "string"}, {"key": "n", "label": "Units", "type": "integer"},
{"key": "expected", "label": "Expected", "type": "number"}, {"key": "share", "label": "Share", "type": "percent"}],
"rows": [{"arm": a, "n": n, "expected": e, "share": n / sum(counts)} for a, n, e in zip(arms, counts, srm_expected)],
}]
if not srm_blocked:
rows = []
for i, (mname, kind, res, theta, red) in enumerate(results):
for a in treatments:
r = res[a]
rows.append({"metric": mname, "role": "primary" if i == 0 else "secondary", "arm": a, "control": r["mean_c"], "treatment": r["mean_t"],
"diff": r["diff"], "ci_low": r["ci_low"], "ci_high": r["ci_high"], "lift": r["lift"],
"lift_low": r["lift_low"], "lift_high": r["lift_high"], "p": r["p"], "p_adj": r["p_adj"]})
tables.append({
"key": "metrics", "title": "Metrics",
"columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "role", "label": "Role", "type": "string"},
{"key": "arm", "label": "Arm", "type": "string"}, {"key": "control", "label": "Control", "type": "number"},
{"key": "treatment", "label": "Treatment", "type": "number"}, {"key": "diff", "label": "Difference", "type": "number"},
{"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"},
{"key": "lift", "label": "Lift", "type": "percent"}, {"key": "lift_low", "label": "Lift low", "type": "percent"},
{"key": "lift_high", "label": "Lift high", "type": "percent"}, {"key": "p", "label": "p", "type": "pvalue"},
{"key": "p_adj", "label": "Adjusted p", "type": "pvalue"}],
"rows": rows,
})
if guard:
tables.append({
"key": "guardrails", "title": f"Guardrails (non-inferiority, margin {ni_margin:.1%} of the control)",
"columns": [{"key": "metric", "label": "Guardrail", "type": "string"}, {"key": "arm", "label": "Arm", "type": "string"},
{"key": "better", "label": "Better", "type": "string"}, {"key": "lift", "label": "Lift", "type": "percent"},
{"key": "p", "label": "Non-inferiority p", "type": "pvalue"}, {"key": "status", "label": "Status", "type": "string"}],
"rows": [{"metric": g[0], "arm": g[1], "better": g[2], "lift": g[3]["lift"], "p": g[5], "status": "pass" if g[6] else "fail"} for g in guard],
})
if bayes:
tables.append({
"key": "bayes", "title": f"Bayesian view of {primary}",
"columns": [{"key": "arm", "label": "Arm", "type": "string"}, {"key": "prob", "label": "P(better than control)", "type": "percent"},
{"key": "loss_t", "label": "Expected loss if shipped", "type": "number"}, {"key": "loss_c", "label": "Expected loss if not", "type": "number"},
{"key": "cred_low", "label": "Credible low", "type": "number"}, {"key": "cred_high", "label": "Credible high", "type": "number"}],
"rows": [{"arm": a, **{k: b[k] for k in ("prob", "loss_t", "loss_c", "cred_low", "cred_high")}} for a, b in bayes],
})
if segs:
tables.append({
"key": "segments", "title": f"Segments of {seg} (exploratory)",
"columns": [{"key": "segment", "label": "Segment", "type": "string"}, {"key": "arm", "label": "Arm", "type": "string"},
{"key": "n", "label": "Units", "type": "integer"}, {"key": "lift", "label": "Lift", "type": "percent"},
{"key": "p_adj", "label": "BH-adjusted p", "type": "pvalue"}],
"rows": [{"segment": s[0], "arm": s[1], "n": s[3], "lift": s[2]["lift"], "p_adj": float(q)} for s, q in zip(segs, seg_adj)],
})
charts = []
if not srm_blocked:
fl, fe, flo, fhi, fg = [], [], [], [], []
for i, (mname, kind, res, _, _) in enumerate(results):
for a in treatments:
fl.append(mname if len(treatments) == 1 else f"{mname} · {a}")
fe.append(100 * res[a]["lift"]); flo.append(100 * res[a]["lift_low"]); fhi.append(100 * res[a]["lift_high"])
fg.append("primary" if i == 0 else "secondary")
for gname, a, direction, r, *_ in guard:
fl.append(gname if len(treatments) == 1 else f"{gname} · {a}")
fe.append(100 * r["lift"]); flo.append(100 * r["lift_low"]); fhi.append(100 * r["lift_high"]); fg.append("guardrail")
charts.append(cs.chart("lifts", "forest", "Relative lift vs the control (%)",
{"label": cs.col("Metric", fl), "estimate": cs.col("Lift (%)", fe), "low": cs.col("Low", flo),
"high": cs.col("High", fhi), "group": cs.col("Role", fg)}, controls={"reference": 0}))
if cum:
charts.append(cs.chart("cumulative", "cumulative-lift", f"Cumulative lift of {primary} (%)",
{"time": cs.col("Time", [time_label(c) for c, _, _ in cum], "temporal" if temporal else None),
"lift": cs.col("Lift (%)", [100 * r["lift"] for _, _, r in cum]),
"low": cs.col("Low", [100 * r["lift_low"] for _, _, r in cum]),
"high": cs.col("High", [100 * r["lift_high"] for _, _, r in cum]),
"metric": cs.col("Arm", [a for _, a, _ in cum])}))
if bayes:
a0, b0 = bayes[0]
if "post" in b0:
xs, dens_ = xa.beta_density_grid(b0["post"], b0["range"])
px = list(xs) * 2
pdn = list(dens_[0]) + list(dens_[1])
pa = [control] * len(xs) + [a0] * len(xs)
else:
d0, s0 = (b0["post_mean"], b0["post_sd"]) if "post_mean" in b0 else (primary_res[a0]["diff"], primary_res[a0]["se"])
xs = [d0 + s0 * (-4.0 + 8.0 * i / 199) for i in range(200)]
px, pdn, pa = xs, [math.exp(-0.5 * ((x - d0) / s0) ** 2) / (s0 * math.sqrt(2 * math.pi)) for x in xs], [f"{a0} − {control}"] * 200
rope_w = 0.002 if decision_rule == "hdi_rope" and "post" not in b0 else None
charts.append(cs.chart("posterior", "posterior-density", f"Posterior of {primary}",
{"x": cs.col(primary, px), "density": cs.col("Density", pdn), "arm": cs.col("Arm", pa)},
controls={"rope_low": -rope_w if rope_w else None, "rope_high": rope_w if rope_w else None}))
ships = [b["loss_t"] if higher_better else b["loss_c"] for _, b in bayes]
keeps = [b["loss_c"] if higher_better else b["loss_t"] for _, b in bayes]
charts.append(cs.chart("loss", "expected-loss", f"Expected loss of each choice ({primary})",
{"arm": cs.col("Arm", [a for a, _ in bayes]), "ship": cs.col("Loss if shipped", ships), "keep": cs.col("Loss if not shipped", keeps)},
controls={"threshold": 0.001 if decision_rule == "expected_loss" else 0}))
tables.append({
"key": "decision", "title": f"Decision by {RULE_LABELS[decision_rule]}",
"columns": [{"key": "arm", "label": "Arm", "type": "string"}, {"key": "decision", "label": "Decision", "type": "string"},
{"key": "reason", "label": "Why", "type": "string"}],
"rows": [{"arm": a, "decision": decisions[a][0], "reason": decisions[a][1]} for a in treatments],
})
if prior is not None:
tables.append({
"key": "prior", "title": "Prior from past experiments (random-effects meta-analysis)",
"columns": [{"key": "k", "label": "Experiments", "type": "integer"}, {"key": "mean", "label": "Pooled effect", "type": "number"},
{"key": "se", "label": "SE of the pooled effect", "type": "number"}, {"key": "tau", "label": "Between-experiment SD (τ)", "type": "number"},
{"key": "sd", "label": "Prior SD (predictive)", "type": "number"}],
"rows": [{"k": prior["k"], "mean": prior["mean"], "se": prior["se"], "tau": math.sqrt(prior["tau2"]), "sd": prior["sd"]}],
})
summary = (f"SRM χ² p = {srm_p:.3g}: results withheld." if srm_blocked else
f"{primary}: {first} vs {control} lift {pr['lift']:.2%} [{pr['lift_low']:.2%}, {pr['lift_high']:.2%}], adjusted p = {pr['p_adj']:.3g}.")
cs.publish({
"method": "experiment.analyze",
"methodVersion": "1.1.1",
"title": "A/B test analysis",
"engine": cs.engine_info("scipy"),
"summary": summary,
"statistics": [
{"key": "srm_p", "label": "SRM p", "value": srm_p, "format": "p"},
*([] if srm_blocked else [
{"key": "primary_lift", "label": f"Lift ({primary})", "value": pr["lift"], "format": "percent"},
{"key": "primary_p_adj", "label": "Adjusted p", "value": pr["p_adj"], "format": "p"},
]),
],
"assumptions": [{"key": "srm", "label": "Sample ratio matches the plan", "status": "fail" if srm_failed else "pass",
"detail": f"χ²({len(arms) - 1}) = {srm_chi2:.2f}, p = {srm_p:.3g}" + (" — results withheld" if srm_blocked else "")}],
"tables": tables,
"charts": charts,
"warnings": warnings,
"notes": [
"Differences are treatment − control; lifts are relative to the control mean with delta-method intervals.",
"Ratio metrics are Σ numerator / Σ denominator per arm with delta-method variances (z tests).",
*(["CUPED adjusts each metric by its pre-period value with θ pooled over all units."] if pre_for and cuped_on else []),
*(["Segment results are exploratory (BH-adjusted); they do not confirm effects."] if segs else []),
*(["Always-valid p-values (mixture SPRT) stay valid however often the cumulative results are checked."] if avp else []),
],
"values": values,
})
Here revenue is the primary metric and sessions is a guardrail that should not fall. Guardrails failed: 0. The verdict is ship, with a lift of 19.1%.
A ratio as the primary metric
PredictPredict first
This test has three treatment arms and uses a Bonferroni correction for the three comparisons. What happens to the p-value for arm A?
Reveal
Raw p is p = .257, and adjusted p is p = .772. The more comparisons you make, the stronger each one's evidence has to be.
Recap
Recap- Name one primary metric tied to the decision before the test begins.
- Guardrails are checks that must not get worse, not extra chances to win.
- Analyze ratio metrics at the randomized unit, with the delta method.
Concepts in this lesson