@yaks/benchmark 0.0.0-stage → 0.2.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/ratchet.js ADDED
@@ -0,0 +1,290 @@
1
+ /** The pure ratchet compares compatible suite measurements. A baseline is a
2
+ * value with its own slack; accepting it is an explicit runner operation.
3
+ * A figure counts only where it clears the noise. A regression is a figure
4
+ * past its reference by more than the noise of both measurements; a baseline
5
+ * moves toward better only by as much, and never on a run the box measured
6
+ * while loaded. Banking worse numbers is a separate, explicit choice
7
+ * (`slower`, for the whole suite or the benches it names), never what an
8
+ * ordinary acceptance does. */ import { insufficient, sameNames, value, workload } from "./result.js";
9
+ export let tolerance = (n)=>{
10
+ if (!Number.isFinite(n) || n < 0 || n >= 1) {
11
+ throw new Error('Tolerance must be in [0, 1)');
12
+ }
13
+ return n;
14
+ };
15
+ /** A bench's slack is this many times the spread its measurement showed. */ export let NOISE = 2;
16
+ /** The most slack noise can earn a bench; a tolerance stays under one. */ export let CAP = .95;
17
+ /** A run is loaded when other work used more than this share of the box's
18
+ * CPUs while the bench rested before a round. Measured on four hyperthreads:
19
+ * one busy costs a CPU-bound bench a few percent, two about a tenth. */ export let BUSY = .25;
20
+ /// loaded({ busy: .5 }) -> true
21
+ /// loaded({ busy: .25 }) -> false
22
+ /// loaded({ busy: null }) -> false
23
+ /** Whether the box was loaded while a run measured. A loaded run confirms no
24
+ * regression and banks no baseline: its figures carry the other work. */ export let loaded = (run)=>(run.busy ?? 0) > BUSY;
25
+ /** Refuses to bank what a loaded box measured. */ export let quiet = (suite, run)=>{
26
+ if (loaded(run)) {
27
+ throw new Error(`${suite} cannot bank on a loaded box: other work used ${Math.round(run.busy * 100)}% of its CPUs`);
28
+ }
29
+ };
30
+ /** How far apart repeated medians of one bench fall, as a fraction of the
31
+ * best of them: the noise a figure carries, which a check has to allow.
32
+ *
33
+ * ```ts
34
+ * import { spread } from '@yaks/benchmark'
35
+ * import { equal } from '@yaks/testing'
36
+ *
37
+ * equal(spread([100, 104, 110], 'lower'), .1)
38
+ * equal(spread([80, 100], 'higher'), .2)
39
+ * equal(spread([5], 'lower'), 0)
40
+ * ```
41
+ */ export let spread = (medians, better)=>{
42
+ let low = Math.min(...medians.map(value)), high = Math.max(...medians);
43
+ let best = better == 'lower' ? low : high;
44
+ return best == 0 ? 0 : (high - low) / best;
45
+ };
46
+ /** Repeated runs of one suite as one run: each bench as the run that measured
47
+ * it best, the median acceptance banks, so a check compares like for like,
48
+ * with the spread of every round median the runs took between them, and the
49
+ * busiest box any of them saw.
50
+ *
51
+ * ```ts
52
+ * import { best, type Run } from '@yaks/benchmark'
53
+ * import { equal } from '@yaks/testing'
54
+ *
55
+ * let run = (write: number, rate: number) => ({
56
+ * benches: [
57
+ * { name: 'write', better: 'lower', rounds: [{ median: write }] },
58
+ * { name: 'rate', better: 'higher', rounds: [{ median: rate }] },
59
+ * ].map((b) => ({ ...b, median: b.rounds[0].median })),
60
+ * }) as Run
61
+ * let one = best([run(12, 40), run(10, 30)])
62
+ * equal(one.benches.map((b) => b.median), [10, 40])
63
+ * equal(one.benches.map((b) => b.spread), [.2, .25])
64
+ * ```
65
+ */ export let best = (runs)=>{
66
+ let last = runs.at(-1);
67
+ if (!last) throw new Error('Expected at least one run');
68
+ let incomplete = runs.find(insufficient);
69
+ if (incomplete) return {
70
+ ...incomplete,
71
+ verdict: 'inconclusive'
72
+ };
73
+ let busy = runs.flatMap((r)=>r.busy ?? []);
74
+ return {
75
+ ...last,
76
+ busy: busy.length ? Math.max(...busy) : null,
77
+ benches: last.benches.map((b)=>{
78
+ let all = runs.map((r)=>r.benches.find((c)=>c.name == b.name));
79
+ let top = all.reduce((a, c)=>(b.better == 'lower' ? c.median < a.median : c.median > a.median) ? c : a);
80
+ let rounds = all.flatMap((r)=>r.rounds.map((round)=>round.median));
81
+ return {
82
+ ...top,
83
+ spread: spread(rounds, b.better)
84
+ };
85
+ })
86
+ };
87
+ };
88
+ export let validate = (base)=>{
89
+ if (base.version !== 1 || [
90
+ base.suite,
91
+ base.metric,
92
+ base.runtime,
93
+ base.cpu
94
+ ].some((s)=>typeof s != 'string' || !s) || ![
95
+ 'number',
96
+ 'string'
97
+ ].includes(typeof base.workload)) {
98
+ throw new Error('Invalid baseline metadata');
99
+ }
100
+ workload(base.workload);
101
+ tolerance(base.tolerance);
102
+ sameNames(base.benches, base.benches);
103
+ for (let b of base.benches){
104
+ value(b.median);
105
+ if (b.tolerance !== undefined) tolerance(b.tolerance);
106
+ if (![
107
+ 'lower',
108
+ 'higher'
109
+ ].includes(b.better)) {
110
+ throw new Error(`Missing direction: ${b.name}`);
111
+ }
112
+ }
113
+ };
114
+ let KEYS = [
115
+ 'version',
116
+ 'suite',
117
+ 'metric',
118
+ 'workload',
119
+ 'runtime',
120
+ 'cpu'
121
+ ];
122
+ /** The first piece of metadata that keeps a run from comparing with a
123
+ * baseline, or undefined when the two compare. */ export let incomparable = (base, current)=>KEYS.find((key)=>base[key] !== current[key]);
124
+ /// past(100, 'lower', 121, .2) -> true
125
+ /// past(100, 'lower', 120, .2) -> false
126
+ /// past(100, 'higher', 79, .2) -> true
127
+ /** Whether a figure is past a median by more than a slack, the wrong way. */ export let past = (median, better, figure, slack)=>better == 'lower' ? figure > median * (1 + slack) : figure < median * (1 - slack);
128
+ /** Bank one run, or several repeated runs of one suite, as a baseline. Each
129
+ * bench banks its best median and, as its slack, NOISE times the spread of
130
+ * its round medians, never under `allowed` and never over CAP. Against a
131
+ * previous baseline a bench moves only when its new median clears the noise
132
+ * of both, that is when the banked median would have regressed against it;
133
+ * otherwise it keeps its median and the wider slack. `slower` banks the
134
+ * measurement as it is, worse or not: every bench's, or only the named ones',
135
+ * leaving every other bench as it was banked. A run the box measured while
136
+ * loaded
137
+ * never banks, and a scoped acceptance retains the workloads it did not
138
+ * measure. */ export let baseline = (current, allowed, previous, slower = false)=>{
139
+ let runs = 'benches' in current ? [
140
+ current
141
+ ] : current;
142
+ let last = runs.at(-1);
143
+ if (!last) throw new Error('Expected at least one run to bank');
144
+ for (let run of runs){
145
+ if (insufficient(run)) throw new Error('Insufficient CPU sampling to bank');
146
+ let key = incomparable(last, run);
147
+ if (key) throw new Error(`Repeated runs differ in ${key}`);
148
+ sameNames(last.benches, run.benches);
149
+ quiet(run.suite, run);
150
+ }
151
+ if (previous) compare(previous, last, 'subset');
152
+ let floor = tolerance(allowed);
153
+ let one = runs.length == 1 ? last : best(runs);
154
+ let named = slower === true || !slower ? undefined : slower;
155
+ for (let name of named ?? []){
156
+ if (!one.benches.some((b)=>b.name == name)) {
157
+ throw new Error(`No bench to bank slower: ${name}`);
158
+ }
159
+ }
160
+ let banked = new Map(previous?.benches.map((b)=>[
161
+ b.name,
162
+ {
163
+ ...b,
164
+ ...b.reference ?? previous.reference ? {
165
+ reference: b.reference ?? previous.reference
166
+ } : {}
167
+ }
168
+ ]));
169
+ // A choice of cost for some benches is not an acceptance of the others.
170
+ let measuring = one.benches.filter((b)=>!named || named.includes(b.name) || !banked.has(b.name));
171
+ let out = {
172
+ version: last.version,
173
+ suite: last.suite,
174
+ metric: last.metric,
175
+ workload: last.workload,
176
+ runtime: last.runtime,
177
+ cpu: last.cpu,
178
+ tolerance: named && previous ? previous.tolerance : Math.min(floor, previous?.tolerance ?? floor),
179
+ benches: measuring.map((b)=>{
180
+ // Rounded up to a tenth of a percent, so a baseline reads plainly.
181
+ let noise = Math.ceil(NOISE * b.spread * 1000) / 1000;
182
+ let measured = Math.min(CAP, Math.max(floor, noise));
183
+ let old = slower === true || named?.includes(b.name) ? undefined : banked.get(b.name);
184
+ let wider = Math.min(CAP, Math.max(old?.tolerance ?? previous?.tolerance ?? 0, measured));
185
+ let kept = old && !past(b.median, b.better, old.median, wider) ? old : undefined;
186
+ return {
187
+ name: b.name,
188
+ unit: b.unit,
189
+ better: b.better,
190
+ median: kept?.median ?? b.median,
191
+ ...kept?.reference ?? (!kept ? one.commit : undefined) ? {
192
+ reference: kept?.reference ?? one.commit
193
+ } : {},
194
+ ...b.resolution !== undefined ? {
195
+ resolution: b.resolution
196
+ } : {},
197
+ tolerance: kept ? wider : measured
198
+ };
199
+ })
200
+ };
201
+ if (previous) {
202
+ let fresh = new Map(out.benches.map((b)=>[
203
+ b.name,
204
+ b
205
+ ]));
206
+ out.benches = [
207
+ ...previous.benches.map((b)=>fresh.get(b.name) ?? banked.get(b.name)),
208
+ ...out.benches.filter((b)=>!banked.has(b.name))
209
+ ];
210
+ }
211
+ let references = [
212
+ ...new Set(out.benches.map((b)=>b.reference))
213
+ ];
214
+ if (references.length == 1 && references[0]) out.reference = references[0];
215
+ validate(out);
216
+ return out;
217
+ };
218
+ /** A baseline banked on another runtime or CPU, banked again from one run on
219
+ * this one: each bench takes the run's median, with the wider of the slack it
220
+ * was banked with and the noise the run measured. */ export let rebased = (base, current)=>{
221
+ let out = baseline(current, base.tolerance);
222
+ let banked = new Map(base.benches.map((b)=>[
223
+ b.name,
224
+ b.tolerance
225
+ ]));
226
+ out.benches = out.benches.map((b)=>({
227
+ ...b,
228
+ tolerance: Math.min(CAP, Math.max(b.tolerance, banked.get(b.name) ?? 0))
229
+ }));
230
+ return out;
231
+ };
232
+ /** Whether every measured workload already has a banked reference. */ export let covered = (base, current)=>{
233
+ let banked = new Set(base.benches.map((b)=>b.name));
234
+ return current.benches.every((b)=>banked.has(b.name));
235
+ };
236
+ /** The figure a banked bench may reach before it has regressed: its median
237
+ * moved by its own slack, else the baseline's, or by NOISE times the `spread`
238
+ * the check itself measured where that is wider, so a figure must clear the
239
+ * noise of both measurements. Rounded to its resolution. */ export let limit = (base, b, spread = 0)=>{
240
+ let slack = Math.max(b.tolerance ?? base.tolerance, NOISE * spread);
241
+ let most = b.median * (b.better == 'lower' ? 1 + slack : Math.max(0, 1 - slack));
242
+ return b.resolution !== undefined ? Math.round(most / b.resolution) * b.resolution : most;
243
+ };
244
+ export let compare = (base, current, coverage = 'exact')=>{
245
+ if (insufficient(current)) {
246
+ throw new Error('Insufficient CPU sampling to compare');
247
+ }
248
+ if (![
249
+ 'exact',
250
+ 'subset'
251
+ ].includes(coverage)) {
252
+ throw new Error(`Unknown benchmark coverage: ${coverage}`);
253
+ }
254
+ validate(base);
255
+ let key = incomparable(base, current);
256
+ if (key) {
257
+ throw new Error(`Incomparable ${key}; explicitly accept a baseline on the target box`);
258
+ }
259
+ if (coverage == 'exact') sameNames(base.benches, current.benches);
260
+ else sameNames(current.benches, current.benches);
261
+ let prior = new Map(base.benches.map((b)=>[
262
+ b.name,
263
+ b
264
+ ]));
265
+ let out = [];
266
+ for (let b of current.benches){
267
+ value(b.median);
268
+ let old = prior.get(b.name);
269
+ if (!old) continue;
270
+ if (b.unit != old.unit || b.better != old.better || b.resolution !== old.resolution) {
271
+ throw new Error(`Incomparable unit/direction/resolution: ${b.name}`);
272
+ }
273
+ let most = limit(base, old, b.spread);
274
+ if (b.better == 'lower' ? b.median > most : b.median < most) {
275
+ out.push({
276
+ name: b.name,
277
+ unit: b.unit,
278
+ baseline: old.median,
279
+ ...old.reference ?? base.reference ? {
280
+ reference: old.reference ?? base.reference
281
+ } : {},
282
+ limit: most,
283
+ current: b.median,
284
+ change: old.median == 0 ? null : (b.median / old.median - 1) * (b.better == 'lower' ? 1 : -1)
285
+ });
286
+ }
287
+ }
288
+ return out;
289
+ };
290
+ //# sourceMappingURL=ratchet.js.map
package/ratchet.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ratchet.js","sources":["./ratchet.ts"],"names":[],"mappings":"AAAA;;;;;;;6BAO6B,GAC7B,SAGE,YAAY,EAGZ,SAAS,EACT,KAAK,EACL,QAAQ,sBACU;AAEpB,OAAO,IAAI,YAAY,CAAC;EACtB,IAAI,CAAC,OAAO,QAAQ,CAAC,MAAM,IAAI,KAAK,KAAK,GAAG;IAC1C,MAAM,IAAI,MAAM;EAClB;EACA,OAAO;AACT,EAAC;AAED,0EAA0E,GAC1E,OAAO,IAAI,QAAQ,EAAC;AACpB,wEAAwE,GACxE,OAAO,IAAI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,IAC5C,EAAE,UAAU,KAAK,IAAI,UAAU,EAC/B;MACA,MAAM,IAAI,MAAM,CAAC,wCAAwC,EAAE,EAAE,IAAI,EAAE;IACrE;IACA,IAAI,OAAO,MAAM,MAAM,KAAK,EAAE,MAAM;IACpC,IAAI,EAAE,MAAM,IAAI,UAAU,EAAE,MAAM,GAAG,OAAO,EAAE,MAAM,GAAG,MAAM;MAC3D,IAAI,IAAI,CAAC;QACP,MAAM,EAAE,IAAI;QACZ,MAAM,EAAE,IAAI;QACZ,UAAU,IAAI,MAAM;QACpB,GAAG,AAAC,IAAI,SAAS,IAAI,KAAK,SAAS,GAC/B;UAAE,WAAW,IAAI,SAAS,IAAI,KAAK,SAAS;QAAC,IAC7C,CAAC,CAAC;QACN,OAAO;QACP,SAAS,EAAE,MAAM;QACjB,QAAQ,IAAI,MAAM,IAAI,IAClB,OACA,CAAC,EAAE,MAAM,GAAG,IAAI,MAAM,GAAG,CAAC,IAAI,CAAC,EAAE,MAAM,IAAI,UAAU,IAAI,CAAC,CAAC;MACjE;IACF;EACF;EACA,OAAO;AACT,EAAC"}
package/ratchet.ts ADDED
@@ -0,0 +1,341 @@
1
+ /** The pure ratchet compares compatible suite measurements. A baseline is a
2
+ * value with its own slack; accepting it is an explicit runner operation.
3
+ * A figure counts only where it clears the noise. A regression is a figure
4
+ * past its reference by more than the noise of both measurements; a baseline
5
+ * moves toward better only by as much, and never on a run the box measured
6
+ * while loaded. Banking worse numbers is a separate, explicit choice
7
+ * (`slower`, for the whole suite or the benches it names), never what an
8
+ * ordinary acceptance does. */
9
+ import {
10
+ type Baseline,
11
+ type Direction,
12
+ insufficient,
13
+ type Regression,
14
+ type Run,
15
+ sameNames,
16
+ value,
17
+ workload,
18
+ } from './result.js'
19
+
20
+ export let tolerance = (n: number): number => {
21
+ if (!Number.isFinite(n) || n < 0 || n >= 1) {
22
+ throw new Error('Tolerance must be in [0, 1)')
23
+ }
24
+ return n
25
+ }
26
+
27
+ /** A bench's slack is this many times the spread its measurement showed. */
28
+ export let NOISE = 2
29
+ /** The most slack noise can earn a bench; a tolerance stays under one. */
30
+ export let CAP = .95
31
+ /** A run is loaded when other work used more than this share of the box's
32
+ * CPUs while the bench rested before a round. Measured on four hyperthreads:
33
+ * one busy costs a CPU-bound bench a few percent, two about a tenth. */
34
+ export let BUSY = .25
35
+
36
+ /// loaded({ busy: .5 }) -> true
37
+ /// loaded({ busy: .25 }) -> false
38
+ /// loaded({ busy: null }) -> false
39
+ /** Whether the box was loaded while a run measured. A loaded run confirms no
40
+ * regression and banks no baseline: its figures carry the other work. */
41
+ export let loaded = (run: Pick<Run, 'busy'>): boolean => (run.busy ?? 0) > BUSY
42
+
43
+ /** Refuses to bank what a loaded box measured. */
44
+ export let quiet = (suite: string, run: Pick<Run, 'busy'>): void => {
45
+ if (loaded(run)) {
46
+ throw new Error(
47
+ `${suite} cannot bank on a loaded box: other work used ${
48
+ Math.round(run.busy! * 100)
49
+ }% of its CPUs`,
50
+ )
51
+ }
52
+ }
53
+
54
+ /** How far apart repeated medians of one bench fall, as a fraction of the
55
+ * best of them: the noise a figure carries, which a check has to allow.
56
+ *
57
+ * ```ts
58
+ * import { spread } from '@yaks/benchmark'
59
+ * import { equal } from '@yaks/testing'
60
+ *
61
+ * equal(spread([100, 104, 110], 'lower'), .1)
62
+ * equal(spread([80, 100], 'higher'), .2)
63
+ * equal(spread([5], 'lower'), 0)
64
+ * ```
65
+ */
66
+ export let spread = (medians: readonly number[], better: Direction): number => {
67
+ let low = Math.min(...medians.map(value)), high = Math.max(...medians)
68
+ let best = better == 'lower' ? low : high
69
+ return best == 0 ? 0 : (high - low) / best
70
+ }
71
+
72
+ /** Repeated runs of one suite as one run: each bench as the run that measured
73
+ * it best, the median acceptance banks, so a check compares like for like,
74
+ * with the spread of every round median the runs took between them, and the
75
+ * busiest box any of them saw.
76
+ *
77
+ * ```ts
78
+ * import { best, type Run } from '@yaks/benchmark'
79
+ * import { equal } from '@yaks/testing'
80
+ *
81
+ * let run = (write: number, rate: number) => ({
82
+ * benches: [
83
+ * { name: 'write', better: 'lower', rounds: [{ median: write }] },
84
+ * { name: 'rate', better: 'higher', rounds: [{ median: rate }] },
85
+ * ].map((b) => ({ ...b, median: b.rounds[0].median })),
86
+ * }) as Run
87
+ * let one = best([run(12, 40), run(10, 30)])
88
+ * equal(one.benches.map((b) => b.median), [10, 40])
89
+ * equal(one.benches.map((b) => b.spread), [.2, .25])
90
+ * ```
91
+ */
92
+ export let best = (runs: readonly Run[]): Run => {
93
+ let last = runs.at(-1)
94
+ if (!last) throw new Error('Expected at least one run')
95
+ let incomplete = runs.find(insufficient)
96
+ if (incomplete) return { ...incomplete, verdict: 'inconclusive' }
97
+ let busy = runs.flatMap((r) => r.busy ?? [])
98
+ return {
99
+ ...last,
100
+ busy: busy.length ? Math.max(...busy) : null,
101
+ benches: last.benches.map((b) => {
102
+ let all = runs.map((r) => r.benches.find((c) => c.name == b.name)!)
103
+ let top = all.reduce((a, c) =>
104
+ (b.better == 'lower' ? c.median < a.median : c.median > a.median)
105
+ ? c
106
+ : a
107
+ )
108
+ let rounds = all.flatMap((r) => r.rounds.map((round) => round.median))
109
+ return { ...top, spread: spread(rounds, b.better) }
110
+ }),
111
+ }
112
+ }
113
+
114
+ export let validate = (base: Baseline): void => {
115
+ if (
116
+ base.version !== 1 ||
117
+ [base.suite, base.metric, base.runtime, base.cpu].some((s) =>
118
+ typeof s != 'string' || !s
119
+ ) ||
120
+ !['number', 'string'].includes(typeof base.workload)
121
+ ) {
122
+ throw new Error('Invalid baseline metadata')
123
+ }
124
+ workload(base.workload)
125
+ tolerance(base.tolerance)
126
+ sameNames(base.benches, base.benches)
127
+ for (let b of base.benches) {
128
+ value(b.median)
129
+ if (b.tolerance !== undefined) tolerance(b.tolerance)
130
+ if (!['lower', 'higher'].includes(b.better)) {
131
+ throw new Error(`Missing direction: ${b.name}`)
132
+ }
133
+ }
134
+ }
135
+
136
+ let KEYS = ['version', 'suite', 'metric', 'workload', 'runtime', 'cpu'] as const
137
+ type Key = typeof KEYS[number]
138
+ /** The first piece of metadata that keeps a run from comparing with a
139
+ * baseline, or undefined when the two compare. */
140
+ export let incomparable = (
141
+ base: Pick<Baseline, Key>,
142
+ current: Pick<Run, Key>,
143
+ ): Key | undefined => KEYS.find((key) => base[key] !== current[key])
144
+
145
+ /// past(100, 'lower', 121, .2) -> true
146
+ /// past(100, 'lower', 120, .2) -> false
147
+ /// past(100, 'higher', 79, .2) -> true
148
+ /** Whether a figure is past a median by more than a slack, the wrong way. */
149
+ export let past = (
150
+ median: number,
151
+ better: Direction,
152
+ figure: number,
153
+ slack: number,
154
+ ): boolean =>
155
+ better == 'lower'
156
+ ? figure > median * (1 + slack)
157
+ : figure < median * (1 - slack)
158
+
159
+ /** Bank one run, or several repeated runs of one suite, as a baseline. Each
160
+ * bench banks its best median and, as its slack, NOISE times the spread of
161
+ * its round medians, never under `allowed` and never over CAP. Against a
162
+ * previous baseline a bench moves only when its new median clears the noise
163
+ * of both, that is when the banked median would have regressed against it;
164
+ * otherwise it keeps its median and the wider slack. `slower` banks the
165
+ * measurement as it is, worse or not: every bench's, or only the named ones',
166
+ * leaving every other bench as it was banked. A run the box measured while
167
+ * loaded
168
+ * never banks, and a scoped acceptance retains the workloads it did not
169
+ * measure. */
170
+ export let baseline = (
171
+ current: Run | readonly Run[],
172
+ allowed: number,
173
+ previous?: Baseline,
174
+ slower: boolean | readonly string[] = false,
175
+ ): Baseline => {
176
+ let runs: readonly Run[] = 'benches' in current ? [current] : current
177
+ let last = runs.at(-1)
178
+ if (!last) throw new Error('Expected at least one run to bank')
179
+ for (let run of runs) {
180
+ if (insufficient(run)) throw new Error('Insufficient CPU sampling to bank')
181
+ let key = incomparable(last, run)
182
+ if (key) throw new Error(`Repeated runs differ in ${key}`)
183
+ sameNames(last.benches, run.benches)
184
+ quiet(run.suite, run)
185
+ }
186
+ if (previous) compare(previous, last, 'subset')
187
+ let floor = tolerance(allowed)
188
+ let one = runs.length == 1 ? last : best(runs)
189
+ let named = slower === true || !slower ? undefined : slower
190
+ for (let name of named ?? []) {
191
+ if (!one.benches.some((b) => b.name == name)) {
192
+ throw new Error(`No bench to bank slower: ${name}`)
193
+ }
194
+ }
195
+ let banked = new Map(
196
+ previous?.benches.map((b) => [b.name, {
197
+ ...b,
198
+ ...(b.reference ?? previous.reference)
199
+ ? { reference: b.reference ?? previous.reference }
200
+ : {},
201
+ }]),
202
+ )
203
+ // A choice of cost for some benches is not an acceptance of the others.
204
+ let measuring = one.benches.filter((b) =>
205
+ !named || named.includes(b.name) || !banked.has(b.name)
206
+ )
207
+ let out: Baseline = {
208
+ version: last.version,
209
+ suite: last.suite,
210
+ metric: last.metric,
211
+ workload: last.workload,
212
+ runtime: last.runtime,
213
+ cpu: last.cpu,
214
+ tolerance: named && previous
215
+ ? previous.tolerance
216
+ : Math.min(floor, previous?.tolerance ?? floor),
217
+ benches: measuring.map((b) => {
218
+ // Rounded up to a tenth of a percent, so a baseline reads plainly.
219
+ let noise = Math.ceil(NOISE * b.spread * 1000) / 1000
220
+ let measured = Math.min(CAP, Math.max(floor, noise))
221
+ let old = slower === true || named?.includes(b.name)
222
+ ? undefined
223
+ : banked.get(b.name)
224
+ let wider = Math.min(
225
+ CAP,
226
+ Math.max(old?.tolerance ?? previous?.tolerance ?? 0, measured),
227
+ )
228
+ let kept = old && !past(b.median, b.better, old.median, wider)
229
+ ? old
230
+ : undefined
231
+ return {
232
+ name: b.name,
233
+ unit: b.unit,
234
+ better: b.better,
235
+ median: kept?.median ?? b.median,
236
+ ...(kept?.reference ?? (!kept ? one.commit : undefined))
237
+ ? { reference: kept?.reference ?? one.commit! }
238
+ : {},
239
+ ...(b.resolution !== undefined ? { resolution: b.resolution } : {}),
240
+ tolerance: kept ? wider : measured,
241
+ }
242
+ }),
243
+ }
244
+ if (previous) {
245
+ let fresh = new Map(out.benches.map((b) => [b.name, b]))
246
+ out.benches = [
247
+ ...previous.benches.map((b) => fresh.get(b.name) ?? banked.get(b.name)!),
248
+ ...out.benches.filter((b) => !banked.has(b.name)),
249
+ ]
250
+ }
251
+ let references = [...new Set(out.benches.map((b) => b.reference))]
252
+ if (references.length == 1 && references[0]) out.reference = references[0]
253
+ validate(out)
254
+ return out
255
+ }
256
+ /** A baseline banked on another runtime or CPU, banked again from one run on
257
+ * this one: each bench takes the run's median, with the wider of the slack it
258
+ * was banked with and the noise the run measured. */
259
+ export let rebased = (base: Baseline, current: Run): Baseline => {
260
+ let out = baseline(current, base.tolerance)
261
+ let banked = new Map(base.benches.map((b) => [b.name, b.tolerance]))
262
+ out.benches = out.benches.map((b) => ({
263
+ ...b,
264
+ tolerance: Math.min(CAP, Math.max(b.tolerance!, banked.get(b.name) ?? 0)),
265
+ }))
266
+ return out
267
+ }
268
+
269
+ export type Coverage = 'exact' | 'subset'
270
+ /** Whether every measured workload already has a banked reference. */
271
+ export let covered = (base: Baseline, current: Run): boolean => {
272
+ let banked = new Set(base.benches.map((b) => b.name))
273
+ return current.benches.every((b) => banked.has(b.name))
274
+ }
275
+ /** The figure a banked bench may reach before it has regressed: its median
276
+ * moved by its own slack, else the baseline's, or by NOISE times the `spread`
277
+ * the check itself measured where that is wider, so a figure must clear the
278
+ * noise of both measurements. Rounded to its resolution. */
279
+ export let limit = (
280
+ base: Baseline,
281
+ b: Baseline['benches'][number],
282
+ spread = 0,
283
+ ): number => {
284
+ let slack = Math.max(b.tolerance ?? base.tolerance, NOISE * spread)
285
+ let most = b.median *
286
+ (b.better == 'lower' ? 1 + slack : Math.max(0, 1 - slack))
287
+ return b.resolution !== undefined
288
+ ? Math.round(most / b.resolution) * b.resolution
289
+ : most
290
+ }
291
+ export let compare = (
292
+ base: Baseline,
293
+ current: Run,
294
+ coverage: Coverage = 'exact',
295
+ ): Regression[] => {
296
+ if (insufficient(current)) {
297
+ throw new Error('Insufficient CPU sampling to compare')
298
+ }
299
+ if (!['exact', 'subset'].includes(coverage)) {
300
+ throw new Error(`Unknown benchmark coverage: ${coverage}`)
301
+ }
302
+ validate(base)
303
+ let key = incomparable(base, current)
304
+ if (key) {
305
+ throw new Error(
306
+ `Incomparable ${key}; explicitly accept a baseline on the target box`,
307
+ )
308
+ }
309
+ if (coverage == 'exact') sameNames(base.benches, current.benches)
310
+ else sameNames(current.benches, current.benches)
311
+ let prior = new Map(base.benches.map((b) => [b.name, b]))
312
+ let out: Regression[] = []
313
+ for (let b of current.benches) {
314
+ value(b.median)
315
+ let old = prior.get(b.name)
316
+ if (!old) continue
317
+ if (
318
+ b.unit != old.unit || b.better != old.better ||
319
+ b.resolution !== old.resolution
320
+ ) {
321
+ throw new Error(`Incomparable unit/direction/resolution: ${b.name}`)
322
+ }
323
+ let most = limit(base, old, b.spread)
324
+ if (b.better == 'lower' ? b.median > most : b.median < most) {
325
+ out.push({
326
+ name: b.name,
327
+ unit: b.unit,
328
+ baseline: old.median,
329
+ ...(old.reference ?? base.reference)
330
+ ? { reference: old.reference ?? base.reference }
331
+ : {},
332
+ limit: most,
333
+ current: b.median,
334
+ change: old.median == 0
335
+ ? null
336
+ : (b.median / old.median - 1) * (b.better == 'lower' ? 1 : -1),
337
+ })
338
+ }
339
+ }
340
+ return out
341
+ }