// Package dokimi holds the rules for a pre-registered experiment. // // A Plan states, before any data exists, what is being tested, which metric // decides it, how big a change counts as a win and how many people each arm // must reach. Judge then compares the recorded numbers with that plan and // nothing else, so the bar cannot move after the results are in. // // The package is pure: it keeps no state and moves no coins. Any realm can // import it to judge its own experiments, or call the Dokimi registry realm // to have them stored in public. // // All rates and lifts are integers in basis points (1% = 100 bps), so every // node computes exactly the same verdict. package dokimi import ( "crypto/sha256" "encoding/hex" "errors" "strconv" "strings" ) const ( // BpsScale is the number of basis points in 100%. BpsScale int64 = 10000 // MaxCount is the largest exposure count a Tally may hold. It keeps the // lift calculation inside int64: MaxCount * MaxCount * BpsScale < 2^63. MaxCount int64 = 10000000 // MaxTargetBps caps a target at a 1,000% relative change. MaxTargetBps int64 = 100000 // Text limits keep stored plans small and readable. MaxNameLen = 60 MaxTextLen = 400 ) // Direction says which way the metric is expected to move. type Direction string const ( Increase Direction = "increase" Decrease Direction = "decrease" ) // Outcome is the result of judging recorded numbers against a Plan. type Outcome string const ( // Inconclusive means the numbers cannot answer the question, usually // because an arm stopped before the pre-registered minimum sample. Inconclusive Outcome = "inconclusive" // Met means the change reached the target in the expected direction. Met Outcome = "met" // Missed means the sample was large enough and the target was not reached. Missed Outcome = "missed" ) // Plan is what gets locked before a test starts. type Plan struct { Title string // short name of the experiment Hypothesis string // the claim being tested, in plain words Metric string // the single event or number that decides it Control string // name of the existing version Variant string // name of the new version Direction Direction // which way the metric should move TargetBps int64 // smallest relative change that counts, in bps MinSample int64 // exposures each arm needs before a verdict counts } // Validate reports the first problem with a plan, or nil. func (p Plan) Validate() error { if err := checkText("title", p.Title, MaxNameLen); err != nil { return err } if err := checkText("hypothesis", p.Hypothesis, MaxTextLen); err != nil { return err } if err := checkText("metric", p.Metric, MaxNameLen); err != nil { return err } if err := checkText("control name", p.Control, MaxNameLen); err != nil { return err } if err := checkText("variant name", p.Variant, MaxNameLen); err != nil { return err } if p.Control == p.Variant { return errors.New("control and variant must have different names") } if p.Direction != Increase && p.Direction != Decrease { return errors.New("direction must be \"increase\" or \"decrease\"") } if p.TargetBps < 1 || p.TargetBps > MaxTargetBps { return errors.New("target must be between 1 and " + strconv.FormatInt(MaxTargetBps, 10) + " bps") } if p.MinSample < 1 || p.MinSample > MaxCount { return errors.New("minimum sample must be between 1 and " + strconv.FormatInt(MaxCount, 10)) } return nil } // Digest returns the SHA-256 fingerprint of the plan as hex. // // Every field is written with its length in front, so two different plans can // never produce the same input. Anyone holding the plan text can recompute // the digest and compare it with the one a registry stored. func (p Plan) Digest() string { buf := "dokimi/plan/v1" buf += field(p.Title) buf += field(p.Hypothesis) buf += field(p.Metric) buf += field(p.Control) buf += field(p.Variant) buf += field(string(p.Direction)) buf += field(strconv.FormatInt(p.TargetBps, 10)) buf += field(strconv.FormatInt(p.MinSample, 10)) sum := sha256.Sum256([]byte(buf)) return hex.EncodeToString(sum[:]) } // Tally is the running total for one arm of an experiment. type Tally struct { Exposures int64 // people who saw this arm Conversions int64 // of those, how many did the thing the metric counts } // Validate reports the first problem with a tally, or nil. func (t Tally) Validate() error { if t.Exposures < 0 || t.Conversions < 0 { return errors.New("counts cannot be negative") } if t.Exposures > MaxCount { return errors.New("exposures above the supported maximum of " + strconv.FormatInt(MaxCount, 10)) } if t.Conversions > t.Exposures { return errors.New("conversions cannot exceed exposures") } return nil } // RateBps returns conversions per exposure in basis points, rounded down. // An arm with no exposures has a rate of 0. func (t Tally) RateBps() int64 { if t.Exposures <= 0 { return 0 } return t.Conversions * BpsScale / t.Exposures } // RateText renders the rate as a percentage for people to read: two decimals // from 1% upwards and four below, so rare events stay visible. For example // 268 of 1,530 is "17.51%" and 33 of 200,745 is "0.0164%". func (t Tally) RateText() string { if t.Exposures <= 0 || t.Conversions < 0 || t.Conversions > t.Exposures || t.Exposures > MaxCount { return "0.00%" } ppm := t.Conversions * 1000000 / t.Exposures // parts per million if ppm >= 10000 { return FormatRate(ppm / 100) } frac := strconv.FormatInt(ppm, 10) for len(frac) < 4 { frac = "0" + frac } return "0." + frac + "%" } // Covers reports whether t has at least as many exposures and conversions as // earlier. A registry uses it to refuse a report that lowers a total. func (t Tally) Covers(earlier Tally) bool { return t.Exposures >= earlier.Exposures && t.Conversions >= earlier.Conversions } // LiftBps returns the relative change of the variant's rate over the // control's, in basis points, rounded toward zero. ok is false when the lift // is undefined: an arm has no exposures or the control has no conversions. // // It is computed from the raw counts, not from the rounded rates: // // (vc/ve - cc/ce) / (cc/ce) = (vc*ce - cc*ve) / (cc*ve) func LiftBps(control, variant Tally) (lift int64, ok bool) { if control.Validate() != nil || variant.Validate() != nil { return 0, false } if control.Exposures == 0 || variant.Exposures == 0 || control.Conversions == 0 { return 0, false } num := variant.Conversions*control.Exposures - control.Conversions*variant.Exposures den := control.Conversions * variant.Exposures return num * BpsScale / den, true } // Verdict is the outcome of Judge with the numbers behind it. type Verdict struct { Outcome Outcome ControlRateBps int64 VariantRateBps int64 LiftBps int64 // meaningful only when LiftDefined is true LiftDefined bool Reason string // one plain sentence explaining the outcome } // Judge compares the recorded totals with the plan. // // The order of the checks is the point of pre-registration: the sample size // promised in advance is checked first, so a test stopped early can never be // reported as a win, however good its numbers look. func Judge(p Plan, control, variant Tally) Verdict { v := Verdict{ Outcome: Inconclusive, ControlRateBps: control.RateBps(), VariantRateBps: variant.RateBps(), } if err := p.Validate(); err != nil { v.Reason = "The plan is not valid: " + err.Error() + "." return v } if control.Validate() != nil || variant.Validate() != nil { v.Reason = "The recorded counts are not valid." return v } lift, ok := LiftBps(control, variant) v.LiftBps = lift v.LiftDefined = ok if control.Exposures < p.MinSample || variant.Exposures < p.MinSample { v.Reason = "Stopped before the planned sample: " + p.Control + " reached " + Commas(control.Exposures) + " and " + p.Variant + " reached " + Commas(variant.Exposures) + " of the " + Commas(p.MinSample) + " exposures promised for each." return v } if !ok { v.Reason = "The lift cannot be computed because " + p.Control + " has no conversions." return v } // Turn the lift into "movement in the promised direction". gain := lift if p.Direction == Decrease { gain = -lift } if gain >= p.TargetBps { v.Outcome = Met v.Reason = "The change of " + FormatBps(lift) + " reached the target of " + targetText(p) + " set before the test." return v } v.Outcome = Missed v.Reason = "The change of " + FormatBps(lift) + " did not reach the target of " + targetText(p) + " set before the test." return v } // FormatBps renders basis points as a signed percentage with two decimals, // for example 1220 -> "+12.20%" and -350 -> "-3.50%". func FormatBps(bps int64) string { sign := "+" if bps < 0 { sign = "-" bps = -bps } frac := strconv.FormatInt(bps%100, 10) if len(frac) < 2 { frac = "0" + frac } return sign + strconv.FormatInt(bps/100, 10) + "." + frac + "%" } // FormatRate renders a rate in basis points as an unsigned percentage, // for example 1750 -> "17.50%". func FormatRate(bps int64) string { if bps < 0 { return FormatBps(bps) } return FormatBps(bps)[1:] } // Commas renders a count with thousands separators: 1530 -> "1,530". func Commas(n int64) string { s := strconv.FormatInt(n, 10) neg := "" if n < 0 { neg = "-" s = s[1:] } for i := len(s) - 3; i > 0; i -= 3 { s = s[:i] + "," + s[i:] } return neg + s } // ParsePercent turns a percentage typed by a person into basis points. // It accepts "15", "15%", "12.5" and "0.25%", with at most two decimals. // Negative values are refused: the plan's Direction carries the sign. func ParsePercent(s string) (int64, error) { s = strings.TrimSpace(s) s = strings.TrimSuffix(s, "%") s = strings.TrimSpace(s) if s == "" { return 0, errors.New("percentage is required") } whole, frac := s, "" if i := strings.IndexByte(s, '.'); i >= 0 { whole, frac = s[:i], s[i+1:] } if whole == "" && frac == "" { return 0, errors.New("percentage is not a number") } if len(whole) > 6 { return 0, errors.New("percentage is too large") } if len(frac) > 2 { return 0, errors.New("percentage can have at most two decimal places") } if !allDigits(whole) || !allDigits(frac) { return 0, errors.New("percentage is not a number") } for len(frac) < 2 { frac += "0" } var bps int64 for i := 0; i < len(whole); i++ { bps = bps*10 + int64(whole[i]-'0') } bps = bps*100 + int64(frac[0]-'0')*10 + int64(frac[1]-'0') return bps, nil } // allDigits reports whether s holds only ASCII digits. An empty string passes. func allDigits(s string) bool { for i := 0; i < len(s); i++ { if s[i] < '0' || s[i] > '9' { return false } } return true } // targetText renders the plan's target with the sign of its direction. func targetText(p Plan) string { if p.Direction == Decrease { return FormatBps(-p.TargetBps) } return FormatBps(p.TargetBps) } // field length-prefixes one value for the digest input. func field(s string) string { return "|" + strconv.Itoa(len(s)) + ":" + s } // checkText requires a non-empty single-line value within max bytes. func checkText(name, s string, max int) error { if s == "" { return errors.New(name + " is required") } if len(s) > max { return errors.New(name + " is longer than " + strconv.Itoa(max) + " bytes") } for i := 0; i < len(s); i++ { if s[i] < 0x20 || s[i] == 0x7f { return errors.New(name + " must be a single line without control characters") } } return nil }