ostia 0.4.0 → 0.6.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 (64) hide show
  1. package/README.md +31 -30
  2. package/docs/agent-protocol.md +13 -9
  3. package/docs/cli.md +174 -126
  4. package/docs/config.md +2 -2
  5. package/docs/document-schema.md +15 -12
  6. package/docs/library.md +32 -21
  7. package/docs/preload-recipes.md +4 -4
  8. package/docs/statistics.md +14 -13
  9. package/index.d.ts +202 -60
  10. package/package.json +1 -1
  11. package/src/ab/ab-runner.ts +6 -6
  12. package/src/ab/index.ts +56 -6
  13. package/src/ab/unpaired.ts +54 -0
  14. package/src/bench/index.ts +40 -3
  15. package/src/bench/registry.ts +6 -4
  16. package/src/bench/run-tasks.ts +16 -2
  17. package/src/bench/runner.ts +10 -3
  18. package/src/bench/support.ts +8 -4
  19. package/src/bench/sweep.ts +2 -2
  20. package/src/cache/fingerprint.ts +2 -2
  21. package/src/capture/bunflags.ts +2 -2
  22. package/src/capture/cpu.ts +2 -2
  23. package/src/capture/heap-parse.ts +2 -2
  24. package/src/ci/index.ts +39 -48
  25. package/src/cli/agent.ts +54 -0
  26. package/src/cli/flags.ts +58 -9
  27. package/src/cli/help.ts +670 -245
  28. package/src/cli/main.ts +2 -3
  29. package/src/cli/output.ts +17 -14
  30. package/src/cli/run.ts +317 -92
  31. package/src/compare/index.ts +4 -4
  32. package/src/config/index.ts +14 -10
  33. package/src/config/validate.ts +4 -4
  34. package/src/glob.ts +2 -2
  35. package/src/index.ts +3 -2
  36. package/src/ir/document.ts +2 -2
  37. package/src/ir/types.ts +49 -24
  38. package/src/measure/alloc.ts +2 -2
  39. package/src/measure/cpu.ts +2 -2
  40. package/src/measure/environment.ts +11 -6
  41. package/src/measure/inprocess.ts +14 -10
  42. package/src/measure/instructions.ts +2 -2
  43. package/src/measure/noise.ts +51 -13
  44. package/src/measure/paired.ts +2 -2
  45. package/src/measure/peak.ts +4 -4
  46. package/src/measure/timing.ts +27 -6
  47. package/src/profile.ts +6 -4
  48. package/src/renderers/collapsed.ts +2 -2
  49. package/src/renderers/concise.ts +148 -0
  50. package/src/renderers/format.ts +13 -4
  51. package/src/renderers/human.ts +402 -0
  52. package/src/renderers/index.ts +9 -2
  53. package/src/renderers/markdown.ts +2 -2
  54. package/src/renderers/mermaid.ts +2 -2
  55. package/src/renderers/minimal.ts +8 -7
  56. package/src/renderers/relative.ts +2 -2
  57. package/src/renderers/select.ts +2 -2
  58. package/src/renderers/terminal.ts +1178 -383
  59. package/src/renderers/types.ts +3 -0
  60. package/src/spawn/index.ts +47 -14
  61. package/src/stats/bootstrap.ts +2 -2
  62. package/src/stats/index.ts +2 -2
  63. package/src/terminal.ts +321 -0
  64. package/src/time.ts +124 -20
@@ -43,8 +43,8 @@ export const DEFAULT_THRESHOLDS: Thresholds = {
43
43
  };
44
44
 
45
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.
46
+ // rule (with a `thin-comparison` warning), because CI and p-value are
47
+ // too noisy.
48
48
  const MIN_SAMPLES_FOR_TEST = 5;
49
49
 
50
50
  function pctDelta(base: number, cand: number): number {
@@ -257,8 +257,8 @@ export function createComparer(
257
257
  unmatched,
258
258
  compared(matched) {
259
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.
260
+ // `task.skip()`) has no comparison either, so it's missing its
261
+ // base too.
262
262
  const compared = new Set(matched.map(([id]) => id));
263
263
  const candOnly = cand.workloads.filter((w) => !compared.has(w.id));
264
264
  const { baseOnly } = unmatched();
@@ -31,18 +31,21 @@ export interface WorkloadConfig {
31
31
  /**
32
32
  * `command`: kills a trial (or prepare hook) after this many ms.
33
33
  * `suites`: kills a suite file's (or isolated task's) process after this
34
- * many ms, overriding `bench.timeoutMs`. Overrides `ostia ci`'s 10-minute
35
- * default. */
34
+ * many ms, overriding `bench.timeoutMs`. Overrides `ostia ci`'s
35
+ * 10-minute default.
36
+ */
36
37
  timeoutMs?: number;
37
38
  /**
38
- * `command` only. Exit codes to treat as success; see
39
- * `TimeOptions.ignoreExitCodes`. */
39
+ * `command` only. Exit codes to treat as success;
40
+ * see `TimeOptions.ignoreExitCodes`.
41
+ */
40
42
  ignoreExitCodes?: number[];
41
43
  }
42
44
 
43
45
  /**
44
- * Launch settings for the suite files matching `suites`; see
45
- * `BenchOptions.projects`. */
46
+ * Launch settings for the suite files matching `suites`;
47
+ * see `BenchOptions.projects`.
48
+ */
46
49
  export interface BenchProject {
47
50
  /**
48
51
  * Globs against the current directory. A suite file takes the first
@@ -103,8 +106,9 @@ export interface AbConfig {
103
106
  * `--base-setup` replaces this list. */
104
107
  setup?: string | string[];
105
108
  /**
106
- * Base trees to keep cached; see `AbOptions.keepTrees`. `--keep-trees`
107
- * overrides. Default: 5. */
109
+ * Base trees to keep cached; see `AbOptions.keepTrees`.
110
+ * `--keep-trees` overrides. Default: 5.
111
+ */
108
112
  keepTrees?: number;
109
113
  /**
110
114
  * Judge rounds by `"time"` or `"instructions"`; see `AbOptions.metric`.
@@ -153,8 +157,8 @@ export interface OstiaConfig {
153
157
  noiseCheck?: boolean;
154
158
  }
155
159
 
156
- // Partial is shallow, so `thresholds` needs its own Partial to merge
157
- // field-by-field.
160
+ // Partial is shallow, so `thresholds` needs its own Partial to
161
+ // merge field-by-field.
158
162
  export type OstiaConfigInput = Omit<Partial<OstiaConfig>, "thresholds"> & {
159
163
  thresholds?: Partial<Thresholds>;
160
164
  };
@@ -1,8 +1,8 @@
1
1
  import { errorMessage } from "../errors.ts";
2
2
 
3
3
  /**
4
- * A config file that exists but can't be used; the CLI reports it as
5
- * `config-invalid`.
4
+ * A config file that exists but can't be used; the CLI reports it
5
+ * as `config-invalid`.
6
6
  */
7
7
  export class ConfigError extends Error {}
8
8
 
@@ -222,8 +222,8 @@ function checkWorkload(
222
222
 
223
223
  // Throws `ConfigError` naming the offending key for a wrong type or value;
224
224
  // `warn` gets keys that are unknown (or inapplicable) and so ignored.
225
- // `raw` is the already-object-checked config with `undefined` values still
226
- // present.
225
+ // `raw` is the already-object-checked config with `undefined` values
226
+ // still present.
227
227
  export function validateConfig(
228
228
  raw: Record<string, unknown>,
229
229
  file: string,
package/src/glob.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { resolve } from "node:path";
2
2
 
3
3
  const SKIPPED_DIRS = ["node_modules", ".git"];
4
- // Wildcards skip it because `ostia ab` extracts copies of the project
5
- // there.
4
+ // Wildcards skip it because `ostia ab` extracts copies of the
5
+ // project there.
6
6
  const AB_TREES = ".ostia/ab";
7
7
  // compat: `@(` and `+(` open extglobs since Bun 1.4.4; a bare `(` isn't a
8
8
  // glob character, so `app/(marketing)` stays literal.
package/src/index.ts CHANGED
@@ -2,7 +2,7 @@ import type { OstiaConfigInput } from "./config/index.ts";
2
2
 
3
3
  export type { AbOptions, AbProgress } from "./ab/index.ts";
4
4
  export { ab, AbBaseError, AbSetupError, AbSuiteError } from "./ab/index.ts";
5
- export type { BenchOptions } from "./bench/index.ts";
5
+ export type { BenchOptions, BenchProgress } from "./bench/index.ts";
6
6
  export { bench } from "./bench/index.ts";
7
7
  export { range } from "./bench/range.ts";
8
8
  export type { GroupOptions, TaskOptions } from "./bench/registry.ts";
@@ -60,6 +60,7 @@ export type {
60
60
  MinimalUnmatchedLine,
61
61
  } from "./renderers/minimal.ts";
62
62
  export { MINIMAL_PROTOCOL_VERSION } from "./renderers/minimal.ts";
63
+ export type { TableOptions } from "./renderers/terminal.ts";
63
64
  export type { FormatName, Renderer, VizOptions } from "./renderers/types.ts";
64
65
  export type {
65
66
  PrepareFn,
@@ -68,7 +69,7 @@ export type {
68
69
  TimeSource,
69
70
  TimeUnit,
70
71
  } from "./spawn/index.ts";
71
- export type { CommandSpec, TimeOptions } from "./time.ts";
72
+ export type { CommandSpec, TimeOptions, TimeProgress } from "./time.ts";
72
73
  export { time } from "./time.ts";
73
74
 
74
75
  /** Identity function that types an `ostia.config.ts` default export. */
@@ -76,8 +76,8 @@ interface SubprocessWorkloadOptions {
76
76
 
77
77
  // `prepare` and `timeSource` join the id only when given, so commands
78
78
  // without them keep their old id. A function `prepare` hashes by source
79
- // text. The id excludes `process.cwd()` so baselines match across
80
- // checkouts.
79
+ // text. The id excludes `process.cwd()` so baselines match
80
+ // across checkouts.
81
81
  export function makeSubprocessWorkload(
82
82
  command: string[],
83
83
  label?: string,
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",
@@ -445,6 +467,7 @@ export const WARNING_CODES: readonly [
445
467
  "environment-mismatch",
446
468
  "peak-hidden",
447
469
  "suite-changed",
470
+ "repeats-disagree",
448
471
  ] = [
449
472
  "slow-first-run",
450
473
  "outliers-detected",
@@ -463,6 +486,7 @@ export const WARNING_CODES: readonly [
463
486
  "environment-mismatch",
464
487
  "peak-hidden",
465
488
  "suite-changed",
489
+ "repeats-disagree",
466
490
  ];
467
491
 
468
492
  export type WarningCode = (typeof WARNING_CODES)[number];
@@ -499,8 +523,8 @@ export interface Comparison {
499
523
  verdict: "improved" | "regressed" | "unchanged";
500
524
  };
501
525
  /**
502
- * Caveats about this comparison, e.g. a thin-sample point-estimate
503
- * verdict.
526
+ * Caveats about this comparison, e.g. a thin-sample
527
+ * point-estimate verdict.
504
528
  */
505
529
  warnings?: Warning[];
506
530
  frames?: {
@@ -526,8 +550,8 @@ export interface Comparison {
526
550
  alpha: number;
527
551
  bootstrapIterations: number;
528
552
  /**
529
- * `max(timingPct, both documents' noise floors)`: what timing was tested
530
- * against.
553
+ * `max(timingPct, both documents' noise floors)`: what timing was
554
+ * tested against.
531
555
  */
532
556
  effectiveTimingPct: number;
533
557
  };
@@ -606,8 +630,9 @@ export interface ComparedTask {
606
630
  export interface MemoryDelta {
607
631
  /**
608
632
  * `heapUsedBefore`/`heapUsedAfter`: in-process heap around the timing
609
- * run; `retained`: `--alloc`; `peak`: `--peak-mem`; `maxRss`: subprocess
610
- * timing. */
633
+ * run; `retained`: `--alloc`; `peak`: `--peak-mem`; `maxRss`:
634
+ * subprocess timing.
635
+ */
611
636
  reading: "heapUsedBefore" | "heapUsedAfter" | "retained" | "peak" | "maxRss";
612
637
  baseBytes: number;
613
638
  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`. */
@@ -48,11 +53,13 @@ interface TimingPhaseIterator {
48
53
  */
49
54
  step(): Promise<boolean>;
50
55
  done(): boolean;
56
+ /** How far toward its stopping criterion, 0 to 1, for a progress line. */
57
+ doneRatio(): number;
51
58
  result(): TimingPhaseResult;
52
59
  }
53
60
 
54
- // `undefined` is a timed-out trial: killed, so it has no exit code to fail
55
- // on.
61
+ // `undefined` is a timed-out trial: killed, so it has no exit code to
62
+ // fail on.
56
63
  function isFailedExit(code: number | undefined, ignored: Set<number>): boolean {
57
64
  return code !== undefined && code !== 0 && !ignored.has(code);
58
65
  }
@@ -99,7 +106,14 @@ export function createTimingPhase(
99
106
  },
100
107
  );
101
108
  }
102
- return runTrial(opts);
109
+ return runTrial(
110
+ opts.outputDir === undefined
111
+ ? opts
112
+ : {
113
+ ...opts,
114
+ outputPath: `${opts.outputDir}/${phase === "warmup" ? "warmup" : "trial"}-${index}.log`,
115
+ },
116
+ );
103
117
  }
104
118
 
105
119
  return {
@@ -132,6 +146,9 @@ export function createTimingPhase(
132
146
  }),
133
147
  ...(result.timedOut && { timedOut: true as const }),
134
148
  ...(result.timeSourceNoMatch && { timeSourceNoMatch: true as const }),
149
+ ...(result.outputPath !== undefined && {
150
+ outputPath: result.outputPath,
151
+ }),
135
152
  });
136
153
  // The budget bounds the loop's wall time even for reported-time samples.
137
154
  totalNs += result.wallNs;
@@ -142,6 +159,12 @@ export function createTimingPhase(
142
159
  return true;
143
160
  },
144
161
  done,
162
+ doneRatio() {
163
+ if (done()) return 1;
164
+ if (samples !== undefined) return i / samples;
165
+ // Both must be met, so the one further from it is how far along.
166
+ return Math.min(i / Math.max(minSamples, 1), totalNs / budgetNs);
167
+ },
145
168
  result(): TimingPhaseResult {
146
169
  // Excluded, never a `wallNs` fallback: that would mix wall time into a
147
170
  // reported-time series.
@@ -192,9 +215,7 @@ export function createTimingPhase(
192
215
  };
193
216
  }
194
217
 
195
- export async function drainTimingPhase(
196
- phase: TimingPhaseIterator,
197
- ): Promise<void> {
218
+ async function drainTimingPhase(phase: TimingPhaseIterator): Promise<void> {
198
219
  await phase.warmup();
199
220
  while (await phase.step()) {
200
221
  // Each step runs one trial.
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