Open source CapCut alternative.
TypeScript
feat(site): the abexp package, host-free A/B experiment infrastructure
David Le318208eefb81
diff --git a/site/eslint.config.mjs b/site/eslint.config.mjsindex d217dc62..f16bb01c 100644--- a/site/eslint.config.mjs+++ b/site/eslint.config.mjs@@ -17,9 +17,9 @@ const eslintConfig = defineConfig(["src/cut/worker/cf/**",]),{- // effects-kit is a standalone package: it must build for any host, so it- // never reaches into the app's source or aliases.- files: ["packages/effects-kit/**/*.ts", "packages/effects-kit/**/*.tsx"],+ // The packages are standalone: each must build for any host, so none+ // reaches into the app's source or aliases.+ files: ["packages/*/**/*.ts", "packages/*/**/*.tsx"],rules: {"no-restricted-imports": ["error",@@ -27,7 +27,7 @@ const eslintConfig = defineConfig([patterns: [{group: ["@/*", "**/src/cut/*", "next", "next/*"],- message: "effects-kit is host-agnostic — no site/src or Next.js imports.",+ message: "Packages are host-agnostic — no site/src or Next.js imports.",},],},diff --git a/site/next.config.ts b/site/next.config.tsindex c2a76e3f..fe14a33c 100644--- a/site/next.config.ts+++ b/site/next.config.ts@@ -4,7 +4,7 @@ import type { NextConfig } from "next";const nextConfig: NextConfig = {pageExtensions: ["js", "jsx", "ts", "tsx", "md", "mdx"],// Workspace packages ship TypeScript source; the app build transpiles them.- transpilePackages: ["@donkeycut/effects-kit"],+ transpilePackages: ["@donkeycut/effects-kit", "@donkeycut/abexp"],// Cache Components: pages prerender to a static shell and anything uncached// streams behind its own Suspense boundary. It is what the `unstable_instant`// export on the public pages and the app's home routes validates against, anddiff --git a/site/package-lock.json b/site/package-lock.jsonindex 64febc95..e71a4195 100644--- a/site/package-lock.json+++ b/site/package-lock.json@@ -21,6 +21,7 @@"@better-auth/core": "1.6.11","@better-auth/kysely-adapter": "1.6.11","@better-auth/utils": "0.4.0",+ "@donkeycut/abexp": "*","@donkeycut/effects-kit": "*","@earendil-works/pi-agent-core": "0.84.1","@earendil-works/pi-ai": "0.84.1",@@ -1436,6 +1437,10 @@"dev": true,"license": "MIT OR Apache-2.0"},+ "node_modules/@donkeycut/abexp": {+ "resolved": "packages/abexp",+ "link": true+ },"node_modules/@donkeycut/effects-kit": {"resolved": "packages/effects-kit","link": true@@ -18451,6 +18456,14 @@"url": "https://github.com/sponsors/wooorm"}},+ "packages/abexp": {+ "name": "@donkeycut/abexp",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "peerDependencies": {+ "zod": "^4.0.0"+ }+ },"packages/effects-kit": {"name": "@donkeycut/effects-kit","version": "0.1.0",diff --git a/site/package.json b/site/package.jsonindex 56370305..34f63f35 100644--- a/site/package.json+++ b/site/package.json@@ -24,7 +24,7 @@"eval:cut-chat": "bun run scripts/eval-cut-chat.ts","eval:cut-headless": "bun run scripts/eval-cut-headless.ts","email:dev": "email dev --dir src/emails --port 3001",- "test": "bun test src packages/effects-kit/src",+ "test": "bun test src packages/effects-kit/src packages/abexp/src","test:genvideo": "bun run scripts/genvideo-selftest.ts","eval:genvideo": "bun run scripts/genvideo-eval.ts","eval:cut-perf": "bun run scripts/eval-cut-perf.ts",@@ -44,6 +44,7 @@"@better-auth/kysely-adapter": "1.6.11","@better-auth/utils": "0.4.0","@donkeycut/effects-kit": "*",+ "@donkeycut/abexp": "*","@earendil-works/pi-agent-core": "0.84.1","@earendil-works/pi-ai": "0.84.1","@elevenlabs/elevenlabs-js": "^2.49.1",diff --git a/site/packages/abexp/package.json b/site/packages/abexp/package.jsonnew file mode 100644index 00000000..c4c2d278--- /dev/null+++ b/site/packages/abexp/package.json@@ -0,0 +1,18 @@+{+ "name": "@donkeycut/abexp",+ "version": "0.1.0",+ "description": "Host-agnostic runtime configuration and A/B experiments: a settings registry with layered resolution, audiences, deterministic assignment, and the statistics that read a result.",+ "license": "Apache-2.0",+ "type": "module",+ "main": "./src/index.ts",+ "types": "./src/index.ts",+ "exports": {+ ".": {+ "types": "./src/index.ts",+ "default": "./src/index.ts"+ }+ },+ "peerDependencies": {+ "zod": "^4.0.0"+ }+}diff --git a/site/packages/abexp/src/assign.test.ts b/site/packages/abexp/src/assign.test.tsnew file mode 100644index 00000000..df7c457d--- /dev/null+++ b/site/packages/abexp/src/assign.test.ts@@ -0,0 +1,95 @@+import { describe, expect, test } from "bun:test";++import { EVERYONE, type AudienceFacts } from "./audience";+import { bucket, isEligible, pickVariant, type AssignableExperiment, type AssignContext } from "./assign";++const experiment = (over: Partial<AssignableExperiment> = {}): AssignableExperiment => ({+ key: "copy_test",+ status: "running",+ variants: [+ { key: "control", name: "Control", weight: 50, config: {} },+ { key: "treatment", name: "Treatment", weight: 50, config: {} },+ ],+ audience: EVERYONE,+ percent: 100,+ ...over,+});++const facts = (over: Partial<AudienceFacts> = {}): AudienceFacts => ({+ country: "US",+ createdAt: new Date("2026-09-01T00:00:00Z"),+ pro: false,+ paid: false,+ lastActiveAt: null,+ storageUsedPercent: null,+ creditsUsedPercent: null,+ ...over,+});++const ctx = (over: { userId?: string; facts?: Partial<AudienceFacts> } = {}): AssignContext => ({+ userId: over.userId ?? "user_1",+ facts: facts(over.facts),+ now: new Date("2026-09-04T00:00:00Z"),+});++const ids = Array.from({ length: 20_000 }, (_, i) => `user_${i}`);++describe("assignment", () => {+ test("is deterministic", () => {+ expect(bucket("k", "u", "rollout")).toBe(bucket("k", "u", "rollout"));+ expect(bucket("k", "u", "rollout")).not.toBe(bucket("k", "u", "variant"));+ expect(pickVariant(experiment(), "user_7")).toBe(pickVariant(experiment(), "user_7"));+ });++ test("splits 20k ids by weight within two points", () => {+ const exp = experiment({+ variants: [+ { key: "a", name: "A", weight: 70, config: {} },+ { key: "b", name: "B", weight: 30, config: {} },+ ],+ });+ let a = 0;+ for (const id of ids) if (pickVariant(exp, id) === "a") a++;+ const share = (a / ids.length) * 100;+ expect(Math.abs(share - 70)).toBeLessThan(2);+ });++ test("never picks a zero-weight variant", () => {+ const exp = experiment({+ variants: [+ { key: "off", name: "Off", weight: 0, config: {} },+ { key: "on", name: "On", weight: 1, config: {} },+ ],+ });+ for (const id of ids.slice(0, 2000)) expect(pickVariant(exp, id)).toBe("on");+ expect(pickVariant(experiment({ variants: [{ key: "x", name: "X", weight: 0, config: {} }] }), "u")).toBeNull();+ });++ test("raising the percent only adds users and keeps their variant", () => {+ const at20 = experiment({ percent: 20 });+ const at60 = experiment({ percent: 60 });+ let enrolled20 = 0;+ for (const id of ids) {+ const c = ctx({ userId: id });+ if (isEligible(at20, c)) {+ enrolled20++;+ expect(isEligible(at60, c)).toBe(true);+ expect(pickVariant(at60, id)).toBe(pickVariant(at20, id));+ }+ }+ expect(Math.abs((enrolled20 / ids.length) * 100 - 20)).toBeLessThan(2);+ });++ test("the audience gates eligibility", () => {+ const pro = experiment({ audience: { ...EVERYONE, plan: "pro" } });+ expect(isEligible(pro, ctx())).toBe(false);+ expect(isEligible(pro, ctx({ facts: { pro: true } }))).toBe(true);+ });++ test("only a running experiment is eligible", () => {+ for (const status of ["draft", "paused", "ended"]) {+ expect(isEligible(experiment({ status }), ctx())).toBe(false);+ }+ expect(isEligible(experiment(), ctx())).toBe(true);+ });+});diff --git a/site/packages/abexp/src/assign.ts b/site/packages/abexp/src/assign.tsnew file mode 100644index 00000000..5de8bd1b--- /dev/null+++ b/site/packages/abexp/src/assign.ts@@ -0,0 +1,48 @@+import { createHash } from "node:crypto";++import { matchesAudience, type Audience, type AudienceFacts } from "./audience";+import type { ExperimentStatus, ExperimentVariant } from "./experiment";++// Deterministic assignment: a user lands in the same bucket on every request,+// on every server, with no coordination. Two salts keep the two decisions+// independent — raising the rollout percent only adds users, and the variant+// a user gets does not shift when the rollout moves.++export type AssignableExperiment = {+ key: string;+ status: string;+ variants: ExperimentVariant[];+ audience: Audience;+ percent: number;+};++export type AssignContext = {+ userId: string;+ facts: AudienceFacts;+ now: Date;+};++/** A stable point in [0, 1) for this user under this key and salt. */+export function bucket(key: string, userId: string, salt: "rollout" | "variant"): number {+ const digest = createHash("sha256").update(`${key}:${salt}:${userId}`).digest();+ return digest.readUInt32BE(0) / 2 ** 32;+}++export function isEligible(experiment: AssignableExperiment, ctx: AssignContext): boolean {+ if ((experiment.status as ExperimentStatus) !== "running") return false;+ if (!matchesAudience(experiment.audience, ctx.facts, ctx.now)) return false;+ return bucket(experiment.key, ctx.userId, "rollout") * 100 < experiment.percent;+}++/** The variant an eligible user draws, by weight. Null when no weight is set. */+export function pickVariant(experiment: AssignableExperiment, userId: string): string | null {+ const total = experiment.variants.reduce((sum, v) => sum + v.weight, 0);+ if (total <= 0) return null;+ const point = bucket(experiment.key, userId, "variant") * total;+ let edge = 0;+ for (const variant of experiment.variants) {+ edge += variant.weight;+ if (variant.weight > 0 && point < edge) return variant.key;+ }+ return experiment.variants.findLast((v) => v.weight > 0)?.key ?? null;+}diff --git a/site/packages/abexp/src/audience.test.ts b/site/packages/abexp/src/audience.test.tsnew file mode 100644index 00000000..bea1b7a1--- /dev/null+++ b/site/packages/abexp/src/audience.test.ts@@ -0,0 +1,85 @@+import { describe, expect, test } from "bun:test";++import {+ audienceNeeds,+ audienceSchema,+ describeAudience,+ EVERYONE,+ matchesAudience,+ type AudienceFacts,+} from "./audience";++const now = new Date("2026-09-04T00:00:00Z");++const facts = (over: Partial<AudienceFacts> = {}): AudienceFacts => ({+ country: "US",+ createdAt: new Date("2026-09-01T00:00:00Z"),+ pro: false,+ paid: false,+ lastActiveAt: new Date("2026-09-03T00:00:00Z"),+ storageUsedPercent: 40,+ creditsUsedPercent: 90,+ ...over,+});++describe("audience", () => {+ test("an empty audience admits everyone and needs no facts", () => {+ expect(audienceSchema.parse({})).toEqual(EVERYONE);+ expect(audienceNeeds(EVERYONE).size).toBe(0);+ expect(matchesAudience(EVERYONE, facts({ country: null }), now)).toBe(true);+ expect(describeAudience(EVERYONE)).toBe("everyone");+ });++ test("each rule reads its own fact", () => {+ const needs = audienceNeeds({ ...EVERYONE, plan: "pro", storageUsedPercentAtLeast: 80 });+ expect([...needs].sort()).toEqual(["pro", "storageUsedPercent"]);+ });++ test("countries", () => {+ const gb = { ...EVERYONE, countries: ["GB"] };+ expect(matchesAudience(gb, facts(), now)).toBe(false);+ expect(matchesAudience(gb, facts({ country: "GB" }), now)).toBe(true);+ expect(matchesAudience(gb, facts({ country: null }), now)).toBe(false);+ expect(audienceSchema.safeParse({ countries: ["us"] }).success).toBe(false);+ });++ test("creation window", () => {+ const from = { ...EVERYONE, createdAfter: "2026-09-02T00:00:00.000Z" };+ expect(matchesAudience(from, facts(), now)).toBe(false);+ expect(matchesAudience(from, facts({ createdAt: new Date("2026-09-02T00:00:00Z") }), now)).toBe(true);+ const before = { ...EVERYONE, createdBefore: "2026-09-01T00:00:00.000Z" };+ expect(matchesAudience(before, facts(), now)).toBe(false);+ expect(matchesAudience(before, facts({ createdAt: new Date("2026-08-31T00:00:00Z") }), now)).toBe(true);+ });++ test("plan and paid", () => {+ expect(matchesAudience({ ...EVERYONE, plan: "pro" }, facts(), now)).toBe(false);+ expect(matchesAudience({ ...EVERYONE, plan: "pro" }, facts({ pro: true }), now)).toBe(true);+ expect(matchesAudience({ ...EVERYONE, plan: "free" }, facts({ pro: true }), now)).toBe(false);+ expect(matchesAudience({ ...EVERYONE, paid: "yes" }, facts(), now)).toBe(false);+ expect(matchesAudience({ ...EVERYONE, paid: "yes" }, facts({ paid: true }), now)).toBe(true);+ expect(matchesAudience({ ...EVERYONE, paid: "no" }, facts({ paid: true }), now)).toBe(false);+ });++ test("activity", () => {+ const active = { ...EVERYONE, activeWithinDays: 2 };+ expect(matchesAudience(active, facts(), now)).toBe(true);+ expect(matchesAudience(active, facts({ lastActiveAt: new Date("2026-08-20T00:00:00Z") }), now)).toBe(false);+ expect(matchesAudience(active, facts({ lastActiveAt: null }), now)).toBe(false);+ });++ test("usage thresholds; an unknown usage never matches", () => {+ expect(matchesAudience({ ...EVERYONE, storageUsedPercentAtLeast: 80 }, facts(), now)).toBe(false);+ expect(matchesAudience({ ...EVERYONE, storageUsedPercentAtLeast: 40 }, facts(), now)).toBe(true);+ expect(matchesAudience({ ...EVERYONE, storageUsedPercentAtLeast: 0 }, facts({ storageUsedPercent: null }), now)).toBe(false);+ expect(matchesAudience({ ...EVERYONE, creditsUsedPercentAtLeast: 90 }, facts(), now)).toBe(true);+ expect(matchesAudience({ ...EVERYONE, creditsUsedPercentAtLeast: 95 }, facts(), now)).toBe(false);+ });++ test("rules combine", () => {+ const a = { ...EVERYONE, countries: ["US"], paid: "no" as const, creditsUsedPercentAtLeast: 80 };+ expect(matchesAudience(a, facts(), now)).toBe(true);+ expect(matchesAudience(a, facts({ paid: true }), now)).toBe(false);+ expect(describeAudience(a)).toBe("US · never paid · credits spent ≥ 80%");+ });+});diff --git a/site/packages/abexp/src/audience.ts b/site/packages/abexp/src/audience.tsnew file mode 100644index 00000000..882f1ef4--- /dev/null+++ b/site/packages/abexp/src/audience.ts@@ -0,0 +1,105 @@+import { z } from "zod";++// Who an experiment can enrol. An audience is a set of rules over facts about+// the account; every rule is optional and an empty audience admits everyone.+// Adding a rule means a field here, a fact in `AudienceFacts`, a line in+// `matchesAudience`, and the query that collects the fact+// (src/lib/config/audienceFacts.ts). Client-safe: zod only.++const alpha2 = z.string().regex(/^[A-Z]{2}$/, "Upper-case alpha-2 codes.");++export const audienceSchema = z+ .object({+ // Where the assigning request came from; empty admits every country.+ countries: z.array(alpha2).max(250).default([]),+ // Account creation window; either edge may be open.+ createdAfter: z.iso.datetime().nullable().default(null),+ createdBefore: z.iso.datetime().nullable().default(null),+ // Whether the account holds an active Pro subscription.+ plan: z.enum(["any", "free", "pro"]).default("any"),+ // Whether the account has ever paid for anything.+ paid: z.enum(["any", "yes", "no"]).default("any"),+ // A session touched within this many days.+ activeWithinDays: z.number().int().min(1).max(365).nullable().default(null),+ // Share of the cloud storage quota in use, at least this much.+ storageUsedPercentAtLeast: z.number().min(0).max(100).nullable().default(null),+ // Share of every credit ever granted that has been spent, at least this much.+ creditsUsedPercentAtLeast: z.number().min(0).max(100).nullable().default(null),+ })+ .strict();++export type Audience = z.output<typeof audienceSchema>;+export type AudienceInput = z.input<typeof audienceSchema>;++export const EVERYONE: Audience = audienceSchema.parse({});++export type AudienceFacts = {+ country: string | null;+ createdAt: Date;+ pro: boolean;+ paid: boolean;+ lastActiveAt: Date | null;+ // null when the account has no quota (unlimited) or the fact was not needed.+ storageUsedPercent: number | null;+ creditsUsedPercent: number | null;+};++export type AudienceFact = keyof AudienceFacts;++/** The facts an audience's rules read; the collector fetches only those. */+export function audienceNeeds(audience: Audience): Set<AudienceFact> {+ const needs = new Set<AudienceFact>();+ if (audience.countries.length > 0) needs.add("country");+ if (audience.createdAfter || audience.createdBefore) needs.add("createdAt");+ if (audience.plan !== "any") needs.add("pro");+ if (audience.paid !== "any") needs.add("paid");+ if (audience.activeWithinDays !== null) needs.add("lastActiveAt");+ if (audience.storageUsedPercentAtLeast !== null) needs.add("storageUsedPercent");+ if (audience.creditsUsedPercentAtLeast !== null) needs.add("creditsUsedPercent");+ return needs;+}++export function matchesAudience(audience: Audience, facts: AudienceFacts, now: Date): boolean {+ if (audience.countries.length > 0) {+ if (!facts.country || !audience.countries.includes(facts.country)) return false;+ }+ if (audience.createdAfter && facts.createdAt.getTime() < Date.parse(audience.createdAfter)) return false;+ if (audience.createdBefore && facts.createdAt.getTime() >= Date.parse(audience.createdBefore)) return false;+ if (audience.plan === "pro" && !facts.pro) return false;+ if (audience.plan === "free" && facts.pro) return false;+ if (audience.paid === "yes" && !facts.paid) return false;+ if (audience.paid === "no" && facts.paid) return false;+ if (audience.activeWithinDays !== null) {+ const since = now.getTime() - audience.activeWithinDays * 86_400_000;+ if (!facts.lastActiveAt || facts.lastActiveAt.getTime() < since) return false;+ }+ if (audience.storageUsedPercentAtLeast !== null) {+ if (facts.storageUsedPercent === null || facts.storageUsedPercent < audience.storageUsedPercentAtLeast) {+ return false;+ }+ }+ if (audience.creditsUsedPercentAtLeast !== null) {+ if (facts.creditsUsedPercent === null || facts.creditsUsedPercent < audience.creditsUsedPercentAtLeast) {+ return false;+ }+ }+ return true;+}++/** One line for a list: the rules an audience sets. */+export function describeAudience(audience: Audience): string {+ const parts: string[] = [];+ if (audience.countries.length) parts.push(audience.countries.join(", "));+ if (audience.createdAfter) parts.push(`created from ${audience.createdAfter.slice(0, 10)}`);+ if (audience.createdBefore) parts.push(`created before ${audience.createdBefore.slice(0, 10)}`);+ if (audience.plan !== "any") parts.push(audience.plan === "pro" ? "Pro" : "no Pro");+ if (audience.paid !== "any") parts.push(audience.paid === "yes" ? "has paid" : "never paid");+ if (audience.activeWithinDays !== null) parts.push(`active within ${audience.activeWithinDays}d`);+ if (audience.storageUsedPercentAtLeast !== null) {+ parts.push(`storage ≥ ${audience.storageUsedPercentAtLeast}%`);+ }+ if (audience.creditsUsedPercentAtLeast !== null) {+ parts.push(`credits spent ≥ ${audience.creditsUsedPercentAtLeast}%`);+ }+ return parts.length ? parts.join(" · ") : "everyone";+}diff --git a/site/packages/abexp/src/experiment.test.ts b/site/packages/abexp/src/experiment.test.tsnew file mode 100644index 00000000..a4e3ebaa--- /dev/null+++ b/site/packages/abexp/src/experiment.test.ts@@ -0,0 +1,89 @@+import { describe, expect, test } from "bun:test";+import { z } from "zod";++import { canTransition, experimentSchemas, removedAssignedVariants } from "./experiment";+import { defineSettings } from "./settings";++const registry = defineSettings({+ greeting: { schema: z.enum(["short", "long"]), default: "short", public: true, title: "Greeting", description: "" },+ serverOnly: { schema: z.boolean(), default: false, public: false, title: "Server", description: "" },+});++const { experimentSchema } = experimentSchemas(registry);++const valid = {+ key: "copy_v1",+ name: "Welcome copy",+ description: null,+ variants: [+ { key: "control", name: "Control", weight: 50, config: {} },+ { key: "treatment", name: "Treatment", weight: 50, config: { greeting: "long" } },+ ],+ audience: { countries: ["US", "GB"], createdAfter: "2026-09-01T00:00:00.000Z", paid: "no" },+ percent: 100,+ metrics: [+ { key: "purchase", name: "Purchase", source: "purchase", event: null },+ { key: "export", name: "Export", source: "event", event: "export_completed" },+ ],+};++describe("experiment schema", () => {+ test("accepts a well-formed experiment and fills the audience's defaults", () => {+ const parsed = experimentSchema.safeParse(valid);+ expect(parsed.success).toBe(true);+ expect(parsed.data?.audience.plan).toBe("any");+ expect(parsed.data?.audience.activeWithinDays).toBeNull();+ });++ test("rejects repeated variant or metric keys", () => {+ const dup = { ...valid, variants: [valid.variants[0], { ...valid.variants[1], key: "control" }] };+ expect(experimentSchema.safeParse(dup).success).toBe(false);+ const dupMetric = { ...valid, metrics: [valid.metrics[0], { ...valid.metrics[1], key: "purchase" }] };+ expect(experimentSchema.safeParse(dupMetric).success).toBe(false);+ });++ test("rejects weights that add to zero", () => {+ const zero = { ...valid, variants: valid.variants.map((v) => ({ ...v, weight: 0 })) };+ expect(experimentSchema.safeParse(zero).success).toBe(false);+ });++ test("rejects a variant over a server setting, which would never apply", () => {+ const server = { ...valid, variants: [{ ...valid.variants[0], config: { serverOnly: true } }] };+ expect(experimentSchema.safeParse(server).success).toBe(false);+ });++ test("rejects an unknown setting or a bad value in a variant", () => {+ const unknown = { ...valid, variants: [{ ...valid.variants[0], config: { nope: 1 } }] };+ expect(experimentSchema.safeParse(unknown).success).toBe(false);+ const bad = { ...valid, variants: [{ ...valid.variants[0], config: { greeting: "x" } }] };+ expect(experimentSchema.safeParse(bad).success).toBe(false);+ });++ test("an event metric names its event; a purchase metric names none", () => {+ const noEvent = { ...valid, metrics: [{ key: "x", name: "X", source: "event", event: null }] };+ expect(experimentSchema.safeParse(noEvent).success).toBe(false);+ const eventOnPurchase = { ...valid, metrics: [{ key: "x", name: "X", source: "purchase", event: "e" }] };+ expect(experimentSchema.safeParse(eventOnPurchase).success).toBe(false);+ });++ test("rejects a bad audience and an out-of-range percent", () => {+ expect(experimentSchema.safeParse({ ...valid, audience: { countries: ["us"] } }).success).toBe(false);+ expect(experimentSchema.safeParse({ ...valid, audience: { plan: "gold" } }).success).toBe(false);+ expect(experimentSchema.safeParse({ ...valid, percent: 101 }).success).toBe(false);+ });++ test("status transitions", () => {+ expect(canTransition("draft", "running")).toBe(true);+ expect(canTransition("draft", "paused")).toBe(false);+ expect(canTransition("running", "paused")).toBe(true);+ expect(canTransition("paused", "running")).toBe(true);+ expect(canTransition("running", "ended")).toBe(true);+ expect(canTransition("ended", "running")).toBe(false);+ });++ test("an assigned variant cannot be removed", () => {+ const next = experimentSchema.parse({ ...valid, variants: [valid.variants[0]] });+ expect(removedAssignedVariants(next, ["control", "treatment"])).toEqual(["treatment"]);+ expect(removedAssignedVariants(next, ["control"])).toEqual([]);+ });+});diff --git a/site/packages/abexp/src/experiment.ts b/site/packages/abexp/src/experiment.tsnew file mode 100644index 00000000..68a5ae62--- /dev/null+++ b/site/packages/abexp/src/experiment.ts@@ -0,0 +1,146 @@+import { z } from "zod";++import { audienceSchema } from "./audience";+import type { SettingsRegistry } from "./settings";++// The shape of an experiment as the host writes it and the assigner reads it.+// The schemas that check variant settings are built per registry, so a form+// and its route validate against the same declarations.++export const EXPERIMENT_STATUSES = ["draft", "running", "paused", "ended"] as const;+export type ExperimentStatus = (typeof EXPERIMENT_STATUSES)[number];++// Where an experiment can go from each status. Ended is final.+export const STATUS_TRANSITIONS: Record<ExperimentStatus, readonly ExperimentStatus[]> = {+ draft: ["running"],+ running: ["paused", "ended"],+ paused: ["running", "ended"],+ ended: [],+};++export const canTransition = (from: ExperimentStatus, to: ExperimentStatus) =>+ STATUS_TRANSITIONS[from].includes(to);++export const statusSchema = z.enum(EXPERIMENT_STATUSES);++const slug = z+ .string()+ .trim()+ .min(1)+ .max(64)+ .regex(/^[a-z0-9_]+$/, "Lower-case letters, digits and underscores only.");++const variantBase = z+ .object({+ key: slug,+ name: z.string().trim().min(1).max(80),+ weight: z.number().int().min(0).max(1000),+ // Full values, one per setting the variant changes, each parsed against+ // that setting's own schema.+ config: z.record(z.string(), z.unknown()),+ })+ .strict();++export type ExperimentVariant = z.output<typeof variantBase>;++// What the results job counts for each exposed account: an analytics event+// it fired after exposure, or a purchase the host recorded. The first metric+// of an experiment is the primary one and decides the verdict.+export const METRIC_SOURCES = ["event", "purchase"] as const;++export const metricSchema = z+ .object({+ key: slug,+ name: z.string().trim().min(1).max(80),+ source: z.enum(METRIC_SOURCES),+ // The event name; required for an event metric, absent otherwise.+ event: z.string().trim().min(1).max(200).nullable(),+ })+ .strict()+ .superRefine((metric, ctx) => {+ if (metric.source === "event" && !metric.event) {+ ctx.addIssue({ code: "custom", message: "An event metric names the event.", path: ["event"] });+ }+ if (metric.source === "purchase" && metric.event) {+ ctx.addIssue({ code: "custom", message: "A purchase metric names no event.", path: ["event"] });+ }+ });++export type ExperimentMetric = z.output<typeof metricSchema>;++const experimentBase = z+ .object({+ key: slug,+ name: z.string().trim().min(1).max(120),+ description: z.string().trim().max(2000).nullable(),+ // The first variant is the control the others are measured against.+ variants: z.array(variantBase).min(1).max(20),+ audience: audienceSchema,+ percent: z.number().int().min(0).max(100),+ metrics: z.array(metricSchema).max(20),+ })+ .strict();++export type ExperimentInput = z.output<typeof experimentBase>;++function uniqueKeys(items: { key: string }[], ctx: z.RefinementCtx, path: string, what: string) {+ const keys = new Set<string>();+ items.forEach((item, i) => {+ if (keys.has(item.key)) {+ ctx.addIssue({ code: "custom", message: `${what} key "${item.key}" repeats.`, path: [path, i, "key"] });+ }+ keys.add(item.key);+ });+}++/** The variant and experiment schemas checked against one registry. */+export function experimentSchemas<T extends SettingsRegistry>(registry: T) {+ const variantSchema = variantBase.superRefine((variant, ctx) => {+ for (const [key, value] of Object.entries(variant.config)) {+ const def = Object.hasOwn(registry, key) ? registry[key] : undefined;+ if (!def) {+ ctx.addIssue({ code: "custom", message: `Unknown setting "${key}".`, path: ["config", key] });+ continue;+ }+ // A variant reaches the product through the account's own config read.+ // A setting only the server reads is resolved without a user, so a+ // variant over it would assign and expose while changing nothing;+ // those are set by an override.+ if (!def.public) {+ ctx.addIssue({+ code: "custom",+ message: `"${key}" is a server setting; change it with an override.`,+ path: ["config", key],+ });+ continue;+ }+ const parsed = def.schema.safeParse(value);+ if (!parsed.success) {+ ctx.addIssue({+ code: "custom",+ message: `Invalid value for "${key}": ${parsed.error.issues[0]?.message ?? "rejected"}`,+ path: ["config", key],+ });+ }+ }+ });++ const experimentSchema = experimentBase+ .extend({ variants: z.array(variantSchema).min(1).max(20) })+ .superRefine((experiment, ctx) => {+ uniqueKeys(experiment.variants, ctx, "variants", "Variant");+ uniqueKeys(experiment.metrics, ctx, "metrics", "Metric");+ if (experiment.variants.reduce((sum, v) => sum + v.weight, 0) <= 0) {+ ctx.addIssue({ code: "custom", message: "Variant weights must add up above zero.", path: ["variants"] });+ }+ });++ return { variantSchema, experimentSchema };+}++/** Variant keys that carry assignments cannot leave: an assigned user would+ * have nothing to read. Adding a variant is fine. */+export function removedAssignedVariants(next: ExperimentInput, assignedKeys: Iterable<string>): string[] {+ const keep = new Set(next.variants.map((v) => v.key));+ return [...new Set(assignedKeys)].filter((key) => !keep.has(key));+}diff --git a/site/packages/abexp/src/index.ts b/site/packages/abexp/src/index.tsnew file mode 100644index 00000000..f77c2653--- /dev/null+++ b/site/packages/abexp/src/index.ts@@ -0,0 +1,6 @@+export * from "./settings";+export * from "./audience";+export * from "./assign";+export * from "./experiment";+export * from "./stats";+export * from "./results";diff --git a/site/packages/abexp/src/results.test.ts b/site/packages/abexp/src/results.test.tsnew file mode 100644index 00000000..02667447--- /dev/null+++ b/site/packages/abexp/src/results.test.ts@@ -0,0 +1,136 @@+import { describe, expect, test } from "bun:test";++import type { ExperimentMetric } from "./experiment";+import { computeResults, DEFAULT_THRESHOLDS, MIN_EXPOSED_PER_VARIANT, type VariantCount } from "./results";++const purchase: ExperimentMetric = { key: "purchase", name: "Purchase", source: "purchase", event: null };++const run = (counts: VariantCount[], metrics: ExperimentMetric[] = [purchase]) =>+ computeResults({+ computedAt: new Date("2026-09-04T00:00:00Z"),+ control: "control",+ metrics: metrics.map((metric) => ({ metric, counts })),+ notes: [],+ });++describe("results", () => {+ test("no metric leaves nothing to read", () => {+ const r = run([], []);+ expect(r.verdict.state).toBe("insufficient");+ expect(r.metrics).toEqual([]);+ });++ test("too few exposures is too early", () => {+ const r = run([+ { key: "control", exposed: 20, converted: 2 },+ { key: "treatment", exposed: 20, converted: 6 },+ ]);+ expect(r.verdict.state).toBe("insufficient");+ expect(r.verdict.neededPerArm).toBeGreaterThanOrEqual(MIN_EXPOSED_PER_VARIANT);+ });++ test("a clear win ships", () => {+ const r = run([+ { key: "control", exposed: 1000, converted: 40 },+ { key: "treatment", exposed: 1000, converted: 80 },+ ]);+ expect(r.verdict.state).toBe("ship");+ expect(r.verdict.variant).toBe("treatment");+ expect(r.metrics[0].comparisons[0].pValue!).toBeLessThan(0.05);+ });++ test("a clear loss stops early, before a full sample", () => {+ const r = run([+ { key: "control", exposed: 60, converted: 12 },+ { key: "treatment", exposed: 60, converted: 1 },+ ]);+ expect(r.verdict.state).toBe("stop");+ expect(r.verdict.variant).toBe("treatment");+ });++ test("a wash with a full sample keeps running", () => {+ const r = run([+ { key: "control", exposed: 500, converted: 25 },+ { key: "treatment", exposed: 500, converted: 27 },+ ]);+ expect(r.verdict.state).toBe("keep_running");+ expect(r.verdict.neededPerArm).not.toBeNull();+ });++ test("the best of several winners is named; one loser among winners does not stop", () => {+ const r = run([+ { key: "control", exposed: 1000, converted: 40 },+ { key: "a", exposed: 1000, converted: 70 },+ { key: "b", exposed: 1000, converted: 90 },+ { key: "c", exposed: 1000, converted: 5 },+ ]);+ expect(r.verdict.state).toBe("ship");+ expect(r.verdict.variant).toBe("b");+ });++ test("the first metric decides; the rest are reported", () => {+ const exportMetric: ExperimentMetric = { key: "export", name: "Export", source: "event", event: "export_completed" };+ const r = computeResults({+ computedAt: new Date(),+ control: "control",+ metrics: [+ {+ metric: purchase,+ counts: [+ { key: "control", exposed: 500, converted: 25 },+ { key: "treatment", exposed: 500, converted: 27 },+ ],+ },+ {+ metric: exportMetric,+ counts: [+ { key: "control", exposed: 500, converted: 100 },+ { key: "treatment", exposed: 500, converted: 200 },+ ],+ },+ ],+ notes: ["a note"],+ });+ expect(r.verdict.state).toBe("keep_running");+ expect(r.metrics.map((m) => m.key)).toEqual(["purchase", "export"]);+ expect(r.notes).toEqual(["a note"]);+ });+});++describe("thresholds", () => {+ const close = [+ { key: "control", exposed: 400, converted: 40 },+ { key: "treatment", exposed: 400, converted: 52 },+ ];++ test("a looser p-value ships what the default keeps running", () => {+ expect(run(close).verdict.state).toBe("keep_running");+ const loose = computeResults({+ computedAt: new Date(),+ control: "control",+ metrics: [{ metric: purchase, counts: close }],+ notes: [],+ thresholds: { ...DEFAULT_THRESHOLDS, shipPValue: 0.2 },+ });+ expect(loose.verdict.state).toBe("ship");+ });++ test("raising the minimum sample makes a shipped result too early", () => {+ const strict = computeResults({+ computedAt: new Date(),+ control: "control",+ metrics: [+ {+ metric: purchase,+ counts: [+ { key: "control", exposed: 1000, converted: 40 },+ { key: "treatment", exposed: 1000, converted: 80 },+ ],+ },+ ],+ notes: [],+ thresholds: { ...DEFAULT_THRESHOLDS, minExposedPerVariant: 5000 },+ });+ expect(strict.verdict.state).toBe("insufficient");+ });+});diff --git a/site/packages/abexp/src/results.ts b/site/packages/abexp/src/results.tsnew file mode 100644index 00000000..a8f936f5--- /dev/null+++ b/site/packages/abexp/src/results.ts@@ -0,0 +1,203 @@+import type { ExperimentMetric } from "./experiment";+import { probabilityBeats, sampleSizePerArm, twoProportionTest } from "./stats";++// An experiment's read, computed from exposure and conversion counts by the+// results job and stored on the row. The verdict answers the one question su+// asks: roll it out, stop it, or keep running — and how much longer.++// Exposures each arm needs, and conversions across the pair, before a+// positive result is believed.+export const MIN_EXPOSED_PER_VARIANT = 100;+export const MIN_CONVERSIONS = 20;+// A loss is called earlier: a variant this unlikely to beat the control, once+// a small sample is in, is stopped before it costs a full run.+export const EARLY_MIN_EXPOSED = 30;+export const EARLY_MIN_CONVERSIONS = 5;+export const SHIP_P_VALUE = 0.05;+export const STOP_PROBABILITY = 0.05;+// The lift the sample-size estimate plans for when the observed one is no+// better than that.+export const PLANNED_RELATIVE_LIFT = 0.2;++export type VariantCount = { key: string; exposed: number; converted: number };++/** The bars a verdict is called against. */+export type Thresholds = {+ minExposedPerVariant: number;+ minConversions: number;+ earlyMinExposed: number;+ earlyMinConversions: number;+ shipPValue: number;+ stopProbability: number;+ plannedRelativeLift: number;+};++export const DEFAULT_THRESHOLDS: Thresholds = {+ minExposedPerVariant: MIN_EXPOSED_PER_VARIANT,+ minConversions: MIN_CONVERSIONS,+ earlyMinExposed: EARLY_MIN_EXPOSED,+ earlyMinConversions: EARLY_MIN_CONVERSIONS,+ shipPValue: SHIP_P_VALUE,+ stopProbability: STOP_PROBABILITY,+ plannedRelativeLift: PLANNED_RELATIVE_LIFT,+};++export type Comparison = {+ variant: string;+ diff: number;+ relativeLift: number | null;+ pValue: number | null;+ probabilityBeatsControl: number;+};++export type MetricResult = {+ key: string;+ name: string;+ source: ExperimentMetric["source"];+ event: string | null;+ variants: (VariantCount & { rate: number })[];+ comparisons: Comparison[];+};++export type VerdictState = "insufficient" | "keep_running" | "ship" | "stop";++export type Verdict = {+ state: VerdictState;+ // The variant the verdict is about: the one to ship, or the one losing.+ variant: string | null;+ reason: string;+ // Exposures each arm needs for the primary metric, when the run is short.+ neededPerArm: number | null;+};++export type ExperimentResults = {+ computedAt: string;+ control: string;+ metrics: MetricResult[];+ verdict: Verdict;+ // What the job could not measure this time.+ notes: string[];+};++export function metricResult(metric: ExperimentMetric, control: string, counts: VariantCount[]): MetricResult {+ const base = counts.find((c) => c.key === control) ?? { key: control, exposed: 0, converted: 0 };+ return {+ key: metric.key,+ name: metric.name,+ source: metric.source,+ event: metric.event,+ variants: counts.map((c) => ({ ...c, rate: c.exposed > 0 ? c.converted / c.exposed : 0 })),+ comparisons: counts+ .filter((c) => c.key !== control)+ .map((c) => {+ const test = twoProportionTest(base.converted, base.exposed, c.converted, c.exposed);+ return {+ variant: c.key,+ diff: test.diff,+ relativeLift: test.relativeLift,+ pValue: test.pValue,+ probabilityBeatsControl: probabilityBeats(base.converted, base.exposed, c.converted, c.exposed),+ };+ }),+ };+}++const percent = (x: number) => `${(100 * x).toFixed(1)}%`;++export function verdictFor(+ primary: MetricResult | undefined,+ control: string,+ bars: Thresholds = DEFAULT_THRESHOLDS,+): Verdict {+ if (!primary) {+ return { state: "insufficient", variant: null, reason: "No metric is set.", neededPerArm: null };+ }+ const base = primary.variants.find((v) => v.key === control);+ if (!base || primary.comparisons.length === 0) {+ return { state: "insufficient", variant: null, reason: "Nothing to compare against the control.", neededPerArm: null };+ }+ const planned = Math.max(+ bars.plannedRelativeLift,+ ...primary.comparisons.map((c) => Math.abs(c.relativeLift ?? 0)),+ );+ const planSize = sampleSizePerArm(base.rate, planned);+ const neededPerArm = planSize === null ? null : Math.max(bars.minExposedPerVariant, planSize);++ const winners = primary.comparisons.filter((c) => {+ const arm = primary.variants.find((v) => v.key === c.variant)!;+ return (+ arm.exposed >= bars.minExposedPerVariant &&+ base.exposed >= bars.minExposedPerVariant &&+ arm.converted + base.converted >= bars.minConversions &&+ c.diff > 0 &&+ c.pValue !== null &&+ c.pValue < bars.shipPValue+ );+ });+ if (winners.length > 0) {+ const best = winners.reduce((a, b) => (b.diff > a.diff ? b : a));+ const arm = primary.variants.find((v) => v.key === best.variant)!;+ return {+ state: "ship",+ variant: best.variant,+ reason: `${best.variant} converts at ${percent(arm.rate)} against ${percent(base.rate)} on ${primary.name} (p = ${best.pValue!.toFixed(3)}).`,+ neededPerArm,+ };+ }++ const losers = primary.comparisons.filter((c) => {+ const arm = primary.variants.find((v) => v.key === c.variant)!;+ return (+ arm.exposed >= bars.earlyMinExposed &&+ base.exposed >= bars.earlyMinExposed &&+ arm.converted + base.converted >= bars.earlyMinConversions &&+ c.probabilityBeatsControl < bars.stopProbability+ );+ });+ if (losers.length === primary.comparisons.length) {+ const worst = losers.reduce((a, b) => (b.probabilityBeatsControl < a.probabilityBeatsControl ? b : a));+ const arm = primary.variants.find((v) => v.key === worst.variant)!;+ return {+ state: "stop",+ variant: worst.variant,+ reason: `${worst.variant} converts at ${percent(arm.rate)} against ${percent(base.rate)} on ${primary.name}; a ${percent(worst.probabilityBeatsControl)} chance it is better.`,+ neededPerArm,+ };+ }++ const short = primary.variants.filter((v) => v.exposed < bars.minExposedPerVariant);+ const conversions = primary.variants.reduce((sum, v) => sum + v.converted, 0);+ if (short.length > 0 || conversions < bars.minConversions) {+ const smallest = Math.min(...primary.variants.map((v) => v.exposed));+ return {+ state: "insufficient",+ variant: null,+ reason: `Too early to read: ${smallest} exposed in the smallest arm and ${conversions} conversions on ${primary.name}.`,+ neededPerArm,+ };+ }+ const lead = primary.comparisons.reduce((a, b) => (b.probabilityBeatsControl > a.probabilityBeatsControl ? b : a));+ return {+ state: "keep_running",+ variant: lead.variant,+ reason: `No clear result yet: ${lead.variant} has a ${percent(lead.probabilityBeatsControl)} chance of beating the control on ${primary.name}.`,+ neededPerArm,+ };+}++export function computeResults(input: {+ computedAt: Date;+ control: string;+ metrics: { metric: ExperimentMetric; counts: VariantCount[] }[];+ notes: string[];+ thresholds?: Thresholds;+}): ExperimentResults {+ const metrics = input.metrics.map((m) => metricResult(m.metric, input.control, m.counts));+ return {+ computedAt: input.computedAt.toISOString(),+ control: input.control,+ metrics,+ verdict: verdictFor(metrics[0], input.control, input.thresholds ?? DEFAULT_THRESHOLDS),+ notes: input.notes,+ };+}diff --git a/site/packages/abexp/src/settings.test.ts b/site/packages/abexp/src/settings.test.tsnew file mode 100644index 00000000..12462a05--- /dev/null+++ b/site/packages/abexp/src/settings.test.ts@@ -0,0 +1,46 @@+import { describe, expect, test } from "bun:test";+import { z } from "zod";++import { defaultSettings, defineSettings, publicSettingKeys, publicSubset, resolveSettings } from "./settings";++const registry = defineSettings({+ greeting: { schema: z.enum(["short", "long"]), default: "short", public: true, title: "Greeting", description: "" },+ serverOnly: { schema: z.boolean(), default: false, public: false, title: "Server", description: "" },+});++describe("settings", () => {+ test("a default the schema rejects fails at definition", () => {+ let threw = false;+ try {+ defineSettings({ bad: { schema: z.number(), default: "x" as never, public: true, title: "", description: "" } });+ } catch {+ threw = true;+ }+ expect(threw).toBe(true);+ });++ test("the public subset carries only public keys", () => {+ expect(publicSettingKeys(registry)).toEqual(["greeting"]);+ expect(publicSubset(registry, defaultSettings(registry))).toEqual({ greeting: "short" });+ });++ test("resolves default < override < variant", () => {+ expect(resolveSettings(registry, {}, []).settings.greeting).toBe("short");+ expect(resolveSettings(registry, { greeting: "long" }, []).settings.greeting).toBe("long");+ const variant = resolveSettings(registry, { greeting: "long" }, [{ greeting: "short" }]);+ expect(variant.settings.greeting).toBe("short");+ expect(variant.invalid).toEqual([]);+ });++ test("a bad override is reported and the default stands", () => {+ const resolved = resolveSettings(registry, { serverOnly: "yes" }, []);+ expect(resolved.settings.serverOnly).toBe(false);+ expect(resolved.invalid).toEqual([{ key: "serverOnly", layer: "override" }]);+ });++ test("a bad variant value is reported and the override stands", () => {+ const resolved = resolveSettings(registry, { greeting: "long" }, [{ greeting: "nope" }]);+ expect(resolved.settings.greeting).toBe("long");+ expect(resolved.invalid).toEqual([{ key: "greeting", layer: "variant" }]);+ });+});diff --git a/site/packages/abexp/src/settings.ts b/site/packages/abexp/src/settings.tsnew file mode 100644index 00000000..7c96a871--- /dev/null+++ b/site/packages/abexp/src/settings.ts@@ -0,0 +1,92 @@+import type { z } from "zod";++// A settings registry: every runtime tunable a product has, declared once+// with a schema and a default. A value resolves default < override < variant;+// the host stores overrides and supplies variants. The registry itself is the+// host's; this module gives it shape and resolution.++export type SettingDef<S extends z.ZodType = z.ZodType> = {+ schema: S;+ default: z.output<S>;+ // A public setting reaches the client through the account's config read; a+ // server setting is read only by handlers, webhooks and jobs.+ public: boolean;+ title: string;+ description: string;+};++export type SettingsRegistry = Record<string, SettingDef>;++export type SettingKeyOf<T extends SettingsRegistry> = keyof T & string;+export type SettingsOf<T extends SettingsRegistry> = { [K in keyof T]: z.output<T[K]["schema"]> };+export type PublicKeyOf<T extends SettingsRegistry> = {+ [K in keyof T]: T[K]["public"] extends true ? K & string : never;+}[keyof T];+export type PublicSettingsOf<T extends SettingsRegistry> = Pick<SettingsOf<T>, PublicKeyOf<T>>;++// Parses every default against its schema at module load, so a registry that+// declares an impossible default fails the process at boot.+export function defineSettings<const T extends SettingsRegistry>(defs: T): T {+ for (const [key, def] of Object.entries(defs)) {+ const parsed = def.schema.safeParse(def.default);+ if (!parsed.success) {+ throw new Error(`Setting "${key}" has a default its schema rejects: ${parsed.error.message}`);+ }+ }+ return defs;+}++export function settingKeys<T extends SettingsRegistry>(registry: T): SettingKeyOf<T>[] {+ return Object.keys(registry) as SettingKeyOf<T>[];+}++export function publicSettingKeys<T extends SettingsRegistry>(registry: T): PublicKeyOf<T>[] {+ return settingKeys(registry).filter((key) => registry[key].public) as PublicKeyOf<T>[];+}++export function defaultSettings<T extends SettingsRegistry>(registry: T): SettingsOf<T> {+ const out: Record<string, unknown> = {};+ for (const key of settingKeys(registry)) out[key] = registry[key].default;+ return out as SettingsOf<T>;+}++export type Resolved<T extends SettingsRegistry> = {+ settings: SettingsOf<T>;+ invalid: { key: SettingKeyOf<T>; layer: "override" | "variant" }[];+};++/** Pure resolution: default < override < variant. An override or a variant+ * value that no longer parses is skipped and named, so a schema change never+ * takes the product down; the host shows the key as invalid so it can be+ * reset. */+export function resolveSettings<T extends SettingsRegistry>(+ registry: T,+ overrides: Record<string, unknown>,+ variantConfigs: Record<string, unknown>[],+): Resolved<T> {+ const settings: Record<string, unknown> = {};+ const invalid: Resolved<T>["invalid"] = [];+ for (const key of settingKeys(registry)) {+ const { schema } = registry[key];+ let value: unknown = registry[key].default;+ if (key in overrides) {+ const parsed = schema.safeParse(overrides[key]);+ if (parsed.success) value = parsed.data;+ else invalid.push({ key, layer: "override" });+ }+ for (const config of variantConfigs) {+ if (!(key in config)) continue;+ const parsed = schema.safeParse(config[key]);+ if (parsed.success) value = parsed.data;+ else invalid.push({ key, layer: "variant" });+ }+ settings[key] = value;+ }+ return { settings: settings as SettingsOf<T>, invalid };+}++export function publicSubset<T extends SettingsRegistry>(registry: T, settings: SettingsOf<T>): PublicSettingsOf<T> {+ const out: Record<string, unknown> = {};+ for (const key of publicSettingKeys(registry)) out[key] = settings[key];+ return out as PublicSettingsOf<T>;+}diff --git a/site/packages/abexp/src/stats.test.ts b/site/packages/abexp/src/stats.test.tsnew file mode 100644index 00000000..b55e88e3--- /dev/null+++ b/site/packages/abexp/src/stats.test.ts@@ -0,0 +1,46 @@+import { describe, expect, test } from "bun:test";++import { logGamma, normalCdf, probabilityBeats, sampleSizePerArm, twoProportionTest } from "./stats";++describe("stats", () => {+ test("normal cdf at known points", () => {+ expect(normalCdf(0)).toBeCloseTo(0.5, 6);+ expect(normalCdf(1.959964)).toBeCloseTo(0.975, 5);+ expect(normalCdf(-1.959964)).toBeCloseTo(0.025, 5);+ });++ test("log gamma matches factorials", () => {+ expect(Math.exp(logGamma(5))).toBeCloseTo(24, 6);+ expect(Math.exp(logGamma(1))).toBeCloseTo(1, 9);+ expect(logGamma(0.5)).toBeCloseTo(Math.log(Math.sqrt(Math.PI)), 9);+ });++ test("two-proportion test", () => {+ const same = twoProportionTest(50, 500, 50, 500);+ expect(same.diff).toBe(0);+ expect(same.pValue).toBeCloseTo(1, 6);+ const better = twoProportionTest(50, 500, 80, 500);+ expect(better.relativeLift).toBeCloseTo(0.6, 9);+ expect(better.pValue!).toBeLessThan(0.01);+ expect(twoProportionTest(0, 100, 0, 100).pValue).toBeNull();+ expect(twoProportionTest(0, 0, 1, 10).pValue).toBeNull();+ });++ test("probability of beating the control", () => {+ expect(probabilityBeats(50, 500, 50, 500)).toBeCloseTo(0.5, 2);+ expect(probabilityBeats(50, 500, 80, 500)).toBeGreaterThan(0.99);+ expect(probabilityBeats(80, 500, 50, 500)).toBeLessThan(0.01);+ // Symmetric: P(B > A) + P(A > B) = 1 for continuous posteriors.+ expect(probabilityBeats(3, 40, 7, 40) + probabilityBeats(7, 40, 3, 40)).toBeCloseTo(1, 6);+ expect(probabilityBeats(0, 0, 0, 0)).toBeCloseTo(0.5, 6);+ });++ test("sample size per arm", () => {+ // 5% control, 20% relative lift: about 8.2k per arm at α .05, power .8.+ const n = sampleSizePerArm(0.05, 0.2)!;+ expect(n).toBeGreaterThan(8000);+ expect(n).toBeLessThan(8400);+ expect(sampleSizePerArm(0, 0.2)).toBeNull();+ expect(sampleSizePerArm(0.9, 0.2)).toBeNull();+ });+});diff --git a/site/packages/abexp/src/stats.ts b/site/packages/abexp/src/stats.tsnew file mode 100644index 00000000..5d298caa--- /dev/null+++ b/site/packages/abexp/src/stats.ts@@ -0,0 +1,97 @@+// The arithmetic behind an experiment's read: a two-proportion test for the+// classical p-value, a Beta-Binomial posterior for the chance a variant beats+// the control, and the sample a run needs. Pure, no dependencies.++/** Standard normal CDF, Abramowitz & Stegun 7.1.26 (error under 2e-7). */+export function normalCdf(z: number): number {+ const sign = z < 0 ? -1 : 1;+ const x = Math.abs(z) / Math.SQRT2;+ const t = 1 / (1 + 0.3275911 * x);+ const poly =+ t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429))));+ const erf = 1 - poly * Math.exp(-x * x);+ return 0.5 * (1 + sign * erf);+}++/** Lanczos approximation of ln Γ(x) for x > 0. */+export function logGamma(x: number): number {+ const g = 7;+ const c = [+ 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,+ -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,+ 1.5056327351493116e-7,+ ];+ if (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);+ x -= 1;+ let a = c[0];+ const t = x + g + 0.5;+ for (let i = 1; i < g + 2; i++) a += c[i] / (x + i);+ return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);+}++const logBeta = (a: number, b: number) => logGamma(a) + logGamma(b) - logGamma(a + b);++export type ProportionTest = {+ rateA: number;+ rateB: number;+ // B's rate minus A's, and the same as a share of A's rate.+ diff: number;+ relativeLift: number | null;+ // Two-sided; null when neither arm has a spread to test against.+ pValue: number | null;+};++/** Classical two-sided test of B's rate against A's, pooled standard error. */+export function twoProportionTest(+ convertedA: number,+ exposedA: number,+ convertedB: number,+ exposedB: number,+): ProportionTest {+ const rateA = exposedA > 0 ? convertedA / exposedA : 0;+ const rateB = exposedB > 0 ? convertedB / exposedB : 0;+ const diff = rateB - rateA;+ const relativeLift = rateA > 0 ? diff / rateA : null;+ if (exposedA === 0 || exposedB === 0) return { rateA, rateB, diff, relativeLift, pValue: null };+ const pooled = (convertedA + convertedB) / (exposedA + exposedB);+ const se = Math.sqrt(pooled * (1 - pooled) * (1 / exposedA + 1 / exposedB));+ if (se === 0) return { rateA, rateB, diff, relativeLift, pValue: null };+ const z = diff / se;+ return { rateA, rateB, diff, relativeLift, pValue: 2 * (1 - normalCdf(Math.abs(z))) };+}++/** P(rate B > rate A) under Beta(1, 1) priors on each arm; exact, via the+ * closed-form sum over B's successes. */+export function probabilityBeats(+ convertedA: number,+ exposedA: number,+ convertedB: number,+ exposedB: number,+): number {+ const alphaA = 1 + convertedA;+ const betaA = 1 + exposedA - convertedA;+ const alphaB = 1 + convertedB;+ const betaB = 1 + exposedB - convertedB;+ let total = 0;+ const base = logBeta(alphaA, betaA);+ for (let i = 0; i < alphaB; i++) {+ total += Math.exp(logBeta(alphaA + i, betaA + betaB) - Math.log(betaB + i) - logBeta(1 + i, betaB) - base);+ }+ return Math.min(1, Math.max(0, total));+}++// Two-sided α = 0.05 and power 0.8, the usual bar.+const Z_ALPHA = 1.959964;+const Z_BETA = 0.841621;++/** Exposures each arm needs to detect a relative lift over the control rate.+ * Null when the control rate leaves nothing to detect. */+export function sampleSizePerArm(controlRate: number, relativeLift: number): number | null {+ const p1 = controlRate;+ const p2 = p1 * (1 + relativeLift);+ if (p1 <= 0 || p2 >= 1 || p2 === p1) return null;+ const pBar = (p1 + p2) / 2;+ const numerator =+ Z_ALPHA * Math.sqrt(2 * pBar * (1 - pBar)) + Z_BETA * Math.sqrt(p1 * (1 - p1) + p2 * (1 - p2));+ return Math.ceil((numerator * numerator) / ((p2 - p1) * (p2 - p1)));+}