ostia 0.3.1 → 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 (60) 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 +197 -126
  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 +9 -7
  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 +3 -3
  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/index.ts +18 -1
  34. package/src/ir/document.ts +2 -2
  35. package/src/ir/types.ts +50 -27
  36. package/src/measure/alloc.ts +2 -2
  37. package/src/measure/cpu.ts +2 -2
  38. package/src/measure/environment.ts +11 -6
  39. package/src/measure/inprocess.ts +14 -10
  40. package/src/measure/instructions.ts +2 -2
  41. package/src/measure/noise.ts +51 -13
  42. package/src/measure/paired.ts +2 -2
  43. package/src/measure/peak.ts +4 -4
  44. package/src/measure/timing.ts +18 -3
  45. package/src/profile.ts +6 -4
  46. package/src/renderers/collapsed.ts +2 -2
  47. package/src/renderers/concise.ts +148 -0
  48. package/src/renderers/format.ts +13 -4
  49. package/src/renderers/index.ts +6 -0
  50. package/src/renderers/markdown.ts +2 -2
  51. package/src/renderers/mermaid.ts +2 -2
  52. package/src/renderers/minimal.ts +11 -10
  53. package/src/renderers/relative.ts +2 -2
  54. package/src/renderers/select.ts +2 -2
  55. package/src/renderers/terminal.ts +6 -3
  56. package/src/renderers/types.ts +3 -0
  57. package/src/spawn/index.ts +47 -14
  58. package/src/stats/bootstrap.ts +2 -2
  59. package/src/stats/index.ts +2 -2
  60. package/src/time.ts +75 -10
package/src/cli/run.ts CHANGED
@@ -40,11 +40,13 @@ import { formatGit, workloadLabel } from "../renderers/format.ts";
40
40
  import { type FormatName, renderers } from "../renderers/index.ts";
41
41
  import type { MinimalProtocolContext } from "../renderers/minimal.ts";
42
42
  import type { TimeSource, TimeUnit } from "../spawn/index.ts";
43
+ import { withDefaultFormat } from "./agent.ts";
43
44
  import {
44
45
  CliUsageError,
45
46
  CONFIG_FLAGS,
46
47
  type ConfigArgs,
47
48
  flag,
49
+ FORMAT_ALIASES,
48
50
  HELP_FLAGS,
49
51
  NOISE_CHECK_FLAGS,
50
52
  OUTPUT_DEFAULTS,
@@ -150,8 +152,8 @@ const TIME_UNITS: readonly TimeUnit[] = ["ns", "us", "ms", "s"];
150
152
  interface TimeArgs extends RunArgs {
151
153
  commands: string[];
152
154
  /**
153
- * Everything after `--`: one more command, whose argv is never
154
- * whitespace-split.
155
+ * Everything after `--`: one more command, whose argv is
156
+ * never whitespace-split.
155
157
  */
156
158
  argvCommand: string[];
157
159
  /** One entry applies to every command; otherwise one per command. */
@@ -169,6 +171,9 @@ interface TimeArgs extends RunArgs {
169
171
  timeoutMs?: number;
170
172
  ignoreExitCodes: number[];
171
173
  outDir?: string;
174
+ shell?: string;
175
+ saveOutput?: string;
176
+ showOutput?: boolean;
172
177
  }
173
178
 
174
179
  const TIME_FLAGS = {
@@ -179,6 +184,9 @@ const TIME_FLAGS = {
179
184
  "--warmup": flag.int("warmup", 0),
180
185
  "--no-interleave": flag.off("interleave"),
181
186
  "--prepare": flag.list("prepare"),
187
+ "--shell": flag.str("shell"),
188
+ "--save-output": flag.str("saveOutput"),
189
+ "--show-output": flag.on("showOutput"),
182
190
  "--time-source": flag.str("timeSource"),
183
191
  "--time-unit": flag.oneOf("timeUnit", TIME_UNITS),
184
192
  "--cpu": flag.on("cpu"),
@@ -284,6 +292,10 @@ async function timeCommand(argv: string[]): Promise<number> {
284
292
  ignoreExitCodes: parsed.ignoreExitCodes,
285
293
  outDir: parsed.outDir,
286
294
  noiseCheck: parsed.noiseCheck,
295
+ noiseBudgetMs: parsed.noiseBudgetMs,
296
+ shell: parsed.shell,
297
+ saveOutput: parsed.saveOutput,
298
+ showOutput: parsed.showOutput,
287
299
  }),
288
300
  signal,
289
301
  }),
@@ -514,6 +526,7 @@ async function abCommand(argv: string[]): Promise<number> {
514
526
  timeoutMs,
515
527
  outDir,
516
528
  noiseCheck,
529
+ noiseBudgetMs,
517
530
  } = await resolveBenchOptions(parsed, config?.bench);
518
531
  if (suites.length === 0) return showHelp(AB_HELP, false);
519
532
 
@@ -553,6 +566,7 @@ async function abCommand(argv: string[]): Promise<number> {
553
566
  outDir,
554
567
  keepTrees: parsed.keepTrees ?? config?.ab?.keepTrees,
555
568
  noiseCheck,
569
+ noiseBudgetMs,
556
570
  }),
557
571
  signal,
558
572
  ...definedFields({ onProgress: progress?.onProgress }),
@@ -718,7 +732,7 @@ interface ReportArgs extends ConfigArgs {
718
732
 
719
733
  const REPORT_FLAGS = {
720
734
  ...HELP_FLAGS,
721
- "--format": flag.oneOf("format", REPORT_FORMATS),
735
+ "--format": flag.oneOf("format", REPORT_FORMATS, FORMAT_ALIASES),
722
736
  "--measurement": flag.str("measurementId"),
723
737
  "--out-dir": flag.str("outDir"),
724
738
  };
@@ -1090,8 +1104,18 @@ function baselineCommand(argv: string[]): Promise<number> {
1090
1104
  );
1091
1105
  }
1092
1106
 
1093
- export function main(): Promise<number> {
1094
- const [subcommand, ...rest] = process.argv.slice(2);
1107
+ // The commands that take `--format`, so the only ones a default
1108
+ // format can be added to.
1109
+ const FORMATTED = new Set(["time", "bench", "ab", "compare", "report", "ci"]);
1110
+
1111
+ export async function main(): Promise<number> {
1112
+ const [subcommand, ...given] = process.argv.slice(2);
1113
+ let rest = given;
1114
+ if (subcommand !== undefined && FORMATTED.has(subcommand)) {
1115
+ const chosen = withDefaultFormat(given);
1116
+ rest = chosen.argv;
1117
+ if (chosen.notice) await Bun.write(Bun.stderr, chosen.notice);
1118
+ }
1095
1119
  return dispatchSubcommand(
1096
1120
  subcommand,
1097
1121
  rest,
@@ -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
@@ -6,19 +6,24 @@ export type { BenchOptions } 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";
9
+ export type { GroupFn, Hook, TaskFn } from "./bench/registry.ts";
9
10
  export { group, task } from "./bench/registry.ts";
11
+ export type { MeasureTasksOpts } from "./bench/run-tasks.ts";
10
12
  export type { RunOptions } from "./bench/run.ts";
11
13
  export { run } from "./bench/run.ts";
14
+ export type { SweepPoint } from "./bench/sweep.ts";
12
15
  export { sweep } from "./bench/sweep.ts";
13
16
  export type { CompareResult, Thresholds } from "./compare/index.ts";
14
17
  export { compareDocuments, DEFAULT_THRESHOLDS } from "./compare/index.ts";
15
18
  export type {
16
19
  AbConfig,
20
+ BenchConfig,
17
21
  BenchProject,
18
22
  OstiaConfig,
19
23
  OstiaConfigInput,
20
24
  WorkloadConfig,
21
25
  } from "./config/index.ts";
26
+ export { OstiaUsageError } from "./errors.ts";
22
27
  export {
23
28
  createDocument,
24
29
  loadDocument,
@@ -26,13 +31,22 @@ export {
26
31
  saveDocument,
27
32
  } from "./ir/document.ts";
28
33
  export type {
34
+ AbSummary,
35
+ ComparedTask,
29
36
  Comparison,
37
+ ComparisonSummary,
38
+ Environment,
39
+ GitMetadata,
40
+ Measurement,
41
+ PairedEvidence,
30
42
  ProfileDocument,
31
43
  Warning,
32
44
  WarningCode,
33
45
  Workload,
34
46
  } from "./ir/types.ts";
47
+ export { WARNING_CODES } from "./ir/types.ts";
35
48
  export { keep } from "./measure/inprocess.ts";
49
+ export type { Side } from "./measure/paired.ts";
36
50
  export type { ProfileOptions, ProfileResult } from "./profile.ts";
37
51
  export { profile } from "./profile.ts";
38
52
  export { renderers } from "./renderers/index.ts";
@@ -41,9 +55,12 @@ export type {
41
55
  MinimalEvent,
42
56
  MinimalProtocolContext,
43
57
  MinimalRenderOptions,
58
+ MinimalRunLine,
59
+ MinimalSummaryLine,
60
+ MinimalUnmatchedLine,
44
61
  } from "./renderers/minimal.ts";
45
62
  export { MINIMAL_PROTOCOL_VERSION } from "./renderers/minimal.ts";
46
- export type { VizOptions } from "./renderers/types.ts";
63
+ export type { FormatName, Renderer, VizOptions } from "./renderers/types.ts";
47
64
  export type {
48
65
  PrepareFn,
49
66
  PrepareHook,
@@ -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;
@@ -420,13 +442,13 @@ export interface AbSummary {
420
442
  verdict: "pass" | "fail";
421
443
  }
422
444
 
445
+ // compat: annotated, since Bun 1.4.6 canary's declaration build overflows
446
+ // its stack when another module imports a type taken with `typeof` from
447
+ // an unannotated array (WarningCode, below).
423
448
  /**
424
- * Every `Warning.code`. A runtime array so a test can assert each is
425
- * emitted.
449
+ * Every `Warning.code`. A runtime array so a test can assert each
450
+ * is emitted.
426
451
  */
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
452
  export const WARNING_CODES: readonly [
431
453
  "slow-first-run",
432
454
  "outliers-detected",
@@ -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);