@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/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Jeff Peterson
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,458 @@
1
- # Temporary Holding Version
1
+ # @yaks/benchmark
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Named workloads, raw samples, JSON runs and explicit baseline ratchets, with
4
+ process-configured reporters.
5
+
6
+ A **bench** is a named workload with a unit, such as `apply` in `ns/op`. A
7
+ **sample** is one measured value, with optional counts and provenance. A
8
+ **round** collects samples from every bench. A **suite** names a set of benches,
9
+ its aggregation metric and its workload version. A **run** keeps the samples,
10
+ round medians, median of round medians, commit, runtime, CPU, load average and
11
+ how busy the box was. A **baseline** is a committed JSON file for one suite,
12
+ with a tolerance: `0.2` allows a 20% deterioration. A **reporter** receives a
13
+ completed run after its JSON has been written.
14
+
15
+ ## Writing a bench
16
+
17
+ `bench()` times sync or async callbacks. `iterations` keeps separate invocation
18
+ samples; `operations` divides each invocation's time by its operation count.
19
+ Setup and teardown run outside the timed interval for every invocation. A unit
20
+ with a denominator, such as `ns/op`, `ns/bundle` or `us/value`, permits
21
+ operation normalization.
22
+
23
+ ```ts
24
+ import { bench, run } from '@yaks/benchmark'
25
+ import { equal, ok } from '@yaks/testing'
26
+
27
+ let calls = 0
28
+ let suite = {
29
+ name: 'arithmetic',
30
+ metric: 'median-of-round-medians',
31
+ workload: 1,
32
+ benches: [bench({
33
+ name: 'increment',
34
+ unit: 'ns/op',
35
+ iterations: 4,
36
+ operations: 10,
37
+ run: () => {
38
+ for (let i = 0; i < 10; i++) calls++
39
+ },
40
+ })],
41
+ }
42
+ let directory = await Deno.makeTempDir()
43
+ try {
44
+ let result = await run(suite, {
45
+ rounds: 3,
46
+ output: directory + '/arithmetic.results.json',
47
+ })
48
+ equal(calls, 120)
49
+ equal(result.benches[0].samples.length, 12)
50
+ equal(result.benches[0].rounds.length, 3)
51
+ ok(result.benches[0].median >= 0)
52
+ equal(
53
+ JSON.parse(await Deno.readTextFile(directory + '/arithmetic.results.json'))
54
+ .suite,
55
+ 'arithmetic',
56
+ )
57
+ } finally {
58
+ await Deno.remove(directory, { recursive: true })
59
+ }
60
+ ```
61
+
62
+ Run bench files separately with `deno run -A path/to/bench.ts`; importing a
63
+ definition registers no test and executes no workload. Bench measurements belong
64
+ outside the test suite. An invocation's return value is ignored; a returned
65
+ Promise is awaited. A bench that times a batch uses `operations` for the number
66
+ of operations in that batch.
67
+
68
+ ## Externally measured samples
69
+
70
+ For a script that already measures a phase, batch, ratio or cost, write a
71
+ `Bench` with `sample(round)` instead of a timed callback. It returns a number, a
72
+ sample or an array of samples. Units are arbitrary strings; `better` is `lower`
73
+ by default and can be `higher` for throughput.
74
+
75
+ ```ts
76
+ import type { Bench } from '@yaks/benchmark'
77
+ import { equal } from '@yaks/testing'
78
+
79
+ let relay: Bench = {
80
+ name: 'relay/10-entities',
81
+ unit: 'us/value',
82
+ sample: (round) => ({
83
+ value: [12, 10, 11][round],
84
+ counts: { values: 2000, statements: 4000 },
85
+ source: 'batch',
86
+ }),
87
+ }
88
+ equal(await relay.sample(1), {
89
+ value: 10,
90
+ counts: { values: 2000, statements: 4000 },
91
+ source: 'batch',
92
+ })
93
+ ```
94
+
95
+ A `CollectedSuite` supplies `collect(round)` and workload names and units. Its
96
+ collector returns a map of samples for exactly those names, allowing one child
97
+ process to measure several benches. Missing, extra and duplicate names fail. A
98
+ suite can supply `close()` to dispose persistent collectors; the runner calls it
99
+ after measurement, including on failure.
100
+
101
+ `@yaks/benchmark/deno` imports reports from a CPU-aware Deno workload collector.
102
+ Each result supplies its wall average (`avg`) and CPU average (`cpu`), both in
103
+ ns/op:
104
+
105
+ ```ts
106
+ import { extract } from '@yaks/benchmark/deno'
107
+ import { equal } from '@yaks/testing'
108
+
109
+ let imported = extract({
110
+ version: 1,
111
+ runtime: 'test-runtime',
112
+ cpu: 'test-cpu',
113
+ benches: [{ name: 'read', results: [{ ok: { avg: 42, cpu: 30, n: 100 } }] }],
114
+ }, ['read'])
115
+ equal(imported.read.value, 42)
116
+ equal(imported.read.cpu, 30)
117
+ equal(imported.read.source, 'deno-cpu-average')
118
+ equal(imported.read.details, { avg: 42, cpu: 30, n: 100 })
119
+ ```
120
+
121
+ The collector supplies batch averages and statistics, not individual invocation
122
+ timings. These samples retain that provenance and their statistics; they cannot
123
+ reconstruct the distribution of operation times. Native timed benches keep every
124
+ invocation sample. All samples must be finite and nonnegative; imported wall
125
+ averages must be positive and imported CPU averages are required. Native
126
+ `deno bench --json` output lacks the CPU average and cannot be imported.
127
+
128
+ ## CPU time
129
+
130
+ `cpu` is the CPU time a step took, in the bench's unit: this process and its
131
+ finished children, every thread, user and system (`cputime()`, getrusage(2) on
132
+ Linux and macOS). `bench()` records it automatically; external collectors spread
133
+ a `stopwatch()` reading into each sample. `run(suite, { figure: 'cpu', ... })`
134
+ requires CPU in every sample and judges its median. Raw `value` retains wall
135
+ time for diagnostics; the result's metric gains a `/cpu` suffix so it cannot
136
+ compare against a baseline of wall values. Missing CPU never falls back to wall
137
+ time. CPU accounting requires getrusage(2) on Linux or macOS; other platforms,
138
+ including Windows, fail explicitly. CPU runs record load averages without
139
+ waiting to sample host pressure.
140
+
141
+ `threadtime()` is the calling thread's CPU time (clock_gettime(2)'s
142
+ `CLOCK_THREAD_CPUTIME_ID`) and the same finished children: `cputime()` without
143
+ the process's other threads. V8 compiles, collects garbage and runs blocking I/O
144
+ on those threads whenever it likes, so a reading of a short span taken with
145
+ `cputime()` can carry work started long before it; the test runner
146
+ (@yaks/testing) times each test with `threadtime()`.
147
+
148
+ ```ts
149
+ import { type Sample, stopwatch } from '@yaks/benchmark'
150
+ import { ok } from '@yaks/testing'
151
+
152
+ let took = stopwatch()
153
+ let x = 0
154
+ for (let i = 0; i < 1e4; i++) x += i
155
+ let sample: Sample = { ...took(), source: 'end-to-end' }
156
+ ok(x > 0 && sample.value >= 0 && (sample.cpu ?? 0) >= 0)
157
+ ```
158
+
159
+ A child counts once it has exited and been waited for. A long-lived server
160
+ reports its own CPU at the measured boundaries. `stopwatch(...sources)` adds
161
+ synchronous CPU counters for other processes or cgroups to the caller's CPU;
162
+ `processCpu(pid)` reads a Linux process tree, including every live thread and
163
+ reaped children. Keep the observed process alive across both readings. Pure
164
+ waiting remains diagnostic rather than a CPU benchmark.
165
+
166
+ ## Runner and ratchet
167
+
168
+ `run()` writes a result in all three modes. `check` reads the committed baseline
169
+ and throws `Regressed` after writing and reporting a failed run. `accept` writes
170
+ a baseline only when explicitly requested, with an explicit tolerance. Commit
171
+ and review that file. A missing or malformed baseline fails a check before any
172
+ work runs. A check never changes the baseline or overrides its tolerance.
173
+
174
+ A sample can carry `sampling` with `status: 'insufficient'`, its required
175
+ `minimum`, measured CPU (`measured`) and whole-invocation CPU (`outer`), all in
176
+ milliseconds. Such a run is `inconclusive` in every mode: its observations are
177
+ saved, no regression is reported, and acceptance leaves the baseline unchanged.
178
+ Fixture work cannot substitute for the measured CPU required by a sampling
179
+ policy.
180
+
181
+ A figure counts only where it clears the noise. A bench's **spread** is how far
182
+ apart its round medians fell, across every run of the measurement, as a fraction
183
+ of the best (`spread()`). With `runs: n`, a run measures the suite n times over
184
+ and keeps each bench's `best()` median and the spread of all its rounds.
185
+ Acceptance banks each bench with a **slack** of its own: `NOISE` (2) times its
186
+ spread, never under the explicit tolerance and never over `CAP` (0.95). A count
187
+ that never varies banks no slack, so any change to it counts. A check holds each
188
+ bench to its banked slack, or to `NOISE` times the spread the check itself
189
+ measured where that is wider, so a regression is a figure past the noise of both
190
+ measurements; each regression carries the `limit()` it passed.
191
+
192
+ A baseline moves only toward better, and only past the noise: `accept` banks a
193
+ bench's new median where the banked one would have regressed against it, and
194
+ otherwise keeps the banked median with the wider of the two slacks.
195
+ `slower: true` banks the measurement as it is, which is a decision about the
196
+ product, not a measurement; `slower: ['close']` makes that decision for the
197
+ named benches only, and every other bench stays as banked. A baseline banked on
198
+ another runtime, CPU or workload version is no reference, and an exact
199
+ acceptance banks the suite as measured. A check against a baseline banked on
200
+ another runtime or CPU is measured, not judged; with `local`, its run banks
201
+ there as this box's own baseline (`rebased()`: each bench's median, with the
202
+ wider of its banked slack and the run's noise), and later checks on this runtime
203
+ and CPU are judged by it. `bench/run.ts check` keeps it in
204
+ `~/.cache/yak/bench/`, so the committed baseline and the checkout stay as they
205
+ are.
206
+
207
+ Each baseline bench can retain a `reference` commit for its median. Acceptance
208
+ stamps a changed median with the measured run's commit and preserves the
209
+ reference of every retained median, including benches outside a scoped
210
+ acceptance. A baseline with one shared reference also keeps it at the top level;
211
+ that field remains the fallback for older baselines without bench references.
212
+
213
+ When judging `value`, a run is **loaded** when other work used more than `BUSY`
214
+ (a quarter) of the box's CPUs (`loaded()`). Before each round of a check or an
215
+ acceptance, inside the lock, the runner samples a second of the box while the
216
+ bench rests (`busy()`, from the cgroup's CPU use, a container's own) and keeps
217
+ the most as the run's `busy`, so the bench's own work, and what it asks of a
218
+ server, never counts against it; where the box does not say, it is null and
219
+ nothing is loaded. It is use, not CPU pressure: a busy hyperthread slows the
220
+ work on its sibling without making anything wait for a CPU. A loaded run banks
221
+ nothing, and a loaded check past its limit is `loaded`, not `regressed`: it can
222
+ tell nothing either way. A box's load average says less: a container's often
223
+ reads its host's.
224
+
225
+ CPU runs skip that host-pressure sampling and use CPU measurements directly.
226
+ `waited()` exposes the calling thread's Linux scheduling delay as a separate
227
+ diagnostic; it does not measure CPU usage.
228
+
229
+ ```ts
230
+ import { type Files, type Host, Regressed, run } from '@yaks/benchmark'
231
+ import { equal, ok, throws } from '@yaks/testing'
232
+
233
+ let cost = 100
234
+ let suite = {
235
+ name: 'cost',
236
+ metric: 'median-of-round-medians',
237
+ workload: 1,
238
+ benches: [{ name: 'write', unit: 'ms', sample: () => cost }],
239
+ }
240
+ let saved = new Map<string, string>()
241
+ let files: Files = {
242
+ read: async (path) => {
243
+ if (!saved.has(path)) throw new Deno.errors.NotFound(path)
244
+ return saved.get(path)!
245
+ },
246
+ write: async (path, value) => void saved.set(path, JSON.stringify(value)),
247
+ }
248
+ let read = (path: string) => JSON.parse(saved.get(path)!)
249
+ let options = {
250
+ output: 'cost.results.json',
251
+ baseline: 'cost.baseline.json',
252
+ files,
253
+ rounds: 1,
254
+ // An idle box, so the example never depends on what else this one runs.
255
+ host: (): Host => ({
256
+ config: {},
257
+ configURL: null,
258
+ commit: null,
259
+ runtime: 'example',
260
+ cpu: 'example',
261
+ load: [0, 0, 0],
262
+ }),
263
+ }
264
+ await run(suite, { ...options, mode: 'accept', tolerance: 0.2 })
265
+ equal((await run(suite, { ...options, mode: 'check' })).verdict, 'passed')
266
+ cost = 130
267
+ let error = await throws(() => run(suite, { ...options, mode: 'check' }))
268
+ ok(error instanceof Regressed)
269
+ equal(read(options.output).verdict, 'regressed')
270
+ equal(read(options.baseline).benches[0].median, 100)
271
+ ```
272
+
273
+ A scoped run measures part of a suite, and a resolution rounds the limit:
274
+
275
+ ```ts
276
+ import { type Files, run } from '@yaks/benchmark'
277
+ import { equal } from '@yaks/testing'
278
+
279
+ let saved = new Map<string, string>()
280
+ let files: Files = {
281
+ read: async (path) => {
282
+ if (!saved.has(path)) throw new Deno.errors.NotFound(path)
283
+ return saved.get(path)!
284
+ },
285
+ write: async (path, value) => void saved.set(path, JSON.stringify(value)),
286
+ }
287
+ let suite = (name: string, sample: () => number, resolution?: number) => ({
288
+ name: 'cost',
289
+ metric: 'median-of-round-medians',
290
+ workload: 1,
291
+ benches: [{ name, unit: 'ms', resolution, sample }],
292
+ })
293
+ let options = (baseline: string) => ({
294
+ output: 'cost.results.json',
295
+ baseline,
296
+ files,
297
+ rounds: 1,
298
+ host: () => ({
299
+ config: {},
300
+ configURL: null,
301
+ commit: null,
302
+ runtime: 'example',
303
+ cpu: 'example',
304
+ load: [0, 0, 0],
305
+ }),
306
+ })
307
+ let base = options('cost.baseline.json')
308
+ await run(suite('write', () => 100), { ...base, mode: 'accept', tolerance: .2 })
309
+ let subset = { ...base, coverage: 'subset' as const }
310
+ let scoped = suite('read', () => 50)
311
+ equal((await run(scoped, { ...subset, mode: 'check' })).verdict, 'measured')
312
+ await run(scoped, { ...subset, mode: 'accept', tolerance: 0.2 })
313
+ equal(
314
+ JSON.parse(saved.get(base.baseline)!).benches.map((b: { name: string }) =>
315
+ b.name
316
+ ),
317
+ ['write', 'read'],
318
+ )
319
+ let duration = 2106
320
+ let rounded = suite('deploy', () => duration, 1)
321
+ let precise = options('rounded.baseline.json')
322
+ await run(rounded, { ...precise, mode: 'accept', tolerance: 0.25 })
323
+ duration = 2633
324
+ equal((await run(rounded, { ...precise, mode: 'check' })).verdict, 'passed')
325
+ ```
326
+
327
+ Compatibility includes suite, metric, workload version, runtime, CPU, bench
328
+ names, units, directions and resolution. Equality at the tolerance boundary
329
+ passes. Change the workload version when the corpus or timed boundary changes.
330
+ `baseline()`, `best()`, `compare()`, `limit()`, `loaded()` and `spread()` expose
331
+ the same ratchet as pure functions.
332
+
333
+ A bench's optional **resolution** declares its sample precision in the bench's
334
+ unit. It must be finite and positive. The ratchet rounds the tolerance boundary
335
+ to the nearest multiple of that resolution, leaving samples and banked medians
336
+ unchanged. For example, `resolution: 1` with `unit: 'ms'` rounds a 2632.5 ms
337
+ limit to 2633 ms. Without a resolution the boundary is unrounded. Baseline and
338
+ current bench resolutions must match.
339
+
340
+ `coverage: 'subset'` permits a run to observe only part of a suite, such as one
341
+ host's deployment measurements. It compares the measured benches that have a
342
+ baseline; if any measured bench is unbanked, a run without regressions is
343
+ `measured` rather than `passed`. Acceptance retains baseline benches outside the
344
+ observation, with matching suite, metric, workload, runtime and CPU. Exact
345
+ coverage is the default and rejects any changed bench set. `baseline()` accepts
346
+ an optional previous baseline to retain unmeasured benches; `compare()` accepts
347
+ the coverage as its third argument.
348
+
349
+ `lock` optionally names a box-wide flock file, shared across worktrees and
350
+ compatible with shell `flock`. Never unlink it. Each round holds the lock
351
+ through its fixture cleanup, then releases it so a queued suite can measure.
352
+ Publishing results and banking a baseline also take the lock and reread the
353
+ latest baseline, so an acceptance cannot undo a faster one banked between
354
+ rounds. Measurements run sequentially; the lock cannot prevent contention from
355
+ programs that do not take it.
356
+
357
+ ## Recorded spans
358
+
359
+ Timed benches use [record()](../trace/README.md) for each invocation. Set
360
+ `target` to the observed object, such as a graph, to record its operation's
361
+ tree. The operation's root must begin synchronously, as `record()` requires.
362
+ Only that root and its descendants are captured: a callback making several
363
+ independent graph calls records the first call's tree. Without a target, the
364
+ tree contains a `bench` span for the invocation. Setup and teardown are outside
365
+ the recording as well as outside timing.
366
+
367
+ ```ts
368
+ import { bench } from '@yaks/benchmark'
369
+ import { during, peek } from '@yaks/trace'
370
+ import { equal } from '@yaks/testing'
371
+
372
+ let target = {}
373
+ let work = bench({
374
+ name: 'apply',
375
+ unit: 'ms',
376
+ target,
377
+ run: () =>
378
+ during(peek(target)?.begin({ kind: 'apply', name: 'apply' }), () => 1),
379
+ })
380
+ let samples = await work.sample(0)
381
+ equal(Array.isArray(samples) && samples[0].spans?.[0].name, 'apply')
382
+ ```
383
+
384
+ Each round keeps the middle sample's tree; each bench result keeps the middle
385
+ round's tree. For an even count the numeric median averages the two middle
386
+ values, and the tree belongs to the upper middle value. Samples without a
387
+ recording have a `null` tree in the run. Recording enables subscribed trace
388
+ instrumentation on the target, so its cost is included in the workload timing.
389
+
390
+ ## Process reporters
391
+
392
+ The runtime boundary reads `$YAK_CONFIG`, else `~/.yak/yak.json`, on each run.
393
+ With no host config it uses an empty config. An explicitly named missing config
394
+ fails. The default reporter factory returns no reporters, so runs write JSON
395
+ only. Provider integration belongs at this boundary, never in bench modules.
396
+
397
+ `configure(factory)` installs a factory for the process. It receives the current
398
+ host config, config URL, commit and machine metadata. Relative provider paths
399
+ can be resolved against `host.configURL`. It returns an undo function for
400
+ temporary installations. `run({…}, {reporters: factory})` overrides the factory
401
+ for an embedding host. The run's JSON is written before every reporter receives
402
+ it, including a regression. Reporters receive an immutable snapshot of the saved
403
+ JSON. A failed factory or reporter is logged and does not prevent other
404
+ reporters from receiving the run or change the ratchet verdict.
405
+
406
+ ```ts
407
+ import { configure, type Host, run } from '@yaks/benchmark'
408
+ import { equal } from '@yaks/testing'
409
+
410
+ let delivered: string[] = []
411
+ let context: Host = {
412
+ config: { destination: 'first' },
413
+ configURL: null,
414
+ commit: 'abc',
415
+ runtime: 'test',
416
+ cpu: 'test',
417
+ load: [0, 0, 0],
418
+ }
419
+ let undo = configure((host) => [() => {
420
+ delivered.push(String(host.config.destination))
421
+ }])
422
+ try {
423
+ let suite = {
424
+ name: 'delivery',
425
+ metric: 'median-of-round-medians',
426
+ workload: 1,
427
+ benches: [{ name: 'read', unit: 'ms', sample: () => 1 }],
428
+ }
429
+ // Runs are kept nowhere: the example is about delivery, not files.
430
+ let files = {
431
+ read: () => Promise.reject(new Deno.errors.NotFound('delivery.json')),
432
+ write: () => Promise.resolve(),
433
+ }
434
+ let options = { output: 'delivery.json', files, host: () => context }
435
+ await run(suite, options)
436
+ context.config.destination = 'second'
437
+ await run(suite, options)
438
+ equal(delivered, ['first', 'second'])
439
+ } finally {
440
+ undo()
441
+ }
442
+ ```
443
+
444
+ ## Exports
445
+
446
+ | Subpath | Exports | Purpose |
447
+ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- |
448
+ | `.` | `bench`, `stopwatch`, `run`, `Regressed` | Timed callbacks and JSON runner. |
449
+ | `.` | `median`, `baseline`, `best`, `compare`, `limit`, `loaded`, `spread`, `Coverage` | Pure aggregation and ratchet. |
450
+ | `.` | `busy`, `cputime`, `threadtime`, `processCpu`, `waited`, `configure`, `host` | Process reporter factory and current host context. |
451
+ | `.` | `Bench`, `TimedBench`, `Iteration`, `TimeUnit`, `Suite`, `CollectedSuite`, `Workload`, `Direction`, `Sample`, `Samples`, `Round`, `Result`, `Run`, `Baseline`, `Regression`, `Host`, `Reporter`, `ReportedRun`, `Reporters`, `Options`, `Files` | Authoring, result, host and effect-boundary types. |
452
+ | `./deno` | `extract`, `DenoReport` | Deno JSON import with provenance. |
453
+
454
+ The package provides no tracker transport, timing buckets, retention or views.
455
+ Those consume the completed run through a reporter. Writing JSON needs Deno
456
+ filesystem permission; host metadata needs environment, read and Git execution
457
+ permission. The root export targets Deno; the pure modules themselves have no
458
+ machine effects.