dokimi.gno
8.81 Kb · 308 lines
1// Package dokimi is a public registry of pre-registered experiments.
2//
3// Before a test starts, its owner locks a plan here: the hypothesis, the one
4// metric that decides it, the size of change that counts as a win and the
5// number of people each arm must reach. The block height and a fingerprint of
6// the plan are stored with it. From then on the plan cannot be edited.
7//
8// While the test runs the owner reports running totals. Every report is kept,
9// totals can only go up, and closing the experiment judges the last report
10// against the plan with the rules in gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v0.
11//
12// An owner is whoever called Register: a person's account, or another realm
13// that wants its own experiments on the public record.
14package dokimi
15
16import (
17 "chain"
18 "chain/runtime"
19 "strconv"
20 "time"
21
22 core "gno.land/p/g1v9mz7rtgkvwkw90ey6496h5fk6pj6cgyawkvft/dokimi/v0"
23 "gno.land/p/nt/avl/v0"
24)
25
26const (
27 // MaxReports bounds how many reports one experiment can hold.
28 MaxReports = 100
29 // MaxNotes bounds how many notes one experiment can hold.
30 MaxNotes = 50
31)
32
33// Report is one snapshot of the running totals, kept forever.
34type Report struct {
35 Height int64
36 Time time.Time
37 Control core.Tally
38 Variant core.Tally
39 Source string // where the numbers came from, in the owner's words
40}
41
42// Note is a public remark by the owner, for example a change of plan that
43// readers should know about. Notes are added, never edited or removed.
44type Note struct {
45 Height int64
46 Time time.Time
47 Text string
48}
49
50// Experiment is one locked plan and everything recorded against it.
51type Experiment struct {
52 id uint64
53 owner address
54 plan core.Plan
55 digest string
56 lockedAt time.Time
57 lockedHeight int64
58 reports []Report
59 notes []Note
60 closed bool
61 closedAt time.Time
62 closedHeight int64
63 verdict core.Verdict
64}
65
66var (
67 experiments = avl.NewTree() // key(id) -> *Experiment
68 lastID uint64
69)
70
71// Register locks a new plan and returns its id. The caller becomes the owner.
72//
73// direction is "increase" or "decrease". target is the smallest relative
74// change that counts as a win, as a percentage such as "15" or "12.5".
75// minSample is the number of exposures each arm must reach before the result
76// can count.
77func Register(cur realm, title, hypothesis, metric, control, variant, direction, target string, minSample int64) uint64 {
78 targetBps, err := core.ParsePercent(target)
79 if err != nil {
80 panic("target: " + err.Error())
81 }
82 plan := core.Plan{
83 Title: title,
84 Hypothesis: hypothesis,
85 Metric: metric,
86 Control: control,
87 Variant: variant,
88 Direction: core.Direction(direction),
89 TargetBps: targetBps,
90 MinSample: minSample,
91 }
92 if err := plan.Validate(); err != nil {
93 panic(err.Error())
94 }
95
96 lastID++
97 exp := &Experiment{
98 id: lastID,
99 owner: cur.Previous().Address(),
100 plan: plan,
101 digest: plan.Digest(),
102 lockedAt: time.Now(),
103 lockedHeight: runtime.ChainHeight(),
104 }
105 experiments.Set(key(exp.id), exp)
106
107 chain.Emit(
108 "PlanLocked",
109 "id", strconv.FormatUint(exp.id, 10),
110 "owner", exp.owner.String(),
111 "digest", exp.digest,
112 )
113 return exp.id
114}
115
116// AddReport records the running totals for both arms. Only the owner can
117// report, only while the experiment is open, and no total may go down.
118// source says where the numbers came from, for example a dashboard link.
119func AddReport(cur realm, id uint64, controlExposures, controlConversions, variantExposures, variantConversions int64, source string) {
120 exp := mustGet(id)
121 assertOwner(cur.Previous().Address(), exp)
122 if exp.closed {
123 panic("experiment is closed")
124 }
125 if len(exp.reports) >= MaxReports {
126 panic("report limit reached, close the experiment")
127 }
128
129 control := core.Tally{Exposures: controlExposures, Conversions: controlConversions}
130 variant := core.Tally{Exposures: variantExposures, Conversions: variantConversions}
131 if err := control.Validate(); err != nil {
132 panic(exp.plan.Control + ": " + err.Error())
133 }
134 if err := variant.Validate(); err != nil {
135 panic(exp.plan.Variant + ": " + err.Error())
136 }
137 if n := len(exp.reports); n > 0 {
138 last := exp.reports[n-1]
139 if !control.Covers(last.Control) || !variant.Covers(last.Variant) {
140 panic("totals cannot go down: report running totals, not the change since last time")
141 }
142 }
143 checkOptionalText("source", source)
144
145 exp.reports = append(exp.reports, Report{
146 Height: runtime.ChainHeight(),
147 Time: time.Now(),
148 Control: control,
149 Variant: variant,
150 Source: source,
151 })
152
153 chain.Emit(
154 "ReportAdded",
155 "id", strconv.FormatUint(exp.id, 10),
156 "report", strconv.Itoa(len(exp.reports)),
157 )
158}
159
160// AddNote attaches a public remark to an experiment. Only the owner can add
161// one, at any time, including after the experiment is closed.
162func AddNote(cur realm, id uint64, text string) {
163 exp := mustGet(id)
164 assertOwner(cur.Previous().Address(), exp)
165 if len(exp.notes) >= MaxNotes {
166 panic("note limit reached")
167 }
168 if text == "" {
169 panic("note is empty")
170 }
171 checkOptionalText("note", text)
172
173 exp.notes = append(exp.notes, Note{
174 Height: runtime.ChainHeight(),
175 Time: time.Now(),
176 Text: text,
177 })
178
179 chain.Emit(
180 "NoteAdded",
181 "id", strconv.FormatUint(exp.id, 10),
182 "note", strconv.Itoa(len(exp.notes)),
183 )
184}
185
186// Close ends an experiment and stores the verdict of its last report judged
187// against the locked plan. Only the owner can close, once, and only after at
188// least one report. It returns the outcome: "met", "missed" or "inconclusive".
189func Close(cur realm, id uint64) string {
190 exp := mustGet(id)
191 assertOwner(cur.Previous().Address(), exp)
192 if exp.closed {
193 panic("experiment is already closed")
194 }
195 if len(exp.reports) == 0 {
196 panic("add at least one report before closing")
197 }
198
199 last := exp.reports[len(exp.reports)-1]
200 exp.verdict = core.Judge(exp.plan, last.Control, last.Variant)
201 exp.closed = true
202 exp.closedAt = time.Now()
203 exp.closedHeight = runtime.ChainHeight()
204
205 chain.Emit(
206 "ExperimentClosed",
207 "id", strconv.FormatUint(exp.id, 10),
208 "outcome", string(exp.verdict.Outcome),
209 )
210 return string(exp.verdict.Outcome)
211}
212
213// Count returns how many experiments have been registered.
214func Count() int {
215 return experiments.Size()
216}
217
218// Status returns "open" while an experiment is running, and afterwards its
219// outcome: "met", "missed" or "inconclusive". Other realms can call it to act
220// on a result, for example to release a reward only when a target was met.
221func Status(id uint64) string {
222 exp := mustGet(id)
223 if !exp.closed {
224 return "open"
225 }
226 return string(exp.verdict.Outcome)
227}
228
229// OwnerOf returns the address that registered the experiment.
230func OwnerOf(id uint64) address {
231 return mustGet(id).owner
232}
233
234// DigestOf returns the fingerprint of the locked plan.
235func DigestOf(id uint64) string {
236 return mustGet(id).digest
237}
238
239// Matches reports whether the given plan text is exactly what was locked
240// under id. It recomputes the fingerprint from the arguments, so anyone can
241// check a plan they were shown against the public record.
242func Matches(id uint64, title, hypothesis, metric, control, variant, direction, target string, minSample int64) bool {
243 targetBps, err := core.ParsePercent(target)
244 if err != nil {
245 return false
246 }
247 plan := core.Plan{
248 Title: title,
249 Hypothesis: hypothesis,
250 Metric: metric,
251 Control: control,
252 Variant: variant,
253 Direction: core.Direction(direction),
254 TargetBps: targetBps,
255 MinSample: minSample,
256 }
257 return plan.Digest() == mustGet(id).digest
258}
259
260// LiftOf returns the lift of the latest report in basis points. ok is false
261// when there is no report yet or the lift is undefined.
262func LiftOf(id uint64) (liftBps int64, ok bool) {
263 exp := mustGet(id)
264 if len(exp.reports) == 0 {
265 return 0, false
266 }
267 last := exp.reports[len(exp.reports)-1]
268 return core.LiftBps(last.Control, last.Variant)
269}
270
271// mustGet returns the experiment or stops the transaction.
272func mustGet(id uint64) *Experiment {
273 exp, ok := experiments.Get(key(id)).(*Experiment)
274 if !ok {
275 panic("experiment " + strconv.FormatUint(id, 10) + " not found")
276 }
277 return exp
278}
279
280// assertOwner stops the transaction unless caller owns exp. Pass the direct
281// caller of the crossing function: cur.Previous().Address().
282func assertOwner(caller address, exp *Experiment) {
283 if caller != exp.owner {
284 panic("only the owner can do this")
285 }
286}
287
288// checkOptionalText allows an empty value, and otherwise a single line
289// within the package text limit.
290func checkOptionalText(name, s string) {
291 if len(s) > core.MaxTextLen {
292 panic(name + " is longer than " + strconv.Itoa(core.MaxTextLen) + " bytes")
293 }
294 for i := 0; i < len(s); i++ {
295 if s[i] < 0x20 || s[i] == 0x7f {
296 panic(name + " must be a single line without control characters")
297 }
298 }
299}
300
301// key turns an id into a fixed-width string so the tree keeps numeric order.
302func key(id uint64) string {
303 s := strconv.FormatUint(id, 10)
304 for len(s) < 20 {
305 s = "0" + s
306 }
307 return s
308}