Playground
dokimi.gno
// 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
}
dokimi_test.gno
package dokimi
import (
"testing"
"gno.land/p/nt/uassert/v0"
)
// samplePlan is a valid plan with a 15% target and 3,800 exposures promised
// for each arm.
func samplePlan() Plan {
return Plan{
Title: "Short signup page vs current page",
Hypothesis: "A shorter signup page gets more visitors to finish signing up than the current page.",
Metric: "signup_completed",
Control: "Current page",
Variant: "Short page",
Direction: Increase,
TargetBps: 1500,
MinSample: 3800,
}
}
func TestPlanValidate(t *testing.T) {
uassert.NoError(t, samplePlan().Validate())
cases := []struct {
name string
change func(p *Plan)
want string
}{
{"empty title", func(p *Plan) { p.Title = "" }, "title is required"},
{"empty hypothesis", func(p *Plan) { p.Hypothesis = "" }, "hypothesis is required"},
{"empty metric", func(p *Plan) { p.Metric = "" }, "metric is required"},
{"same arm names", func(p *Plan) { p.Variant = p.Control }, "different names"},
{"bad direction", func(p *Plan) { p.Direction = "sideways" }, "direction must be"},
{"zero target", func(p *Plan) { p.TargetBps = 0 }, "target must be between"},
{"huge target", func(p *Plan) { p.TargetBps = MaxTargetBps + 1 }, "target must be between"},
{"zero sample", func(p *Plan) { p.MinSample = 0 }, "minimum sample must be between"},
{"huge sample", func(p *Plan) { p.MinSample = MaxCount + 1 }, "minimum sample must be between"},
{"newline in title", func(p *Plan) { p.Title = "a\nb" }, "single line"},
}
for _, c := range cases {
p := samplePlan()
c.change(&p)
uassert.ErrorContains(t, p.Validate(), c.want, c.name)
}
}
func TestPlanValidateLength(t *testing.T) {
p := samplePlan()
long := ""
for i := 0; i <= MaxNameLen; i++ {
long += "x"
}
p.Title = long
uassert.ErrorContains(t, p.Validate(), "title is longer than")
}
func TestDigest(t *testing.T) {
a := samplePlan()
b := samplePlan()
uassert.Equal(t, 64, len(a.Digest()))
uassert.Equal(t, a.Digest(), b.Digest(), "same plan, same digest")
// Changing any single field changes the digest.
b.TargetBps = 1000
uassert.NotEqual(t, a.Digest(), b.Digest(), "target is part of the digest")
c := samplePlan()
c.MinSample = 1500
uassert.NotEqual(t, a.Digest(), c.Digest(), "sample is part of the digest")
d := samplePlan()
d.Direction = Decrease
uassert.NotEqual(t, a.Digest(), d.Digest(), "direction is part of the digest")
}
// Moving text from one field to its neighbour must not keep the digest.
func TestDigestFieldBoundaries(t *testing.T) {
a := samplePlan()
a.Control = "ab"
a.Variant = "c"
b := samplePlan()
b.Control = "a"
b.Variant = "bc"
uassert.NotEqual(t, a.Digest(), b.Digest())
}
func TestTally(t *testing.T) {
uassert.NoError(t, Tally{Exposures: 10, Conversions: 10}.Validate())
uassert.NoError(t, Tally{}.Validate())
uassert.ErrorContains(t, Tally{Exposures: 5, Conversions: 6}.Validate(), "cannot exceed")
uassert.ErrorContains(t, Tally{Exposures: -1}.Validate(), "negative")
uassert.ErrorContains(t, Tally{Exposures: MaxCount + 1}.Validate(), "maximum")
uassert.Equal(t, int64(0), Tally{}.RateBps())
uassert.Equal(t, int64(1751), Tally{Exposures: 1530, Conversions: 268}.RateBps())
uassert.Equal(t, int64(10000), Tally{Exposures: 7, Conversions: 7}.RateBps())
earlier := Tally{Exposures: 100, Conversions: 20}
uassert.True(t, Tally{Exposures: 100, Conversions: 20}.Covers(earlier))
uassert.True(t, Tally{Exposures: 150, Conversions: 21}.Covers(earlier))
uassert.False(t, Tally{Exposures: 99, Conversions: 20}.Covers(earlier))
uassert.False(t, Tally{Exposures: 150, Conversions: 19}.Covers(earlier))
}
func TestLiftBps(t *testing.T) {
// (304*1530 - 268*1547) * 10000 / (268*1547) = 1218.6, rounded toward zero.
lift, ok := LiftBps(Tally{Exposures: 1530, Conversions: 268}, Tally{Exposures: 1547, Conversions: 304})
uassert.True(t, ok)
uassert.Equal(t, int64(1218), lift)
// Equal rates give no lift.
lift, ok = LiftBps(Tally{Exposures: 1000, Conversions: 100}, Tally{Exposures: 500, Conversions: 50})
uassert.True(t, ok)
uassert.Equal(t, int64(0), lift)
// A worse variant gives a negative lift: 8% vs 10% is -20%.
lift, ok = LiftBps(Tally{Exposures: 1000, Conversions: 100}, Tally{Exposures: 1000, Conversions: 80})
uassert.True(t, ok)
uassert.Equal(t, int64(-2000), lift)
// Undefined cases.
_, ok = LiftBps(Tally{Exposures: 1000, Conversions: 0}, Tally{Exposures: 1000, Conversions: 80})
uassert.False(t, ok, "control without conversions")
_, ok = LiftBps(Tally{}, Tally{Exposures: 1000, Conversions: 80})
uassert.False(t, ok, "control without exposures")
_, ok = LiftBps(Tally{Exposures: 1000, Conversions: 80}, Tally{})
uassert.False(t, ok, "variant without exposures")
_, ok = LiftBps(Tally{Exposures: 5, Conversions: 6}, Tally{Exposures: 10, Conversions: 1})
uassert.False(t, ok, "invalid tally")
}
// The largest allowed counts must not overflow int64.
func TestLiftBpsAtLimits(t *testing.T) {
lift, ok := LiftBps(
Tally{Exposures: MaxCount, Conversions: 1},
Tally{Exposures: MaxCount, Conversions: MaxCount},
)
uassert.True(t, ok)
uassert.Equal(t, (MaxCount-1)*BpsScale, lift)
}
func TestJudgeStoppedEarly(t *testing.T) {
// Looks like a win, but both arms are short of the 3,800 promised.
v := Judge(samplePlan(), Tally{Exposures: 1530, Conversions: 268}, Tally{Exposures: 1547, Conversions: 400})
uassert.Equal(t, string(Inconclusive), string(v.Outcome))
uassert.True(t, v.LiftDefined)
uassert.True(t, v.LiftBps > 1500, "the raw lift is above target and still does not count")
uassert.Equal(t, int64(1751), v.ControlRateBps)
uassert.Equal(t, "Stopped before the planned sample: Current page reached 1,530 and Short page reached 1,547 of the 3,800 exposures promised for each.", v.Reason)
}
func TestJudgeOneArmShort(t *testing.T) {
v := Judge(samplePlan(), Tally{Exposures: 3800, Conversions: 665}, Tally{Exposures: 3799, Conversions: 800})
uassert.Equal(t, string(Inconclusive), string(v.Outcome))
}
func TestJudgeMissed(t *testing.T) {
// 17.5% vs 19.6% at full sample: +12.0%, below the 15% target.
v := Judge(samplePlan(), Tally{Exposures: 4000, Conversions: 700}, Tally{Exposures: 4000, Conversions: 784})
uassert.Equal(t, string(Missed), string(v.Outcome))
uassert.Equal(t, int64(1200), v.LiftBps)
}
func TestJudgeMet(t *testing.T) {
// 17.5% vs 20.125% at full sample: exactly +15.0%.
v := Judge(samplePlan(), Tally{Exposures: 4000, Conversions: 700}, Tally{Exposures: 4000, Conversions: 805})
uassert.Equal(t, string(Met), string(v.Outcome))
uassert.Equal(t, int64(1500), v.LiftBps)
// One conversion fewer falls just short.
v = Judge(samplePlan(), Tally{Exposures: 4000, Conversions: 700}, Tally{Exposures: 4000, Conversions: 804})
uassert.Equal(t, string(Missed), string(v.Outcome))
}
func TestJudgeDecrease(t *testing.T) {
p := samplePlan()
p.Direction = Decrease
p.TargetBps = 1000 // the metric should fall by at least 10%
// 10% down to 8% is -20%: met.
v := Judge(p, Tally{Exposures: 4000, Conversions: 400}, Tally{Exposures: 4000, Conversions: 320})
uassert.Equal(t, string(Met), string(v.Outcome))
uassert.Equal(t, int64(-2000), v.LiftBps)
// 10% up to 12% moved the wrong way: missed.
v = Judge(p, Tally{Exposures: 4000, Conversions: 400}, Tally{Exposures: 4000, Conversions: 480})
uassert.Equal(t, string(Missed), string(v.Outcome))
}
func TestJudgeNoControlConversions(t *testing.T) {
v := Judge(samplePlan(), Tally{Exposures: 4000, Conversions: 0}, Tally{Exposures: 4000, Conversions: 10})
uassert.Equal(t, string(Inconclusive), string(v.Outcome))
uassert.False(t, v.LiftDefined)
}
func TestJudgeInvalidInput(t *testing.T) {
bad := samplePlan()
bad.TargetBps = 0
v := Judge(bad, Tally{Exposures: 4000, Conversions: 700}, Tally{Exposures: 4000, Conversions: 900})
uassert.Equal(t, string(Inconclusive), string(v.Outcome))
v = Judge(samplePlan(), Tally{Exposures: 4000, Conversions: 4001}, Tally{Exposures: 4000, Conversions: 900})
uassert.Equal(t, string(Inconclusive), string(v.Outcome))
}
func TestParsePercent(t *testing.T) {
good := []struct {
in string
want int64
}{
{"15", 1500},
{"15%", 1500},
{" 15 % ", 1500},
{"12.5", 1250},
{"12.50", 1250},
{"0.25%", 25},
{".5", 50},
{"7.", 700},
{"0", 0},
{"100", 10000},
}
for _, c := range good {
got, err := ParsePercent(c.in)
uassert.NoError(t, err, c.in)
uassert.Equal(t, c.want, got, c.in)
}
bad := []string{"", "%", ".", "-5", "+5", "1.234", "abc", "1e3", "12,5", "1234567"}
for _, in := range bad {
_, err := ParsePercent(in)
uassert.Error(t, err, in)
}
}
func TestRateText(t *testing.T) {
uassert.Equal(t, "17.51%", Tally{Exposures: 1530, Conversions: 268}.RateText())
uassert.Equal(t, "100.00%", Tally{Exposures: 7, Conversions: 7}.RateText())
uassert.Equal(t, "1.00%", Tally{Exposures: 100, Conversions: 1}.RateText())
uassert.Equal(t, "0.9900%", Tally{Exposures: 10000, Conversions: 99}.RateText())
uassert.Equal(t, "0.0164%", Tally{Exposures: 200745, Conversions: 33}.RateText())
uassert.Equal(t, "0.0571%", Tally{Exposures: 201229, Conversions: 115}.RateText())
uassert.Equal(t, "0.0000%", Tally{Exposures: MaxCount, Conversions: 0}.RateText())
uassert.Equal(t, "0.00%", Tally{}.RateText())
uassert.Equal(t, "0.00%", Tally{Exposures: 5, Conversions: 6}.RateText(), "invalid tally")
}
// A rare-event trial: the lift comes from the raw counts, so it stays exact
// even though both rates are far below one basis point of difference.
func TestJudgeRareEvents(t *testing.T) {
p := samplePlan()
p.Direction = Decrease
p.TargetBps = 5000
p.MinSample = 100000
v := Judge(p, Tally{Exposures: 201229, Conversions: 115}, Tally{Exposures: 200745, Conversions: 33})
uassert.Equal(t, string(Met), string(v.Outcome))
// (33*201229 - 115*200745) * 10000 / (115*200745) = -7123.5
uassert.Equal(t, int64(-7123), v.LiftBps)
}
func TestCommas(t *testing.T) {
uassert.Equal(t, "0", Commas(0))
uassert.Equal(t, "999", Commas(999))
uassert.Equal(t, "1,000", Commas(1000))
uassert.Equal(t, "1,530", Commas(1530))
uassert.Equal(t, "10,000,000", Commas(MaxCount))
uassert.Equal(t, "-1,234", Commas(-1234))
uassert.Equal(t, "-999", Commas(-999))
}
func TestFormat(t *testing.T) {
uassert.Equal(t, "+12.20%", FormatBps(1220))
uassert.Equal(t, "+0.05%", FormatBps(5))
uassert.Equal(t, "+0.00%", FormatBps(0))
uassert.Equal(t, "-3.50%", FormatBps(-350))
uassert.Equal(t, "+100.00%", FormatBps(10000))
uassert.Equal(t, "17.50%", FormatRate(1750))
uassert.Equal(t, "0.00%", FormatRate(0))
}
gnomod.toml
module = "gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v0" gno = "0.9" [addpkg] creator = "g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft" height = 1483129 max_deposit = "100000000ugnot"