ostia 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/index.d.ts +62 -35
  2. package/package.json +1 -1
  3. package/src/ab/ab-runner.ts +57 -44
  4. package/src/ab/index.ts +186 -112
  5. package/src/baseline/index.ts +3 -9
  6. package/src/bench/index.ts +177 -123
  7. package/src/bench/projects.ts +14 -10
  8. package/src/bench/registry.ts +68 -66
  9. package/src/bench/run-tasks.ts +26 -23
  10. package/src/bench/run.ts +2 -1
  11. package/src/bench/runner.ts +20 -5
  12. package/src/bench/support.ts +26 -26
  13. package/src/bench/sweep.ts +6 -4
  14. package/src/cache/fingerprint.ts +9 -6
  15. package/src/cache/store.ts +17 -5
  16. package/src/capture/bunflags.ts +12 -11
  17. package/src/capture/cpu-parse.ts +36 -24
  18. package/src/capture/cpu.ts +7 -4
  19. package/src/capture/frames.ts +7 -1
  20. package/src/capture/heap-parse.ts +30 -5
  21. package/src/capture/heap.ts +9 -5
  22. package/src/capture/inspector.ts +8 -7
  23. package/src/capture/jsc-parse.ts +8 -8
  24. package/src/capture/jsc.ts +4 -4
  25. package/src/ci/index.ts +64 -40
  26. package/src/cli/flags.ts +42 -43
  27. package/src/cli/output.ts +29 -35
  28. package/src/cli/run.ts +95 -95
  29. package/src/compare/index.ts +39 -32
  30. package/src/config/env.ts +13 -0
  31. package/src/config/index.ts +31 -23
  32. package/src/config/validate.ts +33 -27
  33. package/src/format.ts +5 -6
  34. package/src/glob.ts +9 -12
  35. package/src/index.ts +1 -3
  36. package/src/ir/cpu.ts +2 -2
  37. package/src/ir/defined.ts +12 -0
  38. package/src/ir/document.ts +93 -73
  39. package/src/ir/fp.ts +7 -10
  40. package/src/ir/git.ts +4 -3
  41. package/src/measure/alloc.ts +7 -8
  42. package/src/measure/cpu.ts +12 -20
  43. package/src/measure/environment.ts +5 -8
  44. package/src/measure/inprocess.ts +15 -15
  45. package/src/measure/instructions.ts +22 -16
  46. package/src/measure/loop.ts +24 -17
  47. package/src/measure/noise.ts +8 -8
  48. package/src/measure/paired.ts +39 -47
  49. package/src/measure/peak.ts +20 -21
  50. package/src/measure/timing.ts +23 -23
  51. package/src/profile.ts +2 -1
  52. package/src/renderers/collapsed.ts +28 -21
  53. package/src/renderers/cpu-tree.ts +43 -35
  54. package/src/renderers/format.ts +16 -26
  55. package/src/renderers/index.ts +14 -4
  56. package/src/renderers/json.ts +2 -2
  57. package/src/renderers/jsonl.ts +11 -7
  58. package/src/renderers/markdown.ts +54 -36
  59. package/src/renderers/mermaid.ts +43 -31
  60. package/src/renderers/minimal.ts +12 -12
  61. package/src/renderers/paired.ts +31 -37
  62. package/src/renderers/relative.ts +10 -14
  63. package/src/renderers/select.ts +17 -39
  64. package/src/renderers/speedscope.ts +52 -48
  65. package/src/renderers/terminal.ts +37 -33
  66. package/src/spawn/index.ts +38 -47
  67. package/src/stats/bootstrap.ts +56 -58
  68. package/src/stats/index.ts +16 -12
  69. package/src/stats/mannwhitney.ts +11 -10
  70. package/src/time.ts +51 -39
package/src/cli/run.ts CHANGED
@@ -27,6 +27,7 @@ import {
27
27
  } from "../config/index.ts";
28
28
  import { errorMessage } from "../errors.ts";
29
29
  import { type CommandSpec, time } from "../index.ts";
30
+ import { definedFields } from "../ir/defined.ts";
30
31
  import {
31
32
  loadDocument,
32
33
  OstiaDocumentError,
@@ -81,10 +82,8 @@ import {
81
82
 
82
83
  const isHelpArg = (arg: string | undefined) => arg === "--help" || arg === "-h";
83
84
 
84
- /**
85
- * Runs `run` with SIGINT wired to its `AbortSignal`, so Ctrl-C cancels
86
- * cleanly with partial results.
87
- */
85
+ // Runs `run` with SIGINT wired to its `AbortSignal`, so Ctrl-C cancels
86
+ // cleanly with partial results.
88
87
  async function withSigintAbort<T>(
89
88
  failure: string,
90
89
  run: (signal: AbortSignal) => Promise<T>,
@@ -102,10 +101,8 @@ async function withSigintAbort<T>(
102
101
  }
103
102
  }
104
103
 
105
- /**
106
- * `--config PATH`, else discovery (`undefined` when it finds nothing); a
107
- * `--config` path that doesn't exist is `config-missing`.
108
- */
104
+ // `--config PATH`, else discovery (`undefined` when it finds nothing); a
105
+ // `--config` path that doesn't exist is `config-missing`.
109
106
  async function loadProjectConfig(
110
107
  configPath?: string,
111
108
  ): Promise<OstiaConfig | undefined> {
@@ -119,10 +116,6 @@ async function loadProjectConfig(
119
116
  return config;
120
117
  }
121
118
 
122
- /**
123
- * Loads the project config; with `needsWorkloadsFor`, also requires at
124
- * least one workload.
125
- */
126
119
  async function requireConfig(
127
120
  needsWorkloadsFor?: string,
128
121
  configPath?: string,
@@ -148,7 +141,6 @@ async function requireConfig(
148
141
  return config;
149
142
  }
150
143
 
151
- /** compare/ab/ci exit code: 2 nothing matched, 1 gate failed, 0 pass. */
152
144
  function gateExitCode(summary: { matched: number; verdict: string }): number {
153
145
  return summary.matched === 0 ? 2 : summary.verdict === "fail" ? 1 : 0;
154
146
  }
@@ -260,12 +252,17 @@ async function timeCommand(argv: string[]): Promise<number> {
260
252
  }
261
253
  const timeSource: TimeSource | undefined =
262
254
  parsed.timeSource !== undefined
263
- ? { pattern: parsed.timeSource, unit: parsed.timeUnit }
255
+ ? {
256
+ pattern: parsed.timeSource,
257
+ ...definedFields({ unit: parsed.timeUnit }),
258
+ }
264
259
  : undefined;
265
260
  const commands: CommandSpec[] = commandList.map((command, i) => ({
266
261
  command,
267
- prepare:
268
- parsed.prepare.length === 1 ? parsed.prepare[0] : parsed.prepare[i],
262
+ ...definedFields({
263
+ prepare:
264
+ parsed.prepare.length === 1 ? parsed.prepare[0] : parsed.prepare[i],
265
+ }),
269
266
  }));
270
267
 
271
268
  const { result: doc, aborted } = await withSigintAbort(
@@ -273,19 +270,21 @@ async function timeCommand(argv: string[]): Promise<number> {
273
270
  (signal) =>
274
271
  time({
275
272
  commands,
276
- timeSource,
277
- samples: parsed.samples,
278
- budgetMs: parsed.budgetMs,
279
- minSamples: parsed.minSamples,
280
- warmup: parsed.warmup,
281
- interleave: parsed.interleave,
282
- cpu: parsed.cpu,
283
- heap: parsed.heap,
284
- cpuIntervalUs: parsed.cpuIntervalUs,
285
- timeoutMs: parsed.timeoutMs,
286
- ignoreExitCodes: parsed.ignoreExitCodes,
287
- outDir: parsed.outDir,
288
- noiseCheck: parsed.noiseCheck,
273
+ ...definedFields({
274
+ timeSource,
275
+ samples: parsed.samples,
276
+ budgetMs: parsed.budgetMs,
277
+ minSamples: parsed.minSamples,
278
+ warmup: parsed.warmup,
279
+ interleave: parsed.interleave,
280
+ cpu: parsed.cpu,
281
+ heap: parsed.heap,
282
+ cpuIntervalUs: parsed.cpuIntervalUs,
283
+ timeoutMs: parsed.timeoutMs,
284
+ ignoreExitCodes: parsed.ignoreExitCodes,
285
+ outDir: parsed.outDir,
286
+ noiseCheck: parsed.noiseCheck,
287
+ }),
289
288
  signal,
290
289
  }),
291
290
  );
@@ -293,8 +292,8 @@ async function timeCommand(argv: string[]): Promise<number> {
293
292
  await emitDocument(doc, parsed);
294
293
  if (aborted) return 130;
295
294
 
296
- // A failing command is exit 2 (couldn't measure), not 1: 1 is reserved for
297
- // compare/ci's regression verdict.
295
+ // A failing command is exit 2 (couldn't measure), not 1, because 1 is
296
+ // reserved for compare/ci's regression verdict.
298
297
  const timingRuns = doc.workloads.map((w) =>
299
298
  doc.measurements.find((m) => m.workloadId === w.id && m.phase === "timing"),
300
299
  );
@@ -431,7 +430,8 @@ const AB_FLAGS = {
431
430
  "--no-progress": flag.off("progress"),
432
431
  };
433
432
 
434
- /** `[ab] suite 4/13 bench/search.bench.ts · task 3/7 search/regex` */
433
+ // One line, so a terminal can overwrite it with the next:
434
+ // `[ab] suite 4/13 bench/search.bench.ts · task 3/7 search/regex`
435
435
  function formatAbProgress(p: AbProgress): string {
436
436
  switch (p.phase) {
437
437
  case "setup":
@@ -445,11 +445,10 @@ function formatAbProgress(p: AbProgress): string {
445
445
  }
446
446
  }
447
447
 
448
- /**
449
- * Progress lines on stderr, so stdout stays the report alone. On a
450
- * terminal, each line replaces the last, and `done()` clears it before the
451
- * report prints; elsewhere (a log, an agent reading a pipe), one line
452
- * each. Synchronous writes, so lines never interleave out of order. */
448
+ // Progress lines on stderr, so stdout stays the report alone. On a
449
+ // terminal, each line replaces the last, and `done()` clears it before the
450
+ // report prints; elsewhere (a log, an agent reading a pipe), one line
451
+ // each. Synchronous writes, so lines never interleave out of order.
453
452
  function progressWriter(tty: boolean): {
454
453
  onProgress: (p: AbProgress) => void;
455
454
  done: () => void;
@@ -496,9 +495,9 @@ async function abCommand(argv: string[]): Promise<number> {
496
495
 
497
496
  const config = await loadProjectConfig(parsed.config);
498
497
  if (parsed.clean) {
499
- const removed = await cleanAbTrees({
500
- outDir: parsed.outDir ?? config?.bench?.outDir,
501
- });
498
+ const removed = await cleanAbTrees(
499
+ definedFields({ outDir: parsed.outDir ?? config?.bench?.outDir }),
500
+ );
502
501
  if (!parsed.quiet) {
503
502
  await Bun.write(Bun.stderr, `Removed ${removed} cached base tree(s).\n`);
504
503
  }
@@ -531,28 +530,32 @@ async function abCommand(argv: string[]): Promise<number> {
531
530
  try {
532
531
  return await ab({
533
532
  suites,
534
- base: parsed.base,
535
- baseSetup:
536
- parsed.baseSetup.length > 0 ? parsed.baseSetup : config?.ab?.setup,
537
- rounds: parsed.rounds,
538
- metric: parsed.metric ?? config?.ab?.metric,
539
- thresholdPct: parsed.thresholdPct,
540
- geomeanThresholdPct: parsed.geomeanThresholdPct,
541
- confirm: parsed.confirm,
542
- alloc: parsed.alloc ?? config?.ab?.alloc,
543
- peakMem: parsed.peakMem ?? config?.ab?.peakMem,
544
- memThresholdPct:
545
- parsed.memThresholdPct ?? config?.ab?.memThresholdPct,
546
- filter,
547
- preload,
548
- bunFlags,
549
- projects,
550
- timeoutMs,
551
- outDir,
552
- keepTrees: parsed.keepTrees ?? config?.ab?.keepTrees,
553
- noiseCheck,
533
+ ...definedFields({
534
+ base: parsed.base,
535
+ baseSetup:
536
+ parsed.baseSetup.length > 0
537
+ ? parsed.baseSetup
538
+ : config?.ab?.setup,
539
+ rounds: parsed.rounds,
540
+ metric: parsed.metric ?? config?.ab?.metric,
541
+ thresholdPct: parsed.thresholdPct,
542
+ geomeanThresholdPct: parsed.geomeanThresholdPct,
543
+ confirm: parsed.confirm,
544
+ alloc: parsed.alloc ?? config?.ab?.alloc,
545
+ peakMem: parsed.peakMem ?? config?.ab?.peakMem,
546
+ memThresholdPct:
547
+ parsed.memThresholdPct ?? config?.ab?.memThresholdPct,
548
+ filter,
549
+ preload,
550
+ bunFlags,
551
+ projects,
552
+ timeoutMs,
553
+ outDir,
554
+ keepTrees: parsed.keepTrees ?? config?.ab?.keepTrees,
555
+ noiseCheck,
556
+ }),
554
557
  signal,
555
- onProgress: progress?.onProgress,
558
+ ...definedFields({ onProgress: progress?.onProgress }),
556
559
  });
557
560
  } catch (err) {
558
561
  if (err instanceof AbBaseError) {
@@ -571,7 +574,9 @@ async function abCommand(argv: string[]): Promise<number> {
571
574
  },
572
575
  );
573
576
 
574
- const summary = doc.ab!;
577
+ const summary = doc.ab;
578
+ // invariant: ab() stamps its summary on every document it returns.
579
+ if (!summary) throw new Error("ostia ab: the document has no ab summary");
575
580
  // Computed before rendering: `minimal`'s trailing `summary` event carries
576
581
  // it. A task that threw ran on both sides, so it counts as paired here.
577
582
  const exitCode = aborted
@@ -679,8 +684,8 @@ async function compareCommand(argv: string[]): Promise<number> {
679
684
  }
680
685
  }
681
686
 
682
- // Computed before rendering: `minimal`'s trailing `summary` event carries
683
- // it.
687
+ // Computed before rendering because `minimal`'s trailing `summary` event
688
+ // carries it.
684
689
  const exitCode = gateExitCode(result.summary);
685
690
 
686
691
  await emitDocument(outDoc, parsed, {
@@ -688,8 +693,7 @@ async function compareCommand(argv: string[]): Promise<number> {
688
693
  command: "compare",
689
694
  exitCode,
690
695
  unmatched: result.unmatched,
691
- baseGit: base.git,
692
- candGit: cand.git,
696
+ ...definedFields({ baseGit: base.git, candGit: cand.git }),
693
697
  ...(parsed.exportJson && { exportedTo: parsed.exportJson }),
694
698
  } satisfies MinimalProtocolContext,
695
699
  });
@@ -739,12 +743,11 @@ function parseReportArgs(argv: string[]): ReportArgs {
739
743
  const NO_CPU_EVIDENCE =
740
744
  "No CPU evidence in this document; rerun with --cpu (ostia time) or --cpu (ostia bench)";
741
745
 
742
- /** Renders `path`; shared by `report` and `baseline show`. */
743
746
  async function renderReport(
744
747
  path: string,
745
748
  { format, measurementId, outDir }: ReportArgs,
746
749
  ): Promise<number> {
747
- const viz = (VIZ_FORMATS as readonly string[]).includes(format);
750
+ const viz = VIZ_FORMATS.some((f) => f === format);
748
751
  const inapplicable = [
749
752
  measurementId !== undefined && "--measurement",
750
753
  outDir !== undefined && "--out-dir",
@@ -769,7 +772,10 @@ async function renderReport(
769
772
  throw new CliError("no-cpu-evidence", NO_CPU_EVIDENCE);
770
773
  }
771
774
 
772
- const result = await renderers[format].render(doc, { measurementId });
775
+ const result = await renderers[format].render(
776
+ doc,
777
+ definedFields({ measurementId }),
778
+ );
773
779
  if (!result.text && (!result.files || result.files.length === 0)) {
774
780
  throw new CliError(
775
781
  "no-cpu-evidence",
@@ -811,11 +817,9 @@ function parseCiArgs(argv: string[]): CiArgs {
811
817
  const baselineMissing = (err: BaselineError) =>
812
818
  new CliError("baseline-missing", err.message);
813
819
 
814
- /**
815
- * Gives the two baseline problems and an unreadable baseline their own
816
- * codes; anything else (a suite-not-found usage error included) falls
817
- * through to `withSigintAbort`'s `orFail` like every other command.
818
- */
820
+ // Gives the two baseline problems and an unreadable baseline their own
821
+ // codes; anything else (a suite-not-found usage error included) falls
822
+ // through to `withSigintAbort`'s `orFail` like every other command.
819
823
  function ciFailure(err: unknown): never {
820
824
  if (err instanceof BaselineError) throw baselineMissing(err);
821
825
  if (err instanceof OstiaDocumentError) {
@@ -841,7 +845,7 @@ async function ciCommand(argv: string[]): Promise<number> {
841
845
  runCi({
842
846
  config,
843
847
  full,
844
- baselineName: parsed.baseline,
848
+ ...definedFields({ baselineName: parsed.baseline }),
845
849
  signal,
846
850
  }).catch(ciFailure),
847
851
  );
@@ -860,8 +864,8 @@ async function ciCommand(argv: string[]): Promise<number> {
860
864
  await saveDocument(document, baselineFile);
861
865
  }
862
866
 
863
- // Computed before rendering: `minimal`'s trailing `summary` event carries
864
- // it.
867
+ // Computed before rendering because `minimal`'s trailing `summary` event
868
+ // carries it.
865
869
  const exitCode = summary.failed > 0 ? 2 : summary.regressed > 0 ? 1 : 0;
866
870
 
867
871
  if (summary.failed > 0) {
@@ -895,8 +899,10 @@ async function ciCommand(argv: string[]): Promise<number> {
895
899
  command: "ci",
896
900
  exitCode,
897
901
  unmatched: summary.unmatched,
898
- baseGit: outcome.baseline.git,
899
- candGit: document.git,
902
+ ...definedFields({
903
+ baseGit: outcome.baseline.git,
904
+ candGit: document.git,
905
+ }),
900
906
  baseline: { name: baselineName, path: baselineFile },
901
907
  cached: summary.cached,
902
908
  executed: summary.executed,
@@ -919,10 +925,8 @@ function baselineUsageError(message: string): CliError {
919
925
  );
920
926
  }
921
927
 
922
- /**
923
- * The name argument isn't flag-parsed, so reject a typo'd flag instead of
924
- * using it as a filename.
925
- */
928
+ // The name argument isn't flag-parsed, so reject a typo'd flag instead of
929
+ // using it as a filename.
926
930
  function assertBaselineName(name: string): void {
927
931
  if (name.startsWith("-")) {
928
932
  throw baselineUsageError(
@@ -943,19 +947,17 @@ interface BaselineArgs extends ConfigArgs {
943
947
 
944
948
  const BASELINE_FLAGS = { ...HELP_FLAGS, ...CONFIG_FLAGS };
945
949
 
946
- /**
947
- * `baseline save`/`list`: `--config`, and for `save` one optional name
948
- * (`takesName`); anything else is a usage error.
949
- */
950
+ // `baseline save`/`list`: `--config`, and for `save` one optional name
951
+ // (`takesName`); anything else is a usage error.
950
952
  function parseBaselineArgs(
951
953
  argv: string[],
952
954
  command: string,
953
955
  takesName: boolean,
954
956
  ): BaselineArgs {
955
- return parseFlags(argv, {
957
+ return parseFlags<BaselineArgs>(argv, {
956
958
  command,
957
959
  flags: BASELINE_FLAGS,
958
- args: { help: false } as BaselineArgs,
960
+ args: { help: false },
959
961
  positional: (arg, a) => {
960
962
  if (!takesName) {
961
963
  throw baselineUsageError(
@@ -1014,10 +1016,10 @@ async function baselineShowCommand(argv: string[]): Promise<number> {
1014
1016
  if (!name || isHelpArg(name)) return showHelp(BASELINE_HELP, !!name);
1015
1017
  assertBaselineName(name);
1016
1018
 
1017
- const parsed = parseFlags(rest, {
1019
+ const parsed = parseFlags<ReportArgs>(rest, {
1018
1020
  command: "baseline show",
1019
1021
  flags: { ...REPORT_FLAGS, ...CONFIG_FLAGS },
1020
- args: { format: "table", help: false } as ReportArgs,
1022
+ args: { format: "table", help: false },
1021
1023
  positional: (arg) => {
1022
1024
  throw baselineUsageError(
1023
1025
  `"ostia baseline show" takes one name, got "${name}" and "${arg}".`,
@@ -1036,10 +1038,8 @@ async function baselineShowCommand(argv: string[]): Promise<number> {
1036
1038
 
1037
1039
  type Handler = (argv: string[]) => Promise<number>;
1038
1040
 
1039
- /**
1040
- * Shared by `main()` and `baselineCommand()`: no sub-name prints `help`, a
1041
- * known one runs, anything else is exit 2.
1042
- */
1041
+ // Shared by `main()` and `baselineCommand()`: no sub-name prints `help`, a
1042
+ // known one runs, anything else is exit 2.
1043
1043
  async function dispatchSubcommand(
1044
1044
  sub: string | undefined,
1045
1045
  rest: string[],
@@ -29,6 +29,10 @@ export interface Thresholds {
29
29
  bootstrapIterations: number;
30
30
  }
31
31
 
32
+ /**
33
+ * The thresholds `compareDocuments` uses when given none; spread over it
34
+ * to change one field.
35
+ */
32
36
  export const DEFAULT_THRESHOLDS: Thresholds = {
33
37
  timingPct: 5,
34
38
  frameSelfPct: 10,
@@ -38,10 +42,9 @@ export const DEFAULT_THRESHOLDS: Thresholds = {
38
42
  bootstrapIterations: 2000,
39
43
  };
40
44
 
41
- /**
42
- * Below this many samples on either side, fall back to the point-estimate
43
- * rule (with a `thin-comparison` warning): CI and p-value are too noisy.
44
- * */
45
+ // Below this many samples on either side, fall back to the point-estimate
46
+ // rule (with a `thin-comparison` warning), because CI and p-value are too
47
+ // noisy.
45
48
  const MIN_SAMPLES_FOR_TEST = 5;
46
49
 
47
50
  function pctDelta(base: number, cand: number): number {
@@ -80,11 +83,10 @@ function indexMeasurements(doc: ProfileDocument): Lookup {
80
83
  byPhase.get(`${workloadId}\u0000${phase}`);
81
84
  }
82
85
 
83
- type MemoryReadings = Partial<Record<MemoryDelta["reading"], number>>;
86
+ type MemoryReadings = {
87
+ [K in MemoryDelta["reading"]]?: number | undefined;
88
+ };
84
89
 
85
- /**
86
- * Every memory reading per workload, from its timing and `memstats`
87
- * measurements. */
88
90
  function indexMemory(doc: ProfileDocument): (id: string) => MemoryReadings {
89
91
  const byWorkload = new Map<string, MemoryReadings>();
90
92
  for (const m of doc.measurements) {
@@ -105,17 +107,15 @@ function indexMemory(doc: ProfileDocument): (id: string) => MemoryReadings {
105
107
  return (id) => byWorkload.get(id) ?? {};
106
108
  }
107
109
 
108
- /**
109
- * The reference loop's mean speed over a run: the start and end readings
110
- * averaged when the run re-measured it. */
110
+ // The mean of the run's start and end reference readings: the end one is
111
+ // `driftPct` slower than the start, so the mean is `driftPct / 2` slower.
111
112
  function meanReferenceNs(env: Environment): number {
112
113
  const { referenceMedianNs, driftPct } = env.noise;
113
114
  return referenceMedianNs * (1 + (driftPct ?? 0) / 200);
114
115
  }
115
116
 
116
- /**
117
- * How far the machine's speed moved within either run, or between them,
118
- * percent; `undefined` unless both runs measured their noise floor. */
117
+ // How far the machine's speed moved within either run, or between them,
118
+ // percent; `undefined` unless both runs measured their noise floor.
119
119
  function machineDriftPct(
120
120
  base: ProfileDocument,
121
121
  cand: ProfileDocument,
@@ -165,10 +165,9 @@ function buildIndex(
165
165
  };
166
166
  }
167
167
 
168
- /**
169
- * Same warning for every comparison in a pair measured on different
170
- * machines/Bun versions. `cpuModel`/`cores` are compared only when both
171
- * sides have `environment`: missing data is unknown, not a mismatch. */
168
+ // Same warning for every comparison in a pair measured on different
169
+ // machines/Bun versions. `cpuModel`/`cores` are compared only when both
170
+ // sides have `environment`: missing data is unknown, not a mismatch.
172
171
  function environmentMismatchWarning(
173
172
  base: ProfileDocument,
174
173
  cand: ProfileDocument,
@@ -204,10 +203,8 @@ export interface CompareResult {
204
203
  summary: ComparisonSummary;
205
204
  }
206
205
 
207
- /**
208
- * Geometric mean of `cand/base` median ratios over comparisons with a
209
- * timing verdict, as a signed percent (`-4.2` means ~4.2% faster). `null`
210
- * when none has a finite ratio. */
206
+ // A signed percent, so `-4.2` means ~4.2% faster; `null` only when no
207
+ // comparison with a timing verdict has a finite ratio.
211
208
  function geomeanTimingPct(comparisons: Comparison[]): number | null {
212
209
  const logRatios: number[] = [];
213
210
  for (const c of comparisons) {
@@ -223,7 +220,7 @@ function geomeanTimingPct(comparisons: Comparison[]): number | null {
223
220
  /**
224
221
  * A base/candidate pair indexed once: per-workload comparison plus the
225
222
  * pair-level facts `compareDocuments` and `ostia ci` both need. */
226
- export interface Comparer {
223
+ interface Comparer {
227
224
  effectiveTimingPct: number;
228
225
  driftPct: number | undefined;
229
226
  compare(workloadId: string): Comparison | undefined;
@@ -260,7 +257,8 @@ export function createComparer(
260
257
  unmatched,
261
258
  compared(matched) {
262
259
  // A candidate workload whose base has no measurement of it (a base
263
- // `task.skip()`) has no comparison either: it's missing its base too.
260
+ // `task.skip()`) has no comparison either, so it's missing its base
261
+ // too.
264
262
  const compared = new Set(matched.map(([id]) => id));
265
263
  const candOnly = cand.workloads.filter((w) => !compared.has(w.id));
266
264
  const { baseOnly } = unmatched();
@@ -282,7 +280,7 @@ export function createComparer(
282
280
  };
283
281
  }
284
282
 
285
- // Memory readings in the order rows list them.
283
+ // invariant: rows list memory readings in this order.
286
284
  const MEMORY_READINGS: MemoryDelta["reading"][] = [
287
285
  "heapUsedBefore",
288
286
  "heapUsedAfter",
@@ -347,7 +345,6 @@ function comparedTask(
347
345
  return row;
348
346
  }
349
347
 
350
- /** The `comparisonSummary` stamped on a compared document. */
351
348
  export function summarizeComparisons(
352
349
  comparisons: Comparison[],
353
350
  effectiveTimingPct: number,
@@ -479,7 +476,17 @@ function compareFrames(
479
476
  thresholds: Thresholds,
480
477
  ): { frames: NonNullable<Comparison["frames"]>; failed: boolean } {
481
478
  const selfUsByKey = (cpu: typeof baseCpu) =>
482
- new Map(cpu.totals.map((t) => [cpu.frames[t.frameIx]!.key, t.selfUs]));
479
+ new Map(
480
+ cpu.totals.map((t) => {
481
+ const frame = cpu.frames[t.frameIx];
482
+ if (!frame) {
483
+ throw new Error(
484
+ `ostia compare: a CPU total names frame ${t.frameIx}, which the document doesn't have`,
485
+ );
486
+ }
487
+ return [frame.key, t.selfUs];
488
+ }),
489
+ );
483
490
  const nameByKey = (cpu: typeof baseCpu) =>
484
491
  new Map(cpu.frames.map((f) => [f.key, f.name]));
485
492
  const baseSelf = selfUsByKey(baseCpu);
@@ -528,8 +535,8 @@ function compareHeapTypes(
528
535
  type,
529
536
  baseCount: b?.count ?? 0,
530
537
  candCount: c?.count ?? 0,
531
- baseBytes: b?.retainedBytes,
532
- candBytes: c?.retainedBytes,
538
+ ...(b?.retainedBytes !== undefined && { baseBytes: b.retainedBytes }),
539
+ ...(c?.retainedBytes !== undefined && { candBytes: c.retainedBytes }),
533
540
  deltaPct: pctDelta(b?.count ?? 0, c?.count ?? 0),
534
541
  };
535
542
  })
@@ -607,10 +614,10 @@ function compareIndexed(
607
614
  id: fp("cmp", baselineMeasurementId, candidateMeasurementId),
608
615
  baselineMeasurementId,
609
616
  candidateMeasurementId,
610
- timing,
617
+ ...(timing && { timing }),
611
618
  ...(warnings.length > 0 && { warnings }),
612
- frames,
613
- heapTypes,
619
+ ...(frames && { frames }),
620
+ ...(heapTypes && { heapTypes }),
614
621
  thresholds: { ...thresholds, effectiveTimingPct },
615
622
  verdict: failed ? "fail" : "pass",
616
623
  };
@@ -0,0 +1,13 @@
1
+ // The one module that reads the environment (docs: config.md, one reader
2
+ // per package). Everything else receives env values from here.
3
+
4
+ export function processEnv(): Record<string, string | undefined> {
5
+ // eslint-disable-next-line no-restricted-properties -- the one env reader
6
+ return process.env;
7
+ }
8
+
9
+ // The only wall-clock reader, for comparisons against file times.
10
+ export function nowMs(): number {
11
+ // eslint-disable-next-line no-restricted-properties -- the one clock reader
12
+ return Date.now();
13
+ }
@@ -159,7 +159,7 @@ export type OstiaConfigInput = Omit<Partial<OstiaConfig>, "thresholds"> & {
159
159
  thresholds?: Partial<Thresholds>;
160
160
  };
161
161
 
162
- // node_modules/.cache is gitignored everywhere already.
162
+ // Under node_modules/.cache because it's gitignored everywhere already.
163
163
  export const DEFAULT_OUT_DIR = "node_modules/.cache/ostia";
164
164
 
165
165
  // Baselines must survive node_modules churn, so they live outside outDir.
@@ -177,23 +177,34 @@ export const DEFAULT_CONFIG: OstiaConfig = {
177
177
  // Renamed fields fail loudly instead of being silently ignored.
178
178
  const RENAMED_FIELDS: Record<string, string> = { runs: "samples" };
179
179
 
180
- /** In discovery order: `.ts` wins over JSON. */
181
- export const CONFIG_FILES = ["ostia.config.ts", "ostia.config.json"];
180
+ // invariant: in discovery order, so `.ts` wins over JSON.
181
+ export const CONFIG_FILES: string[] = ["ostia.config.ts", "ostia.config.json"];
182
182
 
183
183
  const warnConfig = (message: string) => console.warn(`ostia: ${message}`);
184
184
 
185
- /**
186
- * An explicit `undefined` (`warmup: undefined`) means "unset", not
187
- * "overwrite the default".
188
- */
185
+ // An explicit `undefined` (`warmup: undefined`) means "unset", so it must
186
+ // not overwrite the default.
189
187
  function withoutUndefined<T extends object>(obj: T): T {
190
- return Object.fromEntries(
191
- Object.entries(obj).filter(([, v]) => v !== undefined),
192
- ) as T;
188
+ const out = { ...obj };
189
+ for (const key in out) if (out[key] === undefined) delete out[key];
190
+ return out;
191
+ }
192
+
193
+ function isRecord(v: unknown): v is Record<string, unknown> {
194
+ return typeof v === "object" && v !== null && !Array.isArray(v);
195
+ }
196
+
197
+ // Sound because validateConfig checks every key OstiaConfigInput has; it
198
+ // only warns on the rest and leaves them in.
199
+ function assertConfigInput(
200
+ raw: Record<string, unknown>,
201
+ path: string,
202
+ ): asserts raw is Record<string, unknown> & OstiaConfigInput {
203
+ validateConfig(raw, path, warnConfig);
193
204
  }
194
205
 
195
206
  function resolveConfig(raw: unknown, path: string): OstiaConfig {
196
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
207
+ if (!isRecord(raw)) {
197
208
  throw new ConfigError(`${path}: expected an object.`);
198
209
  }
199
210
  for (const [old, current] of Object.entries(RENAMED_FIELDS)) {
@@ -201,8 +212,8 @@ function resolveConfig(raw: unknown, path: string): OstiaConfig {
201
212
  throw new ConfigError(`${path}: "${old}" was renamed to "${current}".`);
202
213
  }
203
214
  }
204
- validateConfig(raw as Record<string, unknown>, path, warnConfig);
205
- const input = withoutUndefined(raw as OstiaConfigInput);
215
+ assertConfigInput(raw, path);
216
+ const input = withoutUndefined(raw);
206
217
  return {
207
218
  ...DEFAULT_CONFIG,
208
219
  ...input,
@@ -219,7 +230,11 @@ async function readConfigFile(path: string): Promise<unknown> {
219
230
  if (!(await file.exists())) return undefined;
220
231
  try {
221
232
  if (!path.endsWith(".ts")) return await file.json();
222
- const exported = (await import(absPath)).default;
233
+ const mod: unknown = await import(absPath);
234
+ const exported =
235
+ typeof mod === "object" && mod !== null && "default" in mod
236
+ ? mod.default
237
+ : undefined;
223
238
  if (exported === undefined) {
224
239
  throw new Error(
225
240
  `no default export; use "export default defineConfig({ ... })"`,
@@ -239,11 +254,8 @@ async function existingConfigFiles(): Promise<string[]> {
239
254
  return found;
240
255
  }
241
256
 
242
- /**
243
- * Loads `path` (`.ts` or JSON by extension), or with no `path` the file
244
- * `configFilePath()` finds. `undefined` when there is no such file. Throws
245
- * `ConfigError` for a file that exists but is unusable, naming the bad
246
- * key. */
257
+ // `undefined` only when there is no such file; one that exists but is
258
+ // unusable throws `ConfigError` naming the bad key.
247
259
  export async function loadConfig(
248
260
  path?: string,
249
261
  ): Promise<OstiaConfig | undefined> {
@@ -266,10 +278,6 @@ export function baselinePath(config: OstiaConfig, name?: string): string {
266
278
  return `${config.baselineDir}/${name ?? config.baseline}.json`;
267
279
  }
268
280
 
269
- /**
270
- * The config file discovery would load from the current directory, `.ts`
271
- * before JSON.
272
- */
273
281
  export async function configFilePath(): Promise<string | undefined> {
274
282
  return (await existingConfigFiles())[0];
275
283
  }