caelum0x 0d9f755f3a feat(product-analytics): experiment statistics ported from the upstream stats package, checked within 1e-6 (A3)
Frequentist (Welch two-sided t-test and the always-valid sequential test)
and Bayesian (Gaussian posterior, chance to win, credible interval) tests,
ported line by line from PostHog products/experiments/stats (MIT,
645e1a78). jStat 1.9.6 (MIT) vendored unmodified for the distributions;
the chi-square upper tail uses the continued fraction so tiny p-values keep
their digits. Reference vectors come from running the unmodified upstream
Python (scipy 1.18.1) on its own and GrowthBook packages/stats (MIT) test
inputs (fixtures/stats/generate_vectors.py); every value matches within
1e-6, and the published 4-5 decimal expectations of both suites hold. The
sample-ratio check warns below p 0.001 (60/40 on a 50/50 plan warns).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 07:02:57 +03:00

100 lines
6.1 KiB
TypeScript

// Experiment statistics: the TypeScript port matches the upstream Python
// (PostHog products/experiments/stats, MIT) run on its own and GrowthBook's
// test inputs within 1e-6 (fixtures/stats/vectors.json, generated by
// fixtures/stats/generate_vectors.py), and the published 4-5 decimal
// expectations of both upstream test suites. The sample-ratio check matches
// scipy's chi-square test and warns on a 60/40 split of a 50/50 experiment.
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { bayesianTest, frequentistTest, StatisticError, type Stat } from "../../src/experiments/stats/methods.ts";
import { sampleRatioCheck, SRM_P_THRESHOLD } from "../../src/experiments/stats/srm.ts";
import { normalCdf, normalPpf, studentTCdf, studentTPpf, chiSquareSf } from "../../src/experiments/stats/distributions.ts";
const V = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), "fixtures/stats/vectors.json"), "utf8"));
const TOL = 1e-6;
type Raw = { kind: "mean"; sum: number; sum_squares: number; n: number } | { kind: "proportion"; sum: number; n: number } | { kind: "ratio"; n: number; m: Raw; d: Raw; m_d_sum_of_products: number };
const toStat = (r: Raw): Stat =>
r.kind === "ratio" ? { kind: "ratio", n: r.n, m: toStat(r.m), d: toStat(r.d), mdSumOfProducts: r.m_d_sum_of_products } : r.kind === "mean" ? { kind: "mean", n: r.n, sum: r.sum, sumSquares: r.sum_squares } : { kind: "proportion", n: r.n, sum: r.sum };
const close = (got: number, want: number | null, what: string) => {
if (want === null) return assert.ok(Number.isNaN(got), `${what}: expected NaN, got ${got}`);
assert.ok(Math.abs(got - want) <= TOL, `${what}: got ${got}, upstream ${want}, diff ${Math.abs(got - want)}`);
};
test("distributions agree with scipy at known points", () => {
close(normalCdf(1.959963984540054), 0.975, "normal cdf");
close(normalPpf(0.975), 1.959963984540054, "normal ppf");
close(studentTCdf(2.0, 10), 0.9633059826146299, "t cdf df=10");
close(studentTPpf(0.975, 4966.2), 1.9604417823886413, "t ppf");
close(chiSquareSf(40, 1), 2.5396285894708634e-10, "chi2 sf");
});
test("frequentist port matches the upstream code within 1e-6 on every vector", () => {
assert.ok(V.frequentist.length >= 9);
for (const v of V.frequentist) {
const r = frequentistTest(toStat(v.treatment), toStat(v.control), { difference: v.difference, alpha: 0.05, sequentialTuning: v.sequential_tuning ?? null });
close(r.pointEstimate, v.point_estimate, `${v.name} estimate`);
close(r.ci[0], v.ci[0], `${v.name} ci low`);
close(r.ci[1], v.ci[1], `${v.name} ci high`);
close(r.pValue, v.p_value, `${v.name} p`);
close(r.testStatistic, v.t, `${v.name} t`);
close(r.degreesOfFreedom, v.df, `${v.name} df`);
}
});
test("bayesian port matches the upstream code within 1e-6 on every vector", () => {
assert.ok(V.bayesian.length >= 9);
for (const v of V.bayesian) {
const prior = v.prior ? { mean: v.prior[0], variance: v.prior[1], proper: true } : undefined;
const r = bayesianTest(toStat(v.treatment), toStat(v.control), { difference: v.difference, ciLevel: 0.95, prior });
close(r.effectSize, v.effect_size, `${v.name} effect`);
close(r.ci[0], v.ci[0], `${v.name} ci low`);
close(r.ci[1], v.ci[1], `${v.name} ci high`);
close(r.chanceToWin, v.chance_to_win, `${v.name} chance to win`);
close(r.posteriorVariance, v.posterior_variance, `${v.name} posterior variance`);
}
});
test("the published upstream expectations hold (PostHog 4 decimals, GrowthBook 5 decimals)", () => {
const places = (got: number, want: number, n: number) => assert.ok(Math.abs(got - want) < 0.5 * 10 ** -n + 1e-12, `${got} vs ${want}`);
const ph = frequentistTest({ kind: "mean", sum: 1922.7, sumSquares: 94698.29, n: 2461 }, { kind: "mean", sum: 1196.87, sumSquares: 37377.9767, n: 2507 }, { difference: "relative", alpha: 0.05 });
places(ph.pointEstimate, 0.63646, 4);
places(ph.pValue, 0.08487, 4);
places(ph.ci[0], -0.0875, 4);
places(ph.ci[1], 1.36048, 4);
const gb = frequentistTest({ kind: "mean", sum: 2422.7, sumSquares: 134698.29, n: 3461 }, { kind: "mean", sum: 1396.87, sumSquares: 52377.9767, n: 3407 }, { difference: "relative", alpha: 0.05 });
places(gb.pointEstimate, 0.70732, 5);
places(gb.ci[0], -0.03526, 5);
places(gb.ci[1], 1.44989, 5);
places(gb.pValue, 0.06191, 5);
const gbBin = bayesianTest({ kind: "proportion", sum: 51, n: 100 }, { kind: "proportion", sum: 49, n: 100 }, { difference: "relative", ciLevel: 0.95 });
places(gbBin.effectSize, 0.04082, 5);
places(gbBin.ci[0], -0.24779, 5);
places(gbBin.ci[1], 0.32943, 5);
places(gbBin.chanceToWin, 0.60918, 5);
});
test("invalid inputs are refused with plain messages", () => {
assert.throws(() => frequentistTest({ kind: "proportion", sum: 2, n: 3 }, { kind: "proportion", sum: 1, n: 3 }, { difference: "relative", alpha: 0.05 }), StatisticError);
assert.throws(() => bayesianTest({ kind: "proportion", sum: 3, n: 100 }, { kind: "proportion", sum: 40, n: 100 }, { difference: "relative", ciLevel: 0.95 }), /at least 5/);
assert.throws(() => bayesianTest({ kind: "mean", sum: 100, sumSquares: 100, n: 100 }, { kind: "mean", sum: 0, sumSquares: 0, n: 100 }, { difference: "relative", ciLevel: 0.95 }), StatisticError);
assert.throws(() => frequentistTest({ kind: "mean", sum: 1, sumSquares: 1, n: 10 }, { kind: "proportion", sum: 1, n: 10 }, { difference: "absolute", alpha: 0.05 }), /same type/);
});
test("sample ratio check matches scipy and warns on a 60/40 split of a 50/50 experiment", () => {
for (const v of V.srm) {
const r = sampleRatioCheck(v.counts, v.weights);
close(r.chi2, v.chi2, `${v.name} chi2`);
close(r.pValue, v.p_value, `${v.name} p`);
}
assert.equal(sampleRatioCheck([600, 400], [0.5, 0.5]).mismatch, true);
assert.equal(sampleRatioCheck([503, 497], [0.5, 0.5]).mismatch, false);
assert.equal(sampleRatioCheck([9020, 980], [0.9, 0.1]).mismatch, false);
assert.equal(SRM_P_THRESHOLD, 0.001);
assert.equal(sampleRatioCheck([0, 0], [0.5, 0.5]).mismatch, false, "no exposures yet is not a mismatch");
});