Skip to content

Peek as often as you like

Use always-valid p-values for continuous monitoring, and weigh what they cost compared with planned looks.

Advanced ~9 min7 steps

What runs in CodeSplash

You will be able to

  • Explain what makes a p-value always valid
  • Choose between planned looks and continuous monitoring
  • Read a mixture-SPRT p-value that can only fall

Read first

01

A p-value you can watch

Read

Ordinary p-values assume one look. An always-validAlways-valid inferenceP-values and intervals that stay valid however often you look, at some cost in power. p-value keeps its promise at every look at once: under no effect, the chance it ever drops below 5% stays at or below 5%.

The mixture SPRT builds this from a likelihood ratio averaged over a range of possible effects. Because it tracks the strongest evidence so far, the reported p-value can only fall as data arrive.

02

Which do you expect?

Predict

Predict first

At the same sample size, compare a fixed-horizon interval with an always-valid one. Which is wider?

The always-valid interval is narrowerThey are the same widthThe always-valid interval is wider
Reveal

The always-valid interval is wider. The fixed interval on this test's lift runs from −3.9% to 34.2%. Freedom to look at any time is paid for with precision at any given time.

03

See both side by side

In the app
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,
})

This test records when each user first appeared, so the card can show an always-valid p-value next to the ordinary one. The fixed-horizon p-value is p = .093.

04

A hybrid: Haybittle–Peto

Read

Sometimes you want occasional looks with almost no penalty at the end. Haybittle–Peto uses a very high bar at interim looks and nearly the usual one at the last:

Sequential monitoring planRecorded · Python and R agreeRecorded 2026-11-09 · 51 values compared
R

5 looks, inflation 1.0155, final bound z = 1.990.

Information inflation
1.015
Expected size under H1 (fraction of fixed)
0.8594
Expected size under H0 (fraction of fixed)
1.011
Final efficacy z
1.990

Plots

Stopping boundariesAt each interim look, has the test statistic crossed the efficacy or futility boundary?
View data
BoundInformation fractionz
efficacy0.20003
efficacy0.2000−3
efficacy0.40003
efficacy0.4000−3
efficacy0.60003
efficacy0.6000−3
efficacy0.80003
efficacy0.8000−3
efficacy11.990
efficacy1−1.990

Boundaries by look

LookInformationEfficacy zNominal pα spent (cumulative)P(stop for efficacy | H0)P(stop for efficacy | H1)
120.0%3.0030.00270.00270.0412
240.0%3.0030.00490.00220.0854
360.0%3.0030.00670.00180.1124
480.0%3.0030.00830.00150.1227
5100.0%1.990.0470.05000.04170.4383

Always-valid inference (mixture SPRT, τ = 0.01681)

LookDifferenceAlways-valid pLowerUpper
10.0200.686−0.01920.0592
20.0110.686−0.01520.0372
30.0140.452−0.00700.0350
40.0120.452−0.00620.0302
  • Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).
  • Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.
  • Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.
The exact R script · R R version 4.5.1 (2025-06-13)
# Sequential monitoring — group-sequential boundaries and always-valid p-values
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sequential 1.1.0 · spec 09a0cd66dc5cf7fa
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # error-spending bounds cs_exp_gs_* and cs_exp_msprt (twins of codesplash.experiment)

# %% Inputs
looks <- as.integer(5)
timing <- c() # information fractions (empty = equally spaced)
alpha <- 0.05
beta <- 1 - 0.8
two_sided <- "two-sided" == "two-sided"
spending <- "hp" # obf | pocock | hsd | power | hp | pocock_classic | obf_classic | wt
param <- if (spending == "wt") 0.25 else -4 # Delta for Wang-Tsiatis
futility <- if (two_sided) "none" else "none"
fkind <- "hsd"
fparam <- -2
n_fixed <- NULL
observed <- as.numeric(unlist(c()))
m_diff <- as.numeric(unlist(c(0.02, 0.011, 0.014, 0.012)))
m_se <- as.numeric(unlist(c(0.012, 0.0085, 0.0069, 0.006)))
m_tau <- NULL
warnings <- list()
if (spending == "power" && param <= 0) stop("The power family needs rho > 0.")
timing <- as.numeric(unlist(timing))
if (!length(timing)) {
  timing <- (seq_len(looks)) / looks
} else {
  timing <- sort(timing)[seq_len(min(length(timing), looks))]
  if (length(timing) < looks) stop(sprintf("Give %d information fractions (or none for equal spacing).", looks))
  timing[looks] <- 1
}
if (looks > 1 && any(diff(timing) <= 0)) stop("Information fractions must increase.")
if ("none" == "nonbinding" && two_sided) warnings <- c(warnings, "Futility bounds are only offered for one-sided designs; none were added.")

# Equivalent idiom: gsDesign::gsDesign(k = looks, test.type = if (two_sided) 2 else 1, alpha = alpha / 2, beta = beta, timing = timing, sfu = sfLDOF)
# %% Design
d <- cs_exp_gs_design(timing, alpha, beta, two_sided, spending, param, futility, fkind, fparam)
upper <- d$upper
lower <- d$lower

# %% Observed looks
decisions <- character(0)
for (k in seq_len(min(length(observed), looks))) {
  z <- observed[k]
  decisions[k] <- if ((if (two_sided) abs(z) else z) >= upper[k]) "stop: efficacy"
    else if (futility == "nonbinding" && z <= lower[k] && k < looks) "stop: futility (non-binding)"
    else if (k == looks) "final: not significant"
    else "continue"
}
if (length(observed) > looks) warnings <- c(warnings, sprintf("Only the first %d observed z values were used.", looks))

# %% Always-valid monitoring (mixture SPRT)
ms <- NULL
tau_used <- NULL
if (length(m_diff)) {
  if (length(m_se) != length(m_diff)) stop("Give one standard error per observed difference.")
  tau_used <- if (!is.null(m_tau) && m_tau > 0) m_tau else (stats::qnorm(1 - alpha / 2) + stats::qnorm(1 - beta)) * m_se[length(m_se)]
  ms <- cs_exp_msprt(m_diff, m_se^2, tau_used, alpha)
}

# %% Result
mult <- if (two_sided) 2 else 1
rows <- lapply(seq_len(looks), function(k) {
  row <- list(look = k, t = timing[k], upper = upper[k], lower = if (is.finite(lower[k])) lower[k] else NULL,
              nominal_p = (1 - stats::pnorm(upper[k])) * mult, spent = d$alpha_spent[k] * mult,
              cross_h0 = d$pu0[k] * mult, cross_h1 = d$pu1[k])
  if (!is.null(n_fixed)) row$n <- as.integer(ceiling(n_fixed * d$inflation * timing[k] - 1e-9))
  if (k <= length(decisions)) {
    row$z <- observed[k]
    row$decision <- decisions[k]
  }
  row
})
columns <- c(
  list(list(key = "look", label = "Look", type = "integer"), list(key = "t", label = "Information", type = "percent")),
  if (!is.null(n_fixed)) list(list(key = "n", label = "Units per arm", type = "integer")),
  list(list(key = "upper", label = "Efficacy z", type = "number")),
  if (futility == "nonbinding") list(list(key = "lower", label = "Futility z", type = "number")),
  list(list(key = "nominal_p", label = "Nominal p", type = "pvalue"), list(key = "spent", label = "α spent (cumulative)", type = "number"),
       list(key = "cross_h0", label = "P(stop for efficacy | H0)", type = "number"), list(key = "cross_h1", label = "P(stop for efficacy | H1)", type = "number")),
  if (length(decisions)) list(list(key = "z", label = "Observed z", type = "number"), list(key = "decision", label = "Decision", type = "string"))
)
tables <- list(list(key = "bounds", title = "Boundaries by look", columns = columns, rows = rows))
if (!is.null(ms)) {
  tables <- c(tables, list(list(
    key = "msprt", title = sprintf("Always-valid inference (mixture SPRT, τ = %.4g)", tau_used),
    columns = list(list(key = "look", label = "Look", type = "integer"), list(key = "diff", label = "Difference", type = "number"),
                   list(key = "p", label = "Always-valid p", type = "pvalue"), list(key = "low", label = "Lower", type = "number"),
                   list(key = "high", label = "Upper", type = "number")),
    rows = lapply(seq_along(ms$p), function(i) list(look = i, diff = m_diff[i], p = ms$p[i], low = ms$low[i], high = ms$high[i]))
  )))
}
bx <- bz <- numeric(0)
bl <- character(0)
for (k in seq_len(looks)) {
  bx <- c(bx, timing[k]); bz <- c(bz, upper[k]); bl <- c(bl, "efficacy")
  if (two_sided) { bx <- c(bx, timing[k]); bz <- c(bz, -upper[k]); bl <- c(bl, "efficacy") }
  if (futility == "nonbinding") { bx <- c(bx, timing[k]); bz <- c(bz, lower[k]); bl <- c(bl, "futility") }
}
for (k in seq_len(min(length(observed), looks))) { bx <- c(bx, timing[k]); bz <- c(bz, observed[k]); bl <- c(bl, "observed") }
values <- list(
  looks = looks, alpha = alpha, inflation = d$inflation, inflation_pct = d$inflation - 1, i_max = d$i_max,
  i_fix = d$i_fix, en0 = d$en0, en1 = d$en1, power_check = d$power, type1 = d$type1,
  upper_final = upper[looks], n_max = if (is.null(n_fixed)) NA else as.integer(ceiling(n_fixed * d$inflation - 1e-9)),
  decision_last = if (length(decisions)) decisions[length(decisions)] else NA, tau = if (is.null(tau_used)) NA else tau_used
)
for (k in seq_len(looks)) {
  values[[sprintf("upper[%d]", k)]] <- upper[k]
  values[[sprintf("lower[%d]", k)]] <- if (is.finite(lower[k])) lower[k] else NA
  values[[sprintf("spent[%d]", k)]] <- d$alpha_spent[k]
  values[[sprintf("cross_h0[%d]", k)]] <- d$pu0[k]
  values[[sprintf("cross_h1[%d]", k)]] <- d$pu1[k]
}
if (!is.null(ms)) for (i in seq_along(ms$p)) {
  values[[sprintf("msprt_p[%d]", i)]] <- ms$p[i]
  values[[sprintf("msprt_low[%d]", i)]] <- ms$low[i]
  values[[sprintf("msprt_high[%d]", i)]] <- ms$high[i]
}
cs_publish(list(
  method = "experiment.sequential",
  methodVersion = "1.1.0",
  title = "Sequential monitoring plan",
  engine = cs_engine_info("stats"),
  summary = sprintf("%d looks, inflation %.4f, final bound z = %.3f.", looks, d$inflation, upper[looks]),
  statistics = list(
    list(key = "inflation", label = "Information inflation", value = d$inflation),
    list(key = "en1", label = "Expected size under H1 (fraction of fixed)", value = d$en1),
    list(key = "en0", label = "Expected size under H0 (fraction of fixed)", value = d$en0),
    list(key = "upper_final", label = "Final efficacy z", value = upper[looks])
  ),
  tables = tables,
  warnings = warnings,
  notes = c("Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).",
            "Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.",
            "Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values."),
  charts = list(cs_chart(
    "boundaries", "sequential-boundary", "Stopping boundaries",
    list(information = cs_col("Information fraction", bx), z = cs_col("z", bz), bound = cs_col("Bound", bl))
  )),
  values = values
))
Python

5 looks, inflation 1.0155, final bound z = 1.990.

Information inflation
1.015
Expected size under H1 (fraction of fixed)
0.8594
Expected size under H0 (fraction of fixed)
1.011
Final efficacy z
1.990

To keep this page light, the plots are shown once, under the R tab.

Boundaries by look

LookInformationEfficacy zNominal pα spent (cumulative)P(stop for efficacy | H0)P(stop for efficacy | H1)
120.0%3.0030.00270.00270.0412
240.0%3.0030.00490.00220.0854
360.0%3.0030.00670.00180.1124
480.0%3.0030.00830.00150.1227
5100.0%1.990.0470.05000.04170.4383

Always-valid inference (mixture SPRT, τ = 0.01681)

LookDifferenceAlways-valid pLowerUpper
10.0200.686−0.01920.0592
20.0110.686−0.01520.0372
30.0140.452−0.00700.0350
40.0120.452−0.00620.0302
  • Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).
  • Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.
  • Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Sequential monitoring — group-sequential boundaries and always-valid p-values
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method experiment.sequential 1.1.0 · spec 09a0cd66dc5cf7fa
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import math

from scipy.special import ndtr, ndtri

import codesplash as cs
from codesplash.experiment import analyze as xa  # mixture SPRT (twin of R cs_exp_msprt)
from codesplash.experiment import sequential as gs  # error-spending bounds (twin of R cs_exp_gs_*)

# %% Inputs
looks = int(5)
timing = []  # information fractions (empty = equally spaced)
alpha = 0.05
beta = 1.0 - 0.8
two_sided = "two-sided" == "two-sided"
spending = "hp"  # obf | pocock | hsd | power | hp | pocock_classic | obf_classic | wt
param = 0.25 if spending == "wt" else -4  # Δ for Wang–Tsiatis
futility = "none" if not two_sided else "none"
fkind = "hsd"
fparam = -2
n_fixed = None
observed = []
m_diff = [0.02, 0.011, 0.014, 0.012]
m_se = [0.012, 0.0085, 0.0069, 0.006]
m_tau = None
warnings = []
if spending == "power" and param <= 0:
    raise ValueError("The power family needs ρ > 0.")
if not timing:
    timing = [(k + 1) / looks for k in range(looks)]
else:
    timing = sorted(float(t) for t in timing)[:looks]
    if len(timing) < looks:
        raise ValueError(f"Give {looks} information fractions (or none for equal spacing).")
    timing[-1] = 1.0
if any(b <= a for a, b in zip(timing, timing[1:])):
    raise ValueError("Information fractions must increase.")
if "none" == "nonbinding" and two_sided:
    warnings.append("Futility bounds are only offered for one-sided designs; none were added.")

# Equivalent idiom (R): gsDesign::gsDesign(k, test.type = 1 | 2 | 4, alpha, beta, timing, sfu = sfLDOF, sfl = sfHSD).
# %% Design
d = gs.design(timing, alpha, beta, two_sided, spending, param, futility, fkind, fparam)
upper, lower = d["upper"], d["lower"]

# %% Observed looks
decisions = []
for k, z in enumerate(observed[:looks]):
    if (abs(z) if two_sided else z) >= upper[k]:
        decisions.append("stop: efficacy")
    elif futility == "nonbinding" and z <= lower[k] and k < looks - 1:
        decisions.append("stop: futility (non-binding)")
    elif k == looks - 1:
        decisions.append("final: not significant")
    else:
        decisions.append("continue")
if len(observed) > looks:
    warnings.append(f"Only the first {looks} observed z values were used.")

# %% Always-valid monitoring (mixture SPRT)
m_p, m_lo, m_hi = [], [], []
tau_used = None
if m_diff:
    if len(m_se) != len(m_diff):
        raise ValueError("Give one standard error per observed difference.")
    tau_used = m_tau if m_tau else (float(ndtri(1.0 - alpha / 2.0)) + float(ndtri(1.0 - beta))) * m_se[-1]
    m_p, m_lo, m_hi = xa.msprt(m_diff, [s * s for s in m_se], tau_used, alpha)

# %% Result
rows = []
for k, t in enumerate(timing):
    row = {
        "look": k + 1, "t": t, "upper": upper[k],
        "lower": (lower[k] if math.isfinite(lower[k]) else None),
        "nominal_p": float(1.0 - ndtr(upper[k])) * (2.0 if two_sided else 1.0),
        "spent": d["alpha_spent"][k] * (2.0 if two_sided else 1.0),
        "cross_h0": d["pu0"][k] * (2.0 if two_sided else 1.0), "cross_h1": d["pu1"][k],
    }
    if n_fixed is not None:
        row["n"] = int(math.ceil(n_fixed * d["inflation"] * t - 1e-9))
    if k < len(decisions):
        row["z"] = observed[k]
        row["decision"] = decisions[k]
    rows.append(row)
columns = [
    {"key": "look", "label": "Look", "type": "integer"}, {"key": "t", "label": "Information", "type": "percent"},
    *([{"key": "n", "label": "Units per arm", "type": "integer"}] if n_fixed is not None else []),
    {"key": "upper", "label": "Efficacy z", "type": "number"},
    *([{"key": "lower", "label": "Futility z", "type": "number"}] if futility == "nonbinding" else []),
    {"key": "nominal_p", "label": "Nominal p", "type": "pvalue"}, {"key": "spent", "label": "α spent (cumulative)", "type": "number"},
    {"key": "cross_h0", "label": "P(stop for efficacy | H0)", "type": "number"}, {"key": "cross_h1", "label": "P(stop for efficacy | H1)", "type": "number"},
    *([{"key": "z", "label": "Observed z", "type": "number"}, {"key": "decision", "label": "Decision", "type": "string"}] if decisions else []),
]
tables = [{"key": "bounds", "title": "Boundaries by look", "columns": columns, "rows": rows}]
if m_p:
    tables.append({
        "key": "msprt", "title": f"Always-valid inference (mixture SPRT, τ = {tau_used:.4g})",
        "columns": [{"key": "look", "label": "Look", "type": "integer"}, {"key": "diff", "label": "Difference", "type": "number"},
                    {"key": "p", "label": "Always-valid p", "type": "pvalue"}, {"key": "low", "label": "Lower", "type": "number"},
                    {"key": "high", "label": "Upper", "type": "number"}],
        "rows": [{"look": i + 1, "diff": m_diff[i], "p": m_p[i], "low": m_lo[i], "high": m_hi[i]} for i in range(len(m_p))],
    })
bx, bz, bl = [], [], []
for k, t in enumerate(timing):
    bx.append(t); bz.append(upper[k]); bl.append("efficacy")
    if two_sided:
        bx.append(t); bz.append(-upper[k]); bl.append("efficacy")  # one level, both signs: drawn as upper + lower lines
    if futility == "nonbinding":
        bx.append(t); bz.append(lower[k]); bl.append("futility")
for k, z in enumerate(observed[:looks]):
    bx.append(timing[k]); bz.append(z); bl.append("observed")
values = {
    "looks": looks, "alpha": alpha, "inflation": d["inflation"], "inflation_pct": d["inflation"] - 1.0, "i_max": d["i_max"],
    "i_fix": d["i_fix"], "en0": d["en0"], "en1": d["en1"], "power_check": d["power"], "type1": d["type1"],
    "upper_final": upper[-1], "n_max": int(math.ceil(n_fixed * d["inflation"] - 1e-9)) if n_fixed is not None else None,
    "decision_last": decisions[-1] if decisions else None, "tau": tau_used,
}
for k in range(looks):
    values[f"upper[{k + 1}]"] = upper[k]
    values[f"lower[{k + 1}]"] = lower[k] if math.isfinite(lower[k]) else None
    values[f"spent[{k + 1}]"] = d["alpha_spent"][k]
    values[f"cross_h0[{k + 1}]"] = d["pu0"][k]
    values[f"cross_h1[{k + 1}]"] = d["pu1"][k]
for i in range(len(m_p)):
    values[f"msprt_p[{i + 1}]"] = m_p[i]
    values[f"msprt_low[{i + 1}]"] = m_lo[i]
    values[f"msprt_high[{i + 1}]"] = m_hi[i]
cs.publish({
    "method": "experiment.sequential",
    "methodVersion": "1.1.0",
    "title": "Sequential monitoring plan",
    "engine": cs.engine_info("scipy"),
    "summary": f"{looks} looks, inflation {d['inflation']:.4f}, final bound z = {upper[-1]:.3f}.",
    "statistics": [
        {"key": "inflation", "label": "Information inflation", "value": d["inflation"]},
        {"key": "en1", "label": "Expected size under H1 (fraction of fixed)", "value": d["en1"]},
        {"key": "en0", "label": "Expected size under H0 (fraction of fixed)", "value": d["en0"]},
        {"key": "upper_final", "label": "Final efficacy z", "value": upper[-1]},
    ],
    "tables": tables,
    "warnings": warnings,
    "notes": [
        "Bounds on the z scale of the treatment − control difference; information fractions are shares of the maximum information (≈ units).",
        "Non-binding futility: the efficacy bounds assume the trial may continue past a futility bound, so stopping for futility never inflates α.",
        "Always-valid p-values stay valid under continuous peeking; they are larger than fixed-horizon p-values.",
    ],
    "charts": [cs.chart(
        "boundaries", "sequential-boundary", "Stopping boundaries",
        {"information": cs.col("Information fraction", bx), "z": cs.col("z", bz), "bound": cs.col("Bound", bl)},
    )],
    "values": values,
})

The final bar is 1.99, and inflation is only 1.5%. This run also tracks mixture-SPRT values at each look.

05

Choose a plan

Checkpoint

Check yourself

A product team wants a dashboard that anyone can check at any moment. Which plan fits?

Show the answer

Answer: b

Always-valid inference is designed for unplanned, continuous looking. Asking people not to look rarely works.

Check yourself

What does an always-valid p-value of 0.03 mean?

Show the answer

Answer: b

The guarantee covers every look at once. Like any p-value, it says nothing directly about the probability of the null hypothesis.

06

Reflect

Reflect

How do you actually use test results? If decisions wait for a planned review, group-sequential is cheaper. If people will look regardless, always-valid is the honest choice. Which describes your team?

07

Recap

Recap
  • Always-valid p-values keep their guarantee however often you look.
  • The price is wider intervals at any given sample size.
  • Choose based on how decisions really get made, not how you wish they did.

Concepts in this lesson