DEV Community

Nylah Reynard
Nylah Reynard

Posted on

Why Checking A/B Test p-Values Before SRM Is a Bug (Plus CUPED in 45 Lines of Python)

A few months ago, our team nearly shipped a broken architecture change because we celebrated a dashboard green light prematurely. We had refactored our core data pipeline. After seven days, our analytics dashboard surfaced a 4.8% conversion lift with a statistically significant p-value of 0.012. Product managers were drafting victory memos, and engineering queued up rollout to 100% of production traffic.

Then an infrastructure engineer inspected the raw assignment numbers.

Across the experiment window, our tracking pipeline recorded 50,580 users in control and 49,420 users in treatment. Out of 100,000 total participants, that represented an observed split of 50.58% to 49.42%—a drift of just 1.16 percentage points from our intended 50/50 allocation.

To an engineer without deep statistics background, a 1.16 percentage point imbalance feels like harmless network noise. But when you run the math, that drift is not noise. It is an engineering failure known as a Sample Ratio Mismatch (SRM), and it completely invalidates downstream statistical tests.


A randomized experiment relies on a foundational contract: assignment to treatment or control must be independent of user attributes. When assigning traffic 50/50 via hash functions, allocation follows a binomial distribution. With N = 100,000, standard deviation per arm is only 158 users.

Evaluating our observed split of 50,580 versus 49,420 against expected 50,000 users per variant using Pearson's chi-square test yielded chi2 = 13.4560 and p = 0.000244.

In mature experimentation architectures, an SRM gate uses a conservative threshold of p < 0.001 to halt pipeline execution. A p-value of 0.000244 was not an edge case; it was definitive proof that our experiment was compromised.

Where did that missing 1.16% of treatment traffic go? An audit uncovered three technical culprits:

  • Bot filtering asymmetry: Our treatment variant updated DOM hooks. An aggressive CDN bot rule flagged those headers, silently dropping incoming treatment traffic before assignment was logged.
  • Redirect and script timeouts: The treatment path added an asynchronous config call. Mobile users on flaky connections timed out and bounced before the assignment beacon fired.
  • Client crash bias: An unhandled exception crashed older mobile clients immediately upon initialization, preventing conversion telemetry from ever reaching our warehouse.

This is why SRM is lethal: it introduces severe selection bias. The users remaining in treatment were disproportionately on high-speed desktop connections and modern browsers. We were not measuring the lift of our code; we were measuring survivorship bias.

Checking conversion p-values before validating your sample ratio is an architectural bug. If your experiment fails an SRM check, every subsequent t-test, confidence interval, and lift estimate is fiction.


Fixing our telemetry resolved the SRM issue, but brought us face-to-face with the second universal bottleneck of experimentation: statistical power.

In software engineering, true performance gains and conversion wins are rarely massive 20% leaps. Most genuine improvements yield subtle lifts—perhaps an effect size of Cohen's d = 0.12. If you run a standard Welch two-sample t-test with 400 users per arm, your statistical power is under 40%. You have a 60% chance of discarding an effective feature because random variance drowned out the signal.

Extending test duration sounds easy, but running tests for weeks introduces seasonal bias, cookie churn, and team fatigue. Instead of waiting for more traffic, we implemented CUPED (Controlled-experiment Using Pre-Experiment Data), developed by Deng et al. (2013, WSDM).

CUPED leverages pre-experiment baseline metrics to strip away individual user variance that existed before the experiment began. If you track an outcome metric Y during the test, and you possess a pre-experiment metric X for the same users (such as activity in the two weeks prior to assignment), X is completely independent of the treatment.

Deng et al. define the variance-reduced estimator as:

Y_cuped = Y - theta * (X_pre - mean(X_pre_pooled))

where theta = cov(Y, X) / var(X).

Because X is measured prior to the intervention, the expected difference between variants remains unbiased. However, the variance of the adjusted metric contracts by a factor of (1 - rho^2), where rho is the correlation between baseline X and post-experiment Y:

Var(Y_cuped) = Var(Y) * (1 - rho^2)

With a baseline correlation of rho = 0.65, theoretical variance plummets by rho^2 = 42.25%. That is mathematically identical to multiplying your sample size by 1 / (1 - 0.65^2) = 1.73x, giving you a 73% larger effective cohort for zero additional user traffic.


To verify these guarantees before rolling them into our production analytics service, we built a 20,000-trial Monte Carlo benchmark in 45 lines of clean Python:

import numpy as np
from scipy import stats

# 1. Sample Ratio Mismatch (SRM) gate check before trusting any A/B p-value
n_ctrl_obs, n_trt_obs = 50580, 49420
n_total = n_ctrl_obs + n_trt_obs
expected = np.array([n_total * 0.5, n_total * 0.5])
chi2_srm, p_srm = stats.chisquare([n_ctrl_obs, n_trt_obs], f_exp=expected)
print(f"SRM check ({n_ctrl_obs} vs {n_trt_obs}): chi2 = {chi2_srm:.4f}, p = {p_srm:.6f}")

# 2. 20,000-trial Monte Carlo benchmark: Raw Welch t-test vs CUPED variance reduction
# Deng et al. (2013, WSDM): Y_cuped = Y - theta * (X_pre - mean(X_pre_pooled))
rng = np.random.default_rng(20261125)
n_trials = 20000
n_per_arm = 400
rho = 0.65
true_lift = 0.12

# Correlated pre-experiment baseline X and post-experiment metric Y (unit variance)
x_ctrl = rng.normal(0.0, 1.0, size=(n_trials, n_per_arm))
x_trt = rng.normal(0.0, 1.0, size=(n_trials, n_per_arm))
y_ctrl_null = rho * x_ctrl + np.sqrt(1.0 - rho**2) * rng.normal(0.0, 1.0, size=(n_trials, n_per_arm))
y_trt_null = rho * x_trt + np.sqrt(1.0 - rho**2) * rng.normal(0.0, 1.0, size=(n_trials, n_per_arm))
y_trt_alt = y_trt_null + true_lift

def cuped_adjust(y_c, y_t, x_c, x_t):
    x_pool = np.concatenate([x_c, x_t], axis=1)
    y_pool = np.concatenate([y_c, y_t], axis=1)
    x_mean = x_pool.mean(axis=1, keepdims=True)
    y_mean = y_pool.mean(axis=1, keepdims=True)
    cov_xy = np.sum((x_pool - x_mean) * (y_pool - y_mean), axis=1, keepdims=True)
    var_x = np.sum((x_pool - x_mean) ** 2, axis=1, keepdims=True)
    theta = cov_xy / var_x
    return y_c - theta * (x_c - x_mean), y_t - theta * (x_t - x_mean)

yc_null_adj, yt_null_adj = cuped_adjust(y_ctrl_null, y_trt_null, x_ctrl, x_trt)
yc_alt_adj, yt_alt_adj = cuped_adjust(y_ctrl_null, y_trt_alt, x_ctrl, x_trt)

p_raw_null = stats.ttest_ind(y_trt_null, y_ctrl_null, axis=1, equal_var=False).pvalue
p_cuped_null = stats.ttest_ind(yt_null_adj, yc_null_adj, axis=1, equal_var=False).pvalue
p_raw_alt = stats.ttest_ind(y_trt_alt, y_ctrl_null, axis=1, equal_var=False).pvalue
p_cuped_alt = stats.ttest_ind(yt_alt_adj, yc_alt_adj, axis=1, equal_var=False).pvalue

var_raw = np.var(y_trt_alt.mean(axis=1) - y_ctrl_null.mean(axis=1), ddof=1)
var_cuped = np.var(yt_alt_adj.mean(axis=1) - yc_alt_adj.mean(axis=1), ddof=1)

print(f"Theoretical variance reduction (rho={rho:.2f}): {rho**2*100:.2f}% (1/{1-rho**2:.2f} = {1/(1-rho**2):.2f}x effective N)")
print(f"Empirical estimator variance reduction:     {(1.0 - var_cuped / var_raw)*100:.2f}%")
print(f"Null Type I error (alpha=0.05) — Raw: {np.mean(p_raw_null < 0.05):.4f}, CUPED: {np.mean(p_cuped_null < 0.05):.4f}")
print(f"Empirical power (d=0.12, n=400/arm) — Raw: {np.mean(p_raw_alt < 0.05):.4f} ({np.mean(p_raw_alt < 0.05)*100:.2f}%), CUPED: {np.mean(p_cuped_alt < 0.05):.4f} ({np.mean(p_cuped_alt < 0.05)*100:.2f}%)")
Enter fullscreen mode Exit fullscreen mode
SRM check (50580 vs 49420): chi2 = 13.4560, p = 0.000244
Theoretical variance reduction (rho=0.65): 42.25% (1/0.58 = 1.73x effective N)
Empirical estimator variance reduction:     41.96%
Null Type I error (alpha=0.05) — Raw: 0.0519, CUPED: 0.0529
Empirical power (d=0.12, n=400/arm) — Raw: 0.3997 (39.97%), CUPED: 0.6078 (60.78%)
Enter fullscreen mode Exit fullscreen mode

The empirical numbers illustrate three non-negotiable principles for data engineering teams:

First, look at the SRM line: chi2 = 13.4560, p = 0.000244. Even though 50,580 versus 49,420 sounds close, the chi-square test rejects the null hypothesis of equal allocation decisively. In our production code, this line acts as an automated assertion. If p_srm < 0.001, the pipeline raises a hard exception, flags the test in Slack, and disables metric evaluation.

Second, examine the null Type I error rates. Under a strict null hypothesis where no true difference exists, the raw Welch test rejected at 0.0519, and the CUPED estimator rejected at 0.0529. Both align tightly with the nominal 5% alpha threshold. CUPED does not inflate false discoveries or bias your confidence intervals.

Third, look at statistical power. With a true lift of d = 0.12 and n = 400 per variant, standard Welch t-testing achieved only 39.97% statistical power. Over six out of ten winners would have been discarded. Applying CUPED with baseline correlation rho = 0.65 cut empirical estimator variance by 41.96% (matching theoretical 42.25%) and boosted power to 60.78%. We gained over 20 percentage points of detection power without extra traffic or extended runtimes.


If you are maintaining an experimentation platform, treat sample validation and variance reduction as structural engineering requirements. Never calculate a p-value on conversion metrics until your automated pipeline has passed an SRM chi-square gate, and never force your team to run underpowered tests when pre-experiment covariates can cut your estimator variance in half.

Top comments (0)