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,615 @@
1
+ // Profile IR schema v2. Units: ns (time), bytes (memory), µs (sampling
2
+ // interval).
3
+
4
+ export interface ProfileDocument {
5
+ schemaVersion: 2;
6
+ toolVersion: string;
7
+ bunVersion: string;
8
+ platform: { os: string; arch: string };
9
+ /** ISO timestamp; metadata only, never part of an id. */
10
+ createdAt: string;
11
+ workloads: Workload[];
12
+ measurements: Measurement[];
13
+ comparisons?: Comparison[];
14
+ /** Aggregate across `comparisons`; present wherever `comparisons` is. */
15
+ comparisonSummary?: ComparisonSummary;
16
+ /**
17
+ * Workload ids on only one side of the comparison; present wherever
18
+ * `comparisons` is. */
19
+ unmatched?: { baseOnly: string[]; candOnly: string[] };
20
+ /**
21
+ * Every task on either side of the comparison, one entry each: what
22
+ * `--format markdown` prints, flat for scripts. Present wherever
23
+ * `comparisons` is. */
24
+ compared?: ComparedTask[];
25
+ /**
26
+ * Machine conditions at measurement time; absent when the noise check was
27
+ * skipped. */
28
+ environment?: Environment;
29
+ /**
30
+ * Run-level result of `ostia ab` / `ab()`, whose measurements are
31
+ * `phase: "paired"`. */
32
+ ab?: AbSummary;
33
+ /**
34
+ * Repo state of the process's cwd; absent outside a git repo. Never part
35
+ * of an id or fingerprint, so a commit or dirty tree doesn't orphan a
36
+ * baseline. */
37
+ git?: GitMetadata;
38
+ }
39
+
40
+ export interface GitMetadata {
41
+ sha: string;
42
+ branch: string;
43
+ dirty: boolean;
44
+ }
45
+
46
+ export interface NoiseFloor {
47
+ /**
48
+ * `mad / median` of a reference workload, percent: how noisy the machine
49
+ * is right now, independent of what's measured. */
50
+ floorPct: number;
51
+ referenceMedianNs: number;
52
+ samples: number;
53
+ /**
54
+ * How much slower (positive) the reference ran at the end of the run than
55
+ * at the start, percent: the machine's drift over the run. Absent when the
56
+ * run didn't re-measure it (`profile()`, older documents). */
57
+ driftPct?: number;
58
+ }
59
+
60
+ export interface Environment {
61
+ cpuModel: string;
62
+ cores: number;
63
+ loadAvg1: number;
64
+ loadAvg5: number;
65
+ noise: NoiseFloor;
66
+ }
67
+
68
+ export interface Workload {
69
+ /**
70
+ * Identifies what is measured, not where or when. Subprocess: a hash of
71
+ * argv, `prepare` and `timeSource`, excluding `process.cwd()`. In-process:
72
+ * a hash of the function source, or for a registry entry the file, task
73
+ * name and `params`. Annotations (`label`, `description`, `baseline`)
74
+ * never affect it. */
75
+ id: string;
76
+ kind: "subprocess" | "inprocess";
77
+ label?: string;
78
+ command?: string[];
79
+ /**
80
+ * Command-form `prepare` hook run before every trial; part of the id. A
81
+ * function-form hook isn't serializable and is omitted (its source is
82
+ * still hashed into the id). */
83
+ prepare?: string[];
84
+ /**
85
+ * Takes samples from a number in the command's own output instead of the
86
+ * wall clock; part of the id. */
87
+ timeSource?: {
88
+ pattern: string;
89
+ group?: number;
90
+ unit?: "ns" | "us" | "ms" | "s";
91
+ };
92
+ /**
93
+ * `task` is the registry's "group/name" id; `group` is the enclosing
94
+ * `group()` name. Renderers prefer `group` over splitting `task` on "/".
95
+ * */
96
+ entry?: { file: string; task: string; group?: string };
97
+ /** The Relative reference for its group; renderers use the first one found. */
98
+ baseline?: boolean;
99
+ /** What this task measures and why, from `task(..., { description })`. */
100
+ description?: string;
101
+ /** The enclosing group's description, repeated on every workload in it. */
102
+ groupDescription?: string;
103
+ /** Ran in a subprocess of its own rather than sharing its suite file's. */
104
+ isolated?: boolean;
105
+ /**
106
+ * From `task(..., { params })` or a `sweep()` point. Part of the id, so
107
+ * points sharing a task name don't collide. */
108
+ params?: Record<string, string | number | boolean>;
109
+ /**
110
+ * Ids this task had under its former names (`task(..., { aliases })`), so
111
+ * `compare` and `ab` match a base measured before a rename. Never part of
112
+ * the id. */
113
+ formerIds?: string[];
114
+ /**
115
+ * From `task.skip()` / `group.skip()`: never measured, so no
116
+ * `Measurement`. Renderers print a "- skipped" row; `compare` treats it as
117
+ * `unchanged` with a `skipped` warning. */
118
+ skipped?: boolean;
119
+ }
120
+
121
+ export type Phase = "timing" | "cpu" | "heap" | "memstats" | "paired";
122
+
123
+ export interface Measurement {
124
+ id: string;
125
+ workloadId: string;
126
+ phase: Phase;
127
+ instrumented: boolean;
128
+ configFingerprint: string;
129
+ trials: Trial[];
130
+ timing?: TimingStats;
131
+ diagnosticWallNs?: number;
132
+ cpu?: CpuEvidence;
133
+ heap?: HeapEvidence;
134
+ memory?: MemoryEvidence;
135
+ jit?: JitTierBreakdown;
136
+ /**
137
+ * In-process timing, where the machine counts them: instructions the
138
+ * task retired per call, one sample per trial (see `InstructionStats`). */
139
+ instructions?: InstructionStats;
140
+ /** `phase: "paired"` only; `timing` is then the candidate side. */
141
+ paired?: PairedEvidence;
142
+ /**
143
+ * `phase: "paired"` only: the task threw on one side or both
144
+ * (`"both"`). Usually instead of `timing`/`paired`; when it threw in a
145
+ * confirmation repeat, `repeat` (from 1) says which, and `timing`/`paired`
146
+ * stay as the first process measured them. Either way the task isn't in
147
+ * `matched` or the geomean. */
148
+ threw?: { side: "base" | "cand" | "both"; message: string; repeat?: number };
149
+ warnings: Warning[];
150
+ artifacts: ArtifactRef[];
151
+ /**
152
+ * Trials ran round-robin with the other commands of the same `time()`
153
+ * call, so drift over the run hits every command equally. */
154
+ interleaved?: boolean;
155
+ }
156
+
157
+ export interface Trial {
158
+ i: number;
159
+ wallNs: number;
160
+ /**
161
+ * The command's self-reported time (ns) under a `timeSource`; these, not
162
+ * `wallNs`, are then the `timing.samples`. */
163
+ reportedNs?: number;
164
+ exitCode?: number;
165
+ userNs?: number;
166
+ systemNs?: number;
167
+ maxRssBytes?: number;
168
+ /** Killed by `timeoutMs`; `exitCode` is absent. Contributes no sample. */
169
+ timedOut?: true;
170
+ /**
171
+ * Output didn't match the `timeSource` pattern; `reportedNs` is absent
172
+ * (never a `wallNs` fallback). Contributes no sample. */
173
+ timeSourceNoMatch?: true;
174
+ }
175
+
176
+ export interface TimingStats {
177
+ unit: "ns";
178
+ samples: number[];
179
+ mean: number;
180
+ median: number;
181
+ stddev: number;
182
+ min: number;
183
+ max: number;
184
+ outliers: { mild: number; severe: number };
185
+ /** 25th percentile, ns. */
186
+ p25: number;
187
+ /** 75th percentile, ns. */
188
+ p75: number;
189
+ /** 99th percentile, ns. */
190
+ p99: number;
191
+ /**
192
+ * Median absolute deviation, ns: a spread measure that, unlike stddev, the
193
+ * long right tail of wall-clock timings doesn't skew. */
194
+ mad: number;
195
+ /**
196
+ * Calls batched into one timed block; absent (read as 1) unless batching
197
+ * occurred, and always absent for subprocess timing. */
198
+ batch?: number;
199
+ }
200
+
201
+ /**
202
+ * Instructions retired per call on the thread that ran the task, in user
203
+ * mode: a system call's kernel work and other threads' (JIT compiler, GC
204
+ * helpers, I/O pool) don't count. Unlike time, another process taking the
205
+ * CPU doesn't move it. Includes the timing loop's own few hundred
206
+ * instructions per batch. */
207
+ export interface InstructionStats {
208
+ samples: number[];
209
+ median: number;
210
+ }
211
+
212
+ export interface Frame {
213
+ key: string;
214
+ name: string;
215
+ url?: string;
216
+ line?: number;
217
+ col?: number;
218
+ }
219
+
220
+ export interface CallNode {
221
+ id: number;
222
+ frameIx: number;
223
+ children: number[];
224
+ }
225
+
226
+ export interface FrameTotal {
227
+ frameIx: number;
228
+ selfUs: number;
229
+ totalUs: number;
230
+ samples: number;
231
+ }
232
+
233
+ export interface CpuEvidence {
234
+ origin: "cpu-prof" | "inspector" | "jsc-profile";
235
+ samplingIntervalUs: number;
236
+ frames: Frame[];
237
+ nodes: CallNode[];
238
+ totals: FrameTotal[];
239
+ samples?: { nodeIds: number[]; timeDeltasUs: number[] };
240
+ }
241
+
242
+ export interface HeapEvidence {
243
+ origin: "heap-prof";
244
+ heapSizeBytes?: number;
245
+ objectCount?: number;
246
+ typeCounts: { type: string; count: number; retainedBytes?: number }[];
247
+ }
248
+
249
+ export interface MemoryEvidence {
250
+ origin: "resourceUsage" | "heapStats";
251
+ /**
252
+ * `memstats` only: `"retained"` (`--alloc`, `bytesPerOp`) or `"peak"`
253
+ * (`--peak-mem`, `peakBytes`). Absent means `"retained"` on older
254
+ * documents. */
255
+ kind?: "retained" | "peak";
256
+ /** Largest `Trial.maxRssBytes` across a timing measurement's trials. */
257
+ maxRssBytes?: number;
258
+ /**
259
+ * `--alloc`: heap growth per call across one batch bracketed by full GCs,
260
+ * so what the calls keep alive (a leak check), not what they allocate. */
261
+ bytesPerOp?: number;
262
+ /**
263
+ * `--peak-mem`: how far one call raised RSS, garbage included; median over
264
+ * 3 fresh processes. A `peak-hidden` warning says when it may read low. */
265
+ peakBytes?: number;
266
+ /**
267
+ * In-process timing: the JS heap's size as of its last collection, just
268
+ * before the task's warmup and just after its last trial. Read without
269
+ * forcing a GC, so it never perturbs the timing. */
270
+ heapUsedBeforeBytes?: number;
271
+ heapUsedAfterBytes?: number;
272
+ }
273
+
274
+ export interface JitTierBreakdown {
275
+ origin: "jsc-profile";
276
+ tiers: { llint: number; baseline: number; dfg: number; ftl: number };
277
+ topFramesByTier?: { tier: string; frameKey: string; samples: number }[];
278
+ }
279
+
280
+ /**
281
+ * Evidence of a `phase: "paired"` measurement: base and candidate
282
+ * alternate in batches in one process, so drift cancels in the ratio. */
283
+ export interface PairedEvidence {
284
+ /** One base batch and one candidate batch per round, alternating order. */
285
+ rounds: number;
286
+ /** Calls per side per round. */
287
+ batch: number;
288
+ /**
289
+ * Base per-call time for each round, ns; `ratios[i]` pairs with
290
+ * `baseSamples[i]` and the candidate's `timing.samples[i]`. */
291
+ baseSamples: number[];
292
+ baseMedianNs: number;
293
+ /** Candidate/base time per round. */
294
+ ratios: number[];
295
+ medianRatio: number;
296
+ /** 25th/75th percentile of `ratios`. */
297
+ ratioP25: number;
298
+ ratioP75: number;
299
+ /**
300
+ * Instructions retired per call on each side, where the machine counts
301
+ * them; what `AbSummary.metric: "instructions"` judges. */
302
+ instructions?: PairedInstructions;
303
+ /**
304
+ * `AbSummary.metric`'s median ratio past `1 ± threshold` and on the same
305
+ * side of 1 in at least three quarters of rounds. */
306
+ flagged?: "regressed" | "improved";
307
+ /**
308
+ * Each fresh-process re-measurement of a flagged workload; `flagged` by
309
+ * `AbSummary.metric`. */
310
+ repeats?: {
311
+ medianRatio: number;
312
+ ratioP25: number;
313
+ ratioP75: number;
314
+ instructions?: { medianRatio: number; ratioP25: number; ratioP75: number };
315
+ flagged?: "regressed" | "improved";
316
+ }[];
317
+ /** Set when `flagged` is: whether every repeat flagged the same way. */
318
+ confirmed?: boolean;
319
+ /** `flagged` when confirmed, else `"unchanged"`. */
320
+ verdict: "regressed" | "improved" | "unchanged";
321
+ /**
322
+ * First call's return values were deep-equal on both sides; informational,
323
+ * never a failure. */
324
+ sameOutput: boolean;
325
+ /**
326
+ * Set when the suite file's text differs from the base ref's copy, so
327
+ * each side may run a different benchmark (a fixed fixture, a changed
328
+ * input). With `sameOutput: false` too, the task is "not comparable": its
329
+ * verdict is `"unchanged"` and it's left out of the geomean. */
330
+ suiteChanged?: true;
331
+ /**
332
+ * `--alloc`: heap each call keeps alive after a full GC, per side, after
333
+ * a warmup batch; each the median of 3 fresh processes. */
334
+ retained?: MemoryChange;
335
+ /**
336
+ * `--peak-mem`: how far the task's first call raises RSS, per side,
337
+ * each the median of 3 fresh processes. */
338
+ peak?: MemoryChange;
339
+ }
340
+
341
+ /**
342
+ * Instructions a paired task retired per call (see `InstructionStats`),
343
+ * from the same rounds as `PairedEvidence`'s times. */
344
+ export interface PairedInstructions {
345
+ /** Per round, index-aligned with `PairedEvidence.baseSamples`. */
346
+ baseSamples: number[];
347
+ candSamples: number[];
348
+ baseMedian: number;
349
+ candMedian: number;
350
+ /** Candidate/base instructions per round. */
351
+ ratios: number[];
352
+ medianRatio: number;
353
+ ratioP25: number;
354
+ ratioP75: number;
355
+ }
356
+
357
+ /** One memory reading on both sides of an `ab()` task, bytes. */
358
+ export interface MemoryChange {
359
+ baseBytes: number;
360
+ candBytes: number;
361
+ /**
362
+ * Past both `AbSummary.memory.thresholdPct` of the base and
363
+ * `floorBytes`; always `"unchanged"` on a not-comparable task. */
364
+ verdict: "regressed" | "improved" | "unchanged";
365
+ /**
366
+ * The smallest change that counts, bytes: 16 KiB over the batch's calls
367
+ * for `retained`; for `peak`, 1 MiB, or the freed memory a `peak-hidden`
368
+ * warning reports. */
369
+ floorBytes: number;
370
+ }
371
+
372
+ /** Run-level result of `ab()`, stamped on the document as `ab`. */
373
+ export interface AbSummary {
374
+ base: { ref: string; sha: string };
375
+ /**
376
+ * Suite files, as given, that don't exist at the base ref: their tasks
377
+ * are all candidate-only. */
378
+ newSuites?: string[];
379
+ rounds: number;
380
+ /**
381
+ * What verdicts, confirmation and `geomeanPct` judge: each round's time
382
+ * ratio, or its instruction ratio (`PairedEvidence.instructions`). */
383
+ metric: "time" | "instructions";
384
+ thresholdPct: number;
385
+ geomeanThresholdPct: number;
386
+ /** Workloads measured on both sides. */
387
+ matched: number;
388
+ /** Confirmed verdicts. */
389
+ regressed: number;
390
+ improved: number;
391
+ unchanged: number;
392
+ /**
393
+ * Flagged in-process, but a fresh-process repeat disagreed; counted in
394
+ * `unchanged`. */
395
+ unconfirmed: number;
396
+ /** Workloads whose first call returned different values on each side. */
397
+ outputDiffers: number;
398
+ /**
399
+ * Workloads whose suite file and output both changed (see
400
+ * `PairedEvidence.suiteChanged`); counted in `unchanged`, left out of
401
+ * `geomeanPct`. */
402
+ notComparable: number;
403
+ /**
404
+ * Workloads that threw on either side or both, and so weren't timed;
405
+ * not counted in `matched`. */
406
+ threw: number;
407
+ /**
408
+ * Present when any task had a memory reading (`--alloc`, `--peak-mem`):
409
+ * how many tasks' memory regressed or improved, on either reading. */
410
+ memory?: { thresholdPct: number; regressed: number; improved: number };
411
+ /**
412
+ * Geometric mean of the workloads' median `metric` ratios, signed
413
+ * percent (negative: candidate faster); a flagged workload contributes its
414
+ * median over its main run and repeats. `null` when nothing was paired. */
415
+ geomeanPct: number | null;
416
+ /**
417
+ * `"fail"` when any workload regressed (confirmed), threw on the
418
+ * candidate side only, or `geomeanPct` exceeds `geomeanThresholdPct`, or
419
+ * any task's memory regressed. */
420
+ verdict: "pass" | "fail";
421
+ }
422
+
423
+ /**
424
+ * Every `Warning.code`. A runtime array so a test can assert each is
425
+ * emitted.
426
+ */
427
+ // compat: annotated, not `as const`: Bun 1.4.6 canary's declaration
428
+ // build overflows its stack when another module imports a type
429
+ // derived from an `as const` array (WarningCode, below).
430
+ export const WARNING_CODES: readonly [
431
+ "slow-first-run",
432
+ "outliers-detected",
433
+ "fast-command",
434
+ "nonzero-exit",
435
+ "artifact-missing",
436
+ "empty-profile",
437
+ "low-sample-count",
438
+ "thin-comparison",
439
+ "noisy-machine",
440
+ "skipped",
441
+ "jit-cold",
442
+ "timeout",
443
+ "aborted",
444
+ "time-source-no-match",
445
+ "environment-mismatch",
446
+ "peak-hidden",
447
+ "suite-changed",
448
+ ] = [
449
+ "slow-first-run",
450
+ "outliers-detected",
451
+ "fast-command",
452
+ "nonzero-exit",
453
+ "artifact-missing",
454
+ "empty-profile",
455
+ "low-sample-count",
456
+ "thin-comparison",
457
+ "noisy-machine",
458
+ "skipped",
459
+ "jit-cold",
460
+ "timeout",
461
+ "aborted",
462
+ "time-source-no-match",
463
+ "environment-mismatch",
464
+ "peak-hidden",
465
+ "suite-changed",
466
+ ];
467
+
468
+ export type WarningCode = (typeof WARNING_CODES)[number];
469
+
470
+ export interface Warning {
471
+ code: WarningCode;
472
+ message: string;
473
+ data?: Record<string, unknown>;
474
+ }
475
+
476
+ export interface ArtifactRef {
477
+ id: string;
478
+ kind: "cpuprofile" | "heapsnapshot";
479
+ path: string;
480
+ sha256: string;
481
+ bytes: number;
482
+ }
483
+
484
+ export interface Comparison {
485
+ id: string;
486
+ baselineMeasurementId: string;
487
+ candidateMeasurementId: string;
488
+ timing?: {
489
+ medianDeltaPct: number;
490
+ meanDeltaPct: number;
491
+ /**
492
+ * 95% bootstrap CI on the difference of medians, percent of the baseline
493
+ * median. Absent below 5 samples a side (`thin-comparison`). */
494
+ ci95?: [number, number];
495
+ /** Two-sided Mann-Whitney U p-value; absent whenever `ci95` is. */
496
+ pValue?: number;
497
+ /** Bootstrap PRNG seed, so `ci95` is reproducible. */
498
+ seed?: number;
499
+ verdict: "improved" | "regressed" | "unchanged";
500
+ };
501
+ /**
502
+ * Caveats about this comparison, e.g. a thin-sample point-estimate
503
+ * verdict.
504
+ */
505
+ warnings?: Warning[];
506
+ frames?: {
507
+ frameKey: string;
508
+ name: string;
509
+ baseSelfUs: number;
510
+ candSelfUs: number;
511
+ deltaPct: number;
512
+ }[];
513
+ heapTypes?: {
514
+ type: string;
515
+ baseCount: number;
516
+ candCount: number;
517
+ baseBytes?: number;
518
+ candBytes?: number;
519
+ deltaPct: number;
520
+ }[];
521
+ thresholds: {
522
+ timingPct: number;
523
+ frameSelfPct: number;
524
+ heapTypePct: number;
525
+ minFrameSelfUs: number;
526
+ alpha: number;
527
+ bootstrapIterations: number;
528
+ /**
529
+ * `max(timingPct, both documents' noise floors)`: what timing was tested
530
+ * against.
531
+ */
532
+ effectiveTimingPct: number;
533
+ };
534
+ verdict: "pass" | "fail";
535
+ }
536
+
537
+ /** Aggregate view over a `compareDocuments` call's `Comparison[]`. */
538
+ export interface ComparisonSummary {
539
+ /** `comparisons.length`. */
540
+ matched: number;
541
+ regressed: number;
542
+ improved: number;
543
+ unchanged: number;
544
+ /**
545
+ * Geometric mean of `cand/base` median ratios, signed percent (negative:
546
+ * candidate faster). `null` when no comparison had a finite ratio. */
547
+ geomeanPct: number | null;
548
+ /**
549
+ * `Comparison.thresholds.effectiveTimingPct`, which is the same for the
550
+ * whole document pair. */
551
+ effectiveTimingPct: number;
552
+ /**
553
+ * The machine's drift, percent, added to the timing threshold: the
554
+ * largest of each run's own drift (`NoiseFloor.driftPct`) and how far the
555
+ * reference loop's speed moved between the two runs. Absent when either
556
+ * document lacks a noise check. */
557
+ driftPct?: number;
558
+ /** `"fail"` when any comparison's verdict is `"fail"`. */
559
+ verdict: "pass" | "fail";
560
+ }
561
+
562
+ /**
563
+ * One task of a `compare`/`ci` run: matched on both sides, or present on
564
+ * only one (`missing-base`: new, or renamed without an alias;
565
+ * `missing-cand`: removed, or renamed). Times in ns, memory in bytes. */
566
+ export interface ComparedTask {
567
+ /** The candidate's workload id; the base's on a `missing-cand` task. */
568
+ workloadId: string;
569
+ /** Display name: the label, else the command, else the id. */
570
+ task: string;
571
+ group?: string;
572
+ /**
573
+ * Set when the base was matched through one of the task's `aliases`: the
574
+ * base's workload id and display name. */
575
+ renamedFrom?: { workloadId: string; task: string };
576
+ verdict:
577
+ "improved" | "unchanged" | "regressed" | "missing-base" | "missing-cand";
578
+ /**
579
+ * The `Comparison` holding this task's frame and heap-type deltas and
580
+ * warnings; absent on a one-sided task. */
581
+ comparisonId?: string;
582
+ /**
583
+ * Whether the comparison passed the gate (timing, frames, heap types);
584
+ * absent on a one-sided task, which never fails it. */
585
+ pass?: boolean;
586
+ /** Absent on a one-sided or skipped task. */
587
+ timing?: {
588
+ unit: "ns";
589
+ baseMedian: number;
590
+ candMedian: number;
591
+ /** Absent on a document compared before ostia recorded it. */
592
+ baseSamples?: number;
593
+ candSamples: number;
594
+ medianDeltaPct: number;
595
+ /** Absent on a thin (<5 samples a side) comparison, with `pValue`. */
596
+ ci95?: [number, number];
597
+ pValue?: number;
598
+ /** `Comparison.thresholds.effectiveTimingPct`. */
599
+ thresholdPct: number;
600
+ };
601
+ /** Memory readings present on both sides; informational, never gated. */
602
+ memory?: MemoryDelta[];
603
+ }
604
+
605
+ /** One memory reading of a task on both sides of a `compare`/`ci`, bytes. */
606
+ export interface MemoryDelta {
607
+ /**
608
+ * `heapUsedBefore`/`heapUsedAfter`: in-process heap around the timing
609
+ * run; `retained`: `--alloc`; `peak`: `--peak-mem`; `maxRss`: subprocess
610
+ * timing. */
611
+ reading: "heapUsedBefore" | "heapUsedAfter" | "retained" | "peak" | "maxRss";
612
+ baseBytes: number;
613
+ candBytes: number;
614
+ deltaPct: number;
615
+ }
@@ -0,0 +1,57 @@
1
+ import { heapStats } from "bun:jsc";
2
+
3
+ import type { MemoryEvidence } from "../ir/types.ts";
4
+ import { isPromiseLike } from "./loop.ts";
5
+
6
+ const DEFAULT_BATCH_SIZE = 100;
7
+ // Calls stop early once the batch has run this long, so a slow task costs
8
+ // about a second here, not `batchSize` of its calls. Fast tasks never
9
+ // reach it.
10
+ const DEFAULT_BUDGET_MS = 1000;
11
+
12
+ export interface AllocCaptureResult {
13
+ memory: MemoryEvidence;
14
+ /** The heap grows in blocks, so fewer calls mean a coarser `bytesPerOp`. */
15
+ calls: number;
16
+ diagnosticWallNs: number;
17
+ }
18
+
19
+ /**
20
+ * Retained heap growth per call: heap size after a batch and a full GC,
21
+ * minus before, over the calls made: up to `batchSize`, fewer (at least
22
+ * one) once `budgetMs` has passed. Garbage is collected, so this is a leak
23
+ * check and a garbage-heavy task reads near zero. Never feeds timing
24
+ * stats. */
25
+ export async function measureAllocPerOp(
26
+ fn: () => unknown | Promise<unknown>,
27
+ batchSize: number = DEFAULT_BATCH_SIZE,
28
+ budgetMs: number = DEFAULT_BUDGET_MS,
29
+ ): Promise<AllocCaptureResult> {
30
+ const start = Bun.nanoseconds();
31
+ Bun.gc(true);
32
+ const before = heapStats().heapSize;
33
+ const budgetEnd = Bun.nanoseconds() + budgetMs * 1e6;
34
+ let calls = 0;
35
+ while (calls < batchSize && (calls === 0 || Bun.nanoseconds() < budgetEnd)) {
36
+ const result = fn();
37
+ if (isPromiseLike(result)) await result;
38
+ calls++;
39
+ }
40
+ // Return to the event loop first. Bun 1.4.4's conservative GC can still
41
+ // find the last call's allocation through a stale register or stack slot,
42
+ // which read as ~800KB retained for a task that keeps nothing.
43
+ await new Promise((resolve) => setTimeout(resolve, 0));
44
+ Bun.gc(true);
45
+ const after = heapStats().heapSize;
46
+ const diagnosticWallNs = Bun.nanoseconds() - start;
47
+
48
+ return {
49
+ memory: {
50
+ origin: "heapStats",
51
+ kind: "retained",
52
+ bytesPerOp: Math.max(0, (after - before) / calls),
53
+ },
54
+ calls,
55
+ diagnosticWallNs,
56
+ };
57
+ }