Skip to content

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.

index

index: int

start

start: AwareDatetime

end

end: AwareDatetime

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.

mean

mean: float

standard_deviation

standard_deviation: float = Field(ge=0.0)

CandidateMetric

Bases: ToolkitModel

A metric that could decide an experiment.

name

name: str = Field(min_length=1)

metric_type

metric_type: MetricType

baseline

baseline: Baseline | None = Field(description='Null until the metric has data')

ExperimentCandidate

Bases: ToolkitModel

An experiment competing for its surface's traffic and alpha.

name

name: str = Field(min_length=1)

surface

surface: str = Field(min_length=1, description='Experiments on a surface share its alpha')

exposures_per_arm_per_week

exposures_per_arm_per_week: float = Field(ge=0.0)

gathered_per_arm

gathered_per_arm: int = Field(ge=0, description='Exposures in the smaller arm so far')

minimum_per_arm

minimum_per_arm: int = Field(ge=1)

metrics

metrics: tuple[CandidateMetric, ...] = Field(min_length=1)

primary

primary: PrimaryMetric | None = Field(description='The choice of the last plan, or null')

winner

winner: str | None = Field(description='The decided winner, or null while undecided')

MetricSizing

Bases: ToolkitModel

Sample size and time a metric needs at the full alpha.

metric

metric: str

needed_per_arm

needed_per_arm: int | None = Field(description='Null when the effect is undetectable')

weeks_of_data

weeks_of_data: float | None = Field(description='Null when no traffic can reach it')

PlanAssumptions

Bases: ToolkitModel

The design every experiment in a portfolio is sized for.

alpha

alpha: float = Field(gt=0.0, lt=1.0, description='Family-wise alpha shared per surface')

power

power: float = Field(gt=0.5, lt=1.0)

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.

name

name: str

surface

surface: str

status

status: ExperimentStatus

primary

primary: PrimaryMetric

sizings

sizings: tuple[MetricSizing, ...]

alpha

alpha: float = Field(gt=0.0, lt=1.0)

exposures_per_week

exposures_per_week: float = Field(ge=0.0)

gathered_per_arm

gathered_per_arm: int = Field(ge=0)

needed_per_arm

needed_per_arm: int | None

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.

assumptions

assumptions: PlanAssumptions

computed_at

computed_at: AwareDatetime

experiments

experiments: tuple[PlannedExperiment, ...]

PrimaryMetric

Bases: ToolkitModel

The metric that decides an experiment, and since when it does.

metric

metric: str = Field(min_length=1)

since

since: AwareDatetime

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.

experiment

experiment: str = Field(min_length=1)

control

control: str = Field(min_length=1)

treatment

treatment: str = Field(min_length=1)

alpha

alpha: float = Field(gt=0.0, lt=1.0)

correction

correction: CorrectionMethod

srm

srm: SRMResult | None

metrics

metrics: tuple[MetricVerdict, ...]

winner

winner: str | None

vetoed_by

vetoed_by: tuple[str, ...] = Field(description='Guardrails that got worse and kept the control')

primary

primary: MetricVerdict

The verdict of the primary metric.

guardrails

guardrails: tuple[MetricVerdict, ...]

The verdicts of every metric except the primary.

MetricEvidence

Bases: ToolkitModel

One metric of an experiment: the primary metric or a guardrail.

name

name: str = Field(min_length=1)

better

better: Direction

primary

primary: bool

result

result: AnalysisResult | None = Field(description='Two-sided analysis, or null while an arm is below its minimum sample')

MetricVerdict

Bases: ToolkitModel

The decision for one metric after multiple-testing correction.

metric

metric: str

better

better: Direction

primary

primary: bool

verdict

verdict: Verdict

adjusted_p_value

adjusted_p_value: float | None = Field(ge=0.0, le=1.0)

result

result: AnalysisResult | None

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.

Explanation

Bases: ToolkitModel

What was tested, what won, how sure we are and what comes next.

headline

headline: str

tested

tested: str

outcome

outcome: str

certainty

certainty: str

next_step

next_step: str

to_markdown

to_markdown() -> str

The explanation as a short Markdown brief.

explain_verdict

explain_verdict(verdict: ExperimentVerdict, *, plan: PlannedExperiment | None) -> Explanation

Explain a verdict in plain language, with the plan's timing when one is given.

The text follows from the numbers alone, so the same verdict always reads the same.

Sequential

Group-sequential monitoring with Lan-DeMets alpha spending.

HarmResult

Bases: ToolkitModel

Whether a change made a metric worse, and how soon that showed.

harmed

harmed: bool

detected_after

detected_after: int | None = Field(ge=_FIRST_LOOK, description='Observations after the change at the first crossing')

monitoring

monitoring: SequentialTestResult

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.

arm

arm: str

share

share: float = Field(ge=0.0, le=1.0)

probability_best

probability_best: float = Field(ge=0.0, le=1.0)

rate_mean

rate_mean: float = Field(ge=0.0)

rate_lower

rate_lower: float = Field(ge=0.0, description='2.5th posterior percentile of the rate')

rate_upper

rate_upper: float = Field(ge=0.0, description='97.5th posterior percentile of the rate')

ArmEvidence

Bases: ToolkitModel

What one arm earned so far.

arm

arm: str = Field(min_length=1)

reward

reward: float = Field(ge=0.0, description='Total reward, such as frames saved')

events

events: int = Field(ge=0, description='Rewarding events, such as improvements found')

exposure

exposure: float = Field(gt=0.0, description='Exposure, such as worker seconds')

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.

name

name: str = 'A/B experiment'

control

control: Variant | str

treatment

treatment: Variant | str

metrics

metrics: tuple[Metric, ...] = ()

Metric

Bases: ToolkitModel

Metadata for one experiment outcome.

name

name: str = Field(min_length=1)

metric_type

metric_type: MetricType

primary

primary: bool = False

description

description: str | None = None

ToolkitModel

Bases: BaseModel

Strict, immutable base model with standards-compliant JSON output.

model_config

model_config = ConfigDict(extra='forbid', frozen=True, allow_inf_nan=False)

Variant

Bases: ToolkitModel

A named experiment arm.

name

name: str = Field(min_length=1)

AlternativeHypothesis

Bases: StrEnum

Direction of the treatment-minus-control hypothesis test.

TWO_SIDED

TWO_SIDED = 'two-sided'

GREATER

GREATER = 'greater'

LESS

LESS = 'less'

CorrectionMethod

Bases: StrEnum

Supported multiple-testing procedures.

BONFERRONI

BONFERRONI = 'bonferroni'

HOLM

HOLM = 'holm'

BENJAMINI_HOCHBERG

BENJAMINI_HOCHBERG = 'benjamini-hochberg'

DiagnosticStatus

Bases: StrEnum

Status of a factual diagnostic check.

PASS

PASS = 'PASS'

WARN

WARN = 'WARN'

FAIL

FAIL = 'FAIL'

Direction

Bases: StrEnum

Which direction of a metric counts as an improvement.

HIGHER

HIGHER = 'higher'

LOWER

LOWER = 'lower'

ExperimentStatus

Bases: StrEnum

Place of an experiment in a portfolio plan.

RUNNING

RUNNING = 'running'

QUEUED

QUEUED = 'queued'

DECIDED

DECIDED = 'decided'

MDEType

Bases: StrEnum

Scale on which a minimum detectable effect is supplied.

ABSOLUTE

ABSOLUTE = 'absolute'

RELATIVE

RELATIVE = 'relative'

MetricType

Bases: StrEnum

Supported metric families.

PROPORTION

PROPORTION = 'proportion'

CONTINUOUS

CONTINUOUS = 'continuous'

SpendingFunction

Bases: StrEnum

Lan-DeMets alpha-spending functions for group-sequential monitoring.

O_BRIEN_FLEMING

O_BRIEN_FLEMING = 'obrien-fleming'

POCOCK

POCOCK = 'pocock'

Verdict

Bases: StrEnum

Decision for one metric of an experiment.

BETTER

BETTER = 'better'

WORSE

WORSE = 'worse'

UNCLEAR

UNCLEAR = 'no clear change'

TOO_FEW

TOO_FEW = 'not enough data yet'

MISMATCH

MISMATCH = 'sample ratio mismatch'

AchievedPowerResult

Bases: ToolkitModel

Approximate achieved power for fixed group sizes and rates.

baseline_rate

baseline_rate: float = Field(gt=0.0, lt=1.0)

treatment_rate

treatment_rate: float = Field(gt=0.0, lt=1.0)

control_sample_size

control_sample_size: int = Field(gt=0)

treatment_sample_size

treatment_sample_size: int = Field(gt=0)

alpha

alpha: float = Field(gt=0.0, lt=1.0)

power

power: float = Field(ge=0.0, le=1.0)

alternative

alternative: AlternativeHypothesis

method

method: str

AnalysisResult

Bases: ToolkitModel

Common result schema for treatment-minus-control analyses.

metric_name

metric_name: str | None = None

metric_type

metric_type: MetricType

control_estimate

control_estimate: float

treatment_estimate

treatment_estimate: float

absolute_effect

absolute_effect: float

relative_effect

relative_effect: float | None

relative_effect_definition

relative_effect_definition: str | None

confidence_interval

confidence_interval: ConfidenceInterval

test_statistic

test_statistic: float | None

p_value

p_value: float | None = Field(default=None, ge=0.0, le=1.0)

confidence_level

confidence_level: float = Field(gt=0.0, lt=1.0)

alternative

alternative: AlternativeHypothesis

control_sample_size

control_sample_size: int = Field(gt=0)

treatment_sample_size

treatment_sample_size: int = Field(gt=0)

control_standard_deviation

control_standard_deviation: float | None = Field(default=None, ge=0.0)

treatment_standard_deviation

treatment_standard_deviation: float | None = Field(default=None, ge=0.0)

degrees_of_freedom

degrees_of_freedom: float | None = Field(default=None, gt=0.0)

method

method: str

null_hypothesis

null_hypothesis: str

alternative_hypothesis

alternative_hypothesis: str

diagnostics

diagnostics: tuple[DiagnosticResult, ...] = ()

ConfidenceInterval

Bases: ToolkitModel

An interval whose None endpoint represents an unbounded side.

lower

lower: float | None

upper

upper: float | None

confidence_level

confidence_level: float = Field(gt=0.0, lt=1.0)

DiagnosticResult

Bases: ToolkitModel

A factual diagnostic emitted by an analysis.

code

code: str

status

status: DiagnosticStatus

message

message: str

details

details: dict[str, int | float | str | bool | None] = Field(default_factory=dict)

ExperimentReport

Bases: ToolkitModel

Serializable collection of experiment analyses and diagnostics.

experiment

experiment: Experiment

analyses

analyses: tuple[AnalysisResult, ...]

diagnostics

diagnostics: tuple[SRMResult | DiagnosticResult, ...] = ()

multiple_testing

multiple_testing: MultipleTestingResult | None = None

metadata

metadata: dict[str, int | float | str | bool | None] = Field(default_factory=dict)

MultipleTestingResult

Bases: ToolkitModel

Adjusted p-values in the same order as the input hypotheses.

original_p_values

original_p_values: tuple[float, ...]

adjusted_p_values

adjusted_p_values: tuple[float, ...]

rejected

rejected: tuple[bool, ...]

alpha

alpha: float = Field(gt=0.0, lt=1.0)

method

method: CorrectionMethod

hypothesis_labels

hypothesis_labels: tuple[str, ...] | None = None

error_rate_control

error_rate_control: str

ProportionSampleSizeResult

Bases: ToolkitModel

Normal-approximation sample-size planning result.

baseline_rate

baseline_rate: float = Field(gt=0.0, lt=1.0)

treatment_rate

treatment_rate: float = Field(gt=0.0, lt=1.0)

minimum_detectable_effect

minimum_detectable_effect: float = Field(gt=0.0)

mde_type

mde_type: MDEType

alpha

alpha: float = Field(gt=0.0, lt=1.0)

target_power

target_power: float = Field(gt=0.0, lt=1.0)

achieved_power

achieved_power: float = Field(ge=0.0, le=1.0)

allocation_ratio

allocation_ratio: float = Field(gt=0.0)

alternative

alternative: AlternativeHypothesis

control_sample_size

control_sample_size: int = Field(gt=0)

treatment_sample_size

treatment_sample_size: int = Field(gt=0)

total_sample_size

total_sample_size: int = Field(gt=0)

method

method: str

SequentialTestResult

Bases: ToolkitModel

One-sided group-sequential monitoring result, truncated at the first crossing.

metric_name

metric_name: str | None = None

alternative

alternative: AlternativeHypothesis

spending

spending: SpendingFunction

alpha

alpha: float = Field(gt=0.0, lt=0.5)

information_fractions

information_fractions: tuple[float, ...]

z_statistics

z_statistics: tuple[float, ...]

boundaries

boundaries: tuple[float, ...]

cumulative_alpha_spent

cumulative_alpha_spent: tuple[float, ...]

crossed

crossed: bool

crossed_at_look

crossed_at_look: int | None = Field(default=None, ge=0)

method

method: str

SRMResult

Bases: ToolkitModel

Chi-square goodness-of-fit sample-ratio-mismatch result.

observed_counts

observed_counts: dict[str, int]

expected_counts

expected_counts: dict[str, float]

chi_square_statistic

chi_square_statistic: float = Field(ge=0.0)

p_value

p_value: float = Field(ge=0.0, le=1.0)

significance_level

significance_level: float = Field(gt=0.0, lt=1.0)

degrees_of_freedom

degrees_of_freedom: int = Field(ge=1)

status

status: DiagnosticStatus

method

method: str = 'Pearson chi-square goodness-of-fit test'

message

message: str

diagnostics

diagnostics: tuple[DiagnosticResult, ...] = ()

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