experiments

package
v0.7.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package experiments is the domain of experiments: a time-boxed comparison of variations of one flag on a declared unit type, with a hypothesis, an owner, weights, a traffic allocation and two public salts. Every rule spanning the experiment and what it names (its flag, a declared unit type, the salts of the project) is a pure function over what the handler loaded under its project's row lock, so it holds for as long as that lock.

Index

Constants

View Source
const (
	SampleRatioMinimumSample   = 1000
	SampleRatioMinimumExpected = 5
	SampleRatioRaiseBelow      = 0.001
	SampleRatioClearAbove      = 0.01
)

The sample-ratio check's bounds. Below a thousand first exposures a split is too noisy to judge; an expected count under five is where the chi-square approximation stops holding. The two thresholds apart keep an alert from flapping while the p-value hovers around one of them.

View Source
const (
	// ActionStart starts a draft.
	ActionStart = "start"
	// ActionStop stops a running experiment with a decision, which
	// rewrites every rule serving it.
	ActionStop = "stop"
	// ActionSetTrafficAllocation grows a running experiment's traffic
	// allocation.
	ActionSetTrafficAllocation = "set_traffic_allocation"
)

The transitions of an experiment that change what the environments holding its rule serve, and so the ones a change request proposes.

View Source
const (
	MinUniformityUnitIDs  = 1000
	MaxUniformityUnitIDs  = 200000
	DefaultUniformityBins = 100
)

Bounds of a uniformity check.

View Source
const NoExposuresAfter = 24 * time.Hour

NoExposuresAfter is how long a running experiment may go without an exposure in an environment before it is alerted: a day covers every hour of a daily traffic cycle, so a quiet night raises nothing.

View Source
const SaltLength = 16

SaltLength is how many characters a salt has.

View Source
const TotalWeight = 10000

TotalWeight is what an experiment's weights sum to, and the most a traffic allocation can be: basis points, steps of 0.01 %.

Variables

This section is empty.

Functions

func ChiSquarePValue

func ChiSquarePValue(x float64, df int) float64

ChiSquarePValue is the probability that a chi-square variable with df degrees of freedom is at least x: the upper tail Q(df/2, x/2) that the uniformity check and the sample-ratio check both report. A statistic far beyond the tail answers 0, never NaN; with no degrees of freedom there is nothing to test and it answers 1.

func ConflictThreshold

func ConflictThreshold(firstExposures int64) int64

ConflictThreshold is how many conflicting exposures raise the conflicts alert in an environment with firstExposures first exposures: 0.1 % of them, rounded up, never below 3 and never above 10.

func ValidSalt

func ValidSalt(s string) bool

ValidSalt reports whether s has the form of an experiment's salt.

Types

type Alert

type Alert struct {
	ID             AlertID
	Experiment     ExperimentID
	Environment    *workspace.EnvironmentID
	Kind           AlertKind
	RaisedAt       time.Time
	ClearedAt      *time.Time
	AcknowledgedAt *time.Time
	Details        AlertDetails
}

Alert is a condition a check found on an experiment in one environment, or in the experiment as a whole when Environment is nil. It is active until it clears; an acknowledgement hides it until then, and a condition returning after it cleared is a new alert.

func RaiseAlert

func RaiseAlert(alert AlertID, experiment ExperimentID, environment *workspace.EnvironmentID, kind AlertKind, now time.Time,
	details AlertDetails,
) Alert

RaiseAlert returns a new active alert of kind raised at now.

func (Alert) Acknowledge

func (a Alert) Acknowledge(now time.Time) (Alert, bool)

Acknowledge returns the alert acknowledged at now, and whether that changed it: the first acknowledgement is the one kept. An acknowledgement made on a replica whose clock is behind the one that raised the alert is stamped at the raising, since an alert is never acknowledged before it began.

func (Alert) Clear

func (a Alert) Clear(now time.Time) Alert

Clear returns the alert cleared at now, or at its raising when now is earlier: replicas' clocks differ by seconds, and an alert never ends before it began.

type AlertChange

type AlertChange int

AlertChange is what a check does to the alert of its kind.

const (
	AlertKeep AlertChange = iota
	AlertRaise
	AlertClear
)

The changes.

func ConditionChange

func ConditionChange(holds, active bool) AlertChange

ConditionChange returns what a check whose condition holds or not does to the alert of its kind, active or not: raise one while it holds, clear it once it does not.

type AlertDetails

type AlertDetails struct {
	SampleRatio       *SampleRatio
	NoExposures       *NoExposures
	ExposureConflicts *ExposureConflicts
	PastExpectedEnd   *PastExpectedEnd
}

AlertDetails is what the check found when it raised an alert: the block of the alert's kind, every other one nil.

type AlertID

type AlertID = id.Of[Alert]

AlertID identifies an alert.

type AlertKind

type AlertKind string

AlertKind is the condition an alert is about.

const (
	// AlertKindNoExposures is a running experiment no SDK reported an
	// exposure of for a day in an environment holding its rule: the
	// exposure call is most likely missing from the code.
	AlertKindNoExposures AlertKind = "no_exposures"
	// AlertKindExposureConflicts is an environment where too many units
	// were exposed to another variation than their first one.
	AlertKindExposureConflicts AlertKind = "exposure_conflicts"
	// AlertKindPastExpectedEnd is a running experiment past its expected
	// end, about the experiment as a whole.
	AlertKindPastExpectedEnd AlertKind = "past_expected_end"
)

The other kinds of alert, beside the sample-ratio mismatch.

const AlertKindSampleRatio AlertKind = "srm"

AlertKindSampleRatio is a sample-ratio mismatch.

type Assignment

type Assignment struct {
	UnitType string
	UnitID   string
	// InclusionSalt and VariationSalt are the experiment's salts, hashed
	// into InclusionBucket and VariationBucket. The variation bucket is given
	// for a unit left out too: it is the bucket the unit would be assigned by
	// should the allocation grow to include it.
	InclusionSalt     string
	VariationSalt     string
	InclusionBucket   int
	VariationBucket   int
	TrafficAllocation int
	// Included is whether the inclusion bucket is below the traffic
	// allocation.
	Included bool
	// Variation is the variation an included unit is assigned; nil when the
	// unit is not included.
	Variation *string
	// SQL is a ClickHouse query recomputing all of the above for the unit;
	// its subquery stands for any table with a unit_id column.
	SQL string
}

Assignment is how an experiment treats one unit, from the experiment's own fields: what an analyst needs to answer a support question and to recompute the answer in a warehouse.

type Change

type Change struct {
	// Key is refused whatever it holds: an experiment's key never changes.
	Key               *string
	Name              *string
	Hypothesis        *string
	Owner             *Owner
	Tags              *[]string
	FlagKey           *string
	UnitType          *string
	Variations        *[]Weight
	TrafficAllocation *int
	ExpectedEndAt     *time.Time
	// Flag is the flag the experiment compares once changed (the one
	// FlagKey names, else its current one), nil when the project has none
	// with that key. It is judged only when the edit names the flag or the
	// variations, so an archived flag never blocks an edit of the hypothesis.
	Flag *FlagFacts
	// DeclaredUnitTypes are the keys of the project's unit types.
	DeclaredUnitTypes []string
}

Change is an edit of a draft: a nil field stays as it is. The facts about the project are those the handler loaded for the fields the edit names.

type Decision

type Decision struct {
	Outcome         Outcome
	WinnerVariation string
	Note            string
}

Decision is what a stop decided: an outcome, the winning variation for a winner ("" otherwise), and a note saying why ("" for none).

type Desired added in v0.3.0

type Desired struct {
	Name       string
	Hypothesis string
	// Owner is the member to own the experiment, nil to leave the owner.
	Owner *Owner
	Tags  []string
	// Flag is the flag FlagKey names, nil when the project has none.
	Flag              *FlagFacts
	FlagKey           string
	UnitType          string
	DeclaredUnitTypes []string
	Variations        []Weight
	TrafficAllocation int
	// Salts are the salts the document names, "" for one it leaves out,
	// which stays as it is.
	Salts         Salts
	Status        Status
	ExpectedEndAt *time.Time
	StartedAt     *time.Time
	StoppedAt     *time.Time
	ArchivedAt    *time.Time
	Decision      *Decision
}

Desired is what a project document says an experiment that exists already should be.

type Experiment

type Experiment struct {
	ID      ExperimentID
	Project workspace.ProjectID
	// Key names the experiment in rules and exposures and never changes;
	// unique, case sensitively, in its project.
	Key        string
	Name       string
	Hypothesis string
	Owner      access.MemberID
	Tags       []string
	// Flag is the flag the experiment compares variations of, and FlagKey
	// its key as it was when the experiment was written.
	Flag    flags.FlagID
	FlagKey string
	// UnitType is the declared unit type whose units are split.
	UnitType string
	// Variations are the weights, one per variation compared.
	Variations        []Weight
	TrafficAllocation int
	// InclusionSalt decides whether a unit is in the experiment at all and
	// VariationSalt which variation an included unit gets; each is used by
	// no other experiment or rollout of the project.
	InclusionSalt string
	VariationSalt string
	Status        Status
	// ExpectedEndAt is a calendar day, in UTC at midnight; nil when none.
	ExpectedEndAt *time.Time
	StartedAt     *time.Time
	StoppedAt     *time.Time
	ArchivedAt    *time.Time
	// Decision is what the stop decided; nil until the experiment stops.
	Decision *Decision
	// CreatedBy is the member who created the experiment; nil for a
	// project token.
	CreatedBy *access.MemberID
	CreatedAt time.Time
	UpdatedAt time.Time
	// Version counts the experiment's accepted changes, from 1.
	Version int64
}

Experiment is an experiment's definition.

func Import added in v0.3.0

func Import(in Imported) (Experiment, error)

Import returns the experiment the document describes, exactly as it describes it, at version 1 created at in.Now, or invalid_experiment with every field to fix. It is judged as a create is, and by the history its status leaves behind, which is what keeps a copy honest: a draft has none; a running experiment started, with the day it should end; a stopped one started, stopped and decided; an archived one the history of the draft or of the stopped experiment it was archived from. A draft and a running experiment need their flag not archived and a declared unit type, a stopped one a declared unit type, and an archived one neither, since what an experiment measured outlives them; every one needs a flag, because it compares its variations.

func New

func New(in Input) (Experiment, error)

New returns the draft in, at version 1, or invalid_experiment with every field to fix.

func (Experiment) Archive

func (e Experiment) Archive(now time.Time) (Experiment, error)

Archive returns the draft or stopped experiment archived at now, its version incremented: it is hidden from the list and never changes again. A running experiment is stopped first (running), and an archived one is archived already (archived).

func (Experiment) Assign

func (e Experiment) Assign(unitID string) Assignment

Assign answers how e treats unitID in whatever status it is, with the evaluator's own hash: included when the inclusion bucket is below the traffic allocation, then the variation whose cumulative range of weights, in the experiment's order, holds the variation bucket.

func (Experiment) CanDelete

func (e Experiment) CanDelete() error

CanDelete refuses to delete an experiment that is not a draft: once started it has exposures and a history that deleting would erase.

func (Experiment) Change

func (e Experiment) Change(ch Change, now time.Time) (Experiment, bool, error)

Change returns the experiment with ch applied at now, its version incremented, and whether anything changed: an edit to the values the experiment already has changes nothing. A request breaking several rules is invalid_experiment with every field to fix. A draft is edited in full; a running experiment refuses a change to its split first (frozen), and its traffic allocation only grows (traffic_allocation_decrease, judged once the fields are); a stopped one changes its description alone (frozen otherwise); an archived one changes nothing (archived).

func (Experiment) GrowTrafficAllocation

func (e Experiment) GrowTrafficAllocation(to int, now time.Time) (Experiment, error)

GrowTrafficAllocation returns the running experiment with its traffic allocation grown to to at now, its version incremented: the one change to a running experiment that its holders' rulesets carry, and so the one a change request proposes. Only a running experiment grows (not_running; archived for an archived one); the allocation is checked as an edit checks it, never shrinks (traffic_allocation_decrease), and the allocation the experiment has already is no growth (invalid_experiment).

func (Experiment) PastExpectedEnd

func (e Experiment) PastExpectedEnd(now time.Time) bool

PastExpectedEnd reports whether e is running past its expected end at now: from the UTC day after the expected end, so the end day itself is still the experiment's.

func (Experiment) PastExpectedEndDetails

func (e Experiment) PastExpectedEndDetails() PastExpectedEnd

PastExpectedEndDetails is what the past-expected-end alert records of e.

func (Experiment) Reconcile added in v0.3.0

func (e Experiment) Reconcile(d Desired, now time.Time) (Experiment, bool, error)

Reconcile returns the experiment e made what d says it is at now, its version incremented, and whether anything changed: a document that says what the experiment is changes nothing. It changes an experiment only as an ordinary edit of its status allows, and never moves it through its status: a draft takes its whole definition and its salts; a running experiment its name, hypothesis, owner, tags and end date, and a larger traffic allocation (traffic_allocation_decrease for a smaller one); a stopped one its name, hypothesis, owner and tags; an archived one nothing. What the status freezes, and its status, timestamps and decision whatever it is, the document may name only as they are: any other value is frozen, naming every such field at once. The rest is judged as an edit judges it.

func (Experiment) RegenerateSalts

func (e Experiment) RegenerateSalts(s Salts, now time.Time) (Experiment, error)

RegenerateSalts returns the draft with s as its salts at now, its version incremented. Past the draft its assignments exist, and moving every unit is not an edit (not_draft).

func (Experiment) SetDecisionNote

func (e Experiment) SetDecisionNote(note string, now time.Time) (Experiment, bool, error)

SetDecisionNote returns the stopped experiment whose decision has note at now, its version incremented, and whether anything changed: the same note changes nothing, and "" clears it. Only a stopped experiment has a decision (not_stopped; archived for an archived one).

func (Experiment) Start

func (e Experiment) Start(f StartFacts, now time.Time) (Experiment, error)

Start returns the draft running from now, its version incremented. Only a draft starts (not_draft). A draft that is not ready is experiment_not_ready with every precondition it fails: its flag is not archived, its unit type is declared, its weights are valid against the flag, it has a hypothesis and an expected end date, so a running experiment always says what it tests and when it should be over.

func (Experiment) Stop

func (e Experiment) Stop(d Decision, now time.Time) (Experiment, error)

Stop returns the running experiment stopped at now with d, its version incremented. Only a running experiment stops (not_running; archived for an archived one). A winner is one of the experiment's variations, and a removal names none, so that what replaces the experiment's rules is always something the comparison measured; invalid_decision otherwise.

type ExperimentID

type ExperimentID = id.Of[Experiment]

ExperimentID identifies an experiment.

type ExposureConflicts

type ExposureConflicts struct {
	Conflicts        int64
	ConflictingUnits int64
	FirstExposures   int64
	Threshold        int64
}

ExposureConflicts is what the conflicts check found in an environment: the exposures naming another variation than their unit's first one, the units with any, the first exposures and the threshold they make.

func CheckExposureConflicts

func CheckExposureConflicts(conflicts, units, firstExposures int64) ExposureConflicts

CheckExposureConflicts returns the conflicts check of conflicts exposures, from units units, against firstExposures first exposures.

func (ExposureConflicts) Exceeded

func (c ExposureConflicts) Exceeded() bool

Exceeded reports whether the conflicts reach the threshold.

type FlagFacts

type FlagFacts struct {
	ID       flags.FlagID
	Key      string
	Archived bool
	// Variations are the keys of the flag's variations.
	Variations []string
}

FlagFacts are what an experiment is judged against of the flag it names.

type Imported added in v0.3.0

type Imported struct {
	ID         ExperimentID
	Project    workspace.ProjectID
	Key        string
	Name       string
	Hypothesis string
	Owner      Owner
	Tags       []string
	// Flag is the flag FlagKey names, nil when the project has none.
	Flag    *FlagFacts
	FlagKey string
	// UnitType is the unit type the document names, and DeclaredUnitTypes the
	// keys of the project's.
	UnitType          string
	DeclaredUnitTypes []string
	Variations        []Weight
	TrafficAllocation int
	Salts             Salts
	Status            Status
	ExpectedEndAt     *time.Time
	StartedAt         *time.Time
	StoppedAt         *time.Time
	ArchivedAt        *time.Time
	Decision          *Decision
	CreatedBy         *access.MemberID
	Now               time.Time
}

Imported is an experiment as a project document gives it, with the facts about the project it is judged against. A document carries what is needed to make an experiment a copy of another, so that a unit keeps its assignment: its status, both salts, its timestamps and its decision.

type Independence

type Independence struct {
	ChiSquare float64
	DF        int
	PValue    float64
	Verdict   Verdict
}

Independence is Pearson's test of independence on the two-way table of both salts' bins, over its non-empty rows and columns.

type Input

type Input struct {
	ID         ExperimentID
	Project    workspace.ProjectID
	Key        string
	Name       string
	Hypothesis string
	Owner      Owner
	Tags       []string
	// Flag is the flag named, nil when the project has none with the key
	// the request gave; FlagKey is that key.
	Flag     *FlagFacts
	FlagKey  string
	UnitType string
	// DeclaredUnitTypes are the keys of the project's unit types.
	DeclaredUnitTypes []string
	Variations        []Weight
	// TrafficAllocation is every unit's when nil.
	TrafficAllocation *int
	ExpectedEndAt     *time.Time
	// Salts are the two salts the experiment is given, from NewSalts.
	Salts     Salts
	CreatedBy *access.MemberID
	Now       time.Time
}

Input is what an experiment is created with, with the facts about the project it is judged against.

type NoExposures

type NoExposures struct {
	LastExposureAt *time.Time
	Since          time.Time
}

NoExposures is what the no-exposures check found: when the server last received an exposure, nil when it never did, and since when none came, the later of that exposure and the start.

func CheckNoExposures

func CheckNoExposures(started time.Time, last *time.Time, now time.Time) (NoExposures, bool)

CheckNoExposures returns what the no-exposures check finds at now of an experiment started at started whose latest exposure in an environment, an override's excluded, was received at last, nil when none was, and whether it raises the alert: no exposure for NoExposuresAfter since the start or since the last one.

type Outcome

type Outcome string

Outcome is what a stop decided about the experiment's rules.

const (
	// OutcomeWinner serves the winning variation where the experiment was
	// served, each holding rule keeping its identifier and conditions.
	OutcomeWinner Outcome = "winner"
	// OutcomeRemoved deletes the experiment's rules, so the flag goes back
	// to its other rules.
	OutcomeRemoved Outcome = "removed"
)

The outcomes of a stop.

type Owner

type Owner struct {
	Member   access.MemberID
	Eligible bool
}

Owner is the member a write names as an experiment's owner, and whether they may own one: an active member holding a grant in the project, or an instance admin, as for a flag. The handler finds that out; the experiment only refuses one who may not.

type PastExpectedEnd

type PastExpectedEnd struct {
	ExpectedEndAt time.Time
}

PastExpectedEnd is the expected end a running experiment passed.

type Salts

type Salts struct{ Inclusion, Variation string }

Salts are an experiment's two salts.

func NewSalts

func NewSalts(taken []string, next func() (string, error)) (Salts, error)

NewSalts draws salts from next until it has two that differ from each other and from every one of taken: the salts the project's experiments and rollouts already use, so two assignments are never correlated. next returns a candidate in the form of a salt; its error is returned as it is.

type SampleRatio

type SampleRatio struct {
	N          int64
	ChiSquare  *float64
	PValue     *float64
	Skipped    SampleRatioSkip
	Variations []SampleRatioVariation
}

SampleRatio is one sample-ratio check of an experiment in one environment. ChiSquare and PValue are nil when the check was skipped, and Skipped says why.

func CheckSampleRatio

func CheckSampleRatio(weights []Weight, firstExposures map[string]int64) SampleRatio

CheckSampleRatio compares the first exposures per variation with weights: X² = Σ (O − E)² / E over the weighed variations, E = N × weight / 10,000, with one degree of freedom fewer than there are variations. First exposures of a variation the experiment does not weigh, which only an override exposure names, are no part of it.

func (SampleRatio) AlertChange

func (r SampleRatio) AlertChange(active bool) AlertChange

AlertChange returns what r does to the sample-ratio alert, active or not: raise one below the raise threshold, clear the active one above the clear threshold, and otherwise, a skipped check included, leave it as it is.

type SampleRatioSkip

type SampleRatioSkip string

SampleRatioSkip is why a sample-ratio check computed no statistic; "" when it did.

const (
	SkippedBelowMinimumSample SampleRatioSkip = "below_minimum_sample"
	SkippedExpectedBelow5     SampleRatioSkip = "expected_below_5"
)

The reasons a check is skipped.

type SampleRatioVariation

type SampleRatioVariation struct {
	Variation     string
	Observed      int64
	Expected      float64
	ObservedShare float64
	ExpectedShare float64
}

SampleRatioVariation is one variation's side of a sample-ratio check: its first exposures and the count its weight expects of all of them.

type StartFacts

type StartFacts struct {
	Flag FlagFacts
	// DeclaredUnitTypes are the keys of the project's unit types.
	DeclaredUnitTypes []string
}

StartFacts are what a start is judged against: the experiment's flag and the project's unit types as they are now, since either may have changed since the draft was written.

type Status

type Status string

Status is where an experiment is in its life.

const (
	StatusDraft    Status = "draft"
	StatusRunning  Status = "running"
	StatusStopped  Status = "stopped"
	StatusArchived Status = "archived"
)

The statuses, in the order they are reached. There is no pause (the flag's kill switch is the pause) and no restart (a clone with new salts is the rerun).

type Transition

type Transition struct {
	Action            string
	Decision          *Decision
	TrafficAllocation *int
}

Transition is one of those transitions: a start; a stop with Decision; or a growth of a running experiment's traffic allocation to TrafficAllocation.

type Uniformity

type Uniformity struct {
	Salt       string
	SecondSalt *string
	Bins       int
	// Counts are how many unit IDs fell into each bin, in bin order.
	Counts    []int
	Min, Max  int
	ChiSquare float64
	DF        int
	PValue    float64
	Verdict   Verdict
	// Independence is nil without a second salt.
	Independence *Independence
}

Uniformity is the outcome of a uniformity check.

func CheckUniformity

func CheckUniformity(r UniformityRequest) (Uniformity, error)

CheckUniformity checks how evenly the bucketing hash spreads r's unit IDs: the 10,000 buckets are grouped into r.Bins bins of consecutive buckets and each bin's count is compared with what a uniform hash expects of its width by Pearson's chi-square test. It is uniform when the p-value is at least 0.001. It records nothing and reads nothing but r.

type UniformityRequest

type UniformityRequest struct {
	UnitIDs []string
	Salt    string
	// SecondSalt, when not nil, also tests that its buckets are independent
	// of Salt's, as an experiment's inclusion and variation buckets must be.
	SecondSalt *string
	Bins       int
}

UniformityRequest is what a uniformity check runs on: real unit IDs, as often as each occurs, hashed with Salt and grouped into Bins bins.

type Verdict

type Verdict string

Verdict is what a test of the uniformity check concludes.

const (
	VerdictUniform     Verdict = "uniform"
	VerdictNotUniform  Verdict = "not_uniform"
	VerdictIndependent Verdict = "independent"
	VerdictDependent   Verdict = "dependent"
	VerdictUntestable  Verdict = "untestable"
)

The verdicts. An independence test whose table has a single non-empty row or column has no degrees of freedom and is untestable: every unit ID fell into one bin under one of the salts.

type Weight

type Weight struct {
	Variation string
	Weight    int
}

Weight is the share of the allocated traffic one variation of the experiment's flag gets, in basis points. The order of an experiment's weights fixes the cumulative bucket ranges.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL