@abide/harness 0.0.0-stage → 0.2.0

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/package.json CHANGED
@@ -1,6 +1,71 @@
1
1
  {
2
- "name": "@abide/harness",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@abide/harness",
3
+ "version": "0.2.0",
4
+ "type": "module",
5
+ "description": "Ratios against hand-written code, counts of the work an op did, and gates whose revert can be run — three measurement lanes for anything that renders, on bun",
6
+ "license": "MIT",
7
+ "author": "Brian Cray",
8
+ "homepage": "https://github.com/briancray/abide#readme",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/briancray/abide.git",
12
+ "directory": "packages/harness"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/briancray/abide/issues"
16
+ },
17
+ "keywords": [
18
+ "bun",
19
+ "benchmark",
20
+ "testing",
21
+ "measurement",
22
+ "dom",
23
+ "playwright"
24
+ ],
25
+ "engines": {
26
+ "bun": ">=1.4.3"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public",
30
+ "provenance": true
31
+ },
32
+ "files": [
33
+ "src",
34
+ "scripts/buildInjectable.ts"
35
+ ],
36
+ "exports": {
37
+ "./measure": "./src/measure/index.ts",
38
+ "./preload": "./src/measure/preload.ts",
39
+ "./engine": "./src/engine/index.ts",
40
+ "./server": "./src/server/index.ts",
41
+ "./report": "./src/report/index.ts",
42
+ "./gate": "./src/gate/index.ts",
43
+ "./rows": "./src/rows/index.ts",
44
+ "./runner": "./src/runner/index.ts",
45
+ "./abide": "./src/abide/index.ts",
46
+ "./abide/preload": "./src/abide/preload.ts",
47
+ "./package.json": "./package.json"
48
+ },
49
+ "scripts": {
50
+ "typecheck": "bun check",
51
+ "build:injectable": "bun scripts/buildInjectable.ts"
52
+ },
53
+ "dependencies": {
54
+ "@happy-dom/global-registrator": "^20.14.6"
55
+ },
56
+ "peerDependencies": {
57
+ "@playwright/test": "^1.64.0",
58
+ "@abide/abide": ">=0.106.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "@playwright/test": {
62
+ "optional": true
63
+ },
64
+ "@abide/abide": {
65
+ "optional": true
66
+ }
67
+ },
68
+ "devDependencies": {
69
+ "@abide/abide": "workspace:*"
70
+ }
71
+ }
@@ -0,0 +1,27 @@
1
+ // Builds the measure lane into ONE file the browser arm is injected with. The bytes
2
+ // playwright injects and the bytes `bun test` imports have to be the same code, or
3
+ // the lane's one claim — the only lane in both substrates — is a claim about two
4
+ // different instruments.
5
+ //
6
+ // `bun scripts/buildInjectable.ts` prints the path; a spec injects that file with
7
+ // `addInitScript` and reads `__HARNESS_MEASURE__` off the page.
8
+
9
+ const ENTRY = new URL('../src/measure/injectable.ts', import.meta.url).pathname
10
+ const OUT_DIR = new URL('../dist/', import.meta.url).pathname
11
+
12
+ /** Builds the measure lane's injectable into `dist/measure.js` and returns its path. */
13
+ export async function buildInjectable(): Promise<string> {
14
+ const built = await Bun.build({
15
+ entrypoints: [ENTRY],
16
+ outdir: OUT_DIR,
17
+ naming: 'measure.js',
18
+ format: 'iife',
19
+ target: 'browser',
20
+ minify: false,
21
+ })
22
+ if (!built.success)
23
+ throw new AggregateError(built.logs, 'measure did not build')
24
+ return `${OUT_DIR}measure.js`
25
+ }
26
+
27
+ if (import.meta.main) console.log(await buildInjectable())
@@ -0,0 +1,53 @@
1
+ // THE BUILT-IN ADAPTER FOR AN ABIDE APP, and the one entry of this package allowed to know abide.
2
+ // Every lane measures anything; this is what makes the general instrument read like abide's own:
3
+ // `measure` with abide's three counters on the record by name, and abide's `mount` beside it, so an
4
+ // app's test imports both from one place.
5
+ //
6
+ // ABIDE IS NOT IMPORTED TO COUNT. abide publishes its counters on the global every lane reads
7
+ // (`WORK.ts`, 43.21) and this reads them back by name, so the counting stays in the lane and the
8
+ // adapter only names the fields.
9
+
10
+ import {
11
+ measure as measureWork,
12
+ publishedBy,
13
+ type Work,
14
+ } from '../measure/index.ts'
15
+
16
+ export { type Mounted, mount } from '@abide/abide/test'
17
+
18
+ const FIELDS = ['wakes', 'bindingRuns', 'descents'] as const
19
+
20
+ /**
21
+ * What an op did: the DOM rows the harness counts, and abide's own three.
22
+ *
23
+ * Each of the three is `null` where no abide runtime has loaded in the process — absent, never 0
24
+ * (43.19).
25
+ */
26
+ export type AbideWork = Work & {
27
+ /** Effect runs. */
28
+ wakes: number | null
29
+ /** Compiled reactive slots that ran. */
30
+ bindingRuns: number | null
31
+ /** Nodes visited by propagation walks. */
32
+ descents: number | null
33
+ }
34
+
35
+ /**
36
+ * Runs `body` inside an armed case and returns the work it did, abide's counters included.
37
+ *
38
+ * Throws where abide's record is published without one of its fields as a number (43.20).
39
+ */
40
+ export function measure(body: () => void): AbideWork {
41
+ const work = measureWork(body)
42
+ const counted = publishedBy(work, 'abide', FIELDS) ?? {
43
+ wakes: null,
44
+ bindingRuns: null,
45
+ descents: null,
46
+ }
47
+ return {
48
+ ...work,
49
+ wakes: counted.wakes,
50
+ bindingRuns: counted.bindingRuns,
51
+ descents: counted.descents,
52
+ }
53
+ }
@@ -0,0 +1,6 @@
1
+ // AN ABIDE APP'S WHOLE TEST PRELOAD, in one line of its bunfig.toml: a DOM with the measure lane's
2
+ // patches installed, THEN abide's own preload, which builds the app so a test imports its `.abide`
3
+ // files as modules (38.109). In that order, because a module abide's build loads may read the DOM.
4
+
5
+ import '../measure/preload.ts'
6
+ import '@abide/abide/test'
@@ -0,0 +1,54 @@
1
+ /**
2
+ * What Blink did over one traced window, plus the user timing emitted inside it.
3
+ *
4
+ * Both halves are here for the same reason: a fraction needs a numerator that Blink does not
5
+ * name. "Reconcile" is not a Blink layer — style, layout and paint are, and a reconcile is
6
+ * application JS — so the numerator comes from `performance.measure` pairs the code under test
7
+ * emits, and the layers come from the engine.
8
+ */
9
+ export type Trace = {
10
+ /** The op this window is of, and the name `shares()` reports. */
11
+ op: string
12
+ /**
13
+ * `performance.measure` entries, in trace order.
14
+ *
15
+ * `shares()` reads its numerator and its denominator out of these by NAME, and asserts
16
+ * containment rather than assuming it.
17
+ */
18
+ measures: {
19
+ name: string
20
+ startNanoseconds: number
21
+ endNanoseconds: number
22
+ }[]
23
+ /**
24
+ * Style recalcs, layouts, paints and forced layouts over the window.
25
+ *
26
+ * All four, because a count is how two arms REPORT THE WORK. Byte-identical page source ran
27
+ * 4.5x apart and the only difference was that one arm shipped a stylesheet — a class no rule
28
+ * mentions is a write with no style recalculation and no paint after it, so the faster arm
29
+ * was not doing the work at all.
30
+ */
31
+ counters: {
32
+ recalcStyle: number
33
+ layout: number
34
+ paint: number
35
+ /**
36
+ * Layouts forced by a read after a write in the same path.
37
+ *
38
+ * A layout read after a write forces the layout the write invalidated. One such read
39
+ * per row is the whole frame.
40
+ */
41
+ forcedLayout: number
42
+ }
43
+ /**
44
+ * Blink's own per-layer durations over the window, in nanoseconds.
45
+ *
46
+ * Not for pricing — `shares()` prices off the user timing — but for saying which way the
47
+ * headroom runs.
48
+ */
49
+ layers: {
50
+ style: number
51
+ layout: number
52
+ script: number
53
+ }
54
+ }
@@ -0,0 +1,18 @@
1
+ // Lane 2 of 3 — WHAT BLINK DID: style, layout, paint, forced layout, and the
2
+ // per-layer durations `shares()` turns into the fraction of an op each layer took.
3
+ // Read over CDP, so chromium only, and driven from the playwright side — an engine
4
+ // number is not available inside a case body, and that is a property of the lane
5
+ // rather than a gap.
6
+ //
7
+ // `harness/report` is a FOURTH entry and is not a fourth lane: a lane is a DEPENDENCY
8
+ // partition, and the leaf depends on nothing.
9
+
10
+ export {
11
+ durationOf,
12
+ measuresNamed,
13
+ type Shares,
14
+ type SharesSpec,
15
+ shares,
16
+ } from './shares.ts'
17
+ export type { Trace } from './Trace.ts'
18
+ export { traceOp } from './traceOp.ts'
@@ -0,0 +1,143 @@
1
+ // THE FRACTION, WITH A STATED DENOMINATOR. Not a timer — the engine lane's primary
2
+ // export is the number that says whether changing a layer can matter at all.
3
+ //
4
+ // Two reactive-core rewrites landed as no-ops because the path they improved is 0.055
5
+ // of a 1.45 ms op: the ceiling was 4% and both changes were inside the noise. A
6
+ // denominator that is optional is a denominator somebody omits, so it is required,
7
+ // and so is the threshold — "the expectation is that this layer is a few percent" is
8
+ // a prediction and gives nobody a reason to stop, where a frame or an interaction
9
+ // budget is a threshold and does.
10
+
11
+ import { THRESHOLDS } from '../report/THRESHOLDS.ts'
12
+ import type { Trace } from './Trace.ts'
13
+
14
+ /** Which measure is the layer, which is the op, and the threshold the op is judged against. */
15
+ export type SharesSpec = {
16
+ /** The numerator, by the name the code under test measured it under. */
17
+ layer: string
18
+ /** The denominator. The WHOLE op somebody waits on, not the layer's parent. */
19
+ of: string
20
+ threshold: keyof typeof THRESHOLDS
21
+ }
22
+
23
+ /** The fraction of an op one layer took, and whether that can matter to a user. */
24
+ export type Shares = {
25
+ op: string
26
+ layer: string
27
+ layerNanoseconds: number
28
+ opNanoseconds: number
29
+ /**
30
+ * The share, which is also the CPU ceiling.
31
+ *
32
+ * An optimization is capped by the fraction of the op it touches. One number, not two — the
33
+ * sketch returned the fraction twice, once as `layer` and once as `ceilingCpu`.
34
+ */
35
+ ceilingCpu: number
36
+ /**
37
+ * The ceiling a user would experience: zero whenever the op is under one frame.
38
+ *
39
+ * Click -> paint is frame quantized, so removing 4.3% of an op that gets rounded up to the
40
+ * next frame boundary changes observed latency by exactly nothing. CPU is for seeing which
41
+ * way the headroom runs and is never quoted as latency.
42
+ */
43
+ ceilingObserved: number
44
+ threshold: keyof typeof THRESHOLDS
45
+ underOneFrame: boolean
46
+ overTheThreshold: boolean
47
+ }
48
+
49
+ /** Every measure in the trace with this name, in trace order. */
50
+ export function measuresNamed(
51
+ trace: Trace,
52
+ name: string,
53
+ ): { startNanoseconds: number; endNanoseconds: number }[] {
54
+ const found: { startNanoseconds: number; endNanoseconds: number }[] = []
55
+ for (const measure of trace.measures)
56
+ if (measure.name === name) found.push(measure)
57
+ return found
58
+ }
59
+
60
+ /**
61
+ * Total nanoseconds of every measure with this name. Throws when there is none.
62
+ *
63
+ * Summed over every measure of that name — an op measured once, or a layer that ran several
64
+ * times.
65
+ */
66
+ export function durationOf(trace: Trace, name: string): number {
67
+ const found = measuresNamed(trace, name)
68
+ if (found.length === 0)
69
+ throw new Error(
70
+ `no measure named "${name}" in the trace of "${trace.op}"`,
71
+ )
72
+ let nanoseconds = 0
73
+ for (const measure of found)
74
+ nanoseconds += measure.endNanoseconds - measure.startNanoseconds
75
+ return nanoseconds
76
+ }
77
+
78
+ /**
79
+ * The fraction of one op a named layer took, with the op as the stated denominator.
80
+ *
81
+ * Throws on a withdrawn `within`, a denominator that is not exactly one measure, a missing
82
+ * layer, a layer running outside the op, or an op of zero length.
83
+ */
84
+ export function shares(trace: Trace, spec: SharesSpec): Shares {
85
+ // `within` is WITHDRAWN, and it is refused rather than ignored. It was there to
86
+ // compose — a fraction of click -> paint times a fraction of navigation -> paint
87
+ // — but the reconcile does not run inside navigation -> paint; hydration does.
88
+ // Multiplying a fraction of an INTERACTION op by a fraction of a FIRST-LOAD op
89
+ // produces a number describing no op at all, and the two chains never meet.
90
+ if ('within' in spec)
91
+ throw new Error(
92
+ `shares("${spec.of}") was given a \`within\`. Composition is sound down ONE nesting chain, and first load and interaction are two: a first-load ceiling and an interaction ceiling are separate numbers, and neither bounds the other.`,
93
+ )
94
+
95
+ const denominators = measuresNamed(trace, spec.of)
96
+ if (denominators.length !== 1)
97
+ throw new Error(
98
+ `shares("${spec.of}") found ${denominators.length} measures named "${spec.of}" in the trace of "${trace.op}". The denominator is one op somebody waits on.`,
99
+ )
100
+ const numerators = measuresNamed(trace, spec.layer)
101
+ if (numerators.length === 0)
102
+ throw new Error(
103
+ `shares("${spec.of}") found no measure named "${spec.layer}". The code under test emits the marks; the sampler at ~1 ms cannot resolve a layer inside a 1.45 ms op.`,
104
+ )
105
+
106
+ const op = denominators[0] as {
107
+ startNanoseconds: number
108
+ endNanoseconds: number
109
+ }
110
+ // CONTAINMENT IS CHECKED, not assumed — the assumption the withdrawn `within`
111
+ // violated silently. A layer that also runs OUTSIDE the op — a second flush, an
112
+ // idle pass — is a throw, not a smaller fraction.
113
+ let layerNanoseconds = 0
114
+ for (const run of numerators) {
115
+ if (
116
+ run.startNanoseconds < op.startNanoseconds ||
117
+ run.endNanoseconds > op.endNanoseconds
118
+ )
119
+ throw new Error(
120
+ `shares("${spec.of}") found "${spec.layer}" running outside it. A layer that runs outside the op is a throw, not a smaller fraction.`,
121
+ )
122
+ layerNanoseconds += run.endNanoseconds - run.startNanoseconds
123
+ }
124
+
125
+ const opNanoseconds = op.endNanoseconds - op.startNanoseconds
126
+ if (opNanoseconds <= 0)
127
+ throw new Error(
128
+ `shares("${spec.of}") measured the op at ${opNanoseconds} ns. There is no fraction of zero.`,
129
+ )
130
+ const ceilingCpu = layerNanoseconds / opNanoseconds
131
+ const underOneFrame = opNanoseconds < THRESHOLDS.frame
132
+ return {
133
+ op: spec.of,
134
+ layer: spec.layer,
135
+ layerNanoseconds,
136
+ opNanoseconds,
137
+ ceilingCpu,
138
+ ceilingObserved: underOneFrame ? 0 : ceilingCpu,
139
+ threshold: spec.threshold,
140
+ underOneFrame,
141
+ overTheThreshold: opNanoseconds >= THRESHOLDS[spec.threshold],
142
+ }
143
+ }
@@ -0,0 +1,139 @@
1
+ // THE CDP SIDE. Chromium only, driven from the playwright side, and an engine number
2
+ // is not available inside a case body — that is a property of the lane rather than a
3
+ // gap, and any API pretending otherwise is inviting a claim about the emulator.
4
+ //
5
+ // Playwright is imported for TYPES only, so `harness/engine` still resolves in a bun
6
+ // test process that has no browser: `shares()` is a pure function of a `Trace` and is
7
+ // gated there, where the driver below can only run under `bun run bench`.
8
+
9
+ import type { CDPSession, Page } from '@playwright/test'
10
+ import type { Trace } from './Trace.ts'
11
+
12
+ // `devtools.timeline` carries Paint and the Layout events; the `disabled-by-default`
13
+ // twin is what marks a Layout as FORCED, by hanging the JS stack that forced it off
14
+ // the event.
15
+ const TRACE_CATEGORIES = [
16
+ 'devtools.timeline',
17
+ 'disabled-by-default-devtools.timeline',
18
+ 'disabled-by-default-devtools.timeline.stack',
19
+ ]
20
+
21
+ type TraceEvent = {
22
+ name: string
23
+ args?: { beginData?: { stackTrace?: unknown }; data?: unknown }
24
+ }
25
+
26
+ type Metrics = Record<string, number>
27
+
28
+ /** Chromium's `Performance.getMetrics` counters, keyed by name. */
29
+ async function metrics(session: CDPSession): Promise<Metrics> {
30
+ const answer = (await session.send('Performance.getMetrics')) as {
31
+ metrics: { name: string; value: number }[]
32
+ }
33
+ const out: Metrics = {}
34
+ for (const metric of answer.metrics) out[metric.name] = metric.value
35
+ return out
36
+ }
37
+
38
+ /**
39
+ * Runs `body` under a CDP trace and returns what Blink did plus the page's user timing.
40
+ *
41
+ * Chromium only, driven from the playwright side.
42
+ */
43
+ export async function traceOp(
44
+ page: Page,
45
+ op: string,
46
+ body: () => Promise<void>,
47
+ ): Promise<Trace> {
48
+ const session = await page.context().newCDPSession(page)
49
+ try {
50
+ return await traced(page, session, op, body)
51
+ } finally {
52
+ // The session is owed back whatever happened. Left attached, every later
53
+ // `traceOp` on this context adds another live tracing client and the failure
54
+ // surfaces in a case that has nothing wrong with it.
55
+ await session.detach()
56
+ }
57
+ }
58
+
59
+ async function traced(
60
+ page: Page,
61
+ session: CDPSession,
62
+ op: string,
63
+ body: () => Promise<void>,
64
+ ): Promise<Trace> {
65
+ const events: TraceEvent[] = []
66
+ session.on('Tracing.dataCollected', (payload: unknown) => {
67
+ for (const event of (payload as { value: TraceEvent[] }).value)
68
+ events.push(event)
69
+ })
70
+ const complete = new Promise<void>((resolve) => {
71
+ session.once('Tracing.tracingComplete', () => resolve())
72
+ })
73
+
74
+ await session.send('Performance.enable')
75
+ await page.evaluate(() => {
76
+ performance.clearMarks()
77
+ performance.clearMeasures()
78
+ })
79
+ await session.send('Tracing.start', {
80
+ transferMode: 'ReportEvents',
81
+ traceConfig: { includedCategories: TRACE_CATEGORIES },
82
+ })
83
+ // `Tracing.end` is owed even when the op throws. Left started, the NEXT `traceOp`
84
+ // on this page fails with "Tracing is already started" and the failure names the
85
+ // wrong op — a bad assertion in one case body would read as a broken lane in the
86
+ // next one.
87
+ let before: Metrics
88
+ let after: Metrics
89
+ try {
90
+ before = await metrics(session)
91
+ await body()
92
+ after = await metrics(session)
93
+ } finally {
94
+ await session.send('Tracing.end')
95
+ await complete
96
+ }
97
+
98
+ let paint = 0
99
+ let forcedLayout = 0
100
+ for (const event of events) {
101
+ if (event.name === 'Paint') paint += 1
102
+ // A Layout with a JS stack hanging off it is a layout somebody's read forced.
103
+ if (event.name === 'Layout' && event.args?.beginData?.stackTrace)
104
+ forcedLayout += 1
105
+ }
106
+
107
+ // The user timing comes from the page rather than from the trace: the marks are
108
+ // exact there, and parsing them back out of `blink.user_timing` is a second
109
+ // spelling of the same numbers that goes wrong quietly. The COUNTERS are what the
110
+ // trace is for.
111
+ const measures = await page.evaluate(() =>
112
+ performance.getEntriesByType('measure').map((entry) => ({
113
+ name: entry.name,
114
+ startNanoseconds: Math.round(entry.startTime * 1e6),
115
+ endNanoseconds: Math.round(
116
+ (entry.startTime + entry.duration) * 1e6,
117
+ ),
118
+ })),
119
+ )
120
+
121
+ const since = (name: string): number =>
122
+ ((after[name] ?? 0) - (before[name] ?? 0)) * 1e9
123
+ return {
124
+ op,
125
+ measures,
126
+ counters: {
127
+ recalcStyle:
128
+ (after.RecalcStyleCount ?? 0) - (before.RecalcStyleCount ?? 0),
129
+ layout: (after.LayoutCount ?? 0) - (before.LayoutCount ?? 0),
130
+ paint,
131
+ forcedLayout,
132
+ },
133
+ layers: {
134
+ style: since('RecalcStyleDuration'),
135
+ layout: since('LayoutDuration'),
136
+ script: since('ScriptDuration'),
137
+ },
138
+ }
139
+ }
@@ -0,0 +1,42 @@
1
+ import { spawned } from './spawned.ts'
2
+
3
+ const DEFAULT_TIMEOUT_MILLISECONDS = 30_000
4
+
5
+ /**
6
+ * Runs `source` in a child bun with no DOM preload and no worker mark (unless `workerId` is set).
7
+ *
8
+ * Two of the harness's refusals are about the process a number is taken in — `retained()` throws
9
+ * where a DOM is preloaded (43.16), the batcher throws in a parallel worker (43.18) — and
10
+ * `bunfig.toml` preloads happy-dom into every `bun test` process while `bun run test` runs them
11
+ * all under `--parallel`. So a gate on either refusal cannot be taken in the suite that states
12
+ * it: it is taken in a child.
13
+ *
14
+ * PART OF THE VOCABULARY RATHER THAN OF THIS PACKAGE'S TESTS, which is where it started and where
15
+ * it could not do its job. Every allocation gate in the framework needs this same preload-free
16
+ * invocation, and a helper sitting in `packages/harness/tests/` is one `packages/abide/tests/` can
17
+ * only reach by copying. It belongs beside `gate()` for the same reason `gate()` is a fifth
18
+ * entry: both need `bun:test`, and neither is a lane.
19
+ *
20
+ * It is also the only place a HANG can be gated. `bun test`'s own per-test timeout is a timer, so
21
+ * a body that starves the event loop outruns it and the suite reports nothing at all — no failed
22
+ * test, no summary. A child is killed by a timer in THIS process rather than by one inside the
23
+ * process it is measuring — and `spawned` is how, awaited rather than synchronous, its throw at
24
+ * the deadline being the failed test.
25
+ */
26
+ export async function inAFreshProcess(
27
+ source: string,
28
+ workerId?: string,
29
+ timeoutMilliseconds = DEFAULT_TIMEOUT_MILLISECONDS,
30
+ ): Promise<{ ok: boolean; output: string }> {
31
+ const environment: Record<string, string> = {}
32
+ for (const [key, value] of Object.entries(process.env))
33
+ if (value !== undefined && key !== 'BUN_TEST_WORKER_ID')
34
+ environment[key] = value
35
+ if (workerId !== undefined) environment.BUN_TEST_WORKER_ID = workerId
36
+ const run = await spawned(['bun', '-e', source], {
37
+ cwd: process.cwd(),
38
+ env: environment,
39
+ deadline: timeoutMilliseconds,
40
+ })
41
+ return { ok: run.exitCode === 0, output: run.stdout + run.stderr }
42
+ }
@@ -0,0 +1,95 @@
1
+ // A GATE IS VERIFIED BY REVERTING THE FIX AND WATCHING IT FAIL, and this is what
2
+ // turns that from a habit three tests were written in violation of into a mechanism.
3
+ //
4
+ // Not a lane. `harness/measure`, `harness/engine` and `harness/server` are partitioned
5
+ // by DEPENDENCY and `harness/report` depends on nothing; this depends on `bun:test`,
6
+ // which is why it is neither one of the three nor part of the leaf — a `bun:test`
7
+ // import in the leaf would take the browser injectable with it.
8
+ //
9
+ // Two fields and an ORDINARY TEST BODY. The draft that carried `run` and `is` could
10
+ // not typecheck against its own API — `closures()` hands back a PAIR precisely so
11
+ // nobody re-derives it, and a pair does not compare against `is: 0` — and an exact
12
+ // integer cannot express "≤1 promise per call", "within 1.05x", or an `underOneFrame`
13
+ // tag. Absorbing the assertion into a field also costs the stack: the failure would
14
+ // read `expect(received).toBe(expected)` from inside the wrapper rather than from the
15
+ // line making the claim, with nowhere to put setup, teardown or an `await`.
16
+ //
17
+ // `worth` is RUNNABLE, and that is the whole upgrade. As a string it is a note to the
18
+ // next reader; as `revert` — a function installing the broken arm — plus `worth` —
19
+ // what that arm must report — the revert can be RUN and the gate asserted to fail
20
+ // with that number. It also answers the rule about a benchmark case earning its
21
+ // place: a case reporting the same number with the mechanism out distinguishes
22
+ // nothing, and this says so rather than a reader noticing.
23
+ //
24
+ // The cost, stated: an engine number is not available inside a case body, so this
25
+ // structurally cannot wrap an engine assertion. Engine-lane measurements stay a
26
+ // playwright-side convention with no `worth` field.
27
+
28
+ import { test } from 'bun:test'
29
+
30
+ export { inAFreshProcess } from './inAFreshProcess.ts'
31
+ export { spawned } from './spawned.ts'
32
+
33
+ /** A gate's runnable revert and the numbers the broken arm reports. */
34
+ export type GateSpec = {
35
+ /**
36
+ * Installs the broken arm and hands back the undo.
37
+ *
38
+ * A gate whose revert cannot be installed — a module-level guard, a shape decided at
39
+ * construction — keeps its revert in the test's comment with the number it reports; this
40
+ * field is for the ones where the arm is swappable.
41
+ */
42
+ revert: () => unknown
43
+ /**
44
+ * What the broken arm reports.
45
+ *
46
+ * Every value has to appear in the failure the reverted run produces, or the revert did not
47
+ * reach the mechanism.
48
+ */
49
+ worth: Record<string, number | string>
50
+ }
51
+
52
+ // The reverts double the gate count and some are not cheap, so they are opt-in.
53
+ // Whether that becomes a nightly rather than a flag is not decided here.
54
+ const VERIFYING = process.env.HARNESS_VERIFY_GATES === '1'
55
+
56
+ /**
57
+ * Registers `body` as a test and, under `HARNESS_VERIFY_GATES=1`, a second test that runs it
58
+ * with the revert installed and asserts it fails reporting every `worth` value.
59
+ */
60
+ export function gate(
61
+ name: string,
62
+ spec: GateSpec,
63
+ body: () => void | Promise<void>,
64
+ ): void {
65
+ if (Object.keys(spec.worth).length === 0)
66
+ throw new Error(
67
+ `gate("${name}") states no \`worth\`. A revert with nothing to report is a revert nobody can tell landed.`,
68
+ )
69
+ test(name, body)
70
+ if (!VERIFYING) return
71
+ test(`${name} — fails with the mechanism out`, async () => {
72
+ const restore = spec.revert()
73
+ let failure: unknown
74
+ try {
75
+ await body()
76
+ } catch (error) {
77
+ failure = error
78
+ } finally {
79
+ if (typeof restore === 'function') (restore as () => void)()
80
+ }
81
+ if (failure === undefined)
82
+ throw new Error(
83
+ `gate("${name}") passed with the mechanism out. A case reporting the same number either way distinguishes nothing, and this gate is worth nothing.`,
84
+ )
85
+ const reported = String(
86
+ (failure as { message?: string }).message ?? failure,
87
+ )
88
+ for (const [counter, value] of Object.entries(spec.worth)) {
89
+ if (reported.includes(String(value))) continue
90
+ throw new Error(
91
+ `gate("${name}") failed with the mechanism out, but not with the number it is worth: \`${counter}\` should report ${value} and the failure was:\n${reported}`,
92
+ )
93
+ }
94
+ })
95
+ }