ostia 0.2.11 → 0.3.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.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -353
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +942 -642
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +416 -0
  37. package/src/cli/flags.ts +264 -0
  38. package/{chunk-scvezzm9.js → src/cli/help.ts} +31 -15
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-5m601yfv.js +0 -15
  89. package/chunk-82vs1rw1.js +0 -2
  90. package/chunk-dvqggjkn.js +0 -14
  91. package/chunk-fc36fd0b.js +0 -3
  92. package/chunk-pdv5zb3w.js +0 -27
  93. package/chunk-r6hwb84z.js +0 -25
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,617 @@
1
+ import { fp } from "../ir/fp.ts";
2
+ import type {
3
+ ComparedTask,
4
+ Comparison,
5
+ ComparisonSummary,
6
+ Environment,
7
+ Measurement,
8
+ MemoryDelta,
9
+ ProfileDocument,
10
+ TimingStats,
11
+ Warning,
12
+ Workload,
13
+ } from "../ir/types.ts";
14
+ import { workloadLabel } from "../renderers/format.ts";
15
+ import { bootstrapMedianDiffCi } from "../stats/bootstrap.ts";
16
+ import { mannWhitneyU } from "../stats/mannwhitney.ts";
17
+
18
+ export interface Thresholds {
19
+ timingPct: number;
20
+ frameSelfPct: number;
21
+ heapTypePct: number;
22
+ minFrameSelfUs: number;
23
+ /**
24
+ * A `regressed` / `improved` verdict also requires Mann-Whitney `pValue <
25
+ * alpha`.
26
+ */
27
+ alpha: number;
28
+ /** Bootstrap resample rounds for the timing CI. */
29
+ bootstrapIterations: number;
30
+ }
31
+
32
+ export const DEFAULT_THRESHOLDS: Thresholds = {
33
+ timingPct: 5,
34
+ frameSelfPct: 10,
35
+ heapTypePct: 10,
36
+ minFrameSelfUs: 1000,
37
+ alpha: 0.01,
38
+ bootstrapIterations: 2000,
39
+ };
40
+
41
+ /**
42
+ * Below this many samples on either side, fall back to the point-estimate
43
+ * rule (with a `thin-comparison` warning): CI and p-value are too noisy.
44
+ * */
45
+ const MIN_SAMPLES_FOR_TEST = 5;
46
+
47
+ function pctDelta(base: number, cand: number): number {
48
+ if (base === 0) return cand === 0 ? 0 : Infinity;
49
+ return ((cand - base) / base) * 100;
50
+ }
51
+
52
+ type Phase = "timing" | "cpu" | "heap";
53
+
54
+ type Lookup = (workloadId: string, phase: Phase) => Measurement | undefined;
55
+
56
+ /** Built once per pair instead of re-scanning both documents per workload. */
57
+ interface CompareIndex {
58
+ base: Lookup;
59
+ cand: Lookup;
60
+ baseMemory: (workloadId: string) => MemoryReadings;
61
+ candMemory: (workloadId: string) => MemoryReadings;
62
+ baseWorkloads: Map<string, Workload>;
63
+ candWorkloads: Map<string, Workload>;
64
+ /**
65
+ * The base workload a candidate workload compares against: its own id,
66
+ * else the first of its `formerIds` the base has. */
67
+ baseIdFor: (candWorkloadId: string) => string | undefined;
68
+ environmentMismatch: Warning | undefined;
69
+ driftPct: number | undefined;
70
+ effectiveTimingPct: number;
71
+ }
72
+
73
+ function indexMeasurements(doc: ProfileDocument): Lookup {
74
+ const byPhase = new Map<string, Measurement>();
75
+ for (const m of doc.measurements) {
76
+ const key = `${m.workloadId}\u0000${m.phase}`;
77
+ if (!byPhase.has(key)) byPhase.set(key, m);
78
+ }
79
+ return (workloadId: string, phase: Phase) =>
80
+ byPhase.get(`${workloadId}\u0000${phase}`);
81
+ }
82
+
83
+ type MemoryReadings = Partial<Record<MemoryDelta["reading"], number>>;
84
+
85
+ /**
86
+ * Every memory reading per workload, from its timing and `memstats`
87
+ * measurements. */
88
+ function indexMemory(doc: ProfileDocument): (id: string) => MemoryReadings {
89
+ const byWorkload = new Map<string, MemoryReadings>();
90
+ for (const m of doc.measurements) {
91
+ const mem = m.memory;
92
+ if (!mem || (m.phase !== "timing" && m.phase !== "memstats")) continue;
93
+ const readings = byWorkload.get(m.workloadId) ?? {};
94
+ if (m.phase === "timing") {
95
+ readings.heapUsedBefore = mem.heapUsedBeforeBytes;
96
+ readings.heapUsedAfter = mem.heapUsedAfterBytes;
97
+ readings.maxRss = mem.maxRssBytes;
98
+ } else if (mem.kind === "peak") {
99
+ readings.peak = mem.peakBytes;
100
+ } else {
101
+ readings.retained = mem.bytesPerOp;
102
+ }
103
+ byWorkload.set(m.workloadId, readings);
104
+ }
105
+ return (id) => byWorkload.get(id) ?? {};
106
+ }
107
+
108
+ /**
109
+ * The reference loop's mean speed over a run: the start and end readings
110
+ * averaged when the run re-measured it. */
111
+ function meanReferenceNs(env: Environment): number {
112
+ const { referenceMedianNs, driftPct } = env.noise;
113
+ return referenceMedianNs * (1 + (driftPct ?? 0) / 200);
114
+ }
115
+
116
+ /**
117
+ * How far the machine's speed moved within either run, or between them,
118
+ * percent; `undefined` unless both runs measured their noise floor. */
119
+ function machineDriftPct(
120
+ base: ProfileDocument,
121
+ cand: ProfileDocument,
122
+ ): number | undefined {
123
+ if (!base.environment || !cand.environment) return undefined;
124
+ const baseRef = meanReferenceNs(base.environment);
125
+ const between =
126
+ baseRef > 0 ? (meanReferenceNs(cand.environment) / baseRef - 1) * 100 : 0;
127
+ return Math.max(
128
+ Math.abs(base.environment.noise.driftPct ?? 0),
129
+ Math.abs(cand.environment.noise.driftPct ?? 0),
130
+ Math.abs(between),
131
+ );
132
+ }
133
+
134
+ function buildIndex(
135
+ base: ProfileDocument,
136
+ cand: ProfileDocument,
137
+ thresholds: Thresholds,
138
+ ): CompareIndex {
139
+ const baseWorkloads = new Map(base.workloads.map((w) => [w.id, w]));
140
+ const candWorkloads = new Map(cand.workloads.map((w) => [w.id, w]));
141
+ const driftPct = machineDriftPct(base, cand);
142
+ return {
143
+ base: indexMeasurements(base),
144
+ cand: indexMeasurements(cand),
145
+ baseMemory: indexMemory(base),
146
+ candMemory: indexMemory(cand),
147
+ baseWorkloads,
148
+ candWorkloads,
149
+ baseIdFor: (id) => {
150
+ if (baseWorkloads.has(id)) return id;
151
+ return candWorkloads
152
+ .get(id)
153
+ ?.formerIds?.find((former) => baseWorkloads.has(former));
154
+ },
155
+ environmentMismatch: environmentMismatchWarning(base, cand),
156
+ driftPct,
157
+ // Drift moves every task the same way, so it adds to the threshold
158
+ // instead of competing with it.
159
+ effectiveTimingPct:
160
+ Math.max(
161
+ thresholds.timingPct,
162
+ base.environment?.noise.floorPct ?? 0,
163
+ cand.environment?.noise.floorPct ?? 0,
164
+ ) + (driftPct ?? 0),
165
+ };
166
+ }
167
+
168
+ /**
169
+ * Same warning for every comparison in a pair measured on different
170
+ * machines/Bun versions. `cpuModel`/`cores` are compared only when both
171
+ * sides have `environment`: missing data is unknown, not a mismatch. */
172
+ function environmentMismatchWarning(
173
+ base: ProfileDocument,
174
+ cand: ProfileDocument,
175
+ ): Warning | undefined {
176
+ const candidates: [string, string | number, string | number][] = [
177
+ ["platform.os", base.platform.os, cand.platform.os],
178
+ ["platform.arch", base.platform.arch, cand.platform.arch],
179
+ ["bunVersion", base.bunVersion, cand.bunVersion],
180
+ ];
181
+ if (base.environment && cand.environment) {
182
+ candidates.push(
183
+ ["cpuModel", base.environment.cpuModel, cand.environment.cpuModel],
184
+ ["cores", base.environment.cores, cand.environment.cores],
185
+ );
186
+ }
187
+ const fields = candidates
188
+ .filter(([, b, c]) => b !== c)
189
+ .map(([field, b, c]) => ({ field, base: b, cand: c }));
190
+ if (fields.length === 0) return undefined;
191
+
192
+ return {
193
+ code: "environment-mismatch",
194
+ message: `Base and candidate were measured on different environments (${fields.map((f) => f.field).join(", ")}); a timing delta may reflect that instead of the code change.`,
195
+ data: { fields },
196
+ };
197
+ }
198
+
199
+ export interface CompareResult {
200
+ comparisons: Comparison[];
201
+ unmatched: { baseOnly: Workload[]; candOnly: Workload[] };
202
+ /** Every task on either side; see `ProfileDocument.compared`. */
203
+ compared: ComparedTask[];
204
+ summary: ComparisonSummary;
205
+ }
206
+
207
+ /**
208
+ * Geometric mean of `cand/base` median ratios over comparisons with a
209
+ * timing verdict, as a signed percent (`-4.2` means ~4.2% faster). `null`
210
+ * when none has a finite ratio. */
211
+ function geomeanTimingPct(comparisons: Comparison[]): number | null {
212
+ const logRatios: number[] = [];
213
+ for (const c of comparisons) {
214
+ if (!c.timing) continue;
215
+ const ratio = 1 + c.timing.medianDeltaPct / 100;
216
+ if (Number.isFinite(ratio) && ratio > 0) logRatios.push(Math.log(ratio));
217
+ }
218
+ if (logRatios.length === 0) return null;
219
+ const meanLog = logRatios.reduce((a, b) => a + b, 0) / logRatios.length;
220
+ return (Math.exp(meanLog) - 1) * 100;
221
+ }
222
+
223
+ /**
224
+ * A base/candidate pair indexed once: per-workload comparison plus the
225
+ * pair-level facts `compareDocuments` and `ostia ci` both need. */
226
+ export interface Comparer {
227
+ effectiveTimingPct: number;
228
+ driftPct: number | undefined;
229
+ compare(workloadId: string): Comparison | undefined;
230
+ unmatched(): { baseOnly: Workload[]; candOnly: Workload[] };
231
+ /**
232
+ * The document's `compared`: a row per `[candidate workload id,
233
+ * comparison]` in `matched`, in that order, then the unmatched ones. */
234
+ compared(matched: [string, Comparison][]): ComparedTask[];
235
+ }
236
+
237
+ export function createComparer(
238
+ base: ProfileDocument,
239
+ cand: ProfileDocument,
240
+ thresholds: Thresholds = DEFAULT_THRESHOLDS,
241
+ ): Comparer {
242
+ const index = buildIndex(base, cand, thresholds);
243
+ const unmatched = () => {
244
+ const matchedBaseIds = new Set<string>();
245
+ const candOnly: Workload[] = [];
246
+ for (const w of cand.workloads) {
247
+ const baseId = index.baseIdFor(w.id);
248
+ if (baseId === undefined) candOnly.push(w);
249
+ else matchedBaseIds.add(baseId);
250
+ }
251
+ return {
252
+ baseOnly: base.workloads.filter((w) => !matchedBaseIds.has(w.id)),
253
+ candOnly,
254
+ };
255
+ };
256
+ return {
257
+ effectiveTimingPct: index.effectiveTimingPct,
258
+ driftPct: index.driftPct,
259
+ compare: (workloadId) => compareIndexed(index, workloadId, thresholds),
260
+ unmatched,
261
+ compared(matched) {
262
+ // A candidate workload whose base has no measurement of it (a base
263
+ // `task.skip()`) has no comparison either: it's missing its base too.
264
+ const compared = new Set(matched.map(([id]) => id));
265
+ const candOnly = cand.workloads.filter((w) => !compared.has(w.id));
266
+ const { baseOnly } = unmatched();
267
+ const oneSided = (
268
+ w: Workload,
269
+ verdict: "missing-base" | "missing-cand",
270
+ ): ComparedTask => ({
271
+ workloadId: w.id,
272
+ task: workloadLabel(w),
273
+ ...(w.entry?.group !== undefined && { group: w.entry.group }),
274
+ verdict,
275
+ });
276
+ return [
277
+ ...matched.map(([id, cmp]) => comparedTask(index, id, cmp)),
278
+ ...candOnly.map((w) => oneSided(w, "missing-base")),
279
+ ...baseOnly.map((w) => oneSided(w, "missing-cand")),
280
+ ];
281
+ },
282
+ };
283
+ }
284
+
285
+ // Memory readings in the order rows list them.
286
+ const MEMORY_READINGS: MemoryDelta["reading"][] = [
287
+ "heapUsedBefore",
288
+ "heapUsedAfter",
289
+ "retained",
290
+ "peak",
291
+ "maxRss",
292
+ ];
293
+
294
+ function comparedTask(
295
+ index: CompareIndex,
296
+ workloadId: string,
297
+ cmp: Comparison,
298
+ ): ComparedTask {
299
+ const baseId = index.baseIdFor(workloadId) ?? workloadId;
300
+ const cand = index.candWorkloads.get(workloadId);
301
+ const base = index.baseWorkloads.get(baseId);
302
+ const row: ComparedTask = {
303
+ workloadId,
304
+ task: cand ? workloadLabel(cand) : workloadId,
305
+ ...(cand?.entry?.group !== undefined && { group: cand.entry.group }),
306
+ verdict: cmp.timing?.verdict ?? "unchanged",
307
+ comparisonId: cmp.id,
308
+ pass: cmp.verdict === "pass",
309
+ };
310
+ if (baseId !== workloadId) {
311
+ row.renamedFrom = {
312
+ workloadId: baseId,
313
+ task: base ? workloadLabel(base) : baseId,
314
+ };
315
+ }
316
+ const baseTiming = index.base(baseId, "timing")?.timing;
317
+ const candTiming = index.cand(workloadId, "timing")?.timing;
318
+ if (cmp.timing && baseTiming && candTiming) {
319
+ const { medianDeltaPct, ci95, pValue } = cmp.timing;
320
+ row.timing = {
321
+ unit: "ns",
322
+ baseMedian: baseTiming.median,
323
+ candMedian: candTiming.median,
324
+ baseSamples: baseTiming.samples.length,
325
+ candSamples: candTiming.samples.length,
326
+ medianDeltaPct,
327
+ ...(ci95 && { ci95 }),
328
+ ...(pValue !== undefined && { pValue }),
329
+ thresholdPct: cmp.thresholds.effectiveTimingPct,
330
+ };
331
+ }
332
+ const baseMemory = index.baseMemory(baseId);
333
+ const candMemory = index.candMemory(workloadId);
334
+ const memory: MemoryDelta[] = [];
335
+ for (const reading of MEMORY_READINGS) {
336
+ const baseBytes = baseMemory[reading];
337
+ const candBytes = candMemory[reading];
338
+ if (baseBytes === undefined || candBytes === undefined) continue;
339
+ memory.push({
340
+ reading,
341
+ baseBytes,
342
+ candBytes,
343
+ deltaPct: pctDelta(baseBytes, candBytes),
344
+ });
345
+ }
346
+ if (memory.length > 0) row.memory = memory;
347
+ return row;
348
+ }
349
+
350
+ /** The `comparisonSummary` stamped on a compared document. */
351
+ export function summarizeComparisons(
352
+ comparisons: Comparison[],
353
+ effectiveTimingPct: number,
354
+ driftPct?: number,
355
+ ): ComparisonSummary {
356
+ let regressed = 0;
357
+ let improved = 0;
358
+ let unchanged = 0;
359
+ for (const c of comparisons) {
360
+ if (!c.timing) continue;
361
+ if (c.timing.verdict === "regressed") regressed++;
362
+ else if (c.timing.verdict === "improved") improved++;
363
+ else unchanged++;
364
+ }
365
+ return {
366
+ matched: comparisons.length,
367
+ regressed,
368
+ improved,
369
+ unchanged,
370
+ geomeanPct: geomeanTimingPct(comparisons),
371
+ effectiveTimingPct,
372
+ ...(driftPct !== undefined && { driftPct }),
373
+ verdict: comparisons.some((c) => c.verdict === "fail") ? "fail" : "pass",
374
+ };
375
+ }
376
+
377
+ /**
378
+ * Compares every `cand.workloads` entry that has a match in `base` (in
379
+ * candidate order, as `ostia ci` does), and reports what matched only one
380
+ * side in `unmatched` rather than dropping it. */
381
+ export function compareDocuments(
382
+ base: ProfileDocument,
383
+ cand: ProfileDocument,
384
+ thresholds: Thresholds = DEFAULT_THRESHOLDS,
385
+ ): CompareResult {
386
+ const comparer = createComparer(base, cand, thresholds);
387
+ const matched: [string, Comparison][] = [];
388
+ for (const workload of cand.workloads) {
389
+ const comparison = comparer.compare(workload.id);
390
+ if (comparison) matched.push([workload.id, comparison]);
391
+ }
392
+ const comparisons = matched.map(([, c]) => c);
393
+ return {
394
+ comparisons,
395
+ unmatched: comparer.unmatched(),
396
+ compared: comparer.compared(matched),
397
+ summary: summarizeComparisons(
398
+ comparisons,
399
+ comparer.effectiveTimingPct,
400
+ comparer.driftPct,
401
+ ),
402
+ };
403
+ }
404
+
405
+ export function compareWorkload(
406
+ base: ProfileDocument,
407
+ cand: ProfileDocument,
408
+ workloadId: string,
409
+ thresholds: Thresholds = DEFAULT_THRESHOLDS,
410
+ ): Comparison | undefined {
411
+ return createComparer(base, cand, thresholds).compare(workloadId);
412
+ }
413
+
414
+ type TimingComparison = NonNullable<Comparison["timing"]>;
415
+
416
+ function compareTiming(
417
+ baseTiming: TimingStats,
418
+ candTiming: TimingStats,
419
+ effectiveTimingPct: number,
420
+ thresholds: Thresholds,
421
+ ): { timing: TimingComparison; warning?: Warning } {
422
+ const baseSamples = baseTiming.samples;
423
+ const candSamples = candTiming.samples;
424
+ const medianDeltaPct = pctDelta(baseTiming.median, candTiming.median);
425
+ const meanDeltaPct = pctDelta(baseTiming.mean, candTiming.mean);
426
+
427
+ const verdictFor = (
428
+ low: number,
429
+ high: number,
430
+ ): TimingComparison["verdict"] => {
431
+ if (low > effectiveTimingPct) return "regressed";
432
+ if (high < -effectiveTimingPct) return "improved";
433
+ return "unchanged";
434
+ };
435
+
436
+ if (
437
+ baseSamples.length < MIN_SAMPLES_FOR_TEST ||
438
+ candSamples.length < MIN_SAMPLES_FOR_TEST
439
+ ) {
440
+ return {
441
+ timing: {
442
+ medianDeltaPct,
443
+ meanDeltaPct,
444
+ verdict: verdictFor(medianDeltaPct, medianDeltaPct),
445
+ },
446
+ warning: {
447
+ code: "thin-comparison",
448
+ message: `Only ${baseSamples.length} baseline / ${candSamples.length} candidate sample(s); falling back to a point-estimate threshold instead of a bootstrap CI and Mann-Whitney test (needs ${MIN_SAMPLES_FOR_TEST}+ per side).`,
449
+ data: {
450
+ baseSamples: baseSamples.length,
451
+ candSamples: candSamples.length,
452
+ },
453
+ },
454
+ };
455
+ }
456
+
457
+ const bootstrap = bootstrapMedianDiffCi(baseSamples, candSamples, {
458
+ iterations: thresholds.bootstrapIterations,
459
+ });
460
+ const mw = mannWhitneyU(baseSamples, candSamples);
461
+ return {
462
+ timing: {
463
+ medianDeltaPct,
464
+ meanDeltaPct,
465
+ ci95: bootstrap.ci95,
466
+ pValue: mw.pValue,
467
+ seed: bootstrap.seed,
468
+ verdict:
469
+ mw.pValue < thresholds.alpha
470
+ ? verdictFor(bootstrap.ci95[0], bootstrap.ci95[1])
471
+ : "unchanged",
472
+ },
473
+ };
474
+ }
475
+
476
+ function compareFrames(
477
+ baseCpu: NonNullable<Measurement["cpu"]>,
478
+ candCpu: NonNullable<Measurement["cpu"]>,
479
+ thresholds: Thresholds,
480
+ ): { frames: NonNullable<Comparison["frames"]>; failed: boolean } {
481
+ const selfUsByKey = (cpu: typeof baseCpu) =>
482
+ new Map(cpu.totals.map((t) => [cpu.frames[t.frameIx]!.key, t.selfUs]));
483
+ const nameByKey = (cpu: typeof baseCpu) =>
484
+ new Map(cpu.frames.map((f) => [f.key, f.name]));
485
+ const baseSelf = selfUsByKey(baseCpu);
486
+ const candSelf = selfUsByKey(candCpu);
487
+ const baseNames = nameByKey(baseCpu);
488
+ const candNames = nameByKey(candCpu);
489
+
490
+ const frames = [...new Set([...baseSelf.keys(), ...candSelf.keys()])]
491
+ .map((key) => {
492
+ const baseSelfUs = baseSelf.get(key) ?? 0;
493
+ const candSelfUs = candSelf.get(key) ?? 0;
494
+ return {
495
+ frameKey: key,
496
+ name: candNames.get(key) ?? baseNames.get(key) ?? key,
497
+ baseSelfUs,
498
+ candSelfUs,
499
+ deltaPct: pctDelta(baseSelfUs, candSelfUs),
500
+ };
501
+ })
502
+ .sort((a, b) => Math.abs(b.deltaPct) - Math.abs(a.deltaPct));
503
+
504
+ const failed = frames.some(
505
+ (f) =>
506
+ (f.baseSelfUs >= thresholds.minFrameSelfUs ||
507
+ f.candSelfUs >= thresholds.minFrameSelfUs) &&
508
+ f.deltaPct > thresholds.frameSelfPct,
509
+ );
510
+ return { frames, failed };
511
+ }
512
+
513
+ // Gated on object count only: `retainedBytes` is carried on each row for
514
+ // display, never compared against a threshold.
515
+ function compareHeapTypes(
516
+ baseHeap: NonNullable<Measurement["heap"]>,
517
+ candHeap: NonNullable<Measurement["heap"]>,
518
+ thresholds: Thresholds,
519
+ ): { heapTypes: NonNullable<Comparison["heapTypes"]>; failed: boolean } {
520
+ const baseByType = new Map(baseHeap.typeCounts.map((t) => [t.type, t]));
521
+ const candByType = new Map(candHeap.typeCounts.map((t) => [t.type, t]));
522
+
523
+ const heapTypes = [...new Set([...baseByType.keys(), ...candByType.keys()])]
524
+ .map((type) => {
525
+ const b = baseByType.get(type);
526
+ const c = candByType.get(type);
527
+ return {
528
+ type,
529
+ baseCount: b?.count ?? 0,
530
+ candCount: c?.count ?? 0,
531
+ baseBytes: b?.retainedBytes,
532
+ candBytes: c?.retainedBytes,
533
+ deltaPct: pctDelta(b?.count ?? 0, c?.count ?? 0),
534
+ };
535
+ })
536
+ .sort((a, b) => Math.abs(b.deltaPct) - Math.abs(a.deltaPct));
537
+
538
+ return {
539
+ heapTypes,
540
+ failed: heapTypes.some((h) => h.deltaPct > thresholds.heapTypePct),
541
+ };
542
+ }
543
+
544
+ function compareIndexed(
545
+ index: CompareIndex,
546
+ workloadId: string,
547
+ thresholds: Thresholds,
548
+ ): Comparison | undefined {
549
+ const { effectiveTimingPct } = index;
550
+ const baseId = index.baseIdFor(workloadId);
551
+ if (baseId === undefined) return undefined;
552
+ const baseTiming = index.base(baseId, "timing");
553
+ const candTiming = index.cand(workloadId, "timing");
554
+ const baseCpu = index.base(baseId, "cpu");
555
+ const candCpu = index.cand(workloadId, "cpu");
556
+ const baseHeap = index.base(baseId, "heap");
557
+ const candHeap = index.cand(workloadId, "heap");
558
+ const candWorkload = index.candWorkloads.get(workloadId);
559
+
560
+ const baselineMeasurementId = baseTiming?.id ?? baseCpu?.id ?? baseHeap?.id;
561
+ // A task.skip()'d candidate has no measurement; its workload id lets the
562
+ // comparison say "skipped" instead of vanishing.
563
+ const candidateMeasurementId =
564
+ candTiming?.id ?? candCpu?.id ?? candHeap?.id ?? candWorkload?.id;
565
+ if (!baselineMeasurementId || !candidateMeasurementId) return undefined;
566
+
567
+ let failed = false;
568
+ const warnings: Warning[] = [];
569
+ if (index.environmentMismatch) warnings.push(index.environmentMismatch);
570
+
571
+ let timing: Comparison["timing"];
572
+ if (baseTiming?.timing && candWorkload?.skipped && !candTiming?.timing) {
573
+ timing = { medianDeltaPct: 0, meanDeltaPct: 0, verdict: "unchanged" };
574
+ warnings.push({
575
+ code: "skipped",
576
+ message:
577
+ "Candidate has no timing measurement for this workload (task.skip()); treated as unchanged.",
578
+ data: { workloadId },
579
+ });
580
+ } else if (baseTiming?.timing && candTiming?.timing) {
581
+ const result = compareTiming(
582
+ baseTiming.timing,
583
+ candTiming.timing,
584
+ effectiveTimingPct,
585
+ thresholds,
586
+ );
587
+ timing = result.timing;
588
+ if (result.warning) warnings.push(result.warning);
589
+ if (timing.verdict === "regressed") failed = true;
590
+ }
591
+
592
+ let frames: Comparison["frames"];
593
+ if (baseCpu?.cpu && candCpu?.cpu) {
594
+ const result = compareFrames(baseCpu.cpu, candCpu.cpu, thresholds);
595
+ frames = result.frames;
596
+ failed ||= result.failed;
597
+ }
598
+
599
+ let heapTypes: Comparison["heapTypes"];
600
+ if (baseHeap?.heap && candHeap?.heap) {
601
+ const result = compareHeapTypes(baseHeap.heap, candHeap.heap, thresholds);
602
+ heapTypes = result.heapTypes;
603
+ failed ||= result.failed;
604
+ }
605
+
606
+ return {
607
+ id: fp("cmp", baselineMeasurementId, candidateMeasurementId),
608
+ baselineMeasurementId,
609
+ candidateMeasurementId,
610
+ timing,
611
+ ...(warnings.length > 0 && { warnings }),
612
+ frames,
613
+ heapTypes,
614
+ thresholds: { ...thresholds, effectiveTimingPct },
615
+ verdict: failed ? "fail" : "pass",
616
+ };
617
+ }