// Package dokimi is a public registry of pre-registered experiments. // // Before a test starts, its owner locks a plan here: the hypothesis, the one // metric that decides it, the size of change that counts as a win and the // number of people each arm must reach. The block height and a fingerprint of // the plan are stored with it. From then on the plan cannot be edited. // // While the test runs the owner reports running totals. Every report is kept, // totals can only go up, and closing the experiment judges the last report // against the plan with the rules in gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v0. // // An owner is whoever called Register: a person's account, or another realm // that wants its own experiments on the public record. package dokimi import ( "chain" "chain/runtime" "strconv" "time" core "gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v0" "gno.land/p/nt/avl/v0" ) const ( // MaxReports bounds how many reports one experiment can hold. MaxReports = 100 // MaxNotes bounds how many notes one experiment can hold. MaxNotes = 50 ) // Report is one snapshot of the running totals, kept forever. type Report struct { Height int64 Time time.Time Control core.Tally Variant core.Tally Source string // where the numbers came from, in the owner's words } // Note is a public remark by the owner, for example a change of plan that // readers should know about. Notes are added, never edited or removed. type Note struct { Height int64 Time time.Time Text string } // Experiment is one locked plan and everything recorded against it. type Experiment struct { id uint64 owner address plan core.Plan digest string lockedAt time.Time lockedHeight int64 reports []Report notes []Note closed bool closedAt time.Time closedHeight int64 verdict core.Verdict } var ( experiments = avl.NewTree() // key(id) -> *Experiment lastID uint64 ) // Register locks a new plan and returns its id. The caller becomes the owner. // // direction is "increase" or "decrease". target is the smallest relative // change that counts as a win, as a percentage such as "15" or "12.5". // minSample is the number of exposures each arm must reach before the result // can count. func Register(cur realm, title, hypothesis, metric, control, variant, direction, target string, minSample int64) uint64 { targetBps, err := core.ParsePercent(target) if err != nil { panic("target: " + err.Error()) } plan := core.Plan{ Title: title, Hypothesis: hypothesis, Metric: metric, Control: control, Variant: variant, Direction: core.Direction(direction), TargetBps: targetBps, MinSample: minSample, } if err := plan.Validate(); err != nil { panic(err.Error()) } lastID++ exp := &Experiment{ id: lastID, owner: cur.Previous().Address(), plan: plan, digest: plan.Digest(), lockedAt: time.Now(), lockedHeight: runtime.ChainHeight(), } experiments.Set(key(exp.id), exp) chain.Emit( "PlanLocked", "id", strconv.FormatUint(exp.id, 10), "owner", exp.owner.String(), "digest", exp.digest, ) return exp.id } // AddReport records the running totals for both arms. Only the owner can // report, only while the experiment is open, and no total may go down. // source says where the numbers came from, for example a dashboard link. func AddReport(cur realm, id uint64, controlExposures, controlConversions, variantExposures, variantConversions int64, source string) { exp := mustGet(id) assertOwner(cur.Previous().Address(), exp) if exp.closed { panic("experiment is closed") } if len(exp.reports) >= MaxReports { panic("report limit reached, close the experiment") } control := core.Tally{Exposures: controlExposures, Conversions: controlConversions} variant := core.Tally{Exposures: variantExposures, Conversions: variantConversions} if err := control.Validate(); err != nil { panic(exp.plan.Control + ": " + err.Error()) } if err := variant.Validate(); err != nil { panic(exp.plan.Variant + ": " + err.Error()) } if n := len(exp.reports); n > 0 { last := exp.reports[n-1] if !control.Covers(last.Control) || !variant.Covers(last.Variant) { panic("totals cannot go down: report running totals, not the change since last time") } } checkOptionalText("source", source) exp.reports = append(exp.reports, Report{ Height: runtime.ChainHeight(), Time: time.Now(), Control: control, Variant: variant, Source: source, }) chain.Emit( "ReportAdded", "id", strconv.FormatUint(exp.id, 10), "report", strconv.Itoa(len(exp.reports)), ) } // AddNote attaches a public remark to an experiment. Only the owner can add // one, at any time, including after the experiment is closed. func AddNote(cur realm, id uint64, text string) { exp := mustGet(id) assertOwner(cur.Previous().Address(), exp) if len(exp.notes) >= MaxNotes { panic("note limit reached") } if text == "" { panic("note is empty") } checkOptionalText("note", text) exp.notes = append(exp.notes, Note{ Height: runtime.ChainHeight(), Time: time.Now(), Text: text, }) chain.Emit( "NoteAdded", "id", strconv.FormatUint(exp.id, 10), "note", strconv.Itoa(len(exp.notes)), ) } // Close ends an experiment and stores the verdict of its last report judged // against the locked plan. Only the owner can close, once, and only after at // least one report. It returns the outcome: "met", "missed" or "inconclusive". func Close(cur realm, id uint64) string { exp := mustGet(id) assertOwner(cur.Previous().Address(), exp) if exp.closed { panic("experiment is already closed") } if len(exp.reports) == 0 { panic("add at least one report before closing") } last := exp.reports[len(exp.reports)-1] exp.verdict = core.Judge(exp.plan, last.Control, last.Variant) exp.closed = true exp.closedAt = time.Now() exp.closedHeight = runtime.ChainHeight() chain.Emit( "ExperimentClosed", "id", strconv.FormatUint(exp.id, 10), "outcome", string(exp.verdict.Outcome), ) return string(exp.verdict.Outcome) } // Count returns how many experiments have been registered. func Count() int { return experiments.Size() } // Status returns "open" while an experiment is running, and afterwards its // outcome: "met", "missed" or "inconclusive". Other realms can call it to act // on a result, for example to release a reward only when a target was met. func Status(id uint64) string { exp := mustGet(id) if !exp.closed { return "open" } return string(exp.verdict.Outcome) } // OwnerOf returns the address that registered the experiment. func OwnerOf(id uint64) address { return mustGet(id).owner } // DigestOf returns the fingerprint of the locked plan. func DigestOf(id uint64) string { return mustGet(id).digest } // Matches reports whether the given plan text is exactly what was locked // under id. It recomputes the fingerprint from the arguments, so anyone can // check a plan they were shown against the public record. func Matches(id uint64, title, hypothesis, metric, control, variant, direction, target string, minSample int64) bool { targetBps, err := core.ParsePercent(target) if err != nil { return false } plan := core.Plan{ Title: title, Hypothesis: hypothesis, Metric: metric, Control: control, Variant: variant, Direction: core.Direction(direction), TargetBps: targetBps, MinSample: minSample, } return plan.Digest() == mustGet(id).digest } // LiftOf returns the lift of the latest report in basis points. ok is false // when there is no report yet or the lift is undefined. func LiftOf(id uint64) (liftBps int64, ok bool) { exp := mustGet(id) if len(exp.reports) == 0 { return 0, false } last := exp.reports[len(exp.reports)-1] return core.LiftBps(last.Control, last.Variant) } // mustGet returns the experiment or stops the transaction. func mustGet(id uint64) *Experiment { exp, ok := experiments.Get(key(id)).(*Experiment) if !ok { panic("experiment " + strconv.FormatUint(id, 10) + " not found") } return exp } // assertOwner stops the transaction unless caller owns exp. Pass the direct // caller of the crossing function: cur.Previous().Address(). func assertOwner(caller address, exp *Experiment) { if caller != exp.owner { panic("only the owner can do this") } } // checkOptionalText allows an empty value, and otherwise a single line // within the package text limit. func checkOptionalText(name, s string) { if len(s) > core.MaxTextLen { panic(name + " is longer than " + strconv.Itoa(core.MaxTextLen) + " bytes") } for i := 0; i < len(s); i++ { if s[i] < 0x20 || s[i] == 0x7f { panic(name + " must be a single line without control characters") } } } // key turns an id into a fixed-width string so the tree keeps numeric order. func key(id uint64) string { s := strconv.FormatUint(id, 10) for len(s) < 20 { s = "0" + s } return s }