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