BA/B tests · experiment.analyze
A/B test analysis — SRM check, lifts, CUPED, guardrails and a Bayesian view
Did the treatment change the metrics, and is the test trustworthy enough to decide?
Analyzes an online experiment with one row per randomization unit: a sample-ratio-mismatch gate, per-metric differences and relative lifts with confidence intervals (Welch; delta method for ratio metrics), CUPED variance reduction from pre-period metrics, many-arm corrections (Holm, Dunnett, BH), non-inferiority tests for guardrails, Beta/normal posteriors with P(treatment better) and expected loss, exploratory segment breakdowns and cumulative lifts with always-valid p-values over time — and a decision rule (significance, expected loss, credible interval + ROPE, or probability to beat the control) with a flat prior or one pooled from past experiments.
A real result
Example “Conversion guardrail ratio segments time”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
converted: treatment vs control lift 15.17% [-3.85%, 34.20%], adjusted p = 0.0928.
- SRM p
- .164
- Lift (converted)
- 15.2%
- Adjusted p
- .093
Plots
View data
| Lift (%) | Role | High | Metric | Low |
|---|---|---|---|---|
| 15.172 | primary | 34.199 | converted | −3.854 |
| 5.094 | secondary | 11.323 | clicks / sessions | −1.135 |
| −0.6595 | guardrail | 1.492 | page load ms | −2.811 |
View data
| High | Lift (%) | Low | Arm | Time |
|---|---|---|---|---|
| 240.49 | 84.006 | −72.482 | treatment | 1,788,220,800,000 |
| 131.07 | 42.403 | −46.261 | treatment | 1,788,307,200,000 |
| 176.77 | 86.477 | −3.817 | treatment | 1,788,393,600,000 |
| 110.08 | 49.887 | −10.310 | treatment | 1,788,480,000,000 |
| 92.704 | 42.015 | −8.675 | treatment | 1,788,566,400,000 |
| 72.085 | 29.953 | −12.179 | treatment | 1,788,652,800,000 |
| 54.468 | 18.981 | −16.507 | treatment | 1,788,739,200,000 |
| 53.020 | 19.405 | −14.209 | treatment | 1,788,825,600,000 |
| 57.502 | 24.670 | −8.163 | treatment | 1,788,912,000,000 |
| 67.345 | 34.484 | 1.623 | treatment | 1,788,998,400,000 |
| 59.837 | 29.714 | −0.4102 | treatment | 1,789,084,800,000 |
| 58.717 | 30.049 | 1.382 | treatment | 1,789,171,200,000 |
| 63.001 | 34.401 | 5.801 | treatment | 1,789,257,600,000 |
| 54.293 | 28.410 | 2.527 | treatment | 1,789,344,000,000 |
| 46.777 | 22.943 | −0.8912 | treatment | 1,789,430,400,000 |
| 44.847 | 21.747 | −1.353 | treatment | 1,789,516,800,000 |
| 38.642 | 17.203 | −4.236 | treatment | 1,789,603,200,000 |
| 35.080 | 14.679 | −5.723 | treatment | 1,789,689,600,000 |
| 32.390 | 12.784 | −6.822 | treatment | 1,789,776,000,000 |
| 32.304 | 13.111 | −6.083 | treatment | 1,789,862,400,000 |
| 34.199 | 15.172 | −3.854 | treatment | 1,789,948,800,000 |
View data
| Arm | Density | converted |
|---|---|---|
| control | 1.334e-9 | 0.0715 |
| control | 2.904e-9 | 0.0721 |
| control | 6.217e-9 | 0.0727 |
| control | 1.309e-8 | 0.0733 |
| control | 2.714e-8 | 0.0739 |
| control | 5.535e-8 | 0.0745 |
| control | 1.111e-7 | 0.0751 |
| control | 2.197e-7 | 0.0757 |
| control | 4.279e-7 | 0.0763 |
| control | 8.210e-7 | 0.0769 |
| control | 1.552e-6 | 0.0775 |
| control | 2.892e-6 | 0.0781 |
| control | 5.312e-6 | 0.0787 |
| control | 9.620e-6 | 0.0793 |
| control | 1.718e-5 | 0.0799 |
| control | 3.027e-5 | 0.0805 |
| control | 5.261e-5 | 0.0811 |
| control | 9.023e-5 | 0.0817 |
| control | 0.0002 | 0.0824 |
| control | 0.0003 | 0.0830 |
| control | 0.0004 | 0.0836 |
| control | 0.0007 | 0.0842 |
| control | 0.0011 | 0.0848 |
| control | 0.0018 | 0.0854 |
| control | 0.0028 | 0.0860 |
| control | 0.0043 | 0.0866 |
| control | 0.0066 | 0.0872 |
| control | 0.0099 | 0.0878 |
| control | 0.0149 | 0.0884 |
| control | 0.0220 | 0.0890 |
| control | 0.0323 | 0.0896 |
| control | 0.0468 | 0.0902 |
| control | 0.0670 | 0.0908 |
| control | 0.0950 | 0.0914 |
| control | 0.1332 | 0.0920 |
| control | 0.1848 | 0.0926 |
| control | 0.2538 | 0.0932 |
| control | 0.3451 | 0.0939 |
| control | 0.4643 | 0.0945 |
| control | 0.6185 | 0.0951 |
| control | 0.8158 | 0.0957 |
| control | 1.066 | 0.0963 |
| control | 1.378 | 0.0969 |
| control | 1.766 | 0.0975 |
| control | 2.241 | 0.0981 |
| control | 2.817 | 0.0987 |
| control | 3.509 | 0.0993 |
| control | 4.330 | 0.0999 |
| control | 5.296 | 0.1005 |
| control | 6.419 | 0.1011 |
| control | 7.712 | 0.1017 |
| control | 9.184 | 0.1023 |
| control | 10.842 | 0.1029 |
| control | 12.691 | 0.1035 |
| control | 14.728 | 0.1041 |
| control | 16.949 | 0.1047 |
| control | 19.344 | 0.1054 |
| control | 21.895 | 0.1060 |
| control | 24.581 | 0.1066 |
| control | 27.375 | 0.1072 |
First 60 of 400 rows.
View data
| Arm | Loss if not shipped | Loss if shipped |
|---|---|---|
| treatment | 0.0177 | 0.0002 |
Assumptions
- Sample ratio matches the plan — χ²(1) = 1.94, p = 0.164
Sample ratio
| Arm | Units | Expected | Share |
|---|---|---|---|
| control | 1,956 | 2,000 | 48.9% |
| treatment | 2,044 | 2,000 | 51.1% |
Metrics
| Metric | Role | Arm | Control | Treatment | Difference | CI low | CI high | Lift | Lift low | Lift high | p | Adjusted p |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| converted | primary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .093 | .093 |
| clicks / sessions | secondary | treatment | 0.1768 | 0.1858 | 0.0090 | −0.0017 | 0.0197 | 5.1% | -1.1% | 11.3% | .100 | .100 |
Guardrails (non-inferiority, margin 2.0% of the control)
| Guardrail | Arm | Better | Lift | Non-inferiority p | Status |
|---|---|---|---|---|---|
| page load ms | treatment | lower | -0.7% | .008 | pass |
Bayesian view of converted
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 95.3% | 0.0002 | 0.0177 | −0.0030 | 0.0379 |
Segments of device (exploratory)
| Segment | Arm | Units | Lift | BH-adjusted p |
|---|---|---|---|---|
| desktop | treatment | 1,754 | 14.9% | .344 |
| mobile | treatment | 1,867 | 8.0% | .583 |
| tablet | treatment | 379 | 43.7% | .344 |
Decision by significance
| Arm | Decision | Why |
|---|---|---|
| treatment | keep collecting | not 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.
converted: treatment vs control lift 15.17% [-3.85%, 34.20%], adjusted p = 0.0928.
- SRM p
- .164
- Lift (converted)
- 15.2%
- Adjusted p
- .093
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Sample ratio matches the plan — χ²(1) = 1.94, p = 0.164
Sample ratio
| Arm | Units | Expected | Share |
|---|---|---|---|
| control | 1,956 | 2,000 | 48.9% |
| treatment | 2,044 | 2,000 | 51.1% |
Metrics
| Metric | Role | Arm | Control | Treatment | Difference | CI low | CI high | Lift | Lift low | Lift high | p | Adjusted p |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| converted | primary | treatment | 0.1155 | 0.1331 | 0.0175 | −0.0029 | 0.0380 | 15.2% | -3.9% | 34.2% | .093 | .093 |
| clicks / sessions | secondary | treatment | 0.1768 | 0.1858 | 0.0090 | −0.0017 | 0.0197 | 5.1% | -1.1% | 11.3% | .100 | .100 |
Guardrails (non-inferiority, margin 2.0% of the control)
| Guardrail | Arm | Better | Lift | Non-inferiority p | Status |
|---|---|---|---|---|---|
| page load ms | treatment | lower | -0.7% | .008 | pass |
Bayesian view of converted
| Arm | P(better than control) | Expected loss if shipped | Expected loss if not | Credible low | Credible high |
|---|---|---|---|---|---|
| treatment | 95.3% | 0.0002 | 0.0177 | −0.0030 | 0.0379 |
Segments of device (exploratory)
| Segment | Arm | Units | Lift | BH-adjusted p |
|---|---|---|---|---|
| desktop | treatment | 1,754 | 14.9% | .344 |
| mobile | treatment | 1,867 | 8.0% | .583 |
| tablet | treatment | 379 | 43.7% | .344 |
Decision by significance
| Arm | Decision | Why |
|---|---|---|
| treatment | keep collecting | not 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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Conversion guardrail ratio segments timee1_ab · denominators: sessions · guardrails_down: page load ms · metrics: converted · numerators: clicks · segment: device · time: first seen · variant: variant
- Revenue cuped greatere1_ab · guardrails_up: sessions · metrics: revenue, converted · pre: pre revenue · variant: variant
- Multi arm dunnette1_multi · metrics: converted, revenue · pre: pre revenue · variant: variant
- Ratio primarye1_multi · denominators: sessions · metrics: revenue · numerators: clicks · time: first seen · variant: variant
- Srm gatee1_ab · metrics: converted · variant: variant
- Expected loss rulee1_ab · metrics: converted · variant: variant
- Rope with meta priore1_ab · metrics: converted · variant: variant
- Prob to beat lower bettere1_multi · metrics: revenue · variant: variant
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Two independent groups (continuous): Student / Welch t, Mann–Whitney U · Statistics Guide · B — Compare groups
- Two groups, binary outcome: two-proportion z, Fisher's exact · Statistics Guide · B — Compare groups
- Multiple comparisons · Statistics Guide · Additional considerations
- A/B testing (hypothesis testing) · DS & ML Decision Guide · Optimize / decide
What you need
- Assigned armcategorical / boolean · 1 column · 2–10 levels
- The arm each unit was randomized to (control and treatments).
- Metrics (first = primary)numeric / boolean · 0–20 columns
- One value per unit; yes/no metrics are conversion rates.
- Guardrails (higher is better)numeric / boolean · 0–10 columns
- Tested for non-inferiority — must not drop by more than the margin.
- Guardrails (lower is better)numeric / boolean · 0–10 columns
- Tested for non-inferiority — must not rise by more than the margin (latency, errors …).
- Pre-period values (CUPED)numeric · 0–20 columns
- The same metric measured before the test; pairs with the metrics in order (or as set by the pre-period mapping option).
- Ratio metric numeratorsnumeric · 0–10 columns
- Ratio metrics Σ numerator / Σ denominator per arm (clicks per session …); pairs with the denominators in order.
- Ratio metric denominatorsnumeric · 0–10 columns
- Denominators for ratio metrics (e.g. sessions for clicks per session), in the same order as the metrics.
- Segment (exploratory)categorical / boolean · 0–1 column · 2–30 levels
- Optional segment to break results down by. Treat these as exploratory: many segments mean many chances.
- Exposure timetemporal / numeric · 0–1 column
- When each unit entered the test: cumulative lifts and always-valid p-values over time.
Choices you make
hypothesis
- Control armdefault —
Default: the first stored level.
- The primary metric is the first ratio metricdefault off
Off = the first metric is primary.
- Significance level (α)default 0.05
The false-alarm rate you accept: the chance of a significant result when there is truly no effect. 0.05 is conventional.
- Alternative hypothesisdefault two-sided
Which direction counts as evidence. Keep two-sided unless you fixed the direction before seeing the data.
- Treatment differs (≠)(default) — Tests for a treatment effect in either direction; keep it unless you fixed a direction before seeing the data.
- Treatment higher (>) — Tests only for the treatment raising the metric; pick it only if you fixed this direction before seeing the data.
- Treatment lower (<) — Tests only for the treatment lowering the metric; pick it only if you fixed this direction before seeing the data.
posthoc
- Primary metric across treatment armsdefault holm
How the primary metric's p-values are adjusted when there are several treatment arms.
- Holm(default) — Controls the chance of any false positive across arms; a good default when Dunnett doesn't apply.
- Dunnett (many-to-one) — Compares every arm with the control using their shared correlation; the most powerful many-to-one choice.
- Bonferroni — Divides α by the number of comparisons; the plainest choice, and conservative with many arms.
- Benjamini–Hochberg (FDR) — Controls the expected share of false positives across arms; pick it when screening many variants.
- No correction — Tests each arm at full α; fine for one comparison, and overstated for several.
- Secondary metricsdefault BH
How secondary metrics' p-values are adjusted. BH controls the share of false discoveries.
- Benjamini–Hochberg (FDR)(default) — Controls the expected share of false positives among the secondary metrics; the usual choice when there are many.
- Holm — Controls the chance of any false positive among the secondary metrics; pick it when a false claim would be costly.
- Bonferroni — Divides α by the number of secondary metrics; the strictest option, best for a few.
- No correction — Tests each secondary metric at full α; treat any finding as a lead to follow up, not a result.
assumptions
- Planned share of each armdefault
In stored arm order; empty = equal split.
- SRM threshold (p below this blocks the results)default 0.001
If the traffic split differs from the plan with p below this, results are hidden until you investigate.
- Show results despite a sample ratio mismatchdefault off
Show results even though the split looks wrong. Only do this once you know why and it can't bias results.
- Reason for overriding the SRM gatedefault —
Why it is safe to read the results despite the mismatch (recorded with the analysis).
statistics
- CUPED adjustment with the pre-period valuesdefault on
Use each unit's pre-experiment value to remove noise. Same estimate on average, narrower intervals.
- Metric each pre-period column adjusts (1 = primary)default
Empty = the first metrics in order.
- Guardrail non-inferiority margin (share of the control mean)default 0.02
Largest drop in a guardrail metric you accept, as a share of the control mean (0.02 = 2%).
- Bayesian view of the primary metricdefault on
Also show the posterior for the primary metric: the probability treatment beats control and by how much.
- Decision ruledefault frequentist
How the ship decision is made: significance, expected loss, a credible interval vs a ROPE, or probability to beat.
- Significance (ship when the primary metric improves significantly)(default) — Ship on a significant improvement at the planned sample; otherwise keep the control.
- Expected loss below a tolerable loss — Ship (or keep the control) once the expected loss of that choice is below ε — Bayesian, stops sooner on clear results.
- Credible interval vs a region of practical equivalence (ROPE) — Ship if the credible interval lies above the ROPE, keep the control if below or entirely inside it.
- Probability to beat the control — Ship when P(better than control) reaches the threshold; keep the control when it falls to 1 − threshold.
- For the primary metric, better isdefault higher
Which direction counts as an improvement; sets the losses and P(better).
- Higher(default) — A higher value is a win; pick it for conversion, revenue or engagement.
- Lower (latency, cost, errors …) — A lower value is a win; pick it for latency, cost or errors.
- Tolerable loss ε (metric units)default 0.001
The largest expected loss you accept when choosing, in the metric's units (0.001 = 0.1 conversion points).
- ROPE half-width (metric units)default 0.002
Differences within ± this are practically zero. Set it from the smallest effect worth acting on.
- Probability thresholddefault 0.95
Ship when P(treatment better than control) reaches this; keep the control when it falls to 1 − threshold.
- Prior for the primary differencedefault flat
Prior for the primary difference: none (data alone), or one built from a meta-analysis of past experiments.
- Flat (the data alone)(default) — Beta(a, b) posteriors for conversion rates, a flat-prior normal for other metrics.
- From past experiments (meta-analysis) — A normal prior centered on the pooled effect of past experiments, as wide as their predictive spread (τ included).
- Past experiments: effects (differences, same units)default
Differences (treatment − control) measured in earlier, comparable experiments.
- Past experiments: standard errorsdefault
Standard error of each past difference, in the same order.
- Between-experiment variance (τ²)default REML
How the spread between past experiments (τ²) is estimated; REML is the usual default.
- REML (restricted maximum likelihood)(default) — Estimates the spread between past experiments by restricted likelihood; the usual choice.
- DerSimonian–Laird — A fast closed-form moment estimate; can understate the spread when past experiments are few.
- Always-valid p: mixing SD τdefault —
Mixing SD for always-valid p-values: about the effect size you expect. Empty uses a default from the data.
Advanced
- Beta prior a (conversion metrics)default 1
Beta prior a for conversion rates. a = b = 1 is flat; larger values pull estimates toward a / (a + b).
- Beta prior b (conversion metrics)default 1
Beta prior b for conversion rates. a = b = 1 is flat; larger values pull estimates toward a / (a + b).
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Sample ratio matches the plan
χ² test of the arm sizes; a mismatch signals broken randomization or logging.
One row per randomization unitNot checked from data: state why it holds
Units must not appear in two arms; ratio metrics handle several events per unit.
What it reports
- Tests: Primary metric lift
- srm_chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- srm_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- srm_failed
- Group sizes in an experiment differ from the planned split more than chance allows; a sign of a broken pipeline.
- srm_blocked
- Group sizes in an experiment differ from the planned split more than chance allows; a sign of a broken pipeline.
- primary_metric
- The metric listed first; the headline lift, p-value and verdict are all reported for this metric.
- primary_arm
- The treatment arm that the headline lift and verdict describe: the first arm compared with the control.
- primary_lift
- The change in a metric as a share of the control's value, so +0.05 means 5% above control.
- primary_lift_low
- A range of effect values compatible with your data at the chosen confidence level.
- primary_lift_high
- A range of effect values compatible with your data at the chosen confidence level.
- primary_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- primary_p_adj
- How surprising your data would be if the null hypothesis were true, as a probability.
- primary_diff
- One group's mean minus another's, in the outcome's own units.
- decision_rule
- Which rule made the call: frequentist, expected_loss, hdi_rope (credible interval against a ROPE) or prob_to_beat.
- decision_primary
- Verdict for the first treatment arm on the primary metric: ship, keep control, keep collecting, or fix the test.
- comparisons
- Running many tests raises the chance that at least one is a false positive.
- decision_reason
- Plain-language reason for the recommended decision on the primary metric.
- decision_rule_label
- The rule that turned results into a decision: significance, expected loss or probability to beat control.
- guardrails_failed
- Number of guardrail metrics that moved past their allowed harm, which can block a launch.
- primary_significant
- True when the primary metric's adjusted p-value is below α.
Per group, level or term: prior_k, prior_mean, prior_sd, prob_beat_primary
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Credible intervals of a difference of Beta posteriors come from Brent root finding (brentq ↔ uniroot) on identical Gauss–Legendre nodes; Dunnett-adjusted p-values use the deterministic quadrature twin.
The exact script CodeSplash ran for example “Conversion guardrail ratio segments time” · 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,
})
The exact script CodeSplash ran for example “Conversion guardrail ratio segments time” · 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
))
Sources
- Kohavi, R., Tang, D., & Xu, Y. (2020). Trustworthy online controlled experiments. Cambridge University Press.
- Fabijan, A., et al. (2019). Diagnosing sample ratio mismatch in online controlled experiments. KDD '19.
- Deng, A., Xu, Y., Kohavi, R., & Walker, T. (2013). Improving the sensitivity of online controlled experiments by utilizing pre-experiment data. WSDM '13.
- Deng, A., Lu, J., & Litz, J. (2017). Trustworthy analysis of online A/B tests: pitfalls, challenges and solutions. WSDM '17.
- Johari, R., Koomen, P., Pekelis, L., & Walsh, D. (2017). Peeking at A/B tests. KDD '17.
From the CodeSplash method registry · experiment.analyze v1.1.1.