@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.
@@ -0,0 +1,144 @@
1
+ // THE CLAIM. A performance claim is a ratio against hand-written code in the same
2
+ // substrate, and this is the only thing in the package that divides two durations.
3
+ //
4
+ // It returns a DISCRIMINATED result rather than a number, and that is the whole point
5
+ // of the type: two `underOneFrame` samples divide to 1.01x, which is `read-invoice`'s
6
+ // hand-typed "First paint 16.8 ms / 16.7 ms / 1.01x" — noise published as a claim, by
7
+ // the producer that exists to refuse it.
8
+
9
+ import type { Sample } from './Sample.ts'
10
+
11
+ /**
12
+ * A verdict on two samples: a ratio, or the reason there is none.
13
+ *
14
+ * `underOneFrame` and `underTheFloor` carry no value, so noise cannot be printed as a claim.
15
+ */
16
+ export type Ratio =
17
+ | {
18
+ kind: 'ratio'
19
+ case: string
20
+ numerator: string
21
+ denominator: string
22
+ value: number
23
+ workDisagreement: string[]
24
+ }
25
+ | {
26
+ kind: 'underOneFrame'
27
+ case: string
28
+ numerator: string
29
+ denominator: string
30
+ workDisagreement: string[]
31
+ }
32
+ | {
33
+ kind: 'underTheFloor'
34
+ case: string
35
+ numerator: string
36
+ denominator: string
37
+ floor: number
38
+ workDisagreement: string[]
39
+ }
40
+
41
+ /** The floor and work tolerance a `ratio()` is judged against. */
42
+ export type RatioSpec = {
43
+ /** The A/A spread `batch()` measured for this case, on this machine, today. */
44
+ floor: number
45
+ /**
46
+ * How far two arms' work counters may diverge before the comparison is flagged.
47
+ *
48
+ * Byte-identical page source ran 4.5x apart because one arm shipped a stylesheet and the
49
+ * other was therefore not doing the work at all.
50
+ */
51
+ workFactor?: number
52
+ }
53
+
54
+ const DEFAULT_WORK_FACTOR = 1.05
55
+
56
+ /**
57
+ * The work counters on which two samples disagree by more than `factor`, one line each.
58
+ *
59
+ * An existence proof is believed AFTER the counters agree, not before. This was prose with
60
+ * nothing wired to it, and an arm you wrote yourself gets more of this, not less.
61
+ */
62
+ function disagreeingWork(
63
+ numerator: Sample,
64
+ denominator: Sample,
65
+ factor: number,
66
+ ): string[] {
67
+ const one = numerator.work
68
+ const two = denominator.work
69
+ if (!one || !two) return []
70
+ const flagged: string[] = []
71
+ const counters = new Set([...Object.keys(one), ...Object.keys(two)])
72
+ for (const counter of counters) {
73
+ const left = one[counter] ?? 0
74
+ const right = two[counter] ?? 0
75
+ if (left === right) continue
76
+ const larger = Math.max(left, right)
77
+ const smaller = Math.min(left, right)
78
+ if (smaller === 0 || larger / smaller > factor)
79
+ flagged.push(
80
+ `${counter}: ${numerator.arm} ${left}, ${denominator.arm} ${right}`,
81
+ )
82
+ }
83
+ return flagged
84
+ }
85
+
86
+ /**
87
+ * Divides two arms' timings into a `Ratio`, refusing comparisons that should not be made.
88
+ *
89
+ * Throws on the same arm twice, two cases, two substrates, or two batch sizes.
90
+ */
91
+ export function ratio(
92
+ numerator: Sample,
93
+ denominator: Sample,
94
+ spec: RatioSpec,
95
+ ): Ratio {
96
+ if (numerator.arm === denominator.arm)
97
+ throw new Error(
98
+ `ratio() was given "${numerator.arm}" twice — an arm measured against itself.`,
99
+ )
100
+ if (numerator.case !== denominator.case)
101
+ throw new Error(
102
+ `ratio() was given two cases: "${numerator.case}" and "${denominator.case}".`,
103
+ )
104
+ // Refusal 1. The same graph is 1.67x a hand-written signal under JSC and 0.21x
105
+ // under V8 — inverted, not scaled, so there is no number to average.
106
+ if (numerator.substrate !== denominator.substrate)
107
+ throw new Error(
108
+ `ratio("${numerator.case}") was given a ${numerator.substrate} arm and a ${denominator.substrate} arm. Both arms or neither.`,
109
+ )
110
+ if (numerator.n !== denominator.n)
111
+ throw new Error(
112
+ `ratio("${numerator.case}") was given n=${numerator.n} against n=${denominator.n}. A per-op figure at n=10,000 has different GC and cache behavior than at n=10.`,
113
+ )
114
+
115
+ const workDisagreement = disagreeingWork(
116
+ numerator,
117
+ denominator,
118
+ spec.workFactor ?? DEFAULT_WORK_FACTOR,
119
+ )
120
+ const shared = {
121
+ case: numerator.case,
122
+ numerator: numerator.arm,
123
+ denominator: denominator.arm,
124
+ workDisagreement,
125
+ }
126
+ if (numerator.underOneFrame || denominator.underOneFrame)
127
+ return { kind: 'underOneFrame', ...shared }
128
+ const value = numerator.nanoseconds / denominator.nanoseconds
129
+ if (Math.abs(value - 1) <= spec.floor)
130
+ return { kind: 'underTheFloor', ...shared, floor: spec.floor }
131
+ return { kind: 'ratio', ...shared, value }
132
+ }
133
+
134
+ /**
135
+ * A verdict as the text a bench row prints.
136
+ *
137
+ * Only a `ratio` is a number; the other two say why there is none.
138
+ */
139
+ export function claimOf(result: Ratio): string {
140
+ if (result.kind === 'ratio') return `${result.value.toFixed(2)}x`
141
+ if (result.kind === 'underTheFloor')
142
+ return `under the floor (${(result.floor * 100).toFixed(1)}%)`
143
+ return 'under one frame — not resolvable by a wall clock'
144
+ }
@@ -0,0 +1,26 @@
1
+ import { underBun } from './environment.ts'
2
+
3
+ /**
4
+ * Which JS engine this is, read off the user agent rather than probed.
5
+ *
6
+ * A feature probe would be better and there is no longer one: `Error.captureStackTrace` was
7
+ * V8-only and is now in JSC and SpiderMonkey too, `InternalError` reads `undefined` in every
8
+ * engine tested here, and `webkitURL` / `onwebkitanimationend` are true in Chromium as well as
9
+ * WebKit. Measured across chromium 1243 and webkit 2336 — every candidate discriminator came back
10
+ * identical in both.
11
+ *
12
+ * This matters more than it did when the only two substrates were `bun test` and a chromium
13
+ * gate. The same graph reads 1.67x a hand-written signal under JSC and 0.21x under V8, and a
14
+ * panel that measures in the reader's own browser meets all three engines. Reporting `v8` for
15
+ * Safari would let `ratio()` compare two of them.
16
+ */
17
+ export function substrate(): 'jsc' | 'v8' | 'spidermonkey' | 'unknown' {
18
+ // Bun IS JSC, and it is the one case with no user agent worth reading.
19
+ if (underBun()) return 'jsc'
20
+ const agent = globalThis.navigator?.userAgent ?? ''
21
+ if (/Firefox\//.test(agent)) return 'spidermonkey'
22
+ // Chromium's agent carries `Safari/` too, so this order is the whole check.
23
+ if (/Edg\/|Chrome\/|Chromium\//.test(agent)) return 'v8'
24
+ if (/Safari\//.test(agent)) return 'jsc'
25
+ return 'unknown'
26
+ }
@@ -0,0 +1,91 @@
1
+ // WHAT THE BENCH AND TESTS PAGES READ, AND WHAT THE TWO RUNNERS WRITE. Both runners are
2
+ // subprocesses printing one JSON row per line; the docs app pipes those lines to the page without
3
+ // reading them, so this module is the whole of the contract between the two packages.
4
+ //
5
+ // PURE, AND IMPORTED BY THE PAGE: the filter a reader types and the filter the runner applies are
6
+ // this one function, so "run what I can see" runs exactly the rows on screen.
7
+
8
+ export type RowItem = { id: string; section: string; name: string }
9
+
10
+ /**
11
+ * Where a row is in its run.
12
+ *
13
+ * `broken` is the RUNNER failing — no report, a thrown bench — and is not a red result.
14
+ */
15
+ export type RowState = 'queued' | 'running' | 'done' | 'broken'
16
+
17
+ export type BenchRow = {
18
+ id: string
19
+ state: RowState
20
+ unit: string
21
+ /** The code under measurement's figure, in `unit`. */
22
+ subject: number | null
23
+ /** The hand-written arm's figure, in `unit`. */
24
+ handWritten: number | null
25
+ /** subject / handWritten as the lane is allowed to say it: a number, or why there is none. */
26
+ claim: string
27
+ /** The operations batched into one sample — `null` for a row that counts rather than times. */
28
+ n: number | null
29
+ /** The A/A floor as a fraction — `null` for a row that counts rather than times. */
30
+ floor: number | null
31
+ note: string
32
+ }
33
+
34
+ export type TestRow = {
35
+ id: string
36
+ state: RowState
37
+ tests: number
38
+ failures: number
39
+ skipped: number
40
+ milliseconds: number
41
+ /** Every test the file ran, in the order its report lists them. */
42
+ cases: TestCase[]
43
+ note: string
44
+ }
45
+
46
+ /**
47
+ * One test in a file, as its report gave it.
48
+ *
49
+ * A failure carries the message the runner wrote.
50
+ */
51
+ export type TestCase = {
52
+ name: string
53
+ milliseconds: number
54
+ skipped: boolean
55
+ failure: string | null
56
+ }
57
+
58
+ /**
59
+ * The line the docs app writes after the rows it did send when a runner died part way.
60
+ *
61
+ * A stream whose head has gone out cannot fail with a status, and cut off it reads as a network
62
+ * error that says nothing of the runner's own.
63
+ */
64
+ export type RunnerFailure = { failure: string }
65
+
66
+ export function isRunnerFailure(line: object): line is RunnerFailure {
67
+ return typeof (line as { failure?: unknown }).failure === 'string'
68
+ }
69
+
70
+ /**
71
+ * Whether `item` falls in `scope`: `all`, `section:<name>`, `item:<id>`, or nothing at all.
72
+ *
73
+ * The page's first render asks for nothing, so a reader who opened the page has not started a run.
74
+ */
75
+ export function inScope(item: RowItem, scope: string): boolean {
76
+ if (scope === 'all') return true
77
+ if (scope.startsWith('section:'))
78
+ return item.section === scope.slice('section:'.length)
79
+ if (scope.startsWith('item:'))
80
+ return item.id === scope.slice('item:'.length)
81
+ return false
82
+ }
83
+
84
+ /** Whether the typed filter is a case-insensitive substring of the item's section and name. */
85
+ export function matchesFilter(item: RowItem, filter: string): boolean {
86
+ const wanted = filter.trim().toLowerCase()
87
+ return (
88
+ wanted === '' ||
89
+ `${item.section} ${item.name}`.toLowerCase().includes(wanted)
90
+ )
91
+ }
@@ -0,0 +1,9 @@
1
+ // RUNNERS THAT PRINT ROWS. A runner is a subprocess writing one JSON row per line, so a page or a
2
+ // terminal reading it never shares the process a suite or a bench runs in — its clock, its heap,
3
+ // its event loop. `@abide/harness/rows` is the contract the rows keep; this is what writes them.
4
+ //
5
+ // Not a lane: it depends on bun and on whichever test runner a suite names, and it measures
6
+ // nothing itself.
7
+
8
+ export { rowsCommand } from './rowsCommand.ts'
9
+ export { type TestSuite, testRows } from './testRows.ts'
@@ -0,0 +1,33 @@
1
+ // THE COMMAND LINE BOTH ROW RUNNERS SHARE. `--list` prints the catalog as one JSON array; anything
2
+ // else runs what `--scope` and `--filter` select and prints one row per line as each lands.
3
+ // Stdout is the channel, so a runner reports through `emit` and never through `console.log`.
4
+
5
+ import { inScope, matchesFilter, type RowItem } from '../rows/index.ts'
6
+
7
+ function flag(name: string): string {
8
+ const at = process.argv.indexOf(name)
9
+ return at === -1 ? '' : (process.argv[at + 1] ?? '')
10
+ }
11
+
12
+ /** Prints `items` as a catalog under `--list`, or runs the selected ones and streams their rows. */
13
+ export async function rowsCommand<Item extends RowItem, Row>(
14
+ items: Item[],
15
+ run: (selected: Item[], emit: (row: Row) => void) => Promise<void>,
16
+ ): Promise<void> {
17
+ if (process.argv.includes('--list')) {
18
+ const catalog: RowItem[] = []
19
+ for (const { id, section, name } of items)
20
+ catalog.push({ id, section, name })
21
+ process.stdout.write(`${JSON.stringify(catalog)}\n`)
22
+ return
23
+ }
24
+ const scope = flag('--scope')
25
+ const filter = flag('--filter')
26
+ const selected: Item[] = []
27
+ for (const item of items)
28
+ if (inScope(item, scope) && matchesFilter(item, filter))
29
+ selected.push(item)
30
+ await run(selected, (row) => {
31
+ process.stdout.write(`${JSON.stringify(row)}\n`)
32
+ })
33
+ }
@@ -0,0 +1,155 @@
1
+ // ONE TEST FILE, RUN AND PARSED. `bun test` and playwright both speak JUnit, so one parser
2
+ // serves both and the tests page does not learn two shapes.
3
+ //
4
+ // ONE FILE PER PROCESS, so a row lands the moment its file finishes rather than after the
5
+ // slowest one — and a file that fails ALONE is the honest reading (CLAUDE.md, "checks").
6
+ //
7
+ // A FAILING SUITE IS A RESULT, NOT AN ERROR. This never throws on a red run — a page whose
8
+ // whole job is showing what is red cannot fall over when something is. It throws only when the
9
+ // runner produced no report at all, which is a different thing and one the page has to say out
10
+ // loud: a suite that HANGS reports nothing, and "0 failures" read off an absent file is the worst
11
+ // answer available.
12
+
13
+ import { tmpdir } from 'node:os' // bun has no temporary-directory lookup of its own
14
+ import type { TestCase } from '../rows/index.ts'
15
+
16
+ // A RUNNER THAT IS STOPPED STOPS ITS SUITES. SIGTERM reaches this process and nothing under it, so
17
+ // without passing it on a Stop orphans every `bun test` and browser still running, and the next
18
+ // run shares the machine with them — which is what turns a timing gate red.
19
+ // A killed suite never reaches the end where its JUnit file is written, so there is none to delete.
20
+ //
21
+ // SIGINT, NOT SIGTERM, passed on: playwright tears down its `webServer` on the first and not the
22
+ // second, which left `abide start` holding port 3131 under launchd after every Stop.
23
+ //
24
+ // TO THE SUITE'S WHOLE GROUP. A test file that serves an app spawns `abide dev` itself and stops it
25
+ // in `afterAll`, which a stopped file never reaches — so each suite leads a group of its own and
26
+ // the group is what is signaled. Its own group is also why a Ctrl-C at this runner's terminal is
27
+ // passed on rather than reaching the suites directly.
28
+ const LIVE = new Set<Bun.Subprocess>()
29
+ for (const [signal, code] of [
30
+ ['SIGTERM', 143],
31
+ ['SIGINT', 130],
32
+ ] as const)
33
+ process.on(signal, () => {
34
+ for (const child of LIVE) {
35
+ try {
36
+ process.kill(-child.pid, 'SIGINT')
37
+ } catch {
38
+ // The group emptied between its suite ending and this signal.
39
+ }
40
+ }
41
+ process.exit(code)
42
+ })
43
+
44
+ export type Suite = {
45
+ file: string
46
+ tests: number
47
+ failures: number
48
+ skipped: number
49
+ cases: TestCase[]
50
+ }
51
+
52
+ function attribute(tag: string, name: string): string {
53
+ return new RegExp(`${name}="([^"]*)"`).exec(tag)?.[1] ?? ''
54
+ }
55
+
56
+ function unescapeXml(value: string): string {
57
+ return value
58
+ .replaceAll('&#10;', '\n')
59
+ .replaceAll('&quot;', '"')
60
+ .replaceAll('&apos;', "'")
61
+ .replaceAll('&lt;', '<')
62
+ .replaceAll('&gt;', '>')
63
+ .replaceAll('&amp;', '&')
64
+ }
65
+
66
+ /** One `Suite` per `<testsuite>` in a JUnit report, bun's or playwright's. */
67
+ export function parseJUnit(xml: string): Suite[] {
68
+ const suites: Suite[] = []
69
+ for (const block of xml.split('<testsuite ').slice(1)) {
70
+ const head = block.slice(0, block.indexOf('>'))
71
+ const cases: TestCase[] = []
72
+ for (const entry of block.split('<testcase ').slice(1)) {
73
+ const caseHead = entry.slice(0, entry.indexOf('>'))
74
+ const failure = /<failure[^>]*message="([^"]*)"/.exec(entry)
75
+ cases.push({
76
+ name: unescapeXml(attribute(caseHead, 'name')),
77
+ milliseconds:
78
+ Number.parseFloat(attribute(caseHead, 'time')) * 1000,
79
+ // Both runners mark a skipped case, a `todo` included, with the one element.
80
+ skipped: /<skipped\b/.test(entry),
81
+ failure: failure ? unescapeXml(failure[1] ?? '') : null,
82
+ })
83
+ }
84
+ suites.push({
85
+ file: attribute(head, 'name'),
86
+ tests: Number.parseInt(attribute(head, 'tests'), 10) || 0,
87
+ failures: Number.parseInt(attribute(head, 'failures'), 10) || 0,
88
+ skipped: Number.parseInt(attribute(head, 'skipped'), 10) || 0,
89
+ cases,
90
+ })
91
+ }
92
+ return suites
93
+ }
94
+
95
+ /**
96
+ * How a runner is pointed at its JUnit report: the args and environment for a given path.
97
+ *
98
+ * Supplied by the caller rather than branched on here: `bun test` takes `--reporter-outfile` and
99
+ * playwright takes `PLAYWRIGHT_JUNIT_OUTPUT_NAME`, and a runner that took a third spelling would be
100
+ * a third caller rather than a third branch.
101
+ */
102
+ export type ReportTo = (path: string) => {
103
+ args: string[]
104
+ environment: Record<string, string>
105
+ }
106
+
107
+ export const BUN_REPORT: ReportTo = (path) => ({
108
+ args: ['--reporter=junit', `--reporter-outfile=${path}`],
109
+ environment: {},
110
+ })
111
+
112
+ export const PLAYWRIGHT_REPORT: ReportTo = (path) => ({
113
+ args: ['--reporter=junit'],
114
+ environment: { PLAYWRIGHT_JUNIT_OUTPUT_NAME: path },
115
+ })
116
+
117
+ /**
118
+ * Runs one test command with a JUnit reporter and returns its parsed suites and wall time.
119
+ *
120
+ * A red run resolves; only a missing report throws — see the file header.
121
+ */
122
+ export async function runSuite(spec: {
123
+ command: string[]
124
+ reportTo: ReportTo
125
+ cwd: string
126
+ environment?: Record<string, string>
127
+ }): Promise<{ suites: Suite[]; milliseconds: number }> {
128
+ const report = `${tmpdir()}/abide-suite-${crypto.randomUUID()}.xml`
129
+ const pointed = spec.reportTo(report)
130
+ const startedAt = Bun.nanoseconds()
131
+ const child = Bun.spawn({
132
+ cmd: [...spec.command, ...pointed.args],
133
+ cwd: spec.cwd,
134
+ env: { ...process.env, ...spec.environment, ...pointed.environment },
135
+ stdout: 'ignore',
136
+ stderr: 'pipe',
137
+ detached: true,
138
+ })
139
+ LIVE.add(child)
140
+ const [stderr] = await Promise.all([
141
+ new Response(child.stderr).text(),
142
+ child.exited,
143
+ ])
144
+ LIVE.delete(child)
145
+ const milliseconds = (Bun.nanoseconds() - startedAt) / 1e6
146
+
147
+ const file = Bun.file(report)
148
+ if (!(await file.exists()))
149
+ throw new Error(
150
+ `the runner wrote no report — a suite that HANGS or never starts reports nothing, and an absent file must not be read as zero failures.\n${stderr.slice(-2000)}`,
151
+ )
152
+ const suites = parseJUnit(await file.text())
153
+ await file.delete()
154
+ return { suites, milliseconds }
155
+ }
@@ -0,0 +1,168 @@
1
+ // TEST FILES AS ROWS — one row per file, so a row lands the moment its own file finishes. One
2
+ // file per process: `bun test` files eight at a time, playwright specs one at a time, because every
3
+ // spec under one config shares the servers and ports its `webServer` starts.
4
+ //
5
+ // THE SUITES ARE THE CALLER'S. A runner script names which directories hold which kind of file and
6
+ // calls this; `--list`, `--scope` and `--filter` are `rowsCommand`'s, and `--gates` runs every
7
+ // `gate()`'s revert as well (RULEBOOK 43.9).
8
+
9
+ import type { RowItem, TestRow } from '../rows/index.ts'
10
+ import { rowsCommand } from './rowsCommand.ts'
11
+ import { BUN_REPORT, PLAYWRIGHT_REPORT, runSuite } from './runSuite.ts'
12
+
13
+ // The worker count is not a lever (CLAUDE.md, "checks"), so this is only "enough to keep a
14
+ // machine busy without every file timing out against the others".
15
+ const BUN_WIDTH = 8
16
+
17
+ /**
18
+ * One directory of test files, listed under one section.
19
+ *
20
+ * `bun` runs every `*.test.ts` below `root`; `playwright` runs every `*.spec.ts` directly in it,
21
+ * in the named projects, so a spec runs in the projects its directory is served by. `pattern`
22
+ * replaces either glob, relative to `root`.
23
+ */
24
+ export type TestSuite =
25
+ | { section: string; root: string; runner: 'bun'; pattern?: string }
26
+ | {
27
+ section: string
28
+ root: string
29
+ runner: 'playwright'
30
+ projects: string[]
31
+ pattern?: string
32
+ }
33
+
34
+ type TestItem = RowItem & { command: string[]; browser: boolean }
35
+
36
+ function testFiles(cwd: string, root: string, pattern: string): string[] {
37
+ const files: string[] = []
38
+ for (const file of new Bun.Glob(pattern).scanSync({
39
+ cwd: `${cwd}/${root}`,
40
+ }))
41
+ if (!file.includes('node_modules/')) files.push(`${root}/${file}`)
42
+ return files.sort()
43
+ }
44
+
45
+ function itemsOf(suites: TestSuite[], cwd: string): TestItem[] {
46
+ const all: TestItem[] = []
47
+ for (const suite of suites) {
48
+ if (suite.runner === 'bun') {
49
+ for (const file of testFiles(
50
+ cwd,
51
+ suite.root,
52
+ suite.pattern ?? '**/*.test.ts',
53
+ ))
54
+ all.push({
55
+ id: file,
56
+ section: suite.section,
57
+ name: file.slice(suite.root.length + 1),
58
+ // `./` or bun reads the path as a name filter.
59
+ command: ['bun', 'test', `./${file}`],
60
+ browser: false,
61
+ })
62
+ continue
63
+ }
64
+ const named: string[] = []
65
+ for (const project of suite.projects) named.push('--project', project)
66
+ for (const file of testFiles(
67
+ cwd,
68
+ suite.root,
69
+ suite.pattern ?? '*.spec.ts',
70
+ ))
71
+ all.push({
72
+ id: file,
73
+ section: suite.section,
74
+ name: file.slice(suite.root.length + 1),
75
+ command: ['bunx', 'playwright', 'test', file, ...named],
76
+ browser: true,
77
+ })
78
+ }
79
+ return all
80
+ }
81
+
82
+ function emptyRow(id: string, state: TestRow['state']): TestRow {
83
+ return {
84
+ id,
85
+ state,
86
+ tests: 0,
87
+ failures: 0,
88
+ skipped: 0,
89
+ milliseconds: 0,
90
+ cases: [],
91
+ note: '',
92
+ }
93
+ }
94
+
95
+ async function runOne(
96
+ item: TestItem,
97
+ gates: boolean,
98
+ cwd: string,
99
+ ): Promise<TestRow> {
100
+ const row = emptyRow(item.id, 'done')
101
+ try {
102
+ const { suites, milliseconds } = await runSuite({
103
+ command: item.command,
104
+ reportTo: item.browser ? PLAYWRIGHT_REPORT : BUN_REPORT,
105
+ cwd,
106
+ environment: gates ? { HARNESS_VERIFY_GATES: '1' } : {},
107
+ })
108
+ row.milliseconds = milliseconds
109
+ for (const suite of suites) {
110
+ row.tests += suite.tests
111
+ row.failures += suite.failures
112
+ row.skipped += suite.skipped
113
+ for (const one of suite.cases) row.cases.push(one)
114
+ }
115
+ } catch (error) {
116
+ row.state = 'broken'
117
+ row.note = error instanceof Error ? error.message : String(error)
118
+ }
119
+ return row
120
+ }
121
+
122
+ /** A fixed number of workers pulling from one queue, so a row lands when its own file finishes. */
123
+ async function pool<Item>(
124
+ queue: Item[],
125
+ width: number,
126
+ work: (item: Item) => Promise<void>,
127
+ ): Promise<void> {
128
+ let next = 0
129
+ const workers: Promise<void>[] = []
130
+ for (let at = 0; at < Math.min(width, queue.length); at += 1)
131
+ workers.push(
132
+ (async () => {
133
+ while (next < queue.length) await work(queue[next++] as Item)
134
+ })(),
135
+ )
136
+ await Promise.all(workers)
137
+ }
138
+
139
+ /**
140
+ * Lists `suites` as rows under `--list`, or runs the files `--scope` and `--filter` select and
141
+ * prints one `TestRow` per line as each file finishes. `cwd` is what every suite's `root` is
142
+ * relative to, and where each file runs.
143
+ */
144
+ export async function testRows(
145
+ suites: TestSuite[],
146
+ cwd: string,
147
+ ): Promise<void> {
148
+ await rowsCommand<TestItem, TestRow>(
149
+ itemsOf(suites, cwd),
150
+ async (selected, emit) => {
151
+ const gates = process.argv.includes('--gates')
152
+ const unitFiles: TestItem[] = []
153
+ const browserFiles: TestItem[] = []
154
+ for (const item of selected) {
155
+ ;(item.browser ? browserFiles : unitFiles).push(item)
156
+ emit(emptyRow(item.id, 'queued'))
157
+ }
158
+ const run = async (item: TestItem): Promise<void> => {
159
+ emit(emptyRow(item.id, 'running'))
160
+ emit(await runOne(item, gates, cwd))
161
+ }
162
+ await Promise.all([
163
+ pool(unitFiles, BUN_WIDTH, run),
164
+ pool(browserFiles, 1, run),
165
+ ])
166
+ },
167
+ )
168
+ }
@@ -0,0 +1,56 @@
1
+ // WHAT AN OP ALLOCATED, which `heapStats()` cannot see and this therefore does not
2
+ // pretend to report exactly. A batch mean, tagged, and the tag is the point: an exact
3
+ // integer is `retained()`'s to hand out, and a fractional reading like `Object:3.09`
4
+ // is a reachability artifact rather than a genuinely fractional quantity.
5
+ //
6
+ // What a fractional per-rep count IS good for is the other question: a non-integer
7
+ // means the allocation is conditional or amortized — a rehash, an IC transition, a
8
+ // once-per-batch structure — and a mean over the whole batch hides which. So the
9
+ // batch is halved and the two halves are reported apart. Zero growth across them is
10
+ // the leak check.
11
+
12
+ import { countsMoved, liveCounts } from './liveCounts.ts'
13
+
14
+ const DEFAULT_REPS = 1000
15
+
16
+ /**
17
+ * Mean objects per rep by JSC type over a batch, and how that mean grew between its halves.
18
+ *
19
+ * A batch mean, never exact — gate exact counts on `retained()`. Throws in a process with a DOM.
20
+ */
21
+ export function allocated(
22
+ body: () => unknown,
23
+ reps = DEFAULT_REPS,
24
+ ): {
25
+ /**
26
+ * Always `'batch mean'`.
27
+ *
28
+ * A literal, so this record can never be `toMatchObject`'d against an exact integer the way a
29
+ * `retained()` diff is.
30
+ */
31
+ tagged: 'batch mean'
32
+ reps: number
33
+ perRep: Record<string, number>
34
+ /**
35
+ * The last half's mean minus the first half's, per rep.
36
+ *
37
+ * A type that grows across the batch is retaining rather than allocating.
38
+ */
39
+ growth: Record<string, number>
40
+ } {
41
+ const half = Math.max(1, Math.floor(reps / 2))
42
+ const start = liveCounts('allocated')
43
+ for (let rep = 0; rep < half; rep += 1) body()
44
+ const middle = liveCounts('allocated')
45
+ for (let rep = 0; rep < half; rep += 1) body()
46
+ const end = liveCounts('allocated')
47
+
48
+ const first = countsMoved(start, middle, half)
49
+ const second = countsMoved(middle, end, half)
50
+ return {
51
+ tagged: 'batch mean',
52
+ reps: half * 2,
53
+ perRep: countsMoved(start, end, half * 2),
54
+ growth: countsMoved(first, second, 1),
55
+ }
56
+ }