From a result to a decision
See how the same data lead to different actions under significance, expected loss, ROPE and probability-to-beat rules.
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
- Apply four decision rules to one result
- Explain expected loss as what you'd lose if you chose wrong
- Use past experiments as an informed prior, and say what it changes
Read first
A rule picks the action
ReadA test doesn't decide anything. You supply a rule that maps evidence to an action, and the rule should fit what's at stake. The studio offers four:
- Significance: ship when the interval clears zero.
- Expected lossExpected loss (Bayesian A/B)How much you expect to lose, in the metric's units, if you make a choice and it turns out to be the worse one.: ship when the average regret of being wrong is tolerably small.
- Credible interval vs ROPERegion of practical equivalence (ROPE)A band around zero of differences too small to matter; decisions compare the credible interval with it.: act when the interval clears a band of "too small to matter".
- Probability to beat: ship when the treatment is probably better.
Same data, different verdict
PredictPredict first
On the conversion test you've seen, the lift has p = .093 and a 95.3% chance of beating control. The team would accept a small expected loss. Which rule ships?
Reveal
Significance says keep collecting, since p = .093. Expected loss says ship. Being wrong here would cost little, so it's willing to act sooner.
What expected loss means
ReadAverage over your posterior how much you'd give up by choosing treatment if control is actually better. When that falls under your threshold, the choice can't cost much either way.
It suits cheap, reversible changes. For a change that's costly to reverse, it may act too quickly.
converted: treatment vs control lift 15.17% [-3.85%, 34.20%], adjusted p = 0.0928.
- SRM p
- .164
- Lift (converted)
- 15.2%
- Adjusted p
- .093
Plots
View data
| Lift (%) | Role | High | Metric | Low |
|---|---|---|---|---|
| 15.172 | primary | 34.199 | converted | −3.854 |
View data
| Arm | Density | converted |
|---|---|---|
| control | 1.334e-9 | 0.0715 |
| control | 2.904e-9 | 0.0721 |
| control | 6.217e-9 | 0.0727 |
| control | 1.309e-8 | 0.0733 |
| control | 2.714e-8 | 0.0739 |
| control | 5.535e-8 | 0.0745 |
| control | 1.111e-7 | 0.0751 |
| control | 2.197e-7 | 0.0757 |
| control | 4.279e-7 | 0.0763 |
| control | 8.210e-7 | 0.0769 |
| control | 1.552e-6 | 0.0775 |
| control | 2.892e-6 | 0.0781 |
| control | 5.312e-6 | 0.0787 |
| control | 9.620e-6 | 0.0793 |
| control | 1.718e-5 | 0.0799 |
| control | 3.027e-5 | 0.0805 |
| control | 5.261e-5 | 0.0811 |
| control | 9.023e-5 | 0.0817 |
| control | 0.0002 | 0.0824 |
| control | 0.0003 | 0.0830 |
| control | 0.0004 | 0.0836 |
| control | 0.0007 | 0.0842 |
| control | 0.0011 | 0.0848 |
| control | 0.0018 | 0.0854 |
| control | 0.0028 | 0.0860 |
| control | 0.0043 | 0.0866 |
| control | 0.0066 | 0.0872 |
| control | 0.0099 | 0.0878 |
| control | 0.0149 | 0.0884 |
| control | 0.0220 | 0.0890 |
| control | 0.0323 | 0.0896 |
| control | 0.0468 | 0.0902 |
| control | 0.0670 | 0.0908 |
| control | 0.0950 | 0.0914 |
| control | 0.1332 | 0.0920 |
| control | 0.1848 | 0.0926 |
| control | 0.2538 | 0.0932 |
| control | 0.3451 | 0.0939 |
| control | 0.4643 | 0.0945 |
| control | 0.6185 | 0.0951 |
| control | 0.8158 | 0.0957 |
| control | 1.066 | 0.0963 |
| control | 1.378 | 0.0969 |
| control | 1.766 | 0.0975 |
| control | 2.241 | 0.0981 |
| control | 2.817 | 0.0987 |
| control | 3.509 | 0.0993 |
| control | 4.330 | 0.0999 |
| control | 5.296 | 0.1005 |
| control | 6.419 | 0.1011 |
| control | 7.712 | 0.1017 |
| control | 9.184 | 0.1023 |
| control | 10.842 | 0.1029 |
| control | 12.691 | 0.1035 |
| control | 14.728 | 0.1041 |
| control | 16.949 | 0.1047 |
| control | 19.344 | 0.1054 |
| control | 21.895 | 0.1060 |
| control | 24.581 | 0.1066 |
| control | 27.375 | 0.1072 |
First 60 of 400 rows.
View data
| Arm | Loss if not shipped | Loss if shipped |
|---|---|---|
| treatment | 0.0177 | 0.0002 |
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| converted | primary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .093 | .093 |
Bayesian view of converted
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 95.3% | 0.0002 | 0.0177 | −0.0030 | 0.0379 |
Decision by expected loss
| Arm | Decision | Why |
|---|---|---|
| treatment | ship | expected loss of shipping 0.0002022 is below the tolerable 0.002 |
- 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).
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 f3d7a4288fb474b9
# 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("converted") # first = primary
g_up <- c() # higher is better
g_down <- c() # lower is better
pre_cols <- c()
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", "converted")))
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", "converted")) # 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 <- "two-sided"
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 <- "expected_loss" # 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.002, 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.002 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
))
converted: treatment vs control lift 15.17% [-3.85%, 34.20%], adjusted p = 0.0928.
- SRM p
- .164
- Lift (converted)
- 15.2%
- Adjusted p
- .093
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| converted | primary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .093 | .093 |
Bayesian view of converted
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 95.3% | 0.0002 | 0.0177 | −0.0030 | 0.0379 |
Decision by expected loss
| Arm | Decision | Why |
|---|---|---|
| treatment | ship | expected loss of shipping 0.0002022 is below the tolerable 0.002 |
- 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).
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 f3d7a4288fb474b9
# 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 = ["converted"] # first = primary
g_up = [] # higher is better
g_down = [] # lower is better
pre_cols = []
nums, dens = [], []
seg = None
tcol = None
bool_cols = ["converted", ]
df = pd.read_parquet("tests/parity/fixtures/e1_ab.parquet", columns=["variant", "converted"])
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", "converted"]) # 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 = "two-sided"
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 = "expected_loss" # 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.002, 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.002 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,
})
Priors from past experiments
In the appYour past tests say something about typical effects. Most are small. An informed prior shrinks a surprising lift toward that history.
converted: treatment vs control lift 15.17% [-3.85%, 34.20%], adjusted p = 0.0928.
- SRM p
- .164
- Lift (converted)
- 15.2%
- Adjusted p
- .093
Plots
View data
| Lift (%) | Role | High | Metric | Low |
|---|---|---|---|---|
| 15.172 | primary | 34.199 | converted | −3.854 |
View data
| Arm | Density | converted |
|---|---|---|
| treatment − control | 0.0378 | −0.0081 |
| treatment − control | 0.0444 | −0.0079 |
| treatment − control | 0.0520 | −0.0078 |
| treatment − control | 0.0609 | −0.0076 |
| treatment − control | 0.0711 | −0.0075 |
| treatment − control | 0.0829 | −0.0074 |
| treatment − control | 0.0965 | −0.0072 |
| treatment − control | 0.1121 | −0.0071 |
| treatment − control | 0.1301 | −0.0069 |
| treatment − control | 0.1507 | −0.0068 |
| treatment − control | 0.1743 | −0.0066 |
| treatment − control | 0.2013 | −0.0065 |
| treatment − control | 0.2320 | −0.0064 |
| treatment − control | 0.2670 | −0.0062 |
| treatment − control | 0.3069 | −0.0061 |
| treatment − control | 0.3521 | −0.0059 |
| treatment − control | 0.4032 | −0.0058 |
| treatment − control | 0.4611 | −0.0057 |
| treatment − control | 0.5265 | −0.0055 |
| treatment − control | 0.6001 | −0.0054 |
| treatment − control | 0.6829 | −0.0052 |
| treatment − control | 0.7759 | −0.0051 |
| treatment − control | 0.8802 | −0.0049 |
| treatment − control | 0.9968 | −0.0048 |
| treatment − control | 1.127 | −0.0047 |
| treatment − control | 1.272 | −0.0045 |
| treatment − control | 1.434 | −0.0044 |
| treatment − control | 1.614 | −0.0042 |
| treatment − control | 1.813 | −0.0041 |
| treatment − control | 2.033 | −0.0039 |
| treatment − control | 2.277 | −0.0038 |
| treatment − control | 2.545 | −0.0037 |
| treatment − control | 2.841 | −0.0035 |
| treatment − control | 3.166 | −0.0034 |
| treatment − control | 3.522 | −0.0032 |
| treatment − control | 3.912 | −0.0031 |
| treatment − control | 4.338 | −0.0030 |
| treatment − control | 4.803 | −0.0028 |
| treatment − control | 5.310 | −0.0027 |
| treatment − control | 5.860 | −0.0025 |
| treatment − control | 6.456 | −0.0024 |
| treatment − control | 7.102 | −0.0022 |
| treatment − control | 7.800 | −0.0021 |
| treatment − control | 8.553 | −0.0020 |
| treatment − control | 9.363 | −0.0018 |
| treatment − control | 10.233 | −0.0017 |
| treatment − control | 11.166 | −0.0015 |
| treatment − control | 12.165 | −0.0014 |
| treatment − control | 13.232 | −0.0012 |
| treatment − control | 14.368 | −0.0011 |
| treatment − control | 15.578 | −0.0010 |
| treatment − control | 16.861 | −0.0008 |
| treatment − control | 18.221 | −0.0007 |
| treatment − control | 19.659 | −0.0005 |
| treatment − control | 21.177 | −0.0004 |
| treatment − control | 22.774 | −0.0002 |
| treatment − control | 24.453 | −0.0001 |
| treatment − control | 26.212 | 3.474e-5 |
| treatment − control | 28.053 | 0.0002 |
| treatment − control | 29.975 | 0.0003 |
First 60 of 200 rows.
View data
| Arm | Loss if not shipped | Loss if shipped |
|---|---|---|
| treatment | 0.0061 | 6.183e-5 |
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| converted | primary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .093 | .093 |
Bayesian view of converted
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 95.7% | 6.183e-5 | 0.0061 | −0.0009 | 0.0130 |
Decision by credible interval vs ROPE
| Arm | Decision | Why |
|---|---|---|
| treatment | keep collecting | the credible interval overlaps the region of practical equivalence |
Prior from past experiments (random-effects meta-analysis)
| Experiments | Pooled effect | SE of the pooled effect | Between-experiment SD (τ) | Prior SD (predictive) |
|---|---|---|---|---|
| 5 | 0.0046 | 0.0026 | 0.0027 | 0.0038 |
- 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).
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 46a1519155df5536
# 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("converted") # first = primary
g_up <- c() # higher is better
g_down <- c() # lower is better
pre_cols <- c()
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", "converted")))
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", "converted")) # 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 <- "two-sided"
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 <- "hdi_rope" # frequentist | expected_loss | hdi_rope | prob_to_beat
higher_better <- "higher" != "lower"
prior <- NULL
if ("meta" == "meta") {
# Informed prior: random-effects pooled effect of past experiments, predictive SD (tau included).
prior <- cs_exp_meta_prior(as.numeric(unlist(c(0.004, 0.011, -0.002, 0.007, 0.009))), as.numeric(unlist(c(0.005, 0.006, 0.004, 0.005, 0.007))), "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.004, 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.004 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
))
converted: treatment vs control lift 15.17% [-3.85%, 34.20%], adjusted p = 0.0928.
- SRM p
- .164
- Lift (converted)
- 15.2%
- Adjusted p
- .093
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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| converted | primary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .093 | .093 |
Bayesian view of converted
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 95.7% | 6.183e-5 | 0.0061 | −0.0009 | 0.0130 |
Decision by credible interval vs ROPE
| Arm | Decision | Why |
|---|---|---|
| treatment | keep collecting | the credible interval overlaps the region of practical equivalence |
Prior from past experiments (random-effects meta-analysis)
| Experiments | Pooled effect | SE of the pooled effect | Between-experiment SD (τ) | Prior SD (predictive) |
|---|---|---|---|---|
| 5 | 0.0046 | 0.0026 | 0.0027 | 0.0038 |
- 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).
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 46a1519155df5536
# 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 = ["converted"] # first = primary
g_up = [] # higher is better
g_down = [] # lower is better
pre_cols = []
nums, dens = [], []
seg = None
tcol = None
bool_cols = ["converted", ]
df = pd.read_parquet("tests/parity/fixtures/e1_ab.parquet", columns=["variant", "converted"])
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", "converted"]) # 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 = "two-sided"
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 = "hdi_rope" # frequentist | expected_loss | hdi_rope | prob_to_beat
higher_better = "higher" != "lower"
prior = None
if "meta" == "meta":
# Informed prior: random-effects pooled effect of past experiments, predictive SD (τ included).
prior = xa.meta_prior([0.004, 0.011, -0.002, 0.007, 0.009], [0.005, 0.006, 0.004, 0.005, 0.007], "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.004,
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.004 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,
})
From 5 past experiments, the prior centers on 0.46%. Under the ROPE rule the verdict is keep collecting, because the shrunken interval doesn't clear the band yet.
Check your understanding
CheckpointCheck yourself
When does an expected-loss rule make most sense?
Show the answer
Answer: a
Expected loss weighs the size of a possible mistake. That's a fair trade when mistakes are small and can be undone.
Check yourself
The credible interval sits entirely inside the ROPE. What does that support?
Show the answer
Answer: b
A ROPE lets you conclude "practically nothing here", which a significance test can't do.
Check yourself
"A 95% probability to beat control" means:
Show the answer
Answer: b
It says nothing about how much better. Pair it with the size of the lift and its interval.
Choose your rule first
ReflectPick the rule when you pre-register, because switching after you see the results is a forking path. For your next test, how costly is a wrong call? Which rule fits?
Record the decision
In the appThe Decide step records Ship, Iterate, Stop or Extend with your reasoning, next to the numbers that informed it.
Recap
Recap- The decision rule, not the p-value, maps evidence to action.
- Expected loss suits cheap, reversible changes.
- Choose the rule when you pre-register, and use past experiments as priors when you have them.
Concepts in this lesson