Skip to content

Capstone: a memo someone can act on

Write the one-page memo for the checkout test, with a call, a finding, safety checks and limits. Critique a weak draft, then hand over a PDF and something a reviewer can rerun.

Applied ~20 min10 steps

What runs in CodeSplash

You will be able to

  • Build an executive report from a saved result
  • Write a call, a finding, safety checks and limits a reader can act on
  • Disclose what you tried, and hand over something a reviewer can check

Read first

01

Your brief

Read

The checkout test from the first lesson is ready to write up. The product lead decides on Friday and wants one page. A reviewer will want to see how you got there.

Here is what the analysis found:

  • Primary metric: conversion changed by 15.2%, 95% CI −3.9% to 34.2%, p = .093.
  • Split check: the arms are compatible with the planned split, p = .164.
  • Guardrails: 0 failed. Page load was checked for harm.
02

Get a saved result

In the app

A report is built from saved results. Take the walkthrough to run this test on the practice data, or use a saved analysis of your own and follow along with those numbers.

A/B test analysisRecorded · Python and R agreeRecorded 2026-11-17 · 76 values compared · largest relative difference 1.4e-12
R

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

Relative lift vs the control (%)How large are several estimates, how precise, and which exclude the null?
View data
Lift (%)RoleHighMetricLow
15.172primary34.199converted−3.854
5.094secondary11.323clicks / sessions−1.135
−0.6595guardrail1.492page load ms−2.811
Cumulative lift of converted (%)Is the treatment effect stable over the test, or fading (novelty) or growing (primacy)?
View data
HighLift (%)LowArmTime
240.4984.006−72.482treatment1,788,220,800,000
131.0742.403−46.261treatment1,788,307,200,000
176.7786.477−3.817treatment1,788,393,600,000
110.0849.887−10.310treatment1,788,480,000,000
92.70442.015−8.675treatment1,788,566,400,000
72.08529.953−12.179treatment1,788,652,800,000
54.46818.981−16.507treatment1,788,739,200,000
53.02019.405−14.209treatment1,788,825,600,000
57.50224.670−8.163treatment1,788,912,000,000
67.34534.4841.623treatment1,788,998,400,000
59.83729.714−0.4102treatment1,789,084,800,000
58.71730.0491.382treatment1,789,171,200,000
63.00134.4015.801treatment1,789,257,600,000
54.29328.4102.527treatment1,789,344,000,000
46.77722.943−0.8912treatment1,789,430,400,000
44.84721.747−1.353treatment1,789,516,800,000
38.64217.203−4.236treatment1,789,603,200,000
35.08014.679−5.723treatment1,789,689,600,000
32.39012.784−6.822treatment1,789,776,000,000
32.30413.111−6.083treatment1,789,862,400,000
34.19915.172−3.854treatment1,789,948,800,000
Posterior of convertedGiven the data, where does each arm's true rate (or the lift) probably lie, and how much do the posteriors overlap?
View data
ArmDensityconverted
control1.334e-90.0715
control2.904e-90.0721
control6.217e-90.0727
control1.309e-80.0733
control2.714e-80.0739
control5.535e-80.0745
control1.111e-70.0751
control2.197e-70.0757
control4.279e-70.0763
control8.210e-70.0769
control1.552e-60.0775
control2.892e-60.0781
control5.312e-60.0787
control9.620e-60.0793
control1.718e-50.0799
control3.027e-50.0805
control5.261e-50.0811
control9.023e-50.0817
control0.00020.0824
control0.00030.0830
control0.00040.0836
control0.00070.0842
control0.00110.0848
control0.00180.0854
control0.00280.0860
control0.00430.0866
control0.00660.0872
control0.00990.0878
control0.01490.0884
control0.02200.0890
control0.03230.0896
control0.04680.0902
control0.06700.0908
control0.09500.0914
control0.13320.0920
control0.18480.0926
control0.25380.0932
control0.34510.0939
control0.46430.0945
control0.61850.0951
control0.81580.0957
control1.0660.0963
control1.3780.0969
control1.7660.0975
control2.2410.0981
control2.8170.0987
control3.5090.0993
control4.3300.0999
control5.2960.1005
control6.4190.1011
control7.7120.1017
control9.1840.1023
control10.8420.1029
control12.6910.1035
control14.7280.1041
control16.9490.1047
control19.3440.1054
control21.8950.1060
control24.5810.1066
control27.3750.1072

First 60 of 400 rows.

Expected loss of each choice (converted)If we ship (or keep the control) now, how much do we expect to lose if that choice turns out wrong?
View data
ArmLoss if not shippedLoss if shipped
treatment0.01770.0002

Assumptions

  • Sample ratio matches the plan — χ²(1) = 1.94, p = 0.164

Sample ratio

ArmUnitsExpectedShare
control1,9562,00048.9%
treatment2,0442,00051.1%

Metrics

MetricRoleArmControlTreatmentDifferenceCI lowCI highLiftLift lowLift highpAdjusted p
convertedprimarytreatment0.11550.13310.0175−0.00290.038015.2%-3.9%34.2%.093.093
clicks / sessionssecondarytreatment0.17680.18580.0090−0.00170.01975.1%-1.1%11.3%.100.100

Guardrails (non-inferiority, margin 2.0% of the control)

GuardrailArmBetterLiftNon-inferiority pStatus
page load mstreatmentlower-0.7%.008pass

Bayesian view of converted

ArmP(better than control)Expected loss if shippedExpected loss if notCredible lowCredible high
treatment95.3%0.00020.0177−0.00300.0379

Segments of device (exploratory)

SegmentArmUnitsLiftBH-adjusted p
desktoptreatment1,75414.9%.344
mobiletreatment1,8678.0%.583
tablettreatment37943.7%.344

Decision by significance

ArmDecisionWhy
treatmentkeep collectingnot significant: keep collecting until the planned sample, then keep the control
  • 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).
  • Segment results are exploratory (BH-adjusted); they do not confirm effects.
  • Always-valid p-values (mixture SPRT) stay valid however often the cumulative results are checked.
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 578557e054508d0b
# 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("page load ms") # lower is better
pre_cols <- c()
nums <- c("clicks")
dens <- c("sessions")
seg <- "device"
tcol <- "first seen"
bool_cols <- c("converted", NULL)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/e1_ab.parquet", col_select = c("variant", "converted", "page load ms", "clicks", "sessions", "device", "first seen")))
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", "page load ms", "clicks", "sessions", "device", "first seen"))  # 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 <- "frequentist" # frequentist | expected_loss | hdi_rope | prob_to_beat
higher_better <- "higher" != "lower"
prior <- NULL
if ("flat" == "meta") {
  # Informed prior: random-effects pooled effect of past experiments, predictive SD (tau included).
  prior <- cs_exp_meta_prior(as.numeric(unlist(c())), as.numeric(unlist(c())), "REML")
}
bayes <- list()
if (TRUE || decision_rule != "frequentist" || !is.null(prior)) {
  cred <- 1 - alpha
  binary <- primary_kind == "metric" && primary %in% bool_cols
  yb <- if (binary) values_of(primary) else NULL
  for (a in treatments) {
    bres <- if (!is.null(prior)) {
      cs_exp_normal_posterior(results[[1]]$res[[a]]$diff, results[[1]]$res[[a]]$se, prior$mean, prior$sd, cred)
    } else if (binary) {
      okc <- is_c & !is.na(yb)
      okt <- arm == a & !is.na(yb)
      cs_exp_beta_compare(sum(yb[okc]), sum(okc), sum(yb[okt]), sum(okt), 1, 1, cred)
    } else {
      cs_exp_normal_compare(results[[1]]$res[[a]]$diff, results[[1]]$res[[a]]$se, cred)
    }
    bayes[[a]] <- bres
  }
}

# %% Segments (exploratory)
segs <- list()
if (!is.null(seg) && primary_kind == "metric") {
  y <- values_of(primary)
  sv <- as.character(df[[seg]])
  seg_levels <- c("desktop", "mobile", "tablet")
  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 <- TRUE
  tt <- if (inherits(t_raw, "Date")) as.numeric(t_raw) else if (inherits(t_raw, "POSIXt")) as.numeric(t_raw) / 86400 else as.numeric(t_raw)
  cuts <- cs_exp_cut_points(tt[!is.na(tt)])
  if (primary_kind == "metric") {
    y <- values_of(primary)
  } else {
    nn <- values_of(nums[1])
    dd <- values_of(dens[1])
  }
  for (a in treatments) {
    diffs <- variances <- numeric(0)
    for (cut in cuts) {
      win <- !is.na(tt) & tt <= cut
      if (primary_kind == "metric") {
        selc <- win & is_c & !is.na(y)
        selt <- win & arm == a & !is.na(y)
        if (sum(selc) < 2 || sum(selt) < 2) next
        mc <- cs_exp_moments(y[selc])
        mt <- cs_exp_moments(y[selt])
        if (!(mc$var > 0 || mt$var > 0)) next
        r <- cs_exp_welch(mc$n, mc$mean, mc$var, mt$n, mt$mean, mt$var, alpha, alternative)
      } else {
        okr <- win & !(is.na(nn) | is.na(dd))
        if (sum(okr & is_c) < 2 || sum(okr & arm == a) < 2) next
        rc <- cs_exp_ratio_arm(nn[okr & is_c], dd[okr & is_c])
        rt <- cs_exp_ratio_arm(nn[okr & arm == a], dd[okr & arm == a])
        r <- cs_exp_ratio_compare(rc$ratio, rc$var, rt$ratio, rt$var, alpha, alternative)
      }
      diffs <- c(diffs, r$diff)
      variances <- c(variances, r$se^2)
      cum[[length(cum) + 1]] <- list(cut = cut, arm = a, r = r)
    }
    if (length(diffs)) {
      tau <- NULL
      if (is.null(tau) || tau <= 0) tau <- (z + stats::qnorm(0.8)) * sqrt(variances[length(variances)])
      ms <- cs_exp_msprt(diffs, variances, tau, alpha)
      n <- length(ms$p)
      avp[[a]] <- c(ms$p[n], ms$low[n], ms$high[n], tau)
    }
  }
}
time_label <- function(cut) if (temporal) format(as.Date(cut, origin = "1970-01-01")) else cut

# %% Result
values <- list(control = control, arms = length(arms), comparisons = length(treatments), srm_chi2 = srm$chi2, srm_p = srm$p,
               srm_failed = srm_failed, srm_blocked = srm_blocked, alpha = alpha, primary_metric = primary)
for (i in seq_along(arms)) values[[sprintf("n[%s]", arms[i])]] <- counts[[i]]
for (res in results) {
  mname <- res$name
  if (!is.null(res$theta)) {
    values[[sprintf("cuped_theta[%s]", mname)]] <- res$theta
    values[[sprintf("cuped_reduction[%s]", mname)]] <- res$red
  }
  values[[sprintf("mean[%s|%s]", mname, control)]] <- res$res[[treatments[1]]]$mean_c
  for (a in treatments) {
    r <- res$res[[a]]
    k <- sprintf("%s|%s", mname, a)
    values[[sprintf("mean[%s]", k)]] <- r$mean_t
    for (key in c("diff", "se", "df", "stat", "p", "p_adj", "ci_low", "ci_high", "lift", "lift_low", "lift_high")) values[[sprintf("%s[%s]", key, k)]] <- r[[key]]
  }
}
first <- treatments[1]
pr <- results[[1]]$res[[first]]
values$primary_arm <- first
values$primary_diff <- pr$diff
values$primary_lift <- pr$lift
values$primary_lift_low <- pr$lift_low
values$primary_lift_high <- pr$lift_high
values$primary_p <- pr$p
values$primary_p_adj <- pr$p_adj
values$primary_significant <- pr$p_adj < alpha
for (g in guard) {
  k <- sprintf("%s|%s", g$name, g$arm)
  values[[sprintf("guard_diff[%s]", k)]] <- g$r$diff
  values[[sprintf("guard_lift[%s]", k)]] <- g$r$lift
  values[[sprintf("ni_stat[%s]", k)]] <- g$t
  values[[sprintf("ni_p[%s]", k)]] <- g$p
  values[[sprintf("ni_pass[%s]", k)]] <- g$pass
}
values$guardrails_failed <- sum(vapply(guard, function(g) !g$pass, logical(1)))
for (a in names(bayes)) {
  k <- sprintf("%s|%s", primary, a)
  for (key in c("prob", "loss_t", "loss_c", "cred_low", "cred_high")) values[[sprintf("bayes_%s[%s]", key, k)]] <- bayes[[a]][[key]]
}
values$prob_beat_primary <- if (length(bayes)) bayes[[1]]$prob else NA
# %% Decision
rule_labels <- c(frequentist = "significance", expected_loss = "expected loss", hdi_rope = "credible interval vs ROPE", prob_to_beat = "probability to beat the control")
decisions <- list()
for (a in treatments) {
  r <- results[[1]]$res[[a]]
  decisions[[a]] <- if (srm_blocked) c("fix the test", "sample ratio mismatch: check randomization and logging") else
    cs_exp_decide(decision_rule, bayes[[a]], r$p_adj < alpha, r$diff, higher_better, 0.001, 0.002, 0.95)
  values[[sprintf("decision[%s|%s]", primary, a)]] <- decisions[[a]][1]
}
values$decision_rule <- decision_rule
values$decision_rule_label <- unname(rule_labels[decision_rule])
values$decision_primary <- decisions[[first]][1]
values$decision_reason <- decisions[[first]][2]
values$prior_mean <- if (is.null(prior)) NA else prior$mean
values$prior_sd <- if (is.null(prior)) NA else prior$sd
values$prior_k <- if (is.null(prior)) NA else prior$k
values$prior_tau2 <- if (is.null(prior)) NA else prior$tau2
for (a in names(bayes)) if (!is.null(bayes[[a]]$post_mean)) {
  values[[sprintf("post_mean[%s|%s]", primary, a)]] <- bayes[[a]]$post_mean
  values[[sprintf("post_sd[%s|%s]", primary, a)]] <- bayes[[a]]$post_sd
}
if (length(segs)) for (i in seq_along(segs)) {
  values[[sprintf("seg_lift[%s|%s]", segs[[i]]$level, segs[[i]]$arm)]] <- segs[[i]]$r$lift
  values[[sprintf("seg_p_adj[%s|%s]", segs[[i]]$level, segs[[i]]$arm)]] <- seg_adj[i]
}
for (a in names(avp)) {
  values[[sprintf("avp[%s]", a)]] <- avp[[a]][1]
  values[[sprintf("avp_low[%s]", a)]] <- avp[[a]][2]
  values[[sprintf("avp_high[%s]", a)]] <- avp[[a]][3]
  values[[sprintf("avp_tau[%s]", a)]] <- avp[[a]][4]
}

tables <- list(list(
  key = "srm", title = "Sample ratio",
  columns = list(list(key = "arm", label = "Arm", type = "string"), list(key = "n", label = "Units", type = "integer"),
                 list(key = "expected", label = "Expected", type = "number"), list(key = "share", label = "Share", type = "percent")),
  rows = lapply(seq_along(arms), function(i) list(arm = arms[i], n = counts[[i]], expected = srm$expected[i], share = counts[[i]] / sum(counts)))
))
charts <- list()
if (!srm_blocked) {
  rows <- list()
  for (j in seq_along(results)) for (a in treatments) {
    r <- results[[j]]$res[[a]]
    rows[[length(rows) + 1]] <- list(metric = results[[j]]$name, role = if (j == 1) "primary" else "secondary", arm = a, control = r$mean_c,
                                     treatment = r$mean_t, diff = r$diff, ci_low = r$ci_low, ci_high = r$ci_high, lift = r$lift,
                                     lift_low = r$lift_low, lift_high = r$lift_high, p = r$p, p_adj = r$p_adj)
  }
  tables <- c(tables, list(list(
    key = "metrics", title = "Metrics",
    columns = list(list(key = "metric", label = "Metric", type = "string"), list(key = "role", label = "Role", type = "string"),
                   list(key = "arm", label = "Arm", type = "string"), list(key = "control", label = "Control", type = "number"),
                   list(key = "treatment", label = "Treatment", type = "number"), list(key = "diff", label = "Difference", type = "number"),
                   list(key = "ci_low", label = "CI low", type = "number"), list(key = "ci_high", label = "CI high", type = "number"),
                   list(key = "lift", label = "Lift", type = "percent"), list(key = "lift_low", label = "Lift low", type = "percent"),
                   list(key = "lift_high", label = "Lift high", type = "percent"), list(key = "p", label = "p", type = "pvalue"),
                   list(key = "p_adj", label = "Adjusted p", type = "pvalue")),
    rows = rows
  )))
  if (length(guard)) {
    tables <- c(tables, list(list(
      key = "guardrails", title = sprintf("Guardrails (non-inferiority, margin %.1f%% of the control)", 100 * ni_margin),
      columns = list(list(key = "metric", label = "Guardrail", type = "string"), list(key = "arm", label = "Arm", type = "string"),
                     list(key = "better", label = "Better", type = "string"), list(key = "lift", label = "Lift", type = "percent"),
                     list(key = "p", label = "Non-inferiority p", type = "pvalue"), list(key = "status", label = "Status", type = "string")),
      rows = lapply(guard, function(g) list(metric = g$name, arm = g$arm, better = g$direction, lift = g$r$lift, p = g$p, status = if (g$pass) "pass" else "fail"))
    )))
  }
  if (length(bayes)) {
    tables <- c(tables, list(list(
      key = "bayes", title = sprintf("Bayesian view of %s", primary),
      columns = list(list(key = "arm", label = "Arm", type = "string"), list(key = "prob", label = "P(better than control)", type = "percent"),
                     list(key = "loss_t", label = "Expected loss if shipped", type = "number"), list(key = "loss_c", label = "Expected loss if not", type = "number"),
                     list(key = "cred_low", label = "Credible low", type = "number"), list(key = "cred_high", label = "Credible high", type = "number")),
      rows = lapply(names(bayes), function(a) list(arm = a, prob = bayes[[a]]$prob, loss_t = bayes[[a]]$loss_t, loss_c = bayes[[a]]$loss_c,
                                                   cred_low = bayes[[a]]$cred_low, cred_high = bayes[[a]]$cred_high))
    )))
  }
  if (length(segs)) {
    tables <- c(tables, list(list(
      key = "segments", title = sprintf("Segments of %s (exploratory)", seg),
      columns = list(list(key = "segment", label = "Segment", type = "string"), list(key = "arm", label = "Arm", type = "string"),
                     list(key = "n", label = "Units", type = "integer"), list(key = "lift", label = "Lift", type = "percent"),
                     list(key = "p_adj", label = "BH-adjusted p", type = "pvalue")),
      rows = lapply(seq_along(segs), function(i) list(segment = segs[[i]]$level, arm = segs[[i]]$arm, n = segs[[i]]$n, lift = segs[[i]]$r$lift, p_adj = seg_adj[i]))
    )))
  }
  fl <- fg <- character(0)
  fe <- flo <- fhi <- numeric(0)
  for (j in seq_along(results)) for (a in treatments) {
    r <- results[[j]]$res[[a]]
    fl <- c(fl, if (length(treatments) == 1) results[[j]]$name else sprintf("%s · %s", results[[j]]$name, a))
    fe <- c(fe, 100 * r$lift); flo <- c(flo, 100 * r$lift_low); fhi <- c(fhi, 100 * r$lift_high)
    fg <- c(fg, if (j == 1) "primary" else "secondary")
  }
  for (g in guard) {
    fl <- c(fl, if (length(treatments) == 1) g$name else sprintf("%s · %s", g$name, g$arm))
    fe <- c(fe, 100 * g$r$lift); flo <- c(flo, 100 * g$r$lift_low); fhi <- c(fhi, 100 * g$r$lift_high); fg <- c(fg, "guardrail")
  }
  charts <- c(charts, list(cs_chart("lifts", "forest", "Relative lift vs the control (%)",
    list(label = cs_col("Metric", fl), estimate = cs_col("Lift (%)", fe), low = cs_col("Low", flo), high = cs_col("High", fhi), group = cs_col("Role", fg)),
    controls = list(reference = 0))))
  if (length(cum)) {
    charts <- c(charts, list(cs_chart("cumulative", "cumulative-lift", sprintf("Cumulative lift of %s (%%)", primary),
      list(time = cs_col("Time", vapply(cum, function(cc) as.character(time_label(cc$cut)), character(1)), if (temporal) "temporal" else NULL),
           lift = cs_col("Lift (%)", vapply(cum, function(cc) 100 * cc$r$lift, numeric(1))),
           low = cs_col("Low", vapply(cum, function(cc) 100 * cc$r$lift_low, numeric(1))),
           high = cs_col("High", vapply(cum, function(cc) 100 * cc$r$lift_high, numeric(1))),
           metric = cs_col("Arm", vapply(cum, function(cc) cc$arm, character(1)))))))
  }
  if (length(bayes)) {
    a0 <- names(bayes)[1]
    b0 <- bayes[[1]]
    if (!is.null(b0$post)) {
      dg <- cs_exp_beta_density(b0$post, b0$range)
      px <- c(dg$x, dg$x)
      pdn <- c(dg$densities[[1]], dg$densities[[2]])
      pa <- c(rep(control, length(dg$x)), rep(a0, length(dg$x)))
    } else {
      d0 <- if (!is.null(b0$post_mean)) b0$post_mean else results[[1]]$res[[a0]]$diff
      s0 <- if (!is.null(b0$post_mean)) b0$post_sd else results[[1]]$res[[a0]]$se
      px <- d0 + s0 * (-4 + 8 * (0:199) / 199)
      pdn <- stats::dnorm(px, d0, s0)
      pa <- rep(sprintf("%s − %s", a0, control), 200)
    }
    rope_w <- if (decision_rule == "hdi_rope" && is.null(b0$post)) 0.002 else NULL
    charts <- c(charts, list(cs_chart("posterior", "posterior-density", sprintf("Posterior of %s", primary),
      list(x = cs_col(primary, px), density = cs_col("Density", pdn), arm = cs_col("Arm", pa)),
      controls = list(rope_low = if (is.null(rope_w) || rope_w == 0) NULL else -rope_w, rope_high = if (is.null(rope_w) || rope_w == 0) NULL else rope_w))))
    ships <- vapply(names(bayes), function(a) if (higher_better) bayes[[a]]$loss_t else bayes[[a]]$loss_c, numeric(1))
    keeps <- vapply(names(bayes), function(a) if (higher_better) bayes[[a]]$loss_c else bayes[[a]]$loss_t, numeric(1))
    charts <- c(charts, list(cs_chart("loss", "expected-loss", sprintf("Expected loss of each choice (%s)", primary),
      list(arm = cs_col("Arm", names(bayes)), ship = cs_col("Loss if shipped", unname(ships)), keep = cs_col("Loss if not shipped", unname(keeps))),
      controls = list(threshold = if (decision_rule == "expected_loss") 0.001 else 0))))
  }
  tables <- c(tables, list(list(
    key = "decision", title = sprintf("Decision by %s", rule_labels[[decision_rule]]),
    columns = list(list(key = "arm", label = "Arm", type = "string"), list(key = "decision", label = "Decision", type = "string"),
                   list(key = "reason", label = "Why", type = "string")),
    rows = lapply(treatments, function(a) list(arm = a, decision = decisions[[a]][1], reason = decisions[[a]][2]))
  )))
  if (!is.null(prior)) tables <- c(tables, list(list(
    key = "prior", title = "Prior from past experiments (random-effects meta-analysis)",
    columns = list(list(key = "k", label = "Experiments", type = "integer"), list(key = "mean", label = "Pooled effect", type = "number"),
                   list(key = "se", label = "SE of the pooled effect", type = "number"), list(key = "tau", label = "Between-experiment SD (τ)", type = "number"),
                   list(key = "sd", label = "Prior SD (predictive)", type = "number")),
    rows = list(list(k = prior$k, mean = prior$mean, se = prior$se, tau = sqrt(prior$tau2), sd = prior$sd))
  )))
}
summary_text <- if (srm_blocked) sprintf("SRM χ² p = %.3g: results withheld.", srm$p) else
  sprintf("%s: %s vs %s lift %.2f%% [%.2f%%, %.2f%%], adjusted p = %.3g.", primary, first, control, 100 * pr$lift, 100 * pr$lift_low, 100 * pr$lift_high, pr$p_adj)
stats_list <- list(list(key = "srm_p", label = "SRM p", value = srm$p, format = "p"))
if (!srm_blocked) stats_list <- c(stats_list, list(
  list(key = "primary_lift", label = sprintf("Lift (%s)", primary), value = pr$lift, format = "percent"),
  list(key = "primary_p_adj", label = "Adjusted p", value = pr$p_adj, format = "p")))
cs_publish(list(
  method = "experiment.analyze",
  methodVersion = "1.1.1",
  title = "A/B test analysis",
  engine = cs_engine_info("stats"),
  summary = summary_text,
  statistics = stats_list,
  assumptions = list(list(key = "srm", label = "Sample ratio matches the plan", status = if (srm_failed) "fail" else "pass",
                          detail = paste0(sprintf("χ²(%d) = %.2f, p = %.3g", length(arms) - 1, srm$chi2, srm$p), if (srm_blocked) " — results withheld" else ""))),
  tables = tables,
  charts = charts,
  warnings = warnings,
  notes = c("Differences are treatment − control; lifts are relative to the control mean with delta-method intervals.",
            "Ratio metrics are Σ numerator / Σ denominator per arm with delta-method variances (z tests).",
            if (length(pre_for) && cuped_on) "CUPED adjusts each metric by its pre-period value with θ pooled over all units.",
            if (length(segs)) "Segment results are exploratory (BH-adjusted); they do not confirm effects.",
            if (length(avp)) "Always-valid p-values (mixture SPRT) stay valid however often the cumulative results are checked."),
  values = values
))
Python

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

ArmUnitsExpectedShare
control1,9562,00048.9%
treatment2,0442,00051.1%

Metrics

MetricRoleArmControlTreatmentDifferenceCI lowCI highLiftLift lowLift highpAdjusted p
convertedprimarytreatment0.11550.13310.0175−0.00290.038015.2%-3.9%34.2%.093.093
clicks / sessionssecondarytreatment0.17680.18580.0090−0.00170.01975.1%-1.1%11.3%.100.100

Guardrails (non-inferiority, margin 2.0% of the control)

GuardrailArmBetterLiftNon-inferiority pStatus
page load mstreatmentlower-0.7%.008pass

Bayesian view of converted

ArmP(better than control)Expected loss if shippedExpected loss if notCredible lowCredible high
treatment95.3%0.00020.0177−0.00300.0379

Segments of device (exploratory)

SegmentArmUnitsLiftBH-adjusted p
desktoptreatment1,75414.9%.344
mobiletreatment1,8678.0%.583
tablettreatment37943.7%.344

Decision by significance

ArmDecisionWhy
treatmentkeep collectingnot significant: keep collecting until the planned sample, then keep the control
  • 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).
  • Segment results are exploratory (BH-adjusted); they do not confirm effects.
  • Always-valid p-values (mixture SPRT) stay valid however often the cumulative results are checked.
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 578557e054508d0b
# 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 = ["page load ms"]  # lower is better
pre_cols = []
nums, dens = ["clicks"], ["sessions"]
seg = "device"
tcol = "first seen"
bool_cols = ["converted", ]
df = pd.read_parquet("tests/parity/fixtures/e1_ab.parquet", columns=["variant", "converted", "page load ms", "clicks", "sessions", "device", "first seen"])
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", "page load ms", "clicks", "sessions", "device", "first seen"])  # 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 = "frequentist"  # frequentist | expected_loss | hdi_rope | prob_to_beat
higher_better = "higher" != "lower"
prior = None
if "flat" == "meta":
    # Informed prior: random-effects pooled effect of past experiments, predictive SD (τ included).
    prior = xa.meta_prior([], [], "REML")
bayes = []
if True or decision_rule != "frequentist" or prior is not None:
    cred = 1.0 - alpha
    binary = primary_kind == "metric" and primary in bool_cols
    yb = values_of(primary) if binary else None
    for a in treatments:
        if prior is not None:
            bres = xa.normal_posterior(primary_res[a]["diff"], primary_res[a]["se"], prior["mean"], prior["sd"], cred)
        elif binary:
            okc, okt = is_c & ~np.isnan(yb), (arm == a) & ~np.isnan(yb)
            bres = xa.beta_compare(float(np.sum(yb[okc])), int(np.sum(okc)), float(np.sum(yb[okt])), int(np.sum(okt)),
                                   1, 1, cred)
        else:
            bres = xa.normal_compare(primary_res[a]["diff"], primary_res[a]["se"], cred)
        bayes.append((a, bres))

# %% Segments (exploratory)
segs = []
if seg is not None and primary_kind == "metric":
    y = values_of(primary)
    sv = df[seg].astype(str).to_numpy()
    seg_levels = [lv for lv in ["desktop", "mobile", "tablet"] 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 = True
    if temporal:
        ts = pd.to_datetime(t_raw)
        if ts.dt.tz is not None:
            ts = ts.dt.tz_localize(None)
        tt = ((ts - pd.Timestamp("1970-01-01")) / pd.Timedelta(days=1)).to_numpy(dtype=float)
    else:
        tt = t_raw.to_numpy(dtype=float)
    cuts = xa.cut_points([float(t) for t in tt[~np.isnan(tt)]])
    if primary_kind == "metric":
        y = values_of(primary)
    else:
        nn, dd = values_of(nums[0]), values_of(dens[0])
    for a in treatments:
        diffs, variances = [], []
        for c in cuts:
            win = ~np.isnan(tt) & (tt <= c)
            if primary_kind == "metric":
                selc, selt = win & is_c & ~np.isnan(y), win & (arm == a) & ~np.isnan(y)
                if selc.sum() < 2 or selt.sum() < 2:
                    continue
                nc, mc, vc = xa.moments(y[selc])
                nt, mt, vt = xa.moments(y[selt])
                if not (vc > 0 or vt > 0):
                    continue
                r = xa.welch(nc, mc, vc, nt, mt, vt, alpha, alternative)
            else:
                okr = win & ~(np.isnan(nn) | np.isnan(dd))
                if (okr & is_c).sum() < 2 or (okr & (arm == a)).sum() < 2:
                    continue
                _, rc, vc = xa.ratio_arm(nn[okr & is_c], dd[okr & is_c])
                _, rt, vt = xa.ratio_arm(nn[okr & (arm == a)], dd[okr & (arm == a)])
                r = xa.ratio_compare(rc, vc, rt, vt, alpha, alternative)
            diffs.append(r["diff"])
            variances.append(r["se"] ** 2)
            cum.append((c, a, r))
        if diffs:
            tau = None or (z + float(ndtri(0.8))) * math.sqrt(variances[-1])
            pv, lo, hi = xa.msprt(diffs, variances, tau, alpha)
            avp[a] = (pv[-1], lo[-1], hi[-1], tau)


def time_label(c):
    return (pd.Timestamp("1970-01-01") + pd.Timedelta(days=c)).date().isoformat() if temporal else c


# %% Result
values = {
    "control": control, "arms": len(arms), "comparisons": len(treatments), "srm_chi2": srm_chi2, "srm_p": srm_p,
    "srm_failed": bool(srm_failed), "srm_blocked": bool(srm_blocked), "alpha": alpha, "primary_metric": primary,
}
for a, n in zip(arms, counts):
    values[f"n[{a}]"] = n
for mname, kind, res, theta, red in results:
    if theta is not None:
        values[f"cuped_theta[{mname}]"] = theta
        values[f"cuped_reduction[{mname}]"] = red
    values[f"mean[{mname}|{control}]"] = res[treatments[0]]["mean_c"]
    for a in treatments:
        r = res[a]
        k = f"{mname}|{a}"
        values[f"mean[{k}]"] = r["mean_t"]
        for key in ("diff", "se", "df", "stat", "p", "p_adj", "ci_low", "ci_high", "lift", "lift_low", "lift_high"):
            values[f"{key}[{k}]"] = r[key]
first = treatments[0]
pr = primary_res[first]
values.update({
    "primary_arm": first, "primary_diff": pr["diff"], "primary_lift": pr["lift"], "primary_lift_low": pr["lift_low"],
    "primary_lift_high": pr["lift_high"], "primary_p": pr["p"], "primary_p_adj": pr["p_adj"],
    "primary_significant": bool(pr["p_adj"] < alpha),
})
for gname, a, direction, r, t_ni, p_ni, passed in guard:
    k = f"{gname}|{a}"
    values[f"guard_diff[{k}]"] = r["diff"]
    values[f"guard_lift[{k}]"] = r["lift"]
    values[f"ni_stat[{k}]"] = t_ni
    values[f"ni_p[{k}]"] = p_ni
    values[f"ni_pass[{k}]"] = bool(passed)
values["guardrails_failed"] = sum(1 for g in guard if not g[6])
for a, b in bayes:
    k = f"{primary}|{a}"
    for key in ("prob", "loss_t", "loss_c", "cred_low", "cred_high"):
        values[f"bayes_{key}[{k}]"] = b[key]
values["prob_beat_primary"] = bayes[0][1]["prob"] if bayes else None
# %% Decision
RULE_LABELS = {"frequentist": "significance", "expected_loss": "expected loss", "hdi_rope": "credible interval vs ROPE", "prob_to_beat": "probability to beat the control"}
decisions = {}
bayes_by_arm = dict(bayes)
for a in treatments:
    r = primary_res[a]
    decisions[a] = (("fix the test", "sample ratio mismatch: check randomization and logging") if srm_blocked else
                    xa.decide(decision_rule, bayes_by_arm.get(a), significant=bool(r["p_adj"] < alpha), diff=r["diff"],
                              higher_better=higher_better, loss_threshold=0.001, rope=0.002,
                              prob_threshold=0.95))
    values[f"decision[{primary}|{a}]"] = decisions[a][0]
values.update({"decision_rule": decision_rule, "decision_rule_label": RULE_LABELS[decision_rule],
               "decision_primary": decisions[first][0], "decision_reason": decisions[first][1],
               "prior_mean": prior["mean"] if prior else None, "prior_sd": prior["sd"] if prior else None,
               "prior_k": prior["k"] if prior else None, "prior_tau2": prior["tau2"] if prior else None})
for a, b in bayes:
    if "post_mean" in b:
        values[f"post_mean[{primary}|{a}]"] = b["post_mean"]
        values[f"post_sd[{primary}|{a}]"] = b["post_sd"]
if segs:
    for (lv, a, r, _), q in zip(segs, seg_adj):
        values[f"seg_lift[{lv}|{a}]"] = r["lift"]
        values[f"seg_p_adj[{lv}|{a}]"] = float(q)
for a, (pv_, lo_, hi_, tau) in avp.items():
    values[f"avp[{a}]"] = pv_
    values[f"avp_low[{a}]"] = lo_
    values[f"avp_high[{a}]"] = hi_
    values[f"avp_tau[{a}]"] = tau

tables = [{
    "key": "srm", "title": "Sample ratio",
    "columns": [{"key": "arm", "label": "Arm", "type": "string"}, {"key": "n", "label": "Units", "type": "integer"},
                {"key": "expected", "label": "Expected", "type": "number"}, {"key": "share", "label": "Share", "type": "percent"}],
    "rows": [{"arm": a, "n": n, "expected": e, "share": n / sum(counts)} for a, n, e in zip(arms, counts, srm_expected)],
}]
if not srm_blocked:
    rows = []
    for i, (mname, kind, res, theta, red) in enumerate(results):
        for a in treatments:
            r = res[a]
            rows.append({"metric": mname, "role": "primary" if i == 0 else "secondary", "arm": a, "control": r["mean_c"], "treatment": r["mean_t"],
                         "diff": r["diff"], "ci_low": r["ci_low"], "ci_high": r["ci_high"], "lift": r["lift"],
                         "lift_low": r["lift_low"], "lift_high": r["lift_high"], "p": r["p"], "p_adj": r["p_adj"]})
    tables.append({
        "key": "metrics", "title": "Metrics",
        "columns": [{"key": "metric", "label": "Metric", "type": "string"}, {"key": "role", "label": "Role", "type": "string"},
                    {"key": "arm", "label": "Arm", "type": "string"}, {"key": "control", "label": "Control", "type": "number"},
                    {"key": "treatment", "label": "Treatment", "type": "number"}, {"key": "diff", "label": "Difference", "type": "number"},
                    {"key": "ci_low", "label": "CI low", "type": "number"}, {"key": "ci_high", "label": "CI high", "type": "number"},
                    {"key": "lift", "label": "Lift", "type": "percent"}, {"key": "lift_low", "label": "Lift low", "type": "percent"},
                    {"key": "lift_high", "label": "Lift high", "type": "percent"}, {"key": "p", "label": "p", "type": "pvalue"},
                    {"key": "p_adj", "label": "Adjusted p", "type": "pvalue"}],
        "rows": rows,
    })
    if guard:
        tables.append({
            "key": "guardrails", "title": f"Guardrails (non-inferiority, margin {ni_margin:.1%} of the control)",
            "columns": [{"key": "metric", "label": "Guardrail", "type": "string"}, {"key": "arm", "label": "Arm", "type": "string"},
                        {"key": "better", "label": "Better", "type": "string"}, {"key": "lift", "label": "Lift", "type": "percent"},
                        {"key": "p", "label": "Non-inferiority p", "type": "pvalue"}, {"key": "status", "label": "Status", "type": "string"}],
            "rows": [{"metric": g[0], "arm": g[1], "better": g[2], "lift": g[3]["lift"], "p": g[5], "status": "pass" if g[6] else "fail"} for g in guard],
        })
    if bayes:
        tables.append({
            "key": "bayes", "title": f"Bayesian view of {primary}",
            "columns": [{"key": "arm", "label": "Arm", "type": "string"}, {"key": "prob", "label": "P(better than control)", "type": "percent"},
                        {"key": "loss_t", "label": "Expected loss if shipped", "type": "number"}, {"key": "loss_c", "label": "Expected loss if not", "type": "number"},
                        {"key": "cred_low", "label": "Credible low", "type": "number"}, {"key": "cred_high", "label": "Credible high", "type": "number"}],
            "rows": [{"arm": a, **{k: b[k] for k in ("prob", "loss_t", "loss_c", "cred_low", "cred_high")}} for a, b in bayes],
        })
    if segs:
        tables.append({
            "key": "segments", "title": f"Segments of {seg} (exploratory)",
            "columns": [{"key": "segment", "label": "Segment", "type": "string"}, {"key": "arm", "label": "Arm", "type": "string"},
                        {"key": "n", "label": "Units", "type": "integer"}, {"key": "lift", "label": "Lift", "type": "percent"},
                        {"key": "p_adj", "label": "BH-adjusted p", "type": "pvalue"}],
            "rows": [{"segment": s[0], "arm": s[1], "n": s[3], "lift": s[2]["lift"], "p_adj": float(q)} for s, q in zip(segs, seg_adj)],
        })

charts = []
if not srm_blocked:
    fl, fe, flo, fhi, fg = [], [], [], [], []
    for i, (mname, kind, res, _, _) in enumerate(results):
        for a in treatments:
            fl.append(mname if len(treatments) == 1 else f"{mname} · {a}")
            fe.append(100 * res[a]["lift"]); flo.append(100 * res[a]["lift_low"]); fhi.append(100 * res[a]["lift_high"])
            fg.append("primary" if i == 0 else "secondary")
    for gname, a, direction, r, *_ in guard:
        fl.append(gname if len(treatments) == 1 else f"{gname} · {a}")
        fe.append(100 * r["lift"]); flo.append(100 * r["lift_low"]); fhi.append(100 * r["lift_high"]); fg.append("guardrail")
    charts.append(cs.chart("lifts", "forest", "Relative lift vs the control (%)",
                           {"label": cs.col("Metric", fl), "estimate": cs.col("Lift (%)", fe), "low": cs.col("Low", flo),
                            "high": cs.col("High", fhi), "group": cs.col("Role", fg)}, controls={"reference": 0}))
    if cum:
        charts.append(cs.chart("cumulative", "cumulative-lift", f"Cumulative lift of {primary} (%)",
                               {"time": cs.col("Time", [time_label(c) for c, _, _ in cum], "temporal" if temporal else None),
                                "lift": cs.col("Lift (%)", [100 * r["lift"] for _, _, r in cum]),
                                "low": cs.col("Low", [100 * r["lift_low"] for _, _, r in cum]),
                                "high": cs.col("High", [100 * r["lift_high"] for _, _, r in cum]),
                                "metric": cs.col("Arm", [a for _, a, _ in cum])}))
    if bayes:
        a0, b0 = bayes[0]
        if "post" in b0:
            xs, dens_ = xa.beta_density_grid(b0["post"], b0["range"])
            px = list(xs) * 2
            pdn = list(dens_[0]) + list(dens_[1])
            pa = [control] * len(xs) + [a0] * len(xs)
        else:
            d0, s0 = (b0["post_mean"], b0["post_sd"]) if "post_mean" in b0 else (primary_res[a0]["diff"], primary_res[a0]["se"])
            xs = [d0 + s0 * (-4.0 + 8.0 * i / 199) for i in range(200)]
            px, pdn, pa = xs, [math.exp(-0.5 * ((x - d0) / s0) ** 2) / (s0 * math.sqrt(2 * math.pi)) for x in xs], [f"{a0} − {control}"] * 200
        rope_w = 0.002 if decision_rule == "hdi_rope" and "post" not in b0 else None
        charts.append(cs.chart("posterior", "posterior-density", f"Posterior of {primary}",
                               {"x": cs.col(primary, px), "density": cs.col("Density", pdn), "arm": cs.col("Arm", pa)},
                               controls={"rope_low": -rope_w if rope_w else None, "rope_high": rope_w if rope_w else None}))
        ships = [b["loss_t"] if higher_better else b["loss_c"] for _, b in bayes]
        keeps = [b["loss_c"] if higher_better else b["loss_t"] for _, b in bayes]
        charts.append(cs.chart("loss", "expected-loss", f"Expected loss of each choice ({primary})",
                               {"arm": cs.col("Arm", [a for a, _ in bayes]), "ship": cs.col("Loss if shipped", ships), "keep": cs.col("Loss if not shipped", keeps)},
                               controls={"threshold": 0.001 if decision_rule == "expected_loss" else 0}))
    tables.append({
        "key": "decision", "title": f"Decision by {RULE_LABELS[decision_rule]}",
        "columns": [{"key": "arm", "label": "Arm", "type": "string"}, {"key": "decision", "label": "Decision", "type": "string"},
                    {"key": "reason", "label": "Why", "type": "string"}],
        "rows": [{"arm": a, "decision": decisions[a][0], "reason": decisions[a][1]} for a in treatments],
    })
    if prior is not None:
        tables.append({
            "key": "prior", "title": "Prior from past experiments (random-effects meta-analysis)",
            "columns": [{"key": "k", "label": "Experiments", "type": "integer"}, {"key": "mean", "label": "Pooled effect", "type": "number"},
                        {"key": "se", "label": "SE of the pooled effect", "type": "number"}, {"key": "tau", "label": "Between-experiment SD (τ)", "type": "number"},
                        {"key": "sd", "label": "Prior SD (predictive)", "type": "number"}],
            "rows": [{"k": prior["k"], "mean": prior["mean"], "se": prior["se"], "tau": math.sqrt(prior["tau2"]), "sd": prior["sd"]}],
        })

summary = (f"SRM χ² p = {srm_p:.3g}: results withheld." if srm_blocked else
           f"{primary}: {first} vs {control} lift {pr['lift']:.2%} [{pr['lift_low']:.2%}, {pr['lift_high']:.2%}], adjusted p = {pr['p_adj']:.3g}.")
cs.publish({
    "method": "experiment.analyze",
    "methodVersion": "1.1.1",
    "title": "A/B test analysis",
    "engine": cs.engine_info("scipy"),
    "summary": summary,
    "statistics": [
        {"key": "srm_p", "label": "SRM p", "value": srm_p, "format": "p"},
        *([] if srm_blocked else [
            {"key": "primary_lift", "label": f"Lift ({primary})", "value": pr["lift"], "format": "percent"},
            {"key": "primary_p_adj", "label": "Adjusted p", "value": pr["p_adj"], "format": "p"},
        ]),
    ],
    "assumptions": [{"key": "srm", "label": "Sample ratio matches the plan", "status": "fail" if srm_failed else "pass",
                     "detail": f"χ²({len(arms) - 1}) = {srm_chi2:.2f}, p = {srm_p:.3g}" + (" — results withheld" if srm_blocked else "")}],
    "tables": tables,
    "charts": charts,
    "warnings": warnings,
    "notes": [
        "Differences are treatment − control; lifts are relative to the control mean with delta-method intervals.",
        "Ratio metrics are Σ numerator / Σ denominator per arm with delta-method variances (z tests).",
        *(["CUPED adjusts each metric by its pre-period value with θ pooled over all units."] if pre_for and cuped_on else []),
        *(["Segment results are exploratory (BH-adjusted); they do not confirm effects."] if segs else []),
        *(["Always-valid p-values (mixture SPRT) stay valid however often the cumulative results are checked."] if avp else []),
    ],
    "values": values,
})
03

Which template?

Predict

Predict first

Open Reports and press New report. Which template fits the product lead's page?

APA resultsExecutive summaryData quality
Reveal

Executive summary. It opens with Key findings, made from each result's summary sentence, and leaves the APA lines out. Your own Summary bullets and a KPI row follow. Your reviewer gets a separate Technical appendix later, built from the same saved result.

04

Write the call

Explore

Replace the starter bullets in the Text item with four lines of your own. Key findings comes first on the page, so put your call in the report's title too.

The memo's four lines

Write each line yourself first, using the numbers in the brief. Then compare.

  1. Recommendation: Keep the test running to its planned sample, then decide.
  2. Finding: Conversion is 15.2% higher so far. The data are compatible with anything from −3.9% to 34.2%, so a small loss isn't ruled out.
  3. Safety: The traffic split looks right, and page load shows no harm beyond the margin.
  4. Try this step yourself, then reveal it
    Limits: One test, on the people who reached checkout during it. It says nothing about returning customers over months.
05

Say what you tried

Explore

A memo also has to say what else you looked at. If you ran several segments and report only the best, a reader can't discount it. Try that here.

BExplorable · The garden of forking paths

How often does a study with no effect find p < .05 if the analysis is chosen after seeing the data?

With these choices, how often will a study of nothing find p < .05?

0.50
How sure?
3
30
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Choosing the analysis after seeing the data makes false alarms far more common. The multiple-testing ledgerMultiple-testing ledgerCodeSplash's record of every hypothesis test in a project, used to adjust for multiple comparisons. keeps count of what you ran, and the chips on each card show it.

So state it plainly: "We also looked at device segments. These are exploratory, and none is the basis for this recommendation."

06

Critique this draft

Checkpoint

A colleague offers this draft instead.

The new checkout drives a significant 15% increase in conversion, proving the redesign works. We recommend immediate rollout.

Check yourself

What's the most serious problem with the draft?

Show the answer

Answer: b

The test is randomized, so causal wording could be fine. But p is above 0.05 and the interval crosses zero. The sentence misreports the result, and that matters far more than style.

Check yourself

Which word in the draft would the lint flag on an A/B test analysis, even with its causal rule off?

Show the answer

Answer: b

"Proving" trips the overclaim rule. The causal rule, which would catch "drives", is off for experiments.

Check yourself

What's missing that the product lead would want?

Show the answer

Answer: c

They're deciding under uncertainty. The range tells them what they may be risking, and that matters more than any test detail.

07

Check your wording

In the app

Put your finding line through the checks. On the test's result card, open Learn from this result and choose Check my interpretation…. Paste your line and press Check.

Then fix what it flags, and look at what it can't flag: does the recommendation follow from the finding? Would you defend every word to the person who has to make the decision?

08

Hand it over

In the app

Press PDF to export, and use More formats, the arrow beside it, if the reader wants Word or PowerPoint.

Then make a second report from the Technical appendix template with the same analysis, for your reviewer. Use Export package on it: the report, code, data and environment in one bundle they can rerun.

Your lead gets one page. Your reviewer gets everything else. Both show the same numbers.

09

Look back

Reflect

Read your memo as the product lead would, with only one minute to spare. What do they do next? If you aren't sure, change the first line.

10

Recap

Recap
  • Open with the call, then the finding, safety checks and limits.
  • Say what you tried, and label what's exploratory.
  • Give the decision-maker one page and the reviewer something they can rerun.

Concepts in this lesson