API reference¶
Everything below is importable from the top-level package, for example from experimentation_toolkit import judge_experiment. Keyword arguments are required unless a default is shown.
Assignment¶
Deterministic hashed and switchback assignment.
SwitchbackBlock ¶
Bases: ToolkitModel
A fixed-length time block, numbered from the Unix epoch.
hashed_variant ¶
hashed_variant(*, experiment: str, variants: Sequence[str], unit: str) -> str
Assign a unit, such as a visit, to one variant with equal probability.
A unit keeps its variant for the life of the experiment, and experiments hash independently, so one unit's variants in two experiments are uncorrelated.
in_holdout ¶
in_holdout(*, surface: str, unit: str, share: float) -> bool
Return whether a unit belongs to the holdout that keeps the static behavior.
unit_interval ¶
unit_interval(*parts: str) -> float
Map the parts to a uniform number in [0, 1) with an 8-byte BLAKE2b digest.
The same parts always map to the same number, on every machine and Python version.
switchback_block ¶
switchback_block(moment: datetime, *, minutes: int) -> SwitchbackBlock
Return the block of the given length that contains a timezone-aware moment.
switchback_variant ¶
switchback_variant(*, experiment: str, variants: Sequence[str], block: SwitchbackBlock) -> str
Return the variant that owns a block.
Consecutive blocks form cycles of one block per variant. Each cycle shows every variant once, in an order shuffled by a seed of the experiment and the cycle, so time-of-day effects spread evenly over the variants.
Planning¶
Power and sample-size planning.
proportion_achieved_power ¶
proportion_achieved_power(*, baseline_rate: float, treatment_rate: float, control_sample_size: int, treatment_sample_size: int, alpha: float = 0.05, alternative: AlternativeHypothesis | str = AlternativeHypothesis.TWO_SIDED) -> AchievedPowerResult
Estimate achieved power for a fixed two-proportion design.
proportion_sample_size ¶
proportion_sample_size(*, baseline_rate: float, minimum_detectable_effect: float, mde_type: MDEType | str, alpha: float = 0.05, power: float = 0.8, allocation_ratio: float = 1.0, alternative: AlternativeHypothesis | str = AlternativeHypothesis.TWO_SIDED) -> ProportionSampleSizeResult
Plan group sizes for a two-proportion experiment.
allocation_ratio is treatment/control. The MDE is a positive magnitude:
it is added to the baseline for two-sided/greater alternatives and subtracted
for a less alternative. A relative MDE is a fraction of the baseline (0.1
means a 10% relative change), never percentage points.
Power and portfolio planning for concurrent experiments.
Baseline ¶
Bases: ToolkitModel
The pooled mean and standard deviation of a metric so far.
CandidateMetric ¶
Bases: ToolkitModel
A metric that could decide an experiment.
ExperimentCandidate ¶
Bases: ToolkitModel
An experiment competing for its surface's traffic and alpha.
MetricSizing ¶
Bases: ToolkitModel
Sample size and time a metric needs at the full alpha.
PlanAssumptions ¶
Bases: ToolkitModel
The design every experiment in a portfolio is sized for.
minimum_effect ¶
minimum_effect: float = Field(gt=0.0, description='Relative effect worth detecting')
horizon_weeks ¶
horizon_weeks: float = Field(gt=0.0, description='Concurrent experiments must decide by then')
window_weeks ¶
window_weeks: float = Field(gt=0.0, description='Data older than the window is dropped')
switch_speedup ¶
switch_speedup: float = Field(gt=1.0, description='Speedup needed to change a primary')
PlannedExperiment ¶
Bases: ToolkitModel
One experiment's place in the plan.
weeks_to_decision ¶
weeks_to_decision: float | None = Field(description='Remaining weeks, or null when it cannot decide within the window')
PortfolioPlan ¶
Bases: ToolkitModel
Which experiments run, at which alpha, and which wait.
PrimaryMetric ¶
Bases: ToolkitModel
The metric that decides an experiment, and since when it does.
plan_portfolio ¶
plan_portfolio(candidates: Sequence[ExperimentCandidate], *, assumptions: PlanAssumptions, now: datetime) -> PortfolioPlan
Plan the experiments of every surface for the next period.
Per surface, undecided experiments join the running set from the most trafficked down, as long as every running experiment still decides within the horizon with the surface's alpha split evenly (Bonferroni) among them. If none fits, the one that decides soonest runs alone. The others queue, sized at the alpha they would get by joining.
choose_primary_metric ¶
choose_primary_metric(candidate: ExperimentCandidate, *, assumptions: PlanAssumptions, now: datetime) -> PrimaryMetric
Pick the metric that decides soonest, and keep it until another is much faster.
The current primary stays unless the fastest metric needs fewer than
1 / switch_speedup of its weeks, so the primary does not flip with noise.
Analysis¶
Metric analysis functions.
analyze_continuous ¶
analyze_continuous(*, control: ArrayLike, treatment: ArrayLike, confidence_level: float = 0.95, alternative: AlternativeHypothesis | str = AlternativeHypothesis.TWO_SIDED, nonfinite_policy: Literal['raise', 'omit'] = 'raise', metric_name: str | None = None) -> AnalysisResult
Analyze independent means using Welch's unequal-variance t procedure.
Inputs must be one-dimensional and contain at least two finite values per arm. Non-finite observations raise by default; callers may explicitly request omission. A relative effect is emitted only when both group means are non-negative and the control mean is numerically resolved relative to the observed data scale.
analyze_proportion ¶
analyze_proportion(*, control_successes: int, control_total: int, treatment_successes: int, treatment_total: int, confidence_level: float = 0.95, alternative: AlternativeHypothesis | str = AlternativeHypothesis.TWO_SIDED, metric_name: str | None = None) -> AnalysisResult
Analyze a treatment-minus-control difference in independent proportions.
The test is the pooled two-sample score z-test for H0: p_t - p_c = 0.
The confidence interval is Newcombe's hybrid score interval based on Wilson
intervals, without continuity correction. One-sided alternatives return the
corresponding one-sided interval with None for its unbounded endpoint.
Experiment diagnostics.
check_sample_ratio_mismatch ¶
check_sample_ratio_mismatch(*, observed_counts: Mapping[str, int], expected_proportions: Mapping[str, float], significance_level: float = 0.01, proportion_tolerance: float = 1e-12) -> SRMResult
Run Pearson's chi-square goodness-of-fit test for assignment counts.
A failing result flags a potential randomization or instrumentation problem. It does not identify the cause. The chi-square approximation assumes independent assignments and sufficiently large positive expected counts.
Multiple-testing procedures.
adjust_p_values ¶
adjust_p_values(p_values: Iterable[float], *, method: CorrectionMethod | str, alpha: float = 0.05, hypothesis_labels: Sequence[str] | None = None) -> MultipleTestingResult
Adjust p-values with Bonferroni, Holm, or Benjamini-Hochberg.
Bonferroni and Holm control family-wise error rate. Benjamini-Hochberg controls false discovery rate under independence or positive dependence; it does not generally control family-wise error rate.
Decision¶
Experiment decisions: SRM gate, multiplicity correction and guardrail veto.
ExperimentVerdict ¶
Bases: ToolkitModel
The decision for a two-arm experiment.
vetoed_by ¶
vetoed_by: tuple[str, ...] = Field(description='Guardrails that got worse and kept the control')
MetricEvidence ¶
Bases: ToolkitModel
One metric of an experiment: the primary metric or a guardrail.
MetricVerdict ¶
judge_experiment ¶
judge_experiment(*, experiment: str, control: str, treatment: str, metrics: Sequence[MetricEvidence], srm: SRMResult | None, correction: CorrectionMethod | str, alpha: float) -> ExperimentVerdict
Decide a two-arm experiment from its primary metric and guardrails.
The p-values of all analysed metrics form one family, corrected with correction.
A metric is better or worse only when its adjusted p-value is at most alpha and
its confidence interval excludes zero. A failed SRM check turns every analysed metric
into a mismatch, because the arms are no longer comparable. The primary metric names
the winner, and a guardrail that got worse vetoes a treatment win. Pass srm=None
only for arms that were not randomized, such as before and after a deploy.
Deterministic plain-language explanations of experiment results.
Sequential¶
Group-sequential monitoring with Lan-DeMets alpha spending.
HarmResult ¶
Bases: ToolkitModel
Whether a change made a metric worse, and how soon that showed.
alpha_spent ¶
alpha_spent(information_fraction: float, *, alpha: float, spending: SpendingFunction | str) -> float
Return the cumulative one-sided alpha spent at an information fraction in [0, 1].
O'Brien-Fleming-type spending is 2 - 2 Phi(z_{1-alpha/2} / sqrt(t)) and Pocock-type
spending is alpha ln(1 + (e - 1) t); both spend exactly alpha at t = 1.
group_sequential_boundaries ¶
group_sequential_boundaries(information_fractions: Sequence[float], *, alpha: float = 0.05, spending: SpendingFunction | str = SpendingFunction.O_BRIEN_FLEMING) -> tuple[float, ...]
Return one-sided upper z boundaries for Lan-DeMets alpha spending.
The z statistics follow the canonical joint distribution with
Corr(Z_i, Z_j) = sqrt(t_i / t_j). Each boundary is solved so that the probability of
first crossing at that look under the null equals the alpha-spending increment, using
recursive numerical integration of the score process on a grid.
analyze_sequential_continuous ¶
analyze_sequential_continuous(*, control: ArrayLike, treatment: ArrayLike, control_looks: Sequence[int], treatment_looks: Sequence[int], maximum_control_size: int, maximum_treatment_size: int, alpha: float = 0.05, alternative: AlternativeHypothesis | str, spending: SpendingFunction | str = SpendingFunction.O_BRIEN_FLEMING, metric_name: str | None = None) -> SequentialTestResult
Monitor a mean difference with a one-sided Lan-DeMets group-sequential test.
control and treatment are ordered observations; look k analyzes the first
control_looks[k] and treatment_looks[k] of them, and the last look covers all of
them. Each look's Welch statistic is mapped to a z statistic with the same tail
probability. Information fractions use the full-data arm variances and the planned
maximum sizes. Monitoring stops at the first look that crosses its boundary.
detect_harm ¶
detect_harm(*, before: ArrayLike, after: ArrayLike, maximum_after: int, better: Direction, alpha: float, spending: SpendingFunction | str, metric_name: str | None) -> HarmResult
Look for harm after every new observation since a change, such as a deploy.
The observations before the change are the fixed control. Each observation after
it adds one look, from the second on, up to maximum_after, fixed before
monitoring starts. The one-sided test points in the harmful direction, so a crossing
means the change made the metric worse; no crossing is not evidence of no harm.
Bandit¶
Thompson-sampling allocation with a floor, and whole-unit apportionment.
ArmAllocation ¶
Bases: ToolkitModel
The share an arm gets and the posterior behind it.
ArmEvidence ¶
thompson_allocation ¶
thompson_allocation(evidence: Sequence[ArmEvidence], *, minimum_share: float, prior_exposure: float, draws: int, rng: Generator) -> tuple[ArmAllocation, ...]
Give each arm the floor plus its posterior probability of having the best rate.
Each arm's reward rate per unit of exposure gets a Gamma posterior. Reward arrives in
clumps of the average reward per event, which widens the posterior for lumpy rewards.
The prior is worth prior_exposure units at the pooled rate of all arms, so a new
arm starts at the average instead of at zero. minimum_share keeps every arm
explored; the rest is split by the share of draws in which an arm was best.
apportion ¶
apportion(shares: Mapping[str, float], *, total: int) -> dict[str, int]
Split total whole units by shares, at least one unit for every arm.
After one unit each, the rest follows the shares by the largest-remainder method,
so the counts always add up to total.
Models¶
Public domain and result models.
Experiment ¶
Bases: ToolkitModel
Metadata for a two-arm controlled experiment.
Metric ¶
Bases: ToolkitModel
Metadata for one experiment outcome.
ToolkitModel ¶
Bases: BaseModel
Strict, immutable base model with standards-compliant JSON output.
Variant ¶
AlternativeHypothesis ¶
CorrectionMethod ¶
DiagnosticStatus ¶
Direction ¶
ExperimentStatus ¶
MDEType ¶
MetricType ¶
SpendingFunction ¶
Verdict ¶
AchievedPowerResult ¶
AnalysisResult ¶
Bases: ToolkitModel
Common result schema for treatment-minus-control analyses.
treatment_standard_deviation ¶
treatment_standard_deviation: float | None = Field(default=None, ge=0.0)
ConfidenceInterval ¶
Bases: ToolkitModel
An interval whose None endpoint represents an unbounded side.
DiagnosticResult ¶
Bases: ToolkitModel
A factual diagnostic emitted by an analysis.
ExperimentReport ¶
MultipleTestingResult ¶
ProportionSampleSizeResult ¶
SequentialTestResult ¶
SRMResult ¶
MCP tools¶
experimentation-toolkit-mcp (extra agent) serves these read-only tools over stdio:
| Tool | Does | Library call |
|---|---|---|
size_experiment |
Exposures per arm for a two-sided, evenly split test of a rate | proportion_sample_size |
plan_experiments |
Which experiments run per surface, at which alpha, and which queue | plan_portfolio |
judge_experiment |
Verdict from raw counts or observations: sample ratio check, corrected metrics, guardrail veto | check_sample_ratio_mismatch, judge_experiment |
explain_result |
Stakeholder explanation of a verdict | explain_verdict |