# Peeking at A/B Tests: Simulate the Damage and Fix It with Sequential Testing

> The A/B test peeking problem in Python. Simulate repeated looks at A/A tests, measure the false positive inflation, and compare fixed-horizon, constant and O'Brien-Fleming boundaries and mSPRT always-valid p-values on false positives, power and sample size.

Source: https://www.pythoncharts.com/ab-testing/ab-test-peeking-sequential-testing-python/ | Published: 2026-11-25 | Author: Alex Scott | Category: A/B Testing | Tags: ab testing, experimentation, peeking, sequential testing, msprt, group sequential, false positive rate, simulation

If you check an A/B test's p-value every day and stop as soon as it dips under 0.05, your false positive rate is far above 5%. The fix is either to look only once, at a sample size set in advance, or to use a sequential method: **group sequential boundaries** (a stricter z threshold at each look) or an **always-valid p-value** such as mSPRT. This post simulates the problem with NumPy and SciPy and then compares the fixes on false positives, power, and how early they stop.

## Quick Example

An A/A test splits users into two identical groups, so every "significant" result is a false positive. The simulation below runs 20,000 A/A tests with 10,000 users per arm and records the p-value after every 500 users. It then counts how often a test gets under 0.05 at least once, as a function of how many times you look.

```python
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats

N_SIMS, N_MAX, K = 20_000, 10_000, 20
SIGMA = 3.0                          # sd of the metric for one user
V = 2 * SIGMA**2                     # variance of one control-minus-treatment pair
looks = np.arange(1, K + 1) * (N_MAX // K)      # 500, 1000, ..., 10000
block = N_MAX // K

def simulate(delta, seed):
    """Running sums of paired differences at each look, and the z statistic."""
    rng = np.random.default_rng(seed)
    # the sum of 500 differences is Normal(500 * delta, 500 * V), so draw it directly
    increments = rng.normal(block * delta, np.sqrt(block * V), size=(N_SIMS, K))
    S = np.cumsum(increments, axis=1)
    Z = S / np.sqrt(V * looks)
    return S, Z

S0, Z0 = simulate(0.0, seed=12)          # A/A tests: no real difference
P0 = 2 * stats.norm.sf(np.abs(Z0))

ks = [1, 2, 5, 10, 20]
rates = []
for k in ks:
    idx = np.round(np.linspace(K / k, K, k)).astype(int) - 1     # k evenly spaced looks
    rates.append((P0[:, idx] < 0.05).any(axis=1).mean())
    print("looks:", k, "false positive rate:", round(rates[-1], 3))

fig, ax = plt.subplots(figsize=(6, 4))
ax.bar([str(k) for k in ks], rates, color="#be123c")
ax.axhline(0.05, color="black", ls="--")
ax.set(xlabel="Number of times you look", ylabel="False positive rate")
```

The false positive rate is 5.2% with one look, and it climbs with every extra look:

| Looks | False positive rate |
|---|---|
| 1 | 5.2% |
| 2 | 8.4% |
| 5 | 14.2% |
| 10 | 19.3% |
| 20 | **24.8%** |

Each look is another chance for noise to cross the line, and a test that crosses it once gets declared a winner. Checking daily for 20 days gives a roughly 1-in-4 chance of a fake win when nothing is going on. (The simulation draws each block of 500 differences directly from its Normal distribution instead of generating every user, which gives the same results for z statistics and runs fast. The one-look rate of 5.2% rather than 5.0% is simulation noise with 20,000 runs.)

![Left: bar chart of false positive rate rising from 5% with one look to 25% with 20 looks. Right: stopping boundaries over time, with a constant line at 2.69, an O'Brien-Fleming curve falling from above 9 to 2.15, and the naive 1.96 line](https://www.pythoncharts.com/ab-testing/ab-test-peeking-sequential-testing-python/images/peeking-inflation-boundaries.png)

## What Peeking Looks Like in Individual Tests

![Lines of p-values over 10,000 users in A/A tests; a few red lines dip below the dashed 0.05 line at some point and later rise again, while gray ones stay above it](https://www.pythoncharts.com/ab-testing/ab-test-peeking-sequential-testing-python/images/peeking-pvalue-paths.png)

Each line is one A/A test. The red ones dipped under 0.05 at some look, and most of them crossed back above it later. A fixed-horizon test, read once at 10,000 users, would call them null. An experimenter who stopped at the dip would have shipped a change that does nothing.

## Fix 1: Pick the Sample Size and Look Once

The simplest correct approach is to compute the sample size with a power analysis, run to that number, and read the result once: see [A/B Test Sample Size and Power Analysis in Python](https://www.pythoncharts.com/ab-testing/ab-test-sample-size-power-python/). The cost is waiting for the full sample even when the result is obvious early. The other fixes below buy the right to stop early at a price in power.

## Fix 2: Group Sequential Boundaries

Instead of comparing every look to 1.96, compare it to a larger threshold chosen so that the *overall* false positive rate across all looks is 5%. Two classic shapes:

- **Constant boundary** (Pocock-style): the same threshold at every look.
- **O'Brien-Fleming style**: a threshold proportional to `1 / sqrt(fraction of data seen)`. It is very strict early and close to 1.96 at the end, so it rarely stops early on noise and keeps most of the power.

Exact boundaries come from alpha-spending functions. A simple way to get the same shapes is to calibrate the constant by simulation on A/A runs:

```python
def calibrate(shape):
    """Find c so that |Z_k| > c * shape_k at some look in 5% of A/A runs."""
    return np.quantile((np.abs(Z0) / shape).max(axis=1), 0.95)

shape_const = np.ones(K)
shape_obf = np.sqrt(N_MAX / looks)       # strict early, loose late
b_const = calibrate(shape_const) * shape_const
b_obf = calibrate(shape_obf) * shape_obf
print("constant boundary:", b_const[0].round(2),
      "| OBF first/last:", b_obf[0].round(2), b_obf[-1].round(2))
```

The constant boundary comes out at |z| > **2.69** at every look. The O'Brien-Fleming style boundary starts at 9.61 for the first look (so effectively no stopping at 500 users) and falls to **2.15** at the final look. You stop at the first look where `abs(Z)` exceeds the boundary. The right panel of the chart above plots both.

## Fix 3: Always-Valid P-Values with mSPRT

The mixture sequential probability ratio test (mSPRT) gives a p-value that stays valid however often you look and whenever you stop. It averages the likelihood ratio over a normal prior on the effect size, with standard deviation `tau`. The likelihood ratio after `n` pairs, with `S` the running sum of differences, is:

`Λ_n = sqrt(V / (V + n·tau²)) · exp(tau² · S² / (2 V (V + n·tau²)))`

and the always-valid p-value is `min(1, 1 / max over time of Λ)`. The code is the same formula:

```python
TAU = 0.2                            # sd of the effect-size prior the test mixes over

def msprt_pvalues(S):
    """Always-valid p-values at each look from the running sums of differences."""
    n = looks
    log_lr = (0.5 * np.log(V / (V + n * TAU**2))
              + TAU**2 * S**2 / (2 * V * (V + n * TAU**2)))
    return np.minimum(1, np.exp(-np.maximum.accumulate(log_lr, axis=1)))

DELTA = 0.12
S1, Z1 = simulate(DELTA, seed=77)
p_aa, p_ab = msprt_pvalues(S0), msprt_pvalues(S1)
```

![Two panels of step-shaped always-valid p-value paths on a log scale; in A/A tests they stay above the 0.05 line, while in tests with a true effect many fall below it as users accumulate](https://www.pythoncharts.com/ab-testing/ab-test-peeking-sequential-testing-python/images/peeking-msprt.png)

Always-valid p-values only move down (they are a running minimum), so once a test crosses 0.05 it can stop. In the A/A tests on the left, none of the 40 plotted runs crossed. In the tests with a true effect of +0.12 on the right, many drift below 0.05 as data accumulates. `TAU` should reflect the effect sizes you care about. A `TAU` far larger than the real effect makes the test slow to detect it.

## Compare the Methods: False Positives, Power and Stopping Time

Each rule was run on fresh simulated A/A tests (no effect) and on tests with a true effect of +0.12 (a 0.12 shift on a metric with a standard deviation of 3), with up to 10,000 users per arm and 20 looks:

```python
def evaluate(S, Z):
    rules = {
        "Fixed: one look at 10,000": (np.abs(Z[:, -1]) > 1.96)[:, None],
        "Naive peeking (|z| > 1.96, 20 looks)": np.abs(Z) > 1.96,
        "Constant boundary, 20 looks": np.abs(Z) > b_const,
        "O'Brien-Fleming style, 20 looks": np.abs(Z) > b_obf,
        "mSPRT, 20 looks": msprt_pvalues(S) < 0.05,
    }
    out = {}
    for name, rej in rules.items():
        stop = rej.any(axis=1)
        first = np.where(stop, looks[rej.argmax(axis=1)] if rej.shape[1] > 1 else N_MAX, N_MAX)
        out[name] = (stop.mean(), first.mean())
    return out

for label, delta, seed in [("A/A", 0.0, 101), (f"effect {DELTA}", DELTA, 202)]:
    print(label)
    for name, (rate, avg_n) in evaluate(*simulate(delta, seed)).items():
        print(f"  {name:40s} rejects {rate:.3f}  avg users per arm {avg_n:,.0f}")
```

| Rule | False positive rate (A/A) | Power (effect +0.12) | Average users per arm |
|---|---|---|---|
| Fixed: one look at 10,000 | 5.0% | 80.4% | 10,000 |
| Naive peeking, 20 looks | **25.0%** | 88.6% | 4,388 |
| Constant boundary, 20 looks | 4.8% | 65.3% | 6,868 |
| O'Brien-Fleming style, 20 looks | 4.7% | 77.8% | 7,566 |
| mSPRT, 20 looks | 1.4% | 49.6% | 7,951 |

Naive peeking has the best "power" only because it gives up the 5% guarantee: it also rejects a quarter of the A/A tests. Among the valid methods, the O'Brien-Fleming style loses the least power (77.8% against 80.4% for a fixed test) while stopping 24% earlier on average, which is why it is the common default for group sequential tests. The constant boundary stops earliest of the valid rules (6,868 users on average) but power drops to 65%. mSPRT is the most conservative here, with 50% power, because it protects against looking at any moment and this version was tuned loosely (`TAU = 0.2`). Its advantage is flexibility: no look schedule needs to be fixed in advance.

These are results from one simulation setup. Your power and stopping times depend on the effect size, the number of looks and the maximum sample, so treat the table as a demonstration of the trade-off, not as a ranking to copy. To recover the lost power, raise the maximum sample size for the sequential design.

## Practical Tips

- **Decide the look schedule before the test starts.** Group sequential boundaries are valid only for the looks you planned.
- **Use the same rule in the dashboard and the decision.** If the dashboard shows an ordinary p-value every day, people will peek. Show the sequential one or hide the p-value until the end.
- **Stopping early inflates the effect estimate.** Tests that stop because they crossed a boundary tend to overstate the lift. Treat early-stop estimates as rough.
- **Guardrail metrics are different.** Stopping a test early because a guardrail got worse is a safety decision, not a significance claim. Still, write the rule down in advance.
- **Bayesian tests don't escape this.** A rule like "stop when P(B > A) > 95%" has the same problem: see [Bayesian A/B Testing in Python](https://www.pythoncharts.com/ab-testing/bayesian-ab-test-python/).

## Similar Topics

- [A/B Test Sample Size and Power Analysis in Python](https://www.pythoncharts.com/ab-testing/ab-test-sample-size-power-python/)
- [A/B Test Analysis in Python](https://www.pythoncharts.com/ab-testing/ab-test-analysis-python/)
- [Bayesian A/B Testing in Python](https://www.pythoncharts.com/ab-testing/bayesian-ab-test-python/)
- [A/B Testing in Python: A Guide from Sample Size to Sequential Tests](https://www.pythoncharts.com/ab-testing/ab-testing-python-guide/)
