ostia 0.4.0 → 0.5.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 (59) hide show
  1. package/README.md +4 -4
  2. package/docs/agent-protocol.md +13 -9
  3. package/docs/cli.md +90 -73
  4. package/docs/config.md +2 -2
  5. package/docs/document-schema.md +14 -12
  6. package/docs/library.md +17 -15
  7. package/docs/preload-recipes.md +4 -4
  8. package/docs/statistics.md +10 -10
  9. package/index.d.ts +128 -58
  10. package/package.json +1 -1
  11. package/src/ab/ab-runner.ts +6 -6
  12. package/src/ab/index.ts +15 -6
  13. package/src/bench/index.ts +12 -3
  14. package/src/bench/registry.ts +6 -4
  15. package/src/bench/run-tasks.ts +2 -2
  16. package/src/bench/runner.ts +2 -2
  17. package/src/bench/support.ts +8 -4
  18. package/src/bench/sweep.ts +2 -2
  19. package/src/cache/fingerprint.ts +2 -2
  20. package/src/capture/bunflags.ts +2 -2
  21. package/src/capture/cpu.ts +2 -2
  22. package/src/capture/heap-parse.ts +2 -2
  23. package/src/ci/index.ts +7 -6
  24. package/src/cli/agent.ts +54 -0
  25. package/src/cli/flags.ts +50 -9
  26. package/src/cli/help.ts +29 -11
  27. package/src/cli/output.ts +6 -3
  28. package/src/cli/run.ts +29 -5
  29. package/src/compare/index.ts +4 -4
  30. package/src/config/index.ts +14 -10
  31. package/src/config/validate.ts +4 -4
  32. package/src/glob.ts +2 -2
  33. package/src/ir/document.ts +2 -2
  34. package/src/ir/types.ts +47 -24
  35. package/src/measure/alloc.ts +2 -2
  36. package/src/measure/cpu.ts +2 -2
  37. package/src/measure/environment.ts +11 -6
  38. package/src/measure/inprocess.ts +14 -10
  39. package/src/measure/instructions.ts +2 -2
  40. package/src/measure/noise.ts +51 -13
  41. package/src/measure/paired.ts +2 -2
  42. package/src/measure/peak.ts +4 -4
  43. package/src/measure/timing.ts +18 -3
  44. package/src/profile.ts +6 -4
  45. package/src/renderers/collapsed.ts +2 -2
  46. package/src/renderers/concise.ts +148 -0
  47. package/src/renderers/format.ts +13 -4
  48. package/src/renderers/index.ts +6 -0
  49. package/src/renderers/markdown.ts +2 -2
  50. package/src/renderers/mermaid.ts +2 -2
  51. package/src/renderers/minimal.ts +8 -7
  52. package/src/renderers/relative.ts +2 -2
  53. package/src/renderers/select.ts +2 -2
  54. package/src/renderers/terminal.ts +6 -3
  55. package/src/renderers/types.ts +3 -0
  56. package/src/spawn/index.ts +47 -14
  57. package/src/stats/bootstrap.ts +2 -2
  58. package/src/stats/index.ts +2 -2
  59. package/src/time.ts +75 -10
package/src/ir/types.ts CHANGED
@@ -1,5 +1,5 @@
1
- // Profile IR schema v2. Units: ns (time), bytes (memory), µs (sampling
2
- // interval).
1
+ // Profile IR schema v2. Units: ns (time), bytes (memory), µs
2
+ // (sampling interval).
3
3
 
4
4
  export interface ProfileDocument {
5
5
  schemaVersion: 2;
@@ -23,17 +23,25 @@ export interface ProfileDocument {
23
23
  * `comparisons` is. */
24
24
  compared?: ComparedTask[];
25
25
  /**
26
- * Machine conditions at measurement time; absent when the noise check was
27
- * skipped. */
26
+ * Machine conditions at measurement time; absent when the noise check
27
+ * was skipped.
28
+ */
28
29
  environment?: Environment;
29
30
  /**
30
- * Run-level result of `ostia ab` / `ab()`, whose measurements are
31
- * `phase: "paired"`. */
31
+ * The shell `time({ shell })` ran each string command through, and its
32
+ * startup (`shell -c :`, median wall time, ns), which the timings include
33
+ * and nothing subtracts. Absent without a shell. */
34
+ shell?: { command: string; startupNs: number };
35
+ /**
36
+ * Run-level result of `ostia ab` / `ab()`, whose measurements
37
+ * are `phase: "paired"`.
38
+ */
32
39
  ab?: AbSummary;
33
40
  /**
34
41
  * 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. */
42
+ * of an id or fingerprint, so a commit or dirty tree doesn't orphan
43
+ * a baseline.
44
+ */
37
45
  git?: GitMetadata;
38
46
  }
39
47
 
@@ -50,6 +58,14 @@ export interface NoiseFloor {
50
58
  floorPct: number;
51
59
  referenceMedianNs: number;
52
60
  samples: number;
61
+ /**
62
+ * How long the check sampled, in milliseconds: 25 to 50 by default, as
63
+ * long as the median took to hold. Absent in older documents. */
64
+ checkMs?: number;
65
+ /**
66
+ * The fixed budget `--noise-budget` asked for, in milliseconds; absent
67
+ * for the default, adaptive check. */
68
+ budgetMs?: number;
53
69
  /**
54
70
  * How much slower (positive) the reference ran at the end of the run than
55
71
  * at the start, percent: the machine's drift over the run. Absent when the
@@ -157,6 +173,8 @@ export interface Measurement {
157
173
  export interface Trial {
158
174
  i: number;
159
175
  wallNs: number;
176
+ /** The file `--save-output` wrote this trial's stdout and stderr to. */
177
+ outputPath?: string;
160
178
  /**
161
179
  * The command's self-reported time (ns) under a `timeSource`; these, not
162
180
  * `wallNs`, are then the `timing.samples`. */
@@ -250,8 +268,9 @@ export interface MemoryEvidence {
250
268
  origin: "resourceUsage" | "heapStats";
251
269
  /**
252
270
  * `memstats` only: `"retained"` (`--alloc`, `bytesPerOp`) or `"peak"`
253
- * (`--peak-mem`, `peakBytes`). Absent means `"retained"` on older
254
- * documents. */
271
+ * (`--peak-mem`, `peakBytes`). Absent means `"retained"` on
272
+ * older documents.
273
+ */
255
274
  kind?: "retained" | "peak";
256
275
  /** Largest `Trial.maxRssBytes` across a timing measurement's trials. */
257
276
  maxRssBytes?: number;
@@ -305,8 +324,9 @@ export interface PairedEvidence {
305
324
  * side of 1 in at least three quarters of rounds. */
306
325
  flagged?: "regressed" | "improved";
307
326
  /**
308
- * Each fresh-process re-measurement of a flagged workload; `flagged` by
309
- * `AbSummary.metric`. */
327
+ * Each fresh-process re-measurement of a flagged workload; `flagged`
328
+ * by `AbSummary.metric`.
329
+ */
310
330
  repeats?: {
311
331
  medianRatio: number;
312
332
  ratioP25: number;
@@ -390,15 +410,17 @@ export interface AbSummary {
390
410
  improved: number;
391
411
  unchanged: number;
392
412
  /**
393
- * Flagged in-process, but a fresh-process repeat disagreed; counted in
394
- * `unchanged`. */
413
+ * Flagged in-process, but a fresh-process repeat disagreed; counted
414
+ * in `unchanged`.
415
+ */
395
416
  unconfirmed: number;
396
417
  /** Workloads whose first call returned different values on each side. */
397
418
  outputDiffers: number;
398
419
  /**
399
420
  * Workloads whose suite file and output both changed (see
400
- * `PairedEvidence.suiteChanged`); counted in `unchanged`, left out of
401
- * `geomeanPct`. */
421
+ * `PairedEvidence.suiteChanged`); counted in `unchanged`, left out
422
+ * of `geomeanPct`.
423
+ */
402
424
  notComparable: number;
403
425
  /**
404
426
  * Workloads that threw on either side or both, and so weren't timed;
@@ -424,8 +446,8 @@ export interface AbSummary {
424
446
  // its stack when another module imports a type taken with `typeof` from
425
447
  // an unannotated array (WarningCode, below).
426
448
  /**
427
- * Every `Warning.code`. A runtime array so a test can assert each is
428
- * emitted.
449
+ * Every `Warning.code`. A runtime array so a test can assert each
450
+ * is emitted.
429
451
  */
430
452
  export const WARNING_CODES: readonly [
431
453
  "slow-first-run",
@@ -499,8 +521,8 @@ export interface Comparison {
499
521
  verdict: "improved" | "regressed" | "unchanged";
500
522
  };
501
523
  /**
502
- * Caveats about this comparison, e.g. a thin-sample point-estimate
503
- * verdict.
524
+ * Caveats about this comparison, e.g. a thin-sample
525
+ * point-estimate verdict.
504
526
  */
505
527
  warnings?: Warning[];
506
528
  frames?: {
@@ -526,8 +548,8 @@ export interface Comparison {
526
548
  alpha: number;
527
549
  bootstrapIterations: number;
528
550
  /**
529
- * `max(timingPct, both documents' noise floors)`: what timing was tested
530
- * against.
551
+ * `max(timingPct, both documents' noise floors)`: what timing was
552
+ * tested against.
531
553
  */
532
554
  effectiveTimingPct: number;
533
555
  };
@@ -606,8 +628,9 @@ export interface ComparedTask {
606
628
  export interface MemoryDelta {
607
629
  /**
608
630
  * `heapUsedBefore`/`heapUsedAfter`: in-process heap around the timing
609
- * run; `retained`: `--alloc`; `peak`: `--peak-mem`; `maxRss`: subprocess
610
- * timing. */
631
+ * run; `retained`: `--alloc`; `peak`: `--peak-mem`; `maxRss`:
632
+ * subprocess timing.
633
+ */
611
634
  reading: "heapUsedBefore" | "heapUsedAfter" | "retained" | "peak" | "maxRss";
612
635
  baseBytes: number;
613
636
  candBytes: number;
@@ -19,8 +19,8 @@ interface AllocCaptureResult {
19
19
  // Retained heap growth per call: heap size after a batch and a full GC,
20
20
  // minus before, over the calls made: up to `batchSize`, fewer (at least
21
21
  // one) once `budgetMs` has passed. Garbage is collected, so this is a leak
22
- // check and a garbage-heavy task reads near zero. Never feeds timing
23
- // stats.
22
+ // check and a garbage-heavy task reads near zero. Never feeds
23
+ // timing stats.
24
24
  export async function measureAllocPerOp(
25
25
  fn: () => unknown,
26
26
  batchSize: number = DEFAULT_BATCH_SIZE,
@@ -7,8 +7,8 @@ import { isPromiseLike } from "./loop.ts";
7
7
  // call, too few for a top-frame table to hold still between runs.
8
8
  export const DEFAULT_TASK_CPU_INTERVAL_US = 100;
9
9
  // perf: the sampler manages well under one sample per interval (about 0.6
10
- // at 100µs, 0.8 at 1000µs on an idle M2), hence the 2x slack on the
11
- // window.
10
+ // at 100µs, 0.8 at 1000µs on an idle M2), hence the 2x slack on
11
+ // the window.
12
12
  const TARGET_SAMPLES = 2000;
13
13
  const WINDOW_SLACK = 2;
14
14
  const MIN_WINDOW_MS = 200;
@@ -1,20 +1,21 @@
1
1
  import os from "node:os";
2
2
 
3
3
  import type { Environment, Warning } from "../ir/types.ts";
4
- import { measureNoiseFloor } from "./noise.ts";
4
+ import { DRIFT_BUDGET_MS, measureNoiseFloor } from "./noise.ts";
5
5
 
6
6
  const LOAD_WARNING_FRACTION = 0.75;
7
7
 
8
- // perf: takes ~200ms (runs the noise-floor workload), so call it once per
9
- // invocation, never per workload.
10
- export function captureEnvironment(): Environment {
8
+ // perf: takes 25 to 50 ms (runs the noise-floor workload), or the
9
+ // `noiseBudgetMs` asked for, so call it once per invocation, never
10
+ // per workload.
11
+ export function captureEnvironment(noiseBudgetMs?: number): Environment {
11
12
  const [loadAvg1 = 0, loadAvg5 = 0] = os.loadavg();
12
13
  return {
13
14
  cpuModel: os.cpus()[0]?.model ?? "unknown",
14
15
  cores: os.availableParallelism(),
15
16
  loadAvg1,
16
17
  loadAvg5,
17
- noise: measureNoiseFloor(),
18
+ noise: measureNoiseFloor(noiseBudgetMs),
18
19
  };
19
20
  }
20
21
 
@@ -24,7 +25,11 @@ export function captureEnvironment(): Environment {
24
25
  export function stampDrift(env: Environment | undefined): void {
25
26
  if (!env) return;
26
27
  const start = env.noise.referenceMedianNs;
27
- const end = measureNoiseFloor().referenceMedianNs;
28
+ // The start check's own budget when one was asked for, so the two
29
+ // medians are measured alike.
30
+ const end = measureNoiseFloor(
31
+ env.noise.budgetMs ?? DRIFT_BUDGET_MS,
32
+ ).referenceMedianNs;
28
33
  env.noise.driftPct = start > 0 ? (end / start - 1) * 100 : 0;
29
34
  }
30
35
 
@@ -22,23 +22,25 @@ export interface InprocessTimingOptions {
22
22
  /** Keep sampling past the budget until this many trials exist. When unset
23
23
  * the floor is cost-aware (see `defaultSampleFloor`). */
24
24
  minSamples?: number;
25
- /** Warmup budget as a fraction of `budgetMs` (default: 0.1); unlike
26
- * `time()`'s `warmup`, which is a trial count. Always runs at least one
27
- * call. */
25
+ /**
26
+ * Warmup budget as a fraction of `budgetMs` (default: 0.1); unlike
27
+ * `time()`'s `warmup`, which is a trial count. Always runs at least
28
+ * one call.
29
+ */
28
30
  warmup?: number;
29
31
  gc?: boolean;
30
32
  }
31
33
 
32
34
  const DEFAULT_TIME_BUDGET_MS = 500;
33
- // Upper bound only: a task cheap enough to fit 20 trials in the budget is
34
- // time-bound.
35
+ // Upper bound only: a task cheap enough to fit 20 trials in the budget
36
+ // is time-bound.
35
37
  const BUDGET_FLOOR_CAP = 20;
36
38
  const RIGOR_FLOOR_MIN = 3;
37
39
  const RIGOR_FLOOR_CAP = 10;
38
40
  const RIGOR_SAMPLES_PER_DECADE = 2;
39
41
  const DEFAULT_WARMUP_FRACTION = 0.1;
40
- // Batch each trial to at least this long so timer resolution doesn't
41
- // dominate.
42
+ // Batch each trial to at least this long so timer resolution
43
+ // doesn't dominate.
42
44
  const BATCH_THRESHOLD_NS = 1000;
43
45
  // Batch further so a full budget yields about this many trials: every
44
46
  // trial is sorted, serialized over IPC and parsed back, which costs
@@ -83,9 +85,11 @@ export function defaultSampleFloor(
83
85
  // Write-only on purpose: a store to module state is never provably dead.
84
86
  const kept: { value?: unknown } = {};
85
87
 
86
- /** Pins `value` against dead-code elimination for an intermediate inside a
87
- * task body. A task's own return value is already pinned by the timing
88
- * loop. */
88
+ /**
89
+ * Pins `value` against dead-code elimination for an intermediate inside a
90
+ * task body. A task's own return value is already pinned by the
91
+ * timing loop.
92
+ */
89
93
  export function keep(value: unknown): void {
90
94
  kept.value = value;
91
95
  }
@@ -38,8 +38,8 @@ function openCounter(): InstructionCounter {
38
38
  }
39
39
 
40
40
  // spec: thread_selfcounts(1, ...) fills { instructions, cycles } for the
41
- // calling thread: what `/usr/bin/time -l` totals over a process, read per
42
- // thread.
41
+ // calling thread: what `/usr/bin/time -l` totals over a process, read
42
+ // per thread.
43
43
  function darwinCounter(): InstructionCounter {
44
44
  const { symbols } = dlopen("/usr/lib/libSystem.B.dylib", {
45
45
  thread_selfcounts: {
@@ -1,13 +1,23 @@
1
1
  import type { NoiseFloor } from "../ir/types.ts";
2
2
  import { computeTimingStats } from "../stats/index.ts";
3
3
 
4
- const DEFAULT_BUDGET_MS = 200;
5
- // Keeps a trial in the microsecond range so timer resolution doesn't
6
- // dominate.
4
+ // The default check samples for at least MIN_MS, then until its median
5
+ // holds within STABLE_PCT between checkpoints, for at most MAX_MS: a
6
+ // longer check doesn't give a steadier floor, since the spread comes from
7
+ // the machine, not the sample count (metonym/ostia#52).
8
+ const MIN_MS = 25;
9
+ const MAX_MS = 50;
10
+ const CHECK_EVERY = 16;
11
+ const STABLE_PCT = 1;
12
+ // perf: the end-of-run check only needs the median, for drift, and the
13
+ // median holds from 25 ms.
14
+ export const DRIFT_BUDGET_MS = 25;
15
+ // Keeps a trial in the microsecond range so timer resolution
16
+ // doesn't dominate.
7
17
  const HASHES_PER_TRIAL = 64;
8
18
 
9
- // Fixed and allocation-free, so trial-to-trial variance is the machine's
10
- // noise.
19
+ // Fixed and allocation-free, so trial-to-trial variance is the
20
+ // machine's noise.
11
21
  const REFERENCE_BUFFER = (() => {
12
22
  const buf = new Uint8Array(4096);
13
23
  for (let i = 0; i < buf.length; i++) buf[i] = (i * 2654435761) & 0xff;
@@ -32,17 +42,41 @@ export function computeNoiseFloor(samples: number[]): NoiseFloor {
32
42
  };
33
43
  }
34
44
 
35
- // Samples the reference hash loop for `budgetMs`; characterizes the
36
- // machine, not any workload, so run it once per document.
37
- export function measureNoiseFloor(
38
- budgetMs: number = DEFAULT_BUDGET_MS,
39
- ): NoiseFloor {
40
- const budgetNs = budgetMs * 1e6;
45
+ function median(values: readonly number[]): number {
46
+ const sorted = [...values].sort((a, b) => a - b);
47
+ const mid = sorted.length >> 1;
48
+ return sorted.length % 2 === 0
49
+ ? ((sorted[mid - 1] ?? 0) + (sorted[mid] ?? 0)) / 2
50
+ : (sorted[mid] ?? 0);
51
+ }
52
+
53
+ // Samples the reference hash loop; characterizes the machine, not any
54
+ // workload, so run it once per document. With `budgetMs`, for exactly
55
+ // that long, as `--noise-budget` asks; without, adaptively.
56
+ export function measureNoiseFloor(budgetMs?: number): NoiseFloor {
57
+ const minNs = (budgetMs ?? MIN_MS) * 1e6;
58
+ const maxNs = (budgetMs ?? MAX_MS) * 1e6;
41
59
  const trials: number[] = [];
42
60
  let sink = 0;
61
+ let checkpoint: number | undefined;
43
62
 
44
63
  const start = Bun.nanoseconds();
45
- while (Bun.nanoseconds() - start < budgetNs) {
64
+ for (;;) {
65
+ const elapsed = Bun.nanoseconds() - start;
66
+ if (elapsed >= maxNs) break;
67
+ if (
68
+ budgetMs === undefined &&
69
+ elapsed >= minNs &&
70
+ trials.length % CHECK_EVERY === 0
71
+ ) {
72
+ const now = median(trials);
73
+ const held =
74
+ checkpoint !== undefined &&
75
+ checkpoint > 0 &&
76
+ (Math.abs(now - checkpoint) / checkpoint) * 100 <= STABLE_PCT;
77
+ if (held) break;
78
+ checkpoint = now;
79
+ }
46
80
  const trialStart = Bun.nanoseconds();
47
81
  for (let i = 0; i < HASHES_PER_TRIAL; i++) {
48
82
  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- write-only, defeats DCE
@@ -51,5 +85,9 @@ export function measureNoiseFloor(
51
85
  trials.push((Bun.nanoseconds() - trialStart) / HASHES_PER_TRIAL);
52
86
  }
53
87
 
54
- return computeNoiseFloor(trials);
88
+ return {
89
+ ...computeNoiseFloor(trials),
90
+ checkMs: (Bun.nanoseconds() - start) / 1e6,
91
+ ...(budgetMs !== undefined && { budgetMs }),
92
+ };
55
93
  }
@@ -286,8 +286,8 @@ export function memoryChange(
286
286
  // `regressed` when the median ratio is above `1 + thresholdPct/100` and
287
287
  // the 25th percentile is above 1 (slower in at least three quarters of
288
288
  // rounds); `improved` is the mirror. The quartile condition is there so a
289
- // few wild rounds can't flag a workload whose typical round shows no
290
- // change.
289
+ // few wild rounds can't flag a workload whose typical round shows
290
+ // no change.
291
291
  export function ratioStats(ratios: number[], thresholdPct: number): RatioStats {
292
292
  const sorted = sortedCopy(ratios);
293
293
  const medianRatio = percentile(sorted, 0.5);
@@ -10,8 +10,8 @@ export interface MemorySnapshot {
10
10
  }
11
11
 
12
12
  // Taken before the suite loads so `measurePeakMem` can split the starting
13
- // RSS into live data and memory setup freed that the allocator still
14
- // holds.
13
+ // RSS into live data and memory setup freed that the allocator
14
+ // still holds.
15
15
  export function memorySnapshot(): MemorySnapshot {
16
16
  const { heapSize, extraMemorySize } = heapStats();
17
17
  const rssBytes = process.memoryUsage.rss();
@@ -23,8 +23,8 @@ export function memorySnapshot(): MemorySnapshot {
23
23
  }
24
24
 
25
25
  // Bun 1.4.3+ reports the physical footprint as RSS on macOS, which misses
26
- // reused freed pages for a while (oven-sh/bun#44951). Resident size
27
- // doesn't.
26
+ // reused freed pages for a while (oven-sh/bun#44951). Resident
27
+ // size doesn't.
28
28
  function residentBytes(): number | undefined {
29
29
  if (process.platform !== "darwin") return undefined;
30
30
  readResident ??= residentReader();
@@ -19,6 +19,11 @@ interface TimingPhaseOptions extends SpawnTrialOptions {
19
19
  budgetMs?: number;
20
20
  /** Runs unmeasured before every trial, warmup included. */
21
21
  prepare?: PrepareHook;
22
+ /**
23
+ * Save each trial's output here, as `trial-N.log`, and each warmup's
24
+ * as `warmup-N.log`.
25
+ */
26
+ outputDir?: string;
22
27
  /**
23
28
  * Exit codes treated as success (hyperfine's `--ignore-failure`): such a
24
29
  * trial still contributes its sample and never triggers `nonzero-exit`. */
@@ -51,8 +56,8 @@ interface TimingPhaseIterator {
51
56
  result(): TimingPhaseResult;
52
57
  }
53
58
 
54
- // `undefined` is a timed-out trial: killed, so it has no exit code to fail
55
- // on.
59
+ // `undefined` is a timed-out trial: killed, so it has no exit code to
60
+ // fail on.
56
61
  function isFailedExit(code: number | undefined, ignored: Set<number>): boolean {
57
62
  return code !== undefined && code !== 0 && !ignored.has(code);
58
63
  }
@@ -99,7 +104,14 @@ export function createTimingPhase(
99
104
  },
100
105
  );
101
106
  }
102
- return runTrial(opts);
107
+ return runTrial(
108
+ opts.outputDir === undefined
109
+ ? opts
110
+ : {
111
+ ...opts,
112
+ outputPath: `${opts.outputDir}/${phase === "warmup" ? "warmup" : "trial"}-${index}.log`,
113
+ },
114
+ );
103
115
  }
104
116
 
105
117
  return {
@@ -132,6 +144,9 @@ export function createTimingPhase(
132
144
  }),
133
145
  ...(result.timedOut && { timedOut: true as const }),
134
146
  ...(result.timeSourceNoMatch && { timeSourceNoMatch: true as const }),
147
+ ...(result.outputPath !== undefined && {
148
+ outputPath: result.outputPath,
149
+ }),
135
150
  });
136
151
  // The budget bounds the loop's wall time even for reported-time samples.
137
152
  totalNs += result.wallNs;
package/src/profile.ts CHANGED
@@ -17,8 +17,9 @@ export interface ProfileOptions {
17
17
  /**
18
18
  * Names the workload: it becomes the label and, instead of the function's
19
19
  * name and source, what the id hashes, so closures that differ only in
20
- * captured values get distinct ids and the id survives editing the
21
- * function. */
20
+ * captured values get distinct ids and the id survives editing
21
+ * the function.
22
+ */
22
23
  name?: string;
23
24
  /**
24
25
  * `"inspector"` (default) captures through CDP and writes a portable
@@ -28,8 +29,9 @@ export interface ProfileOptions {
28
29
  /**
29
30
  * There's no child to kill, so an already-aborted signal skips the
30
31
  * profiler, calls `fn` plain (still returning its `result`) and records an
31
- * `aborted` warning instead of CPU evidence. It can't interrupt a running
32
- * `fn`. */
32
+ * `aborted` warning instead of CPU evidence. It can't interrupt a
33
+ * running `fn`.
34
+ */
33
35
  signal?: AbortSignal;
34
36
  }
35
37
 
@@ -23,8 +23,8 @@ export const collapsedRenderer: Renderer<VizOptions> = {
23
23
  pathOf[i] = p === -1 ? name : `${pathOf[p]};${name}`;
24
24
  }
25
25
 
26
- // Typed counts plus a first-seen list, because this runs over every
27
- // sample.
26
+ // Typed counts plus a first-seen list, because this runs over
27
+ // every sample.
28
28
  const counts = new Float64Array(tree.count);
29
29
  const seen: number[] = [];
30
30
  for (const id of cpu.samples?.nodeIds ?? []) {
@@ -0,0 +1,148 @@
1
+ import { formatDuration, pickDurationUnit } from "../format.ts";
2
+ import type { ProfileDocument, Warning, Workload } from "../ir/types.ts";
3
+ import {
4
+ formatRelative,
5
+ formatShellLine,
6
+ formatSignedPct,
7
+ workloadLabel,
8
+ } from "./format.ts";
9
+ import { abRows, formatAbSummary, formatThrew, pairedCells } from "./paired.ts";
10
+ import { relativeRatios, type TimingRow } from "./relative.ts";
11
+ import {
12
+ comparedRows,
13
+ memoryReadings,
14
+ noSampleRuns,
15
+ oneSidedNote,
16
+ runWarnings,
17
+ timingRuns,
18
+ workloadsById,
19
+ } from "./select.ts";
20
+ import type { Renderer, RenderResult } from "./types.ts";
21
+
22
+ // One line per command or task, and each warning on a short line after
23
+ // them: the fewest tokens that still read as text, for an agent or a
24
+ // person (metonym/ostia#54). `events` is the format a script parses.
25
+
26
+ // Each line's columns, padded so they line up.
27
+ function aligned(rows: string[][]): string[] {
28
+ const widths: number[] = [];
29
+ for (const row of rows) {
30
+ for (const [i, cell] of row.entries()) {
31
+ widths[i] = Math.max(widths[i] ?? 0, cell.length);
32
+ }
33
+ }
34
+ return rows.map((row) =>
35
+ row
36
+ .map((cell, i) =>
37
+ i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0),
38
+ )
39
+ .join(" ")
40
+ .trimEnd(),
41
+ );
42
+ }
43
+
44
+ function warningLines(label: string, warnings: readonly Warning[]): string[] {
45
+ return warnings.map((w) => `! ${label}: ${w.message}`);
46
+ }
47
+
48
+ function timingLines(doc: ProfileDocument): string[] {
49
+ const memory = memoryReadings(doc);
50
+ const byId = new Map(timingRuns(doc).map((run) => [run.workloadId, run]));
51
+ const empty = new Map(noSampleRuns(doc).map((run) => [run.workloadId, run]));
52
+ const measured: TimingRow[] = [];
53
+ for (const workload of doc.workloads) {
54
+ const run = byId.get(workload.id);
55
+ if (run) measured.push({ run, workload });
56
+ }
57
+ const ratios = relativeRatios(measured);
58
+ const rows: string[][] = [];
59
+ const warnings: string[] = [];
60
+ for (const workload of doc.workloads) {
61
+ const label = workloadLabel(workload);
62
+ const run = byId.get(workload.id);
63
+ const noSamples = empty.get(workload.id);
64
+ if (run) {
65
+ const { median, mad } = run.timing;
66
+ const unit = pickDurationUnit(median);
67
+ const row = measured.find((r) => r.run === run);
68
+ const ratio = row && ratios?.get(row);
69
+ rows.push([
70
+ label,
71
+ formatDuration(median, unit),
72
+ `±${(median === 0 ? 0 : (mad / median) * 100).toFixed(1)}%`,
73
+ ratio === undefined ? "" : formatRelative(ratio, !!workload.baseline),
74
+ ]);
75
+ warnings.push(...warningLines(label, runWarnings(run, memory)));
76
+ } else if (noSamples) {
77
+ rows.push([label, "no samples"]);
78
+ warnings.push(...warningLines(label, runWarnings(noSamples, memory)));
79
+ } else if (workload.skipped) {
80
+ rows.push([label, "skipped"]);
81
+ }
82
+ }
83
+ return [...aligned(rows), ...warnings];
84
+ }
85
+
86
+ function comparisonLines(doc: ProfileDocument): string[] {
87
+ const rows: string[][] = [];
88
+ const notCompared: string[] = [];
89
+ for (const { row } of comparedRows(doc)) {
90
+ if (row.verdict === "missing-base" || row.verdict === "missing-cand") {
91
+ notCompared.push(`- ${row.task}: ${oneSidedNote(row.verdict)}`);
92
+ continue;
93
+ }
94
+ const mark = row.pass === false ? "✗" : "✓";
95
+ if (!row.timing) {
96
+ rows.push([`${mark} ${row.task}`, `(${row.verdict})`]);
97
+ continue;
98
+ }
99
+ const { baseMedian, candMedian, medianDeltaPct } = row.timing;
100
+ const unit = pickDurationUnit(Math.max(baseMedian, candMedian));
101
+ rows.push([
102
+ `${mark} ${row.task}`,
103
+ `${formatDuration(baseMedian, unit)} -> ${formatDuration(candMedian, unit)}`,
104
+ formatSignedPct(medianDeltaPct),
105
+ `(${row.verdict})`,
106
+ ]);
107
+ }
108
+ return [...aligned(rows), ...notCompared];
109
+ }
110
+
111
+ function abLines(
112
+ doc: ProfileDocument,
113
+ ab: NonNullable<ProfileDocument["ab"]>,
114
+ ): string[] {
115
+ const workloads = workloadsById(doc);
116
+ const label = (id: string) => {
117
+ const workload: Workload | undefined = workloads.get(id);
118
+ return workload ? workloadLabel(workload) : id;
119
+ };
120
+ const rows: string[][] = [];
121
+ for (const row of abRows(doc)) {
122
+ if (row.kind === "threw") {
123
+ rows.push([label(row.run.workloadId), formatThrew(row.run.threw)]);
124
+ continue;
125
+ }
126
+ const cells = pairedCells(row.run, ab.metric);
127
+ rows.push([
128
+ label(row.run.workloadId),
129
+ `${cells.base} -> ${cells.candidate}`,
130
+ cells.change,
131
+ cells.verdict,
132
+ ]);
133
+ }
134
+ return [formatAbSummary(ab), ...aligned(rows)];
135
+ }
136
+
137
+ export const conciseRenderer: Renderer = {
138
+ name: "concise",
139
+ render(doc: ProfileDocument): Promise<RenderResult> {
140
+ return Promise.try(() => {
141
+ const lines = doc.ab
142
+ ? abLines(doc, doc.ab)
143
+ : [...timingLines(doc), ...comparisonLines(doc)];
144
+ if (doc.shell) lines.push(formatShellLine(doc.shell));
145
+ return { text: lines.length > 0 ? `${lines.join("\n")}\n` : "" };
146
+ });
147
+ },
148
+ };