@abide/harness 0.0.0-stage → 0.2.1

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.
@@ -0,0 +1,36 @@
1
+ // Registers a DOM as globals for `bun test`, and installs the measure lane's patches
2
+ // beside it. Wired from the root bunfig.toml, so it runs once per test process and
3
+ // before any suite imports.
4
+ //
5
+ // The patches land HERE rather than around a case body. Removing them per case cannot
6
+ // be done in the browser arm at all — `addInitScript` runs at document-start and has
7
+ // no removal hook — and re-patching per case invalidates the inline caches on those
8
+ // members once per case, for the process. `arm()`/`disarm()` swap the record instead,
9
+ // so the prototype shape is fixed for the process lifetime.
10
+ import { GlobalRegistrator } from '@happy-dom/global-registrator'
11
+ import { install } from './install.ts'
12
+
13
+ // A child spawned with this env would paint its output in ANSI off a pipe (bun's console, and
14
+ // abide's own log under RULEBOOK 36.9), and the suites compare that output as text. A terminal
15
+ // that exports it made the local gate red where CI, which never sets it, stayed green.
16
+ delete process.env.FORCE_COLOR
17
+
18
+ // THE WIRE STAYS BUN'S. happy-dom registers its own `fetch` family over bun's, and those drop a
19
+ // `cookie` or `origin` header a test sets, hand a handler a `Blob` with no `bytes()`, and are refused
20
+ // by `Bun.serve`. The DOM reaches its own through its window either way.
21
+ const WIRE = [
22
+ 'fetch',
23
+ 'Request',
24
+ 'Response',
25
+ 'Headers',
26
+ 'Blob',
27
+ 'File',
28
+ 'FormData',
29
+ 'AbortController',
30
+ 'AbortSignal',
31
+ ] as const
32
+ const native: Record<string, unknown> = {}
33
+ for (const name of WIRE) native[name] = globalThis[name]
34
+ GlobalRegistrator.register({ url: 'http://localhost/' })
35
+ for (const name of WIRE) Object.assign(globalThis, { [name]: native[name] })
36
+ install()
@@ -0,0 +1,76 @@
1
+ /**
2
+ * One arm's timing, with everything `ratio()` needs to refuse a bad comparison.
3
+ *
4
+ * Every field is required: a record with an optional substrate is a record whose substrate
5
+ * somebody omits, and the JSC/V8 inversion — the same graph at 1.67x a hand-written signal in
6
+ * one engine and 0.21x in the other — is not a difference an average can survive.
7
+ */
8
+ export type Sample = {
9
+ /**
10
+ * The name this arm is reported under.
11
+ *
12
+ * `ratio()` refuses two samples sharing it, which is an arm measured against itself.
13
+ */
14
+ arm: string
15
+ /** The case both arms ran. Refused when they disagree. */
16
+ case: string
17
+ /**
18
+ * Operations batched into ONE timing.
19
+ *
20
+ * Equal across arms or the comparison is refused: a per-op figure at n=10,000 has different
21
+ * GC and cache behavior than at n=10.
22
+ */
23
+ n: number
24
+ /** Timed batches taken, warm-up excluded. */
25
+ reps: number
26
+ /**
27
+ * Batches run and discarded before timing started.
28
+ *
29
+ * JSC tiers LLInt -> Baseline -> DFG -> FTL, so this is not a formality.
30
+ */
31
+ warmup: number
32
+ /**
33
+ * The ENGINE, not the runtime.
34
+ *
35
+ * `bun test` is JSC, a chromium arm is V8, and a reader's own browser is whichever of three
36
+ * they brought.
37
+ */
38
+ substrate: 'jsc' | 'v8' | 'spidermonkey' | 'unknown'
39
+ /**
40
+ * Whether the op touched an EMULATED DOM.
41
+ *
42
+ * Set by the lane rather than sniffed, and a duration carrying `'dom'` is refused at
43
+ * construction — happy-dom can produce a count, never a millisecond anybody should quote.
44
+ */
45
+ emulated: 'dom' | null
46
+ /**
47
+ * Per operation, min-of-reps.
48
+ *
49
+ * Timing noise is one-sided-positive, so the minimum is the robust point estimate and it is
50
+ * free.
51
+ */
52
+ nanoseconds: number
53
+ /**
54
+ * Per operation, 95th percentile of the reps.
55
+ *
56
+ * A mean of 14 ms with a p99 of 40 ms is jank published as smooth.
57
+ */
58
+ p95: number
59
+ /**
60
+ * True when the op was measured UNBATCHED, in a page, and came in under a frame.
61
+ *
62
+ * Never under bun: nothing there waits on a paint, and the clock resolves a whole op.
63
+ *
64
+ * Click -> paint is frame quantized: nine ops reading 16.6-17.0 across six frameworks is the
65
+ * answer, not an instrument to sharpen. `ratio()` will not divide two of these.
66
+ */
67
+ underOneFrame: boolean
68
+ /**
69
+ * What the arm DID, when the lane counted it.
70
+ *
71
+ * Two arms whose work disagrees are not two implementations of one op — byte-identical page
72
+ * source ran 4.5x apart because only one arm shipped a stylesheet, so the faster arm was not
73
+ * doing the work.
74
+ */
75
+ work: Readonly<Record<string, number>> | null
76
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Where a cost crosses perception, in nanoseconds.
3
+ *
4
+ * Optimize here rather than where the ratio is largest: a 2x on a 40 µs op is invisible. A leaf,
5
+ * because `report` and `engine` both name these and a constant crossing a seam is not copied.
6
+ */
7
+ export const THRESHOLDS = {
8
+ /**
9
+ * One frame at 60 Hz.
10
+ *
11
+ * Click -> paint is quantized to it, so every implementation under one frame reads the same
12
+ * ~16.7 ms and the wall clock is a perception detector rather than a blunt one.
13
+ */
14
+ frame: 16_700_000,
15
+ /** An interaction budget. Past this the wait is the thing the user is doing. */
16
+ interaction: 100_000_000,
17
+ } as const
@@ -0,0 +1,339 @@
1
+ // THE BATCHER, and four of the five refusals.
2
+ //
3
+ // It never runs an arm ALONE. Interleaving A/B/A/B is not an option a caller remembers —
4
+ // JSC tiers LLInt -> Baseline -> DFG -> FTL, so whichever arm ran second inherits
5
+ // warmed code, which is a systematic bias and not noise — so the arms are supplied
6
+ // together and the interleave is the only thing this can do. The first arm is run a
7
+ // SECOND time, labeled as its own control — so even a single arm is interleaved
8
+ // against that control — and
9
+ // whatever ratio that produces IS the floor for this case on this machine today.
10
+ // `underTheFloor` then means a number with a provenance rather than a word: "two runs,
11
+ // and if the arms swap places it is noise" is a sign test at n=2 and misses half of it
12
+ // by construction.
13
+
14
+ import { clockResolution, nanoseconds } from './clock.ts'
15
+ import { underBun } from './environment.ts'
16
+ import type { Sample } from './Sample.ts'
17
+ import { substrate } from './substrate.ts'
18
+ import { THRESHOLDS } from './THRESHOLDS.ts'
19
+
20
+ // A timing sample must be at least this many times the clock's resolution, or it
21
+ // reports the clock rather than the code.
22
+ const MIN_CLOCK_MULTIPLE = 100
23
+
24
+ // CLEARING THE CLOCK IS NOT THE SAME AS BEING WARM, and the bar only knows about the
25
+ // clock. Bun's is ~41 ns, so the bar is ~4 µs a sample and a 40 ns op clears it at
26
+ // n in the hundreds — which is below where JSC promotes the body out of its baseline
27
+ // tier. Measured on one publish into a capped ring (a case since removed with the ring): 85.5 ns a call at n=488 and 4.4 at
28
+ // n=2,000,000, the SAME code, a 19x spread chosen by the sample size.
29
+ //
30
+ // IT IS NOT A UNIFORM BIAS, so it cannot be divided out. Swept across n, a write with one
31
+ // watcher moved 2.12x -> 3.15x while a publish into a capped ring moved 1.93x -> 0.55x —
32
+ // the second INVERTING, so the bench reported abide slower at a job it does twice as fast.
33
+ //
34
+ // So each arm is run on its own before anything is timed, bounded by a call count and by
35
+ // a wall clock: an op cheap enough to need the warming is cheap enough to get it inside
36
+ // the time bound, and an op too dear for the bound was never at risk.
37
+ const WARM_CALLS = 200_000
38
+ const WARM_NANOSECONDS = 25_000_000
39
+
40
+ // Growth is multiplicative and capped: an op that cannot clear the bar at a hundred
41
+ // million reps is not an op this batcher can price, and looping forever hides that.
42
+ const GROWTH_FACTOR = 8
43
+
44
+ // How far above the bar a refined n aims. A sample sitting exactly on the bar fails
45
+ // the check it was chosen to pass as soon as the code warms up.
46
+ const BAR_MARGIN = 1.4
47
+ const MAX_N = 100_000_000
48
+
49
+ const DEFAULT_REPS = 7
50
+ const DEFAULT_WARMUP = 3
51
+
52
+ // A WALL-CLOCK CEILING ON THE WHOLE CALL. Growth is multiplicative against a bar set
53
+ // by the clock, and a browser's clock is 100 µs where bun's is 41 ns — so the same op
54
+ // that needs n=64 under bun needs n in the thousands in a page, and an op that cannot
55
+ // clear the bar at all grows until `MAX_N` while doing real DOM work. Measured: a
56
+ // 50-row class toggle in chromium, with no budget, did not finish in five minutes.
57
+ // An op this cannot price in the budget is one it says it cannot price.
58
+ const DEFAULT_BUDGET_NANOSECONDS = 2_000_000_000
59
+
60
+ // `Bun.gc(true)` is a synchronous full collection and it is on the global rather than
61
+ // behind an import, which is what lets this file ship into the browser injectable —
62
+ // `bun:jsc` is a specifier a browser bundler must resolve and nothing stands in for it.
63
+ // Read by the MEMBER, so a browser — which has no `Bun` — gets `undefined` here and
64
+ // `collectGarbage` does nothing, rather than a TypeError in the middle of a timing run.
65
+ const BUN_GC = (globalThis as { Bun?: { gc?(sync: boolean): void } }).Bun?.gc
66
+
67
+ // `bun run test` is `--parallel`, and bun marks a worker process with this.
68
+ const WORKER_ID = (
69
+ globalThis as { process?: { env: Record<string, string | undefined> } }
70
+ ).process?.env?.BUN_TEST_WORKER_ID
71
+
72
+ /** What `batch()` returns: one `Sample` per arm, and the A/A floor they were measured against. */
73
+ export type Batched = {
74
+ case: string
75
+ n: number
76
+ reps: number
77
+ warmup: number
78
+ substrate: ReturnType<typeof substrate>
79
+ /**
80
+ * |control ratio − 1|.
81
+ *
82
+ * The A/A spread, measured, and what `underTheFloor` is compared against.
83
+ */
84
+ floor: number
85
+ samples: Record<string, Sample>
86
+ }
87
+
88
+ /** The arms `batch()` interleaves, and the options that pin or bound the run. */
89
+ export type BatchSpec = {
90
+ case: string
91
+ /**
92
+ * Arm name -> the op, run once per call.
93
+ *
94
+ * One or more, and the first is also the A/A control — so one arm is still interleaved,
95
+ * against itself, and yields a floor but no ratio.
96
+ */
97
+ arms: Record<string, () => void>
98
+ /**
99
+ * Whether the op touches an emulated DOM. Set by the LANE.
100
+ *
101
+ * A duration whose op touched an emulated DOM is refused here rather than at reporting time,
102
+ * so the number never exists to be quoted.
103
+ */
104
+ emulated: 'dom' | null
105
+ /**
106
+ * What each arm DID, counted in a separate pass.
107
+ *
108
+ * Counting and timing are mutually exclusive passes over the same body — the counter runs
109
+ * inside the path it counts — so the work cannot come off this run and is handed in.
110
+ */
111
+ work?: Readonly<Record<string, Readonly<Record<string, number>>>>
112
+ /**
113
+ * Fixed batch size, when a second `batch()` call has to match a first.
114
+ *
115
+ * Left out, it grows until the sample clears the bar.
116
+ */
117
+ n?: number
118
+ reps?: number
119
+ warmup?: number
120
+ /** Wall clock for the whole call. A page has a reader waiting on it. */
121
+ budgetNanoseconds?: number
122
+ }
123
+
124
+ function collectGarbage(): void {
125
+ if (typeof BUN_GC === 'function') BUN_GC(true)
126
+ }
127
+
128
+ /**
129
+ * One timed batch of `n` operations, in nanoseconds.
130
+ *
131
+ * Not per-op: the caller divides, after taking the minimum.
132
+ */
133
+ function timeBatch(body: () => void, n: number): number {
134
+ const before = nanoseconds()
135
+ for (let index = 0; index < n; index += 1) body()
136
+ return nanoseconds() - before
137
+ }
138
+
139
+ function percentile95(sorted: number[]): number {
140
+ const index = Math.ceil(sorted.length * 0.95) - 1
141
+ return sorted[Math.min(Math.max(index, 0), sorted.length - 1)] as number
142
+ }
143
+
144
+ /**
145
+ * Runs an arm until it is warm, or until the wall clock says it is dear enough not to need it.
146
+ *
147
+ * Batched rather than checked per call — the check is a clock read — but the batch is what
148
+ * decides whether the BOUND means anything: at 1,024 calls, and with the first check only after
149
+ * the 1,024th, a millisecond-scale op ran for a second before anything looked, which is 40x the
150
+ * bound and can spend the whole batch budget before a sample is taken. `& 63` checks after the
151
+ * FIRST call and then every 64, so the overrun is bounded by what the bound is for.
152
+ */
153
+ function warm(body: () => void): void {
154
+ const startedAt = nanoseconds()
155
+ for (let call = 0; call < WARM_CALLS; call += 1) {
156
+ body()
157
+ if ((call & 63) === 0 && nanoseconds() - startedAt > WARM_NANOSECONDS)
158
+ return
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Times every arm interleaved, plus an A/A control of the first, and returns per-op samples.
164
+ *
165
+ * Grows `n` until a sample clears 100x the clock's measured resolution. Throws in a parallel
166
+ * test worker, on an emulated DOM, on an unmeasurable clock, and when the budget runs out.
167
+ */
168
+ export function batch(spec: BatchSpec): Batched {
169
+ // Refusal 5. Eight workers competing for cores measures the scheduler, and with a
170
+ // MEASURED floor the floor goes so wide under contention that every real
171
+ // regression reads as `underTheFloor` — a gate that stops gating without failing.
172
+ if (WORKER_ID !== undefined)
173
+ throw new Error(
174
+ `batch("${spec.case}") ran in parallel worker ${WORKER_ID}. Counts belong in \`bun test\`; anything with a clock runs under \`bun run test:serial\` or \`bun run bench\`.`,
175
+ )
176
+ // Refusal 4 (43.22). Not "a bun sample with unit ms" — that refuses a build-time µs and a
177
+ // TTFB, both DOM-free, and lets a `ns` through on a spelling.
178
+ if (spec.emulated === 'dom')
179
+ throw new Error(
180
+ `batch("${spec.case}") was handed emulated: 'dom'. happy-dom can produce a count; it cannot produce a millisecond anybody should quote.`,
181
+ )
182
+
183
+ const names = Object.keys(spec.arms)
184
+ if (names.length === 0)
185
+ throw new Error(`batch("${spec.case}") was given no arms`)
186
+
187
+ // The A/A control: the first arm again, under a name no caller can collide with.
188
+ const control = `${names[0]} (A/A)`
189
+ const lanes: { name: string; body: () => void }[] = []
190
+ for (const name of names)
191
+ lanes.push({ name, body: spec.arms[name] as () => void })
192
+ lanes.push({
193
+ name: control,
194
+ body: spec.arms[names[0] as string] as () => void,
195
+ })
196
+
197
+ const resolution = clockResolution()
198
+ // An unmeasurable clock makes the bar infinite, and an infinite bar turns the
199
+ // growth loop into `MAX_N` operations of real work. Refused before it starts.
200
+ if (!Number.isFinite(resolution))
201
+ throw new Error(
202
+ `batch("${spec.case}") could not measure this clock: it never stepped inside \`clockResolution()\`'s probe deadline. There is no sample size that makes a reading of it a reading of the code.`,
203
+ )
204
+ const bar = MIN_CLOCK_MULTIPLE * resolution
205
+ const budget = spec.budgetNanoseconds ?? DEFAULT_BUDGET_NANOSECONDS
206
+ const startedAt = nanoseconds()
207
+ const reps = spec.reps ?? DEFAULT_REPS
208
+ const warmup = spec.warmup ?? DEFAULT_WARMUP
209
+
210
+ // GROW UNTIL THE SAMPLE CLEARS THE BAR, and the growth probe is the run itself.
211
+ // A probe taken BEFORE the warm-up reps grows against cold code and then the
212
+ // timed reps come in under the bar anyway — measured: an arm that needed n=512
213
+ // cold reported 1208 ns warm, a third of the bar, and the batcher would have
214
+ // thrown on a sample size it had chosen itself.
215
+ // A CHEAP PROBE FINDS THE STARTING n, and the full run is what proves it. Growing
216
+ // by rerunning warm-up and every rep at each step costs the whole rep set once
217
+ // per doubling — it is what made the browser case unfinishable — and growing off
218
+ // a COLD probe alone undershoots, because the timed reps come back faster than
219
+ // the probe that chose n. So: probe cheaply, run fully, and grow again if the run
220
+ // misses the bar.
221
+ // BEFORE THE GROWTH PROBE, so the probe chooses n against warm code too — a probe
222
+ // taken cold picks an n the warm run then comes in under.
223
+ for (const lane of lanes) warm(lane.body)
224
+
225
+ let n = spec.n ?? 1
226
+ if (spec.n === undefined) {
227
+ while (n < MAX_N) {
228
+ let fastestProbe = Number.POSITIVE_INFINITY
229
+ for (const lane of lanes) {
230
+ const took = timeBatch(lane.body, n)
231
+ if (took < fastestProbe) fastestProbe = took
232
+ }
233
+ if (fastestProbe >= bar) {
234
+ // REFINED DOWN, because growth is multiplicative and the step that
235
+ // clears the bar overshoots it by up to the whole factor. Measured in
236
+ // webkit, whose 1 ms clock puts the bar at 100 ms a batch: n jumped
237
+ // 4,096 -> 32,768, each batch took ~480 ms instead of ~100, and the
238
+ // run blew a 5 s budget it would otherwise have fitted in twice over.
239
+ // The margin keeps the refined n clear of the bar rather than on it.
240
+ n = Math.max(
241
+ 1,
242
+ Math.ceil((n * bar * BAR_MARGIN) / fastestProbe),
243
+ )
244
+ break
245
+ }
246
+ if (nanoseconds() - startedAt > budget)
247
+ throw new Error(
248
+ `batch("${spec.case}") spent its ${budget / 1e6} ms budget growing n and reached ${n} without clearing ${MIN_CLOCK_MULTIPLE}x the clock (${resolution} ns). This op is not priceable on this clock.`,
249
+ )
250
+ n = Math.min(n * GROWTH_FACTOR, MAX_N)
251
+ }
252
+ }
253
+ let timings = new Map<string, number[]>()
254
+ for (;;) {
255
+ timings = new Map<string, number[]>()
256
+ for (const lane of lanes) timings.set(lane.name, [])
257
+ // A/B/A/B, never in blocks. Warm-up reps run through the same interleave and
258
+ // are discarded, so no arm carries the other's tiering into the timed reps.
259
+ for (let rep = 0; rep < warmup + reps; rep += 1) {
260
+ for (const lane of lanes) {
261
+ collectGarbage()
262
+ const took = timeBatch(lane.body, n)
263
+ if (rep >= warmup)
264
+ (timings.get(lane.name) as number[]).push(took)
265
+ }
266
+ // CHECKED PER REP, not only per growth step. One batch at the n a coarse
267
+ // clock forces is not short: webkit clamps `performance.now()` to 1 ms,
268
+ // so the bar is 100 ms a batch and n reached 32,768 — the run took 7.3 s
269
+ // against a 2 s budget and reported nothing, because the only check was
270
+ // between runs.
271
+ if (nanoseconds() - startedAt > budget)
272
+ throw new Error(
273
+ `batch("${spec.case}") spent its ${budget / 1e6} ms budget at n=${n} after ${rep + 1} of ${warmup + reps} reps. This clock (${resolution} ns) needs a bigger sample than the budget buys.`,
274
+ )
275
+ }
276
+ let fastest = Number.POSITIVE_INFINITY
277
+ for (const taken of timings.values())
278
+ for (const took of taken) if (took < fastest) fastest = took
279
+ if (fastest >= bar) break
280
+ if (nanoseconds() - startedAt > budget)
281
+ throw new Error(
282
+ `batch("${spec.case}") spent its ${budget / 1e6} ms budget and the sample still reads ${fastest} ns at n=${n}, under ${MIN_CLOCK_MULTIPLE}x the clock (${resolution} ns).`,
283
+ )
284
+ // Refusal 3. A pinned n is the caller matching a previous run, so growing it
285
+ // silently would break the equality `ratio()` checks. Throw instead.
286
+ if (spec.n !== undefined || n >= MAX_N)
287
+ throw new Error(
288
+ `batch("${spec.case}") took ${fastest} ns at n=${n}, under ${MIN_CLOCK_MULTIPLE}x the clock's measured resolution (${clockResolution()} ns). The sample would be the clock, not the code.`,
289
+ )
290
+ n = Math.min(n * GROWTH_FACTOR, MAX_N)
291
+ }
292
+
293
+ const perOperation = new Map<string, { min: number; p95: number }>()
294
+ for (const [name, taken] of timings) {
295
+ const sorted = taken.slice().sort((one, two) => one - two)
296
+ perOperation.set(name, {
297
+ min: (sorted[0] as number) / n,
298
+ p95: percentile95(sorted) / n,
299
+ })
300
+ }
301
+
302
+ const where = substrate()
303
+ const samples: Record<string, Sample> = {}
304
+ for (const name of names) {
305
+ const taken = perOperation.get(name) as { min: number; p95: number }
306
+ samples[name] = {
307
+ arm: name,
308
+ case: spec.case,
309
+ n,
310
+ reps,
311
+ warmup,
312
+ substrate: where,
313
+ emulated: spec.emulated,
314
+ nanoseconds: taken.min,
315
+ p95: taken.p95,
316
+ // An op measured WHOLE and under a frame, IN A PAGE, is under the
317
+ // quantum a reader sees by. Under bun there is no frame: a string render
318
+ // timed whole on a 41 ns clock is a reading, and tagging it made three
319
+ // benches divide by hand rather than through `ratio()`. A batched
320
+ // micro-op is under a frame by construction and the frame is not its
321
+ // threshold.
322
+ underOneFrame:
323
+ !underBun() && n === 1 && taken.min < THRESHOLDS.frame,
324
+ work: spec.work?.[name] ?? null,
325
+ }
326
+ }
327
+
328
+ const first = perOperation.get(names[0] as string) as { min: number }
329
+ const controlTiming = perOperation.get(control) as { min: number }
330
+ return {
331
+ case: spec.case,
332
+ n,
333
+ reps,
334
+ warmup,
335
+ substrate: where,
336
+ floor: Math.abs(controlTiming.min / first.min - 1),
337
+ samples,
338
+ }
339
+ }
@@ -0,0 +1,60 @@
1
+ // THE CLOCK, and the one number that says how much of it to believe.
2
+ //
3
+ // The two substrates are nowhere near each other and neither is introspectable, so the
4
+ // resolution is MEASURED once per process rather than assumed: `performance.now()`'s
5
+ // minimum non-zero delta is 41 ns under bun here, where the browser figure quoted
6
+ // everywhere is 100 µs — assuming the browser number over-batches by ~2400x, and a
7
+ // cross-origin-isolated page at 5 µs is a 20x error the other way.
8
+
9
+ import { underBun } from './environment.ts'
10
+
11
+ // PROBED AGAINST A DEADLINE, NOT A COUNT, and the count is what got this wrong. A
12
+ // fixed 20,000 pairs sees a step on bun (41 ns) and on chromium (100 µs) and sees
13
+ // NOTHING in webkit, which clamps `performance.now()` harder — 20,000 pairs is about
14
+ // a millisecond of wall time, so a 1 ms clock may not tick once inside the probe. A
15
+ // probe that returns "unmeasurable" for Safari would take every browser timing off the
16
+ // table in one of the three engines a reader might bring.
17
+ //
18
+ // So it runs until it has seen a step, and then keeps going briefly to find the
19
+ // smallest one. 8 ms is under a frame and is paid once per process.
20
+ const PROBE_DEADLINE_MILLISECONDS = 8
21
+ const PROBES_AFTER_FIRST_STEP = 2_000
22
+
23
+ // `Bun.nanoseconds()` is the bun-side clock and it is already integer nanoseconds.
24
+ // `performance.now()` is milliseconds and is what a browser has.
25
+ const BUN_CLOCK = underBun()
26
+ ? (globalThis as unknown as { Bun: { nanoseconds(): number } }).Bun
27
+ : null
28
+
29
+ /** The current time in nanoseconds, from `Bun.nanoseconds()` or `performance.now()`. */
30
+ export function nanoseconds(): number {
31
+ return BUN_CLOCK ? BUN_CLOCK.nanoseconds() : performance.now() * 1e6
32
+ }
33
+
34
+ let measured = 0
35
+
36
+ /**
37
+ * The smallest non-zero step the clock can report, in nanoseconds.
38
+ *
39
+ * Cached: it is a property of the substrate, and the process does not change substrate.
40
+ */
41
+ export function clockResolution(): number {
42
+ if (measured > 0) return measured
43
+ const deadline = Date.now() + PROBE_DEADLINE_MILLISECONDS
44
+ let smallest = Number.POSITIVE_INFINITY
45
+ let sinceFirstStep = 0
46
+ for (;;) {
47
+ const before = nanoseconds()
48
+ const after = nanoseconds()
49
+ const step = after - before
50
+ if (step > 0 && step < smallest) smallest = step
51
+ if (Number.isFinite(smallest)) {
52
+ sinceFirstStep += 1
53
+ if (sinceFirstStep >= PROBES_AFTER_FIRST_STEP) break
54
+ } else if (Date.now() >= deadline) break
55
+ }
56
+ // A clock that never stepped inside the deadline is coarser than a wall clock can
57
+ // see, and reporting 0 would let the batcher accept any sample at all.
58
+ measured = smallest
59
+ return measured
60
+ }
@@ -0,0 +1,22 @@
1
+ // WHERE THIS RUNS, probed once and the same way by every lane.
2
+ //
3
+ // PROBED BY THE MEMBER the clock reads, so the answer is the capability the lanes rely on rather
4
+ // than the name of a global anything could define.
5
+
6
+ const UNDER_BUN =
7
+ typeof (globalThis as { Bun?: { nanoseconds?: unknown } }).Bun
8
+ ?.nanoseconds === 'function'
9
+
10
+ /** Whether this is bun, rather than a browser. */
11
+ export function underBun(): boolean {
12
+ return UNDER_BUN
13
+ }
14
+
15
+ /**
16
+ * `'dom'` where a DOM is present under bun, which makes it an emulator's, and `null` anywhere else.
17
+ *
18
+ * What a lane hands `batch` as `emulated` for an op that touches the DOM (43.22).
19
+ */
20
+ export function emulatedDom(): 'dom' | null {
21
+ return UNDER_BUN && typeof document !== 'undefined' ? 'dom' : null
22
+ }
@@ -0,0 +1,17 @@
1
+ // NOT A LANE. All three lanes need every name in here, in both
2
+ // substrates, and they ship into the browser injectable — so a lane is a DEPENDENCY
3
+ // partition and this depends on nothing, which makes it a leaf rather than a fourth
4
+ // question.
5
+ //
6
+ // What is NOT here: the LOC counter and the `example.json` writer. Both run once, on
7
+ // bun, from a script, and both touch the filesystem — a `Bun.Glob` parked here would
8
+ // make the leaf bun-only, contradicting the one property it is justified by, and an
9
+ // import edge is priced by the module it lands on, so `measure` reaching for a clock
10
+ // would drag a glob into the module the injectable is built from. They live in
11
+ // `bun run bench`.
12
+
13
+ export { type Batched, type BatchSpec, batch } from './batch.ts'
14
+ export { emulatedDom } from './environment.ts'
15
+ export { claimOf, type Ratio, type RatioSpec, ratio } from './ratio.ts'
16
+ export type { Sample } from './Sample.ts'
17
+ export { THRESHOLDS } from './THRESHOLDS.ts'