Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

dokimi.gno

11.31 Kb · 371 lines
  1// Package dokimi holds the rules for a pre-registered experiment.
  2//
  3// A Plan states, before any data exists, what is being tested, which metric
  4// decides it, how big a change counts as a win and how many people each arm
  5// must reach. Judge then compares the recorded numbers with that plan and
  6// nothing else, so the bar cannot move after the results are in.
  7//
  8// The package is pure: it keeps no state and moves no coins. Any realm can
  9// import it to judge its own experiments, or call the Dokimi registry realm
 10// to have them stored in public.
 11//
 12// All rates and lifts are integers in basis points (1% = 100 bps), so every
 13// node computes exactly the same verdict.
 14package dokimi
 15
 16import (
 17	"crypto/sha256"
 18	"encoding/hex"
 19	"errors"
 20	"strconv"
 21	"strings"
 22)
 23
 24const (
 25	// BpsScale is the number of basis points in 100%.
 26	BpsScale int64 = 10000
 27
 28	// MaxCount is the largest exposure count a Tally may hold. It keeps the
 29	// lift calculation inside int64: MaxCount * MaxCount * BpsScale < 2^63.
 30	MaxCount int64 = 10000000
 31
 32	// MaxTargetBps caps a target at a 1,000% relative change.
 33	MaxTargetBps int64 = 100000
 34
 35	// Text limits keep stored plans small and readable.
 36	MaxNameLen = 60
 37	MaxTextLen = 400
 38)
 39
 40// Direction says which way the metric is expected to move.
 41type Direction string
 42
 43const (
 44	Increase Direction = "increase"
 45	Decrease Direction = "decrease"
 46)
 47
 48// Outcome is the result of judging recorded numbers against a Plan.
 49type Outcome string
 50
 51const (
 52	// Inconclusive means the numbers cannot answer the question, usually
 53	// because an arm stopped before the pre-registered minimum sample.
 54	Inconclusive Outcome = "inconclusive"
 55	// Met means the change reached the target in the expected direction.
 56	Met Outcome = "met"
 57	// Missed means the sample was large enough and the target was not reached.
 58	Missed Outcome = "missed"
 59)
 60
 61// Plan is what gets locked before a test starts.
 62type Plan struct {
 63	Title      string    // short name of the experiment
 64	Hypothesis string    // the claim being tested, in plain words
 65	Metric     string    // the single event or number that decides it
 66	Control    string    // name of the existing version
 67	Variant    string    // name of the new version
 68	Direction  Direction // which way the metric should move
 69	TargetBps  int64     // smallest relative change that counts, in bps
 70	MinSample  int64     // exposures each arm needs before a verdict counts
 71}
 72
 73// Validate reports the first problem with a plan, or nil.
 74func (p Plan) Validate() error {
 75	if err := checkText("title", p.Title, MaxNameLen); err != nil {
 76		return err
 77	}
 78	if err := checkText("hypothesis", p.Hypothesis, MaxTextLen); err != nil {
 79		return err
 80	}
 81	if err := checkText("metric", p.Metric, MaxNameLen); err != nil {
 82		return err
 83	}
 84	if err := checkText("control name", p.Control, MaxNameLen); err != nil {
 85		return err
 86	}
 87	if err := checkText("variant name", p.Variant, MaxNameLen); err != nil {
 88		return err
 89	}
 90	if p.Control == p.Variant {
 91		return errors.New("control and variant must have different names")
 92	}
 93	if p.Direction != Increase && p.Direction != Decrease {
 94		return errors.New("direction must be \"increase\" or \"decrease\"")
 95	}
 96	if p.TargetBps < 1 || p.TargetBps > MaxTargetBps {
 97		return errors.New("target must be between 1 and " + strconv.FormatInt(MaxTargetBps, 10) + " bps")
 98	}
 99	if p.MinSample < 1 || p.MinSample > MaxCount {
100		return errors.New("minimum sample must be between 1 and " + strconv.FormatInt(MaxCount, 10))
101	}
102	return nil
103}
104
105// Digest returns the SHA-256 fingerprint of the plan as hex.
106//
107// Every field is written with its length in front, so two different plans can
108// never produce the same input. Anyone holding the plan text can recompute
109// the digest and compare it with the one a registry stored.
110func (p Plan) Digest() string {
111	buf := "dokimi/plan/v1"
112	buf += field(p.Title)
113	buf += field(p.Hypothesis)
114	buf += field(p.Metric)
115	buf += field(p.Control)
116	buf += field(p.Variant)
117	buf += field(string(p.Direction))
118	buf += field(strconv.FormatInt(p.TargetBps, 10))
119	buf += field(strconv.FormatInt(p.MinSample, 10))
120	sum := sha256.Sum256([]byte(buf))
121	return hex.EncodeToString(sum[:])
122}
123
124// Tally is the running total for one arm of an experiment.
125type Tally struct {
126	Exposures   int64 // people who saw this arm
127	Conversions int64 // of those, how many did the thing the metric counts
128}
129
130// Validate reports the first problem with a tally, or nil.
131func (t Tally) Validate() error {
132	if t.Exposures < 0 || t.Conversions < 0 {
133		return errors.New("counts cannot be negative")
134	}
135	if t.Exposures > MaxCount {
136		return errors.New("exposures above the supported maximum of " + strconv.FormatInt(MaxCount, 10))
137	}
138	if t.Conversions > t.Exposures {
139		return errors.New("conversions cannot exceed exposures")
140	}
141	return nil
142}
143
144// RateBps returns conversions per exposure in basis points, rounded down.
145// An arm with no exposures has a rate of 0.
146func (t Tally) RateBps() int64 {
147	if t.Exposures <= 0 {
148		return 0
149	}
150	return t.Conversions * BpsScale / t.Exposures
151}
152
153// RateText renders the rate as a percentage for people to read: two decimals
154// from 1% upwards and four below, so rare events stay visible. For example
155// 268 of 1,530 is "17.51%" and 33 of 200,745 is "0.0164%".
156func (t Tally) RateText() string {
157	if t.Exposures <= 0 || t.Conversions < 0 || t.Conversions > t.Exposures || t.Exposures > MaxCount {
158		return "0.00%"
159	}
160	ppm := t.Conversions * 1000000 / t.Exposures // parts per million
161	if ppm >= 10000 {
162		return FormatRate(ppm / 100)
163	}
164	frac := strconv.FormatInt(ppm, 10)
165	for len(frac) < 4 {
166		frac = "0" + frac
167	}
168	return "0." + frac + "%"
169}
170
171// Covers reports whether t has at least as many exposures and conversions as
172// earlier. A registry uses it to refuse a report that lowers a total.
173func (t Tally) Covers(earlier Tally) bool {
174	return t.Exposures >= earlier.Exposures && t.Conversions >= earlier.Conversions
175}
176
177// LiftBps returns the relative change of the variant's rate over the
178// control's, in basis points, rounded toward zero. ok is false when the lift
179// is undefined: an arm has no exposures or the control has no conversions.
180//
181// It is computed from the raw counts, not from the rounded rates:
182//
183//	(vc/ve - cc/ce) / (cc/ce) = (vc*ce - cc*ve) / (cc*ve)
184func LiftBps(control, variant Tally) (lift int64, ok bool) {
185	if control.Validate() != nil || variant.Validate() != nil {
186		return 0, false
187	}
188	if control.Exposures == 0 || variant.Exposures == 0 || control.Conversions == 0 {
189		return 0, false
190	}
191	num := variant.Conversions*control.Exposures - control.Conversions*variant.Exposures
192	den := control.Conversions * variant.Exposures
193	return num * BpsScale / den, true
194}
195
196// Verdict is the outcome of Judge with the numbers behind it.
197type Verdict struct {
198	Outcome        Outcome
199	ControlRateBps int64
200	VariantRateBps int64
201	LiftBps        int64 // meaningful only when LiftDefined is true
202	LiftDefined    bool
203	Reason         string // one plain sentence explaining the outcome
204}
205
206// Judge compares the recorded totals with the plan.
207//
208// The order of the checks is the point of pre-registration: the sample size
209// promised in advance is checked first, so a test stopped early can never be
210// reported as a win, however good its numbers look.
211func Judge(p Plan, control, variant Tally) Verdict {
212	v := Verdict{
213		Outcome:        Inconclusive,
214		ControlRateBps: control.RateBps(),
215		VariantRateBps: variant.RateBps(),
216	}
217	if err := p.Validate(); err != nil {
218		v.Reason = "The plan is not valid: " + err.Error() + "."
219		return v
220	}
221	if control.Validate() != nil || variant.Validate() != nil {
222		v.Reason = "The recorded counts are not valid."
223		return v
224	}
225
226	lift, ok := LiftBps(control, variant)
227	v.LiftBps = lift
228	v.LiftDefined = ok
229
230	if control.Exposures < p.MinSample || variant.Exposures < p.MinSample {
231		v.Reason = "Stopped before the planned sample: " + p.Control + " reached " +
232			Commas(control.Exposures) + " and " + p.Variant + " reached " +
233			Commas(variant.Exposures) + " of the " +
234			Commas(p.MinSample) + " exposures promised for each."
235		return v
236	}
237	if !ok {
238		v.Reason = "The lift cannot be computed because " + p.Control + " has no conversions."
239		return v
240	}
241
242	// Turn the lift into "movement in the promised direction".
243	gain := lift
244	if p.Direction == Decrease {
245		gain = -lift
246	}
247	if gain >= p.TargetBps {
248		v.Outcome = Met
249		v.Reason = "The change of " + FormatBps(lift) + " reached the target of " +
250			targetText(p) + " locked in the plan."
251		return v
252	}
253	v.Outcome = Missed
254	v.Reason = "The change of " + FormatBps(lift) + " did not reach the target of " +
255		targetText(p) + " locked in the plan."
256	return v
257}
258
259// FormatBps renders basis points as a signed percentage with two decimals,
260// for example 1220 -> "+12.20%" and -350 -> "-3.50%".
261func FormatBps(bps int64) string {
262	sign := "+"
263	if bps < 0 {
264		sign = "-"
265		bps = -bps
266	}
267	frac := strconv.FormatInt(bps%100, 10)
268	if len(frac) < 2 {
269		frac = "0" + frac
270	}
271	return sign + strconv.FormatInt(bps/100, 10) + "." + frac + "%"
272}
273
274// FormatRate renders a rate in basis points as an unsigned percentage,
275// for example 1750 -> "17.50%".
276func FormatRate(bps int64) string {
277	if bps < 0 {
278		return FormatBps(bps)
279	}
280	return FormatBps(bps)[1:]
281}
282
283// Commas renders a count with thousands separators: 1530 -> "1,530".
284func Commas(n int64) string {
285	s := strconv.FormatInt(n, 10)
286	neg := ""
287	if n < 0 {
288		neg = "-"
289		s = s[1:]
290	}
291	for i := len(s) - 3; i > 0; i -= 3 {
292		s = s[:i] + "," + s[i:]
293	}
294	return neg + s
295}
296
297// ParsePercent turns a percentage typed by a person into basis points.
298// It accepts "15", "15%", "12.5" and "0.25%", with at most two decimals.
299// Negative values are refused: the plan's Direction carries the sign.
300func ParsePercent(s string) (int64, error) {
301	s = strings.TrimSpace(s)
302	s = strings.TrimSuffix(s, "%")
303	s = strings.TrimSpace(s)
304	if s == "" {
305		return 0, errors.New("percentage is required")
306	}
307	whole, frac := s, ""
308	if i := strings.IndexByte(s, '.'); i >= 0 {
309		whole, frac = s[:i], s[i+1:]
310	}
311	if whole == "" && frac == "" {
312		return 0, errors.New("percentage is not a number")
313	}
314	if len(whole) > 6 {
315		return 0, errors.New("percentage is too large")
316	}
317	if len(frac) > 2 {
318		return 0, errors.New("percentage can have at most two decimal places")
319	}
320	if !allDigits(whole) || !allDigits(frac) {
321		return 0, errors.New("percentage is not a number")
322	}
323	for len(frac) < 2 {
324		frac += "0"
325	}
326	var bps int64
327	for i := 0; i < len(whole); i++ {
328		bps = bps*10 + int64(whole[i]-'0')
329	}
330	bps = bps*100 + int64(frac[0]-'0')*10 + int64(frac[1]-'0')
331	return bps, nil
332}
333
334// allDigits reports whether s holds only ASCII digits. An empty string passes.
335func allDigits(s string) bool {
336	for i := 0; i < len(s); i++ {
337		if s[i] < '0' || s[i] > '9' {
338			return false
339		}
340	}
341	return true
342}
343
344// targetText renders the plan's target with the sign of its direction.
345func targetText(p Plan) string {
346	if p.Direction == Decrease {
347		return FormatBps(-p.TargetBps)
348	}
349	return FormatBps(p.TargetBps)
350}
351
352// field length-prefixes one value for the digest input.
353func field(s string) string {
354	return "|" + strconv.Itoa(len(s)) + ":" + s
355}
356
357// checkText requires a non-empty single-line value within max bytes.
358func checkText(name, s string, max int) error {
359	if s == "" {
360		return errors.New(name + " is required")
361	}
362	if len(s) > max {
363		return errors.New(name + " is longer than " + strconv.Itoa(max) + " bytes")
364	}
365	for i := 0; i < len(s); i++ {
366		if s[i] < 0x20 || s[i] == 0x7f {
367			return errors.New(name + " must be a single line without control characters")
368		}
369	}
370	return nil
371}