Documentation
¶
Overview ¶
Package abtests measures A/B tests: which version of a feature flag (package flags) did best at a goal. The flag splits visitors; a visitor joins the test at their first Experiment Viewed event for the flag (stored as experiment_viewed, with properties flag and variant, sent by the site script when the page reads the flag, or by a server), and converts when a goal event of theirs follows it before the test ends. A goal can also be measured per visitor: how many times they reached it, or the value they brought (a number on the event, or won deals).
The numbers come from the workspace's own product events (customer_events), so the results, the reports and the event stream agree. The maths is in stats.go.
Index ¶
- Constants
- Variables
- func Baseline(t Traffic, metric string) float64
- func ChanceToBeat(a, b Arm) float64
- func CheckGoals(gs []Goal) string
- func CheckGuardrails(gs []Goal) string
- func Detectable(base Moments, metric string, n int64, minEffect, alpha float64) float64
- func HasVariant(variants []string, v string) bool
- func Lift(a, b Arm) (lift, low, high float64)
- func Recommend(r Result, control string, minEffect float64, started, now time.Time) (string, string)
- func SampleRatioP(arms []Arm, weights []int) float64
- func SequentialP(a, b Arm, minEffect float64) float64
- func VisitorsNeeded(base Moments, metric string, lift, minEffect, alpha float64) int64
- func Winner(r Result, control string) string
- type Arm
- type BreakdownResult
- type Cell
- type Comparison
- type Day
- type Factor
- type FactorialResult
- type Goal
- type GoalResult
- type GuardrailResult
- type HoldoutResult
- type InteractionResult
- type MainEffect
- type Moments
- type Plan
- type PlanRow
- type Querier
- type Result
- type Segment
- type SegmentEffect
- type Spec
- type Traffic
- type VersionInteraction
Constants ¶
const ( MaxGoals = 5 MaxGuardrails = 5 )
MaxGoals is the most goals a test watches, and MaxGuardrails the most guardrails.
const ( // MetricConversion: whether the visitor reached the goal (the rate). MetricConversion = "conversion" // MetricCount: how many times they reached it. MetricCount = "count" // MetricValue: the total of a number on the goal's events, such as // revenue, or for a deal goal the value of won deals in US dollars. MetricValue = "value" )
What a goal measures per visitor.
const ( // AlertReady: a version is the winner, or the control is, so the test // is safe to stop. AlertReady = "ab_test.ready" // AlertSplit: the split between versions is broken. AlertSplit = "ab_test.split_broken" // AlertGuardrail: a version clearly hurts a guardrail. AlertGuardrail = "ab_test.guardrail_hurt" )
Alerts the background check of running tests raises, once each per test (and per guardrail and version).
const ( HoldoutDaysDefault = 28 HoldoutDaysMax = 180 )
HoldoutDays bounds how far back a holdout report reads.
const ( RecommendShip = "ship" // a version is the winner RecommendKeepControl = "keep_control" // every version is worse RecommendFixSplit = "fix_split" // sample ratio mismatch RecommendWait = "wait" // too few visitors to say anything RecommendExtend = "extend" // keep it running RecommendStop = "stop" // unlikely to finish in 8 more weeks // The winner clearly hurts a guardrail: a person weighs the trade. RecommendCheckGuardrails = "check_guardrails" )
Recommendations a results summary can make. The engine decides; an AI only puts it into words.
const ( DefaultMinEffect = 0.25 MinEffectLow = 0.01 MinEffectHigh = 1.0 )
DefaultMinEffect is the smallest relative change a test looks for when it doesn't say: +25% of the control's rate. MinEffectLow and MinEffectHigh bound what a test may choose.
const Alpha = 0.05
Alpha is the false-winner rate the always-valid test and range keep to.
const ExposureEvent = "experiment_viewed"
ExposureEvent is the catalog name of Experiment Viewed.
const InteractionAlpha = 0.01
InteractionAlpha is how sure the check must be before it calls an interaction: stricter than a test's own 0.05, since it is run for every other test and every version.
const MaxFactors = 2
MaxFactors is how many flags a multivariate test may add to its own.
const MaxSegments = 8
MaxSegments is the most groups a breakdown shows; the smaller ones are added up as "other".
const MaxWindowHours = 24 * 366
MaxWindowHours is the longest conversion window: a year.
const MinBaselineVisitors = 200
MinBaselineVisitors is the fewest visitors a recorded baseline is based on; below it, a test tunes itself with its live control rate.
const MissedEvent = "experiment_change_missed"
MissedEvent is the catalog name of Experiment Change Missed: the website script found nothing on a page for some of a version's visual changes.
const PreDays = 28
PreDays is how far before joining a visitor's history counts for variance reduction.
const TrafficWindow = 28 * 24 * time.Hour
TrafficWindow is how far back the planner and the recorded baseline look.
Variables ¶
var ( Kinds = []string{"event", "page", "deal"} Metrics = []string{MetricConversion, MetricCount, MetricValue} )
var Dimensions = []string{"device", "source", "country", "visitor"}
Dimensions are what a breakdown can group visitors by: their device, the source of the visit they first saw their version in (its utm_source, else the referring site, else direct), its country, and whether they had visited before (new or returning).
var PlanLifts = []float64{0.05, 0.10, 0.25, 0.50}
PlanLifts are the true lifts a plan shows.
Functions ¶
func Baseline ¶ added in v0.21.0
Baseline is the mean to record for a goal when its test starts (its rate, for a conversion goal), from the site's recent traffic, or 0 when there is too little of it.
func ChanceToBeat ¶
ChanceToBeat is P(rate_b > rate_a) with Beta(1+conversions, 1+non-conversions) posteriors, computed exactly (Evan Miller's sum), so it needs no sampling and gives the same answer every time.
func CheckGoals ¶
CheckGoals says what is wrong with a test's goals, or "".
func CheckGuardrails ¶ added in v0.27.0
CheckGuardrails says what is wrong with a test's guardrails, or "".
func Detectable ¶ added in v0.21.0
Detectable is the smallest lift (up to +300%) likely to be found safe to stop with n visitors per version, or 0.
func HasVariant ¶
HasVariant reports whether v is one of a flag's variants.
func Lift ¶
Lift is (rate_b - rate_a) / rate_a with a 95% range from the delta method on the log of the ratio. With no control conversions there is no ratio, and all three are 0.
func Recommend ¶ added in v0.21.0
func Recommend(r Result, control string, minEffect float64, started, now time.Time) (string, string)
Recommend says what to do with a running or finished test's results, and why, in a sentence: started is when it began. For a test without a winner, it estimates from the traffic so far whether the smallest change worth finding can still be found within 8 more weeks.
func SampleRatioP ¶
SampleRatioP is the chance of a split at least this uneven if visitors really were assigned by the weights (a chi-square test). Below 0.001, something is losing or double-counting visitors (a redirect, a cache, a bot), and the results shouldn't be trusted.
func SequentialP ¶
SequentialP is the always-valid p-value of the mixture sequential probability ratio test (Johari, Pekelis and Walsh, "Always valid inference", 2017) for a difference in two rates, with a normal mixing distribution whose spread is minEffect times the control's rate: the test is most sensitive to changes of about that relative size (0 means DefaultMinEffect). This is one look; CompareSeries keeps the lowest over a test's daily looks.
func VisitorsNeeded ¶ added in v0.21.0
VisitorsNeeded is the visitors each version needs before the always-valid test reaches p < alpha, if the version truly moves a goal whose visitors' values have base by lift and the observed means equal the true ones. 0 means more than maxPlanVisitors.
func Winner ¶
Winner is the variant the results favour, or "" while none is clear: a version whose chance to beat the control is at least 95% and whose always-valid p-value is under 0.05 on the primary goal, or the control when every version is at most 5% likely to beat it with the same proof. A sample ratio mismatch means no winner.
Types ¶
type Arm ¶
type Arm struct {
Variant string `json:"variant"`
Visitors int64 `json:"visitors"`
Conversions int64 `json:"conversions"`
// Sum is the total of the visitors' values for a count or value goal;
// Mean is Sum over Visitors. Both are 0 for a conversion goal.
Sum float64 `json:"sum,omitempty"`
Mean float64 `json:"mean,omitempty"`
// SumSq is the total of the squared values, for the variance.
SumSq float64 `json:"-"`
// SumX, SumXX and SumXY are the totals of each visitor's value of the
// goal before they joined (X, the covariate for variance reduction),
// its square, and its product with their value since (Y).
SumX float64 `json:"-"`
SumXX float64 `json:"-"`
SumXY float64 `json:"-"`
}
Arm is what one version of a test saw: visitors who were shown it, how many of them went on to reach the goal, and for a count or value goal the total of their values (each visitor's capped at the goal's cap).
type BreakdownResult ¶ added in v0.25.0
type BreakdownResult struct {
Dimension string `json:"dimension"`
Goal Goal `json:"goal"`
Metric string `json:"metric"`
Segments []Segment `json:"segments"`
// CorrectedFor is how many comparisons the p-values and ranges are
// corrected for: every version in every group.
CorrectedFor int `json:"corrected_for"`
}
BreakdownResult is a test's first goal, group by group.
type Cell ¶ added in v0.45.0
type Cell struct {
Versions map[string]string `json:"versions"`
Arm Arm `json:"arm"`
// Against the cell where every factor shows its control; nil for that
// cell. Corrected for every other cell.
Comparison *Comparison `json:"comparison"`
}
Cell is one combination of versions, by flag key.
type Comparison ¶
type Comparison struct {
Variant string `json:"variant"`
// Chance this version's true mean (the rate, for a conversion goal) is
// above the control's: Bayesian with a flat Beta(1,1) prior for a
// rate, and the normal approximation for a count or value.
ChanceToBeat float64 `json:"chance_to_beat"`
// Relative lift of the observed mean over the control's, and an
// always-valid 95% range for it: the same sequential test as PValue,
// inverted (at the corrected level when several versions compete), so
// the range excludes 0 exactly when PValue is under 0.05.
Lift float64 `json:"lift"`
LiftLow float64 `json:"lift_low"`
LiftHigh float64 `json:"lift_high"`
// An always-valid p-value (mSPRT): it stays honest however often the
// results are looked at, so people may check every day and stop when
// it is low, unlike a classic p-value. It is the lowest over the
// test's daily looks, so it never rises again. When several versions
// compete with the control it is corrected for that (Bonferroni: the
// raw p-value times the number of versions), and RawPValue is the
// uncorrected one.
PValue float64 `json:"p_value"`
RawPValue float64 `json:"raw_p_value"`
// VarianceReduction is the share of the variance the visitors' history
// took out (CUPED), at the last look; 0 when none was used.
VarianceReduction float64 `json:"variance_reduction"`
}
Comparison is one version against the control.
func Compare ¶
func Compare(arms []Arm, minEffect float64) []Comparison
Compare sets each arm against the first (the control) at one look, for a conversion goal. minEffect is the smallest relative change worth detecting (SequentialP); 0 means DefaultMinEffect.
func CompareAdjusted ¶ added in v0.42.0
func CompareAdjusted(looks [][]Arm, metric string, minEffect, baseline float64) []Comparison
CompareAdjusted is CompareSeries with variance reduction (CUPED): each arm's mean is adjusted for its visitors' value of the goal before they joined (Arm.SumX and the rest), which takes out the part of the noise their history predicts. The adjusted difference has the same expectation, since history can't depend on the version, and a smaller variance, so the same evidence is reached with fewer visitors.
func CompareSeries ¶ added in v0.21.0
func CompareSeries(looks [][]Arm, metric string, minEffect, baseline float64) []Comparison
CompareSeries sets each version against the control over a test's looks: the cumulative arms at the end of each day, control first, the last one being now. The chance to beat and the lift come from the last look; the p-value is the lowest over the looks and the range their intersection, as an always-valid test allows (Johari et al. 2017), so neither moves back once the evidence is in. metric says what an arm's numbers measure (MetricConversion, MetricCount or MetricValue).
baseline is the control's expected mean (its rate, for a conversion goal), recorded when the test started, which fixes the mixing spread (minEffect × baseline) for the whole test. 0 means none was recorded: each look then uses its own control mean, which is only approximately valid at small counts.
With more than one version against the control, each comparison is a separate chance of a false winner, so the p-values and ranges are corrected for their number (Bonferroni): together they keep to Alpha.
type Day ¶ added in v0.21.0
Day is the cumulative arms at the end of one day (UTC), control first; the last day of a running test is today so far.
type Factor ¶ added in v0.45.0
Factor is one flag of a multivariate test beyond the test's own: its key and control version.
type FactorialResult ¶ added in v0.45.0
type FactorialResult struct {
Goal Goal `json:"goal"`
Metric string `json:"metric"`
Factors []string `json:"factors"`
Cells []Cell `json:"cells"`
MainEffects []MainEffect `json:"main_effects"`
// Best is the cell with the highest mean, if any cell beats the
// all-controls one.
Best *Cell `json:"best"`
// Interactions say whether each other factor changes the first
// factor's effect (Cochran's Q over the other factor's versions).
Interactions []VersionInteraction `json:"interactions"`
CorrectedFor int `json:"corrected_for"`
}
FactorialResult is a multivariate test's first goal, cell by cell.
type Goal ¶
type Goal struct {
Kind string `json:"kind"`
Name string `json:"name,omitempty"`
Path string `json:"path,omitempty"`
Metric string `json:"metric,omitempty"`
Property string `json:"property,omitempty"`
WindowHours int `json:"window_hours,omitempty"`
Cap float64 `json:"cap,omitempty"`
// Better is which way is good, for a guardrail: "higher" (the default)
// or "lower", such as for an error event or a refund.
Better string `json:"better,omitempty"`
}
Goal is what counts as success: a product event by name, a view of a page by path (a trailing * matches every path under it), or a won deal of the visitor's (their customer record, once the site knows who they are). Metric says what is measured per visitor; Property names the number on the event a value goal adds up. WindowHours, when set, counts only what happens within that many hours of the visitor first seeing their version; Cap, when set, caps each visitor's count or value so a few huge ones can't swing the result.
type GoalResult ¶
type GoalResult struct {
Goal Goal `json:"goal"`
Arms []Arm `json:"arms"`
Comparisons []Comparison `json:"comparisons"`
// Metric is what the arms measure (MetricConversion, MetricCount or
// MetricValue).
Metric string `json:"metric"`
// Baseline is the control mean the test was tuned with; 0 when none
// was recorded.
Baseline float64 `json:"baseline"`
// Exploratory is true for every goal after the first: the winner is
// decided on the first, and the others are for learning, since
// checking many goals turns up chance differences.
Exploratory bool `json:"exploratory"`
// Days is how the goal's arms grew, one point a day, for the first
// goal only.
Days []Day `json:"days,omitempty"`
}
GoalResult is one goal's arms and their comparison with the control.
type GuardrailResult ¶ added in v0.27.0
type GuardrailResult struct {
GoalResult
Harmed []string `json:"harmed"`
}
GuardrailResult is a guardrail's arms and comparisons, and the versions that clearly hurt it: worse than the control in its bad direction, with the same proof as a winner (at least 95% likely, and safe to stop).
type HoldoutResult ¶ added in v0.54.1
type HoldoutResult struct {
Group string `json:"group"`
Holdout int `json:"holdout"`
Goal Goal `json:"goal"`
Metric string `json:"metric"`
// Arms are the holdout first, then everyone else.
Arms []Arm `json:"arms"`
Comparison *Comparison `json:"comparison"`
From time.Time `json:"from"`
To time.Time `json:"to"`
}
HoldoutResult compares a group's holdout (the control) with the rest of its visitors on one goal.
func Holdout ¶ added in v0.54.1
func Holdout(ctx context.Context, q Querier, ws, brand, group string, holdout int, g Goal, from, to time.Time) (HoldoutResult, error)
Holdout counts every visitor who viewed a page of the site between from and to, by whether they fall in group's holdout (the top holdout percent of its buckets, by the same hash the flags use), and compares the goal after their first view. Only brand's visitors and events count (a group is one brand's); brand "" counts every brand's.
type InteractionResult ¶ added in v0.44.0
type InteractionResult struct {
OtherFlag string `json:"other_flag"`
// Overlap is how many of this test's visitors also saw the other flag.
Overlap int64 `json:"overlap"`
Versions []VersionInteraction `json:"versions"`
}
InteractionResult is this test's first goal split by another flag's versions.
func Interaction ¶ added in v0.44.0
func Interaction(ctx context.Context, q Querier, ws string, s Spec, otherFlag string) (InteractionResult, error)
Interaction measures the test's first goal within each version of another flag the same visitors saw while it ran.
type MainEffect ¶ added in v0.45.0
type MainEffect struct {
FlagKey string `json:"flag_key"`
Arms []Arm `json:"arms"`
Comparisons []Comparison `json:"comparisons"`
}
MainEffect is one factor's versions against its control, pooled over the other factors' versions.
type Moments ¶ added in v0.22.0
Moments is what the statistics need of one visitor's value: its mean and variance. For a conversion goal the value is 1 or 0, so the mean is the rate p and the variance p(1-p).
type Plan ¶ added in v0.21.0
type Plan struct {
// Baseline is the goal's mean per visitor today (its rate, for a
// conversion goal).
Baseline float64 `json:"baseline"`
Metric string `json:"metric"`
WeeklyVisitors float64 `json:"weekly_visitors"`
// The weekly visitors of the smallest version: the comparison with
// the control waits on it.
WeeklyPerVersion float64 `json:"weekly_per_version"`
MinEffect float64 `json:"min_effect"`
// Versions is how many versions compete with the control; past one,
// each needs more visitors, since the results are corrected for the
// extra chances of a false winner.
Versions int `json:"versions"`
Rows []PlanRow `json:"rows"`
// The smallest lift likely to be found safe to stop within 4 and 8
// weeks; 0 when even +300% would take longer.
Detectable4Weeks float64 `json:"detectable_4_weeks"`
Detectable8Weeks float64 `json:"detectable_8_weeks"`
// Weeks the test is likely to need if the change moves the goal by
// MinEffect; 0 when it can't be planned.
Weeks float64 `json:"weeks"`
}
Plan is how long a test is likely to take.
func MakePlan ¶ added in v0.21.0
func MakePlan(base Moments, metric string, weeklyVisitors float64, weights []int, minEffect float64) Plan
MakePlan estimates how long a test takes: base is one visitor's value today for metric, and weeklyVisitors are those the flag will show a version to each week, split by weights (the control's included). The estimate is the typical point where the always-valid test, corrected for the number of versions, reaches p < 0.05 if the observed means equal the true ones; half of tests stop sooner, half later.
type PlanRow ¶ added in v0.21.0
type PlanRow struct {
Lift float64 `json:"lift"`
VisitorsPerVersion int64 `json:"visitors_per_version"`
Weeks float64 `json:"weeks"`
}
PlanRow is how many visitors each version needs, and how long that takes, if the change truly moves the goal by Lift.
type Querier ¶
type Querier interface {
Query(ctx context.Context, sql string, args ...any) (pgx.Rows, error)
QueryRow(ctx context.Context, sql string, args ...any) pgx.Row
}
Querier is what Results reads with: a pool, a connection or a transaction.
type Result ¶
type Result struct {
// Visitors per variant who joined the test, control first.
Arms []Arm `json:"arms"`
Goals []GoalResult `json:"goals"`
Guardrails []GuardrailResult `json:"guardrails"`
// Crossovers is how many visitors saw more than one version: they count
// under the first, but many of them means something (a cache, a
// server that assigns differently) is showing versions inconsistently.
Crossovers int64 `json:"crossovers"`
// The chance of a split this uneven by luck; below 0.001 the results
// shouldn't be trusted (SampleRatioP).
SampleRatioP float64 `json:"sample_ratio_p"`
SampleRatio bool `json:"sample_ratio_mismatch"`
// The smallest change the p-values were tuned to detect.
MinEffect float64 `json:"min_effect"`
// CorrectedFor is how many versions are compared with the control; past
// one, every p-value and range is corrected for that many chances.
CorrectedFor int `json:"corrected_for"`
// VarianceReduction says the comparisons were adjusted for the
// visitors' history (CUPED); each comparison says by how much.
VarianceReduction bool `json:"variance_reduction"`
// FlagChanged says how the flag changed since the test started (its
// split, content, rollout or versions): results that mix the before
// and after need care.
FlagChanged []string `json:"flag_changed"`
ComputedAt time.Time `json:"computed_at"`
}
Result is a test's results at a moment.
type Segment ¶ added in v0.25.0
type Segment struct {
Key string `json:"key"`
Arms []Arm `json:"arms"`
Comparisons []Comparison `json:"comparisons"`
}
Segment is one group's arms and its versions against the control.
type SegmentEffect ¶ added in v0.44.0
type SegmentEffect struct {
OtherVariant string `json:"other_variant"`
Visitors int64 `json:"visitors"`
Difference float64 `json:"difference"`
}
SegmentEffect is a version's difference from the control among the visitors who saw one version of the other test.
type Spec ¶
type Spec struct {
FlagKey string
// The flag's variants in order with their weights, control first or
// not; Control names it.
Variants []string
Weights []int
Control string
Goals []Goal
// The smallest relative change worth detecting, such as 0.25 for
// +25%; 0 means DefaultMinEffect.
MinEffect float64
// Each goal's expected control mean (its rate, for a conversion goal),
// recorded when the test started (Baseline), which fixes the
// sequential test's tuning. A missing or zero one falls back to the
// live control mean.
Baselines []float64
// Guardrails are watched alongside, to catch a version that hurts
// something else.
Guardrails []Goal
From, To time.Time
// JoinUntil, when set, is when new visitors stopped joining (the test
// was frozen); those already in keep counting until To.
JoinUntil time.Time
// ExcludeDomains leaves out visitors from these companies (the
// workspace's own team), as on the Visitors page.
ExcludeDomains []string
// VarianceReduction adjusts each goal and guardrail for its visitors'
// value of it in the PreDays before they joined (CUPED). A test uses
// it for its whole life or not at all, as registered when it started.
VarianceReduction bool
}
Spec is what Results needs of a test.
type Traffic ¶ added in v0.21.0
type Traffic struct {
Visitors int64 `json:"visitors"`
Converted int64 `json:"converted"`
Sum float64 `json:"sum,omitempty"`
SumSq float64 `json:"-"`
}
Traffic is a page's recent visitors and, for a goal, how many reached it after their first view and the total and sum of squares of their values (for a count or value goal, capped as the goal says).
func ReadTraffic ¶ added in v0.21.0
func ReadTraffic(ctx context.Context, q Querier, ws string, g Goal, page string, from, to time.Time) (Traffic, error)
ReadTraffic counts visitors with a page view in [from, to), on page when it is set (a path, or a prefix ending in *), and what they did towards goal g after their first such view: how many reached it and, for a count or value goal, the total of their values.
type VersionInteraction ¶ added in v0.44.0
type VersionInteraction struct {
Variant string `json:"variant"`
// Effects are the version's difference from the control (in the goal's
// mean per visitor), by the other test's version.
Effects []SegmentEffect `json:"effects"`
// PValue is the chance of effects this different if they were really
// the same (Cochran's Q); 1 when there is too little to tell.
PValue float64 `json:"p_value"`
Interacts bool `json:"interacts"`
}
VersionInteraction is one version's effect within each version of the other test.