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