ostia 0.3.0 → 0.4.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 (71) hide show
  1. package/index.d.ts +127 -99
  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 +70 -68
  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 +7 -5
  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 +19 -4
  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/ir/types.ts +3 -3
  42. package/src/measure/alloc.ts +7 -8
  43. package/src/measure/cpu.ts +12 -20
  44. package/src/measure/environment.ts +5 -8
  45. package/src/measure/inprocess.ts +15 -15
  46. package/src/measure/instructions.ts +22 -16
  47. package/src/measure/loop.ts +24 -17
  48. package/src/measure/noise.ts +8 -8
  49. package/src/measure/paired.ts +39 -47
  50. package/src/measure/peak.ts +20 -21
  51. package/src/measure/timing.ts +23 -23
  52. package/src/profile.ts +2 -1
  53. package/src/renderers/collapsed.ts +28 -21
  54. package/src/renderers/cpu-tree.ts +43 -35
  55. package/src/renderers/format.ts +16 -26
  56. package/src/renderers/index.ts +14 -4
  57. package/src/renderers/json.ts +2 -2
  58. package/src/renderers/jsonl.ts +11 -7
  59. package/src/renderers/markdown.ts +54 -36
  60. package/src/renderers/mermaid.ts +43 -31
  61. package/src/renderers/minimal.ts +15 -15
  62. package/src/renderers/paired.ts +31 -37
  63. package/src/renderers/relative.ts +10 -14
  64. package/src/renderers/select.ts +17 -39
  65. package/src/renderers/speedscope.ts +52 -48
  66. package/src/renderers/terminal.ts +37 -33
  67. package/src/spawn/index.ts +38 -47
  68. package/src/stats/bootstrap.ts +56 -58
  69. package/src/stats/index.ts +16 -12
  70. package/src/stats/mannwhitney.ts +11 -10
  71. package/src/time.ts +51 -39
package/src/ab/index.ts CHANGED
@@ -28,8 +28,10 @@ import {
28
28
  stampRunWarnings,
29
29
  uniqueTmpDir,
30
30
  } from "../bench/support.ts";
31
+ import { nowMs, processEnv } from "../config/env.ts";
31
32
  import { type BenchProject, DEFAULT_OUT_DIR } from "../config/index.ts";
32
- import { OstiaUsageError } from "../errors.ts";
33
+ import { errorMessage, OstiaUsageError } from "../errors.ts";
34
+ import { definedFields } from "../ir/defined.ts";
33
35
  import { createDocument, loadDocument } from "../ir/document.ts";
34
36
  import { fp } from "../ir/fp.ts";
35
37
  import type {
@@ -147,11 +149,10 @@ export class AbBaseError extends OstiaUsageError {}
147
149
  /** One side's suite failed outside any task: on import, with no tasks, or
148
150
  * while a task's memory was measured. */
149
151
  export class AbSuiteError extends Error {
150
- constructor(
151
- message: string,
152
- readonly side: Side,
153
- ) {
152
+ readonly side: Side;
153
+ constructor(message: string, side: Side) {
154
154
  super(message);
155
+ this.side = side;
155
156
  }
156
157
  }
157
158
 
@@ -161,11 +162,13 @@ export class AbSetupError extends Error {}
161
162
 
162
163
  const RUNNER_PATH = new URL("./ab-runner.ts", import.meta.url).pathname;
163
164
 
165
+ const DEFAULT_METRIC: AbSummary["metric"] = "time";
166
+
164
167
  const DEFAULTS = {
165
168
  keepTrees: 5,
166
169
  base: "HEAD",
167
170
  rounds: 15,
168
- metric: "time" as AbSummary["metric"],
171
+ metric: DEFAULT_METRIC,
169
172
  thresholdPct: 10,
170
173
  geomeanThresholdPct: 1.5,
171
174
  memThresholdPct: 10,
@@ -216,31 +219,29 @@ interface TreeSetup {
216
219
  * tree. */
217
220
  toplevel: string;
218
221
  cwd: string;
219
- timeoutMs?: number;
220
- signal?: AbortSignal;
221
- onProgress?: (progress: AbProgress) => void;
222
+ timeoutMs?: number | undefined;
223
+ signal?: AbortSignal | undefined;
224
+ onProgress?: ((progress: AbProgress) => void) | undefined;
222
225
  }
223
226
 
224
- /** Where the base tree for `sha` lives: `<sha>`, or with setup commands,
225
- * `<sha>-<hash of the commands>`, so changing them builds a new tree. The
226
- * sha is shortened: code that works on absolute paths costs more on the
227
- * longer ones, so every character the base tree adds reads as a slowdown.
228
- * */
227
+ // Where the base tree for `sha` lives: `<sha>`, or with setup commands,
228
+ // `<sha>-<hash of the commands>`, so changing them builds a new tree. The
229
+ // sha is shortened: code that works on absolute paths costs more on the
230
+ // longer ones, so every character the base tree adds reads as a slowdown.
229
231
  function treeDir(abDir: string, sha: string, commands: string[]): string {
230
232
  const short = sha.slice(0, 12);
231
233
  if (commands.length === 0) return `${abDir}/${short}`;
232
234
  return `${abDir}/${short}-${fp("ab-setup", commands).slice(-8)}`;
233
235
  }
234
236
 
235
- /** Where the base trees of the project at `toplevel` live: inside it, so
236
- * a bare import walks up to the project's own `node_modules` by its real
237
- * path, but not under `node_modules`, which code under test (bundler
238
- * plugins, resolvers, globbers) often skips or treats differently. */
237
+ // Where the base trees of the project at `toplevel` live: inside it, so
238
+ // a bare import walks up to the project's own `node_modules` by its real
239
+ // path, but not under `node_modules`, which code under test (bundler
240
+ // plugins, resolvers, globbers) often skips or treats differently.
239
241
  export function abTreesDir(toplevel: string): string {
240
242
  return `${toplevel}/.ostia/ab`;
241
243
  }
242
244
 
243
- /** Keeps git, and tools that read `.gitignore`, out of the base trees. */
244
245
  function ignoreTrees(abDir: string): void {
245
246
  if (existsSync(`${abDir}/.gitignore`)) return;
246
247
  mkdirSync(abDir, { recursive: true });
@@ -254,8 +255,6 @@ const SETUP_OUTPUT_BYTES = 64 * 1024;
254
255
  // killed. Only a descendant that left the group can hold it open longer.
255
256
  const SETUP_DRAIN_MS = 1000;
256
257
 
257
- /** Reads `stream` as text in the background, keeping its last
258
- * `SETUP_OUTPUT_BYTES`. `stop()` cancels the read and returns the text. */
259
258
  function readTail(stream: ReadableStream<Uint8Array>): {
260
259
  done: Promise<void>;
261
260
  stop: () => Promise<string>;
@@ -286,9 +285,9 @@ function readTail(stream: ReadableStream<Uint8Array>): {
286
285
  };
287
286
  }
288
287
 
289
- /** Runs one setup command in its own process group. A timeout, a cancel,
290
- * or the command's own exit kills the whole group, so no child it started
291
- * can hold the output pipes open or write into the tree later. */
288
+ // Runs one setup command in its own process group. A timeout, a cancel,
289
+ // or the command's own exit kills the whole group, so no child it started
290
+ // can hold the output pipes open or write into the tree later.
292
291
  async function runSetupCommand(
293
292
  command: string,
294
293
  dir: string,
@@ -341,11 +340,11 @@ async function runSetupCommand(
341
340
  }
342
341
  }
343
342
 
344
- /** Runs `setup.commands` in the extracted tree at `tree`. Build scripts
345
- * often read `./node_modules/...` by relative path, which walking up to
346
- * the project's `node_modules` doesn't satisfy, so the project's is linked
347
- * into the tree while they run and unlinked before the salt pass. Returns
348
- * false when `signal` aborted a command. */
343
+ // Runs `setup.commands` in the extracted tree at `tree`. Build scripts
344
+ // often read `./node_modules/...` by relative path, which walking up to
345
+ // the project's `node_modules` doesn't satisfy, so the project's is linked
346
+ // into the tree while they run and unlinked before the salt pass. Returns
347
+ // false when `signal` aborted a command.
349
348
  async function runSetup(
350
349
  tree: string,
351
350
  sha: string,
@@ -370,7 +369,7 @@ async function runSetup(
370
369
  const { exitCode, timedOut, output } = await runSetupCommand(
371
370
  command,
372
371
  dir,
373
- { ...process.env, OSTIA_AB_SHA: sha, OSTIA_AB_CANDIDATE_DIR: cwd },
372
+ { ...processEnv(), OSTIA_AB_SHA: sha, OSTIA_AB_CANDIDATE_DIR: cwd },
374
373
  setup,
375
374
  );
376
375
  if (setup.signal?.aborted) return false;
@@ -389,12 +388,12 @@ async function runSetup(
389
388
  }
390
389
  }
391
390
 
392
- /** The committed tree at `sha`, extracted once under `dir` and reused by
393
- * every later run against the same commit (and setup commands), with each
394
- * script salted (see `BASE_SALT`). Extracted and set up in a temp
395
- * directory and renamed into place, so a directory at `dir` is always
396
- * complete; a failed or cancelled setup leaves nothing behind. Returns
397
- * false when `setup.signal` aborted a setup command. */
391
+ // The committed tree at `sha`, extracted once under `dir` and reused by
392
+ // every later run against the same commit (and setup commands), with each
393
+ // script salted (see `BASE_SALT`). Extracted and set up in a temp
394
+ // directory and renamed into place, so a directory at `dir` is always
395
+ // complete; a failed or cancelled setup leaves nothing behind. Returns
396
+ // false when `setup.signal` aborted a setup command.
398
397
  async function extractTree(
399
398
  sha: string,
400
399
  dir: string,
@@ -443,7 +442,8 @@ async function extractTree(
443
442
  return true;
444
443
  }
445
444
 
446
- // A tree used this recently may belong to a run still going.
445
+ // Never pruned within this long of its last use, since the tree may
446
+ // belong to a run still going.
447
447
  const PRUNE_GRACE_MS = 60 * 60 * 1000;
448
448
 
449
449
  function pidAlive(pid: number): boolean {
@@ -451,12 +451,12 @@ function pidAlive(pid: number): boolean {
451
451
  process.kill(pid, 0);
452
452
  return true;
453
453
  } catch (err) {
454
- return (err as NodeJS.ErrnoException).code === "EPERM";
454
+ return err instanceof Error && "code" in err && err.code === "EPERM";
455
455
  }
456
456
  }
457
457
 
458
- /** Marks a base tree as just used: pruning goes by modification time,
459
- * which, unlike access time, every filesystem keeps. */
458
+ // Sets the modification time because pruning goes by it: unlike access
459
+ // time, every filesystem keeps it.
460
460
  function touchTree(dir: string): void {
461
461
  const now = new Date();
462
462
  try {
@@ -466,12 +466,9 @@ function touchTree(dir: string): void {
466
466
  }
467
467
  }
468
468
 
469
- /** Removes base trees under `abDir` past the `keep` most recently used,
470
- * except any used in the last hour, and temp directories whose process has
471
- * exited. Returns how many it removed. */
472
469
  async function pruneAbTrees(abDir: string, keep: number): Promise<number> {
473
470
  if (!existsSync(abDir)) return 0;
474
- const now = Date.now();
471
+ const now = nowMs();
475
472
  const doomed: string[] = [];
476
473
  const trees: { path: string; mtimeMs: number }[] = [];
477
474
  for (const name of readdirSync(abDir)) {
@@ -496,13 +493,13 @@ async function pruneAbTrees(abDir: string, keep: number): Promise<number> {
496
493
  return doomed.length;
497
494
  }
498
495
 
499
- // A base tree's name under `<outDir>/ab`, where they were cached before
500
- // they moved out of node_modules: `<sha>` or `<sha>-<hash>`, or a temp
501
- // directory for one.
496
+ // compat: base trees were cached under `<outDir>/ab` before they moved
497
+ // out of node_modules; this matches their names (`<sha>`, `<sha>-<hash>`,
498
+ // or a temp directory for one).
502
499
  const LEGACY_TREE = /^[0-9a-f]{40}(?:-[0-9a-f]{8})?(?:\.tmp-\d+(?:-\w+)?)?$/;
503
500
 
504
- /** Removes the base trees left under `dir` by earlier versions, and `dir`
505
- * once nothing else is in it. Returns how many it removed. */
501
+ // Removes the base trees left under `dir` by earlier versions, and `dir`
502
+ // once nothing else is in it. Returns how many it removed.
506
503
  async function removeLegacyTrees(dir: string): Promise<number> {
507
504
  if (!existsSync(dir)) return 0;
508
505
  const names = readdirSync(dir);
@@ -512,9 +509,8 @@ async function removeLegacyTrees(dir: string): Promise<number> {
512
509
  return trees.length;
513
510
  }
514
511
 
515
- /** Removes every base tree `ab()` has cached for the project at `cwd`,
516
- * and any left under `<outDir>/ab`, where they were cached before. Returns
517
- * how many there were. */
512
+ // compat: also removes the trees left under `<outDir>/ab`, where they were
513
+ // cached before.
518
514
  export async function cleanAbTrees(
519
515
  opts: { outDir?: string; cwd?: string } = {},
520
516
  ): Promise<number> {
@@ -531,15 +527,59 @@ export async function cleanAbTrees(
531
527
  return count;
532
528
  }
533
529
 
534
- /** Puts a task's memory readings on its measurement: the median of each
535
- * side's processes, judged against the base's. */
530
+ // invariant: a memory process asked for a reading always writes it, so a
531
+ // missing one is a bug, not a result.
532
+ function reading<T>(value: T | undefined, what: string): T {
533
+ if (value === undefined) {
534
+ throw new Error(`ab: a memory process wrote no ${what} reading`);
535
+ }
536
+ return value;
537
+ }
538
+
539
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
540
+ typeof v === "object" && v !== null && !Array.isArray(v);
541
+
542
+ function isMemoryResult(v: unknown): v is AbMemoryResult {
543
+ if (!isRecord(v)) return false;
544
+ const { peak, alloc } = v;
545
+ return (
546
+ (peak === undefined ||
547
+ (isRecord(peak) &&
548
+ typeof peak.peakBytes === "number" &&
549
+ typeof peak.slackBytes === "number" &&
550
+ typeof peak.wallNs === "number")) &&
551
+ (alloc === undefined ||
552
+ (isRecord(alloc) &&
553
+ typeof alloc.bytesPerOp === "number" &&
554
+ typeof alloc.calls === "number"))
555
+ );
556
+ }
557
+
558
+ function isRunnerPlan(v: unknown): v is AbRunnerPlan {
559
+ return (
560
+ isRecord(v) &&
561
+ Array.isArray(v.memory) &&
562
+ v.memory.every(
563
+ (m) =>
564
+ isRecord(m) &&
565
+ typeof m.workloadId === "string" &&
566
+ typeof m.alloc === "boolean" &&
567
+ typeof m.peakMem === "boolean",
568
+ )
569
+ );
570
+ }
571
+
572
+ function isSide(v: string): v is Side {
573
+ return v === "base" || v === "cand";
574
+ }
575
+
536
576
  function judgeMemory(
537
577
  m: Measurement,
578
+ p: PairedEvidence,
538
579
  task: AbMemoryTask,
539
580
  readings: Record<Side, AbMemoryResult[]>,
540
581
  thresholdPct: number,
541
582
  ): void {
542
- const p = m.paired!;
543
583
  const all = [...readings.base, ...readings.cand];
544
584
  const judge = (read: (r: AbMemoryResult) => number, floorBytes: number) => {
545
585
  const change = memoryChange(
@@ -552,30 +592,31 @@ function judgeMemory(
552
592
  return change;
553
593
  };
554
594
  if (task.alloc) {
555
- const calls = Math.min(...all.map((r) => r.alloc!.calls));
595
+ const calls = Math.min(...all.map((r) => reading(r.alloc, "alloc").calls));
556
596
  p.retained = judge(
557
- (r) => r.alloc!.bytesPerOp,
597
+ (r) => reading(r.alloc, "alloc").bytesPerOp,
558
598
  RETAINED_NOISE_BYTES / calls,
559
599
  );
560
600
  }
561
601
  if (task.peakMem) {
562
- const peaks = all.map((r) => r.peak!);
563
- // Memory freed before the call can hide up to that much of its peak.
602
+ const peaks = all.map((r) => reading(r.peak, "peak"));
603
+ // Memory freed before the call can hide up to `slackBytes` of its peak,
604
+ // so a warned reading's noise floor rises to the slack.
564
605
  const warning = peakHiddenWarning(peaks);
565
606
  const slack = Math.max(...peaks.map((r) => r.slackBytes));
566
607
  p.peak = judge(
567
- (r) => r.peak!.peakBytes,
608
+ (r) => reading(r.peak, "peak").peakBytes,
568
609
  warning ? Math.max(PEAK_NOISE_BYTES, slack) : PEAK_NOISE_BYTES,
569
610
  );
570
611
  if (warning) m.warnings.push(warning);
571
612
  }
572
613
  }
573
614
 
574
- /** Pools a suite's base-first run `a` with its candidate-first run `b`. The
575
- * side that goes first in a process can run several percent faster, the
576
- * same way every time, so one order alone reads as a change on identical
577
- * code; pooled, the bias pulls both ways and cancels. A throw in either
578
- * run counts. */
615
+ // Pools a suite's base-first run `a` with its candidate-first run `b`. The
616
+ // side that goes first in a process can run several percent faster, the
617
+ // same way every time, so one order alone reads as a change on identical
618
+ // code; pooled, the bias pulls both ways and cancels. A throw in either
619
+ // run counts.
579
620
  export function poolOrders(
580
621
  a: ProfileDocument,
581
622
  b: ProfileDocument,
@@ -639,9 +680,9 @@ export function poolOrders(
639
680
  return { ...a, measurements: pooled };
640
681
  }
641
682
 
642
- /** `metric`'s median ratio over the main run and any fresh-process repeats,
643
- * so one process's JIT luck moves the geomean less; undefined when the
644
- * task has no `metric` reading. */
683
+ // `metric`'s median ratio over the main run and any fresh-process repeats,
684
+ // so one process's JIT luck moves the geomean less; undefined when the
685
+ // task has no `metric` reading.
645
686
  function ratioEstimate(
646
687
  p: PairedEvidence,
647
688
  metric: AbSummary["metric"],
@@ -687,7 +728,8 @@ export function summarizePaired(
687
728
  const threw = measurements.filter((m) => m.threw);
688
729
  const candThrew = threw.some((m) => m.threw?.side === "cand");
689
730
  const { memThresholdPct, ...rest } = settings;
690
- // Each task counts once: regressed if either reading regressed.
731
+ // One verdict pair per task, so a task counts once even when both its
732
+ // readings regressed.
691
733
  const memVerdicts = paired
692
734
  .filter((p) => p.retained || p.peak)
693
735
  .map((p) => [p.retained?.verdict, p.peak?.verdict]);
@@ -771,7 +813,7 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
771
813
  throw new RangeError(`ab: ${key} must be >= 0, got ${value}`);
772
814
  }
773
815
  }
774
- assertSamplingOptions("ab", { timeoutMs: opts.timeoutMs });
816
+ assertSamplingOptions("ab", definedFields({ timeoutMs: opts.timeoutMs }));
775
817
 
776
818
  const cwd = opts.cwd ?? process.cwd();
777
819
  const absOutDir = absolutePath(cwd, opts.outDir ?? DEFAULT_OUT_DIR);
@@ -779,8 +821,8 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
779
821
 
780
822
  // Same path join as `bench()`, so workload ids match `ostia bench`'s.
781
823
  const candSuites = opts.suites.map((file) => absolutePath(cwd, file));
782
- for (const [i, suite] of candSuites.entries()) {
783
- assertSuiteExists(opts.suites[i]!, suite);
824
+ for (const file of opts.suites) {
825
+ assertSuiteExists(file, absolutePath(cwd, file));
784
826
  }
785
827
 
786
828
  const toplevel = git(["rev-parse", "--show-toplevel"], cwd);
@@ -849,21 +891,33 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
849
891
 
850
892
  const onProgress = opts.onProgress;
851
893
  let spawned = 0;
852
- /** Runs the A/B runner on suite `s`; resolves with its output path, or
853
- * undefined when cancelled. */
894
+ // Resolves undefined only when cancelled.
854
895
  const runRunner = async (
855
896
  s: number,
856
897
  extra: Partial<AbRunnerOpts> = {},
857
898
  env?: Record<string, string>,
858
899
  ): Promise<string | undefined> => {
900
+ const candSuite = candSuites[s];
901
+ const baseSuite = baseSuites[s];
902
+ const launch = launches[s];
903
+ const file = opts.suites[s];
904
+ // invariant: `s` indexes every per-suite array.
905
+ if (
906
+ candSuite === undefined ||
907
+ baseSuite === undefined ||
908
+ launch === undefined ||
909
+ file === undefined
910
+ ) {
911
+ throw new Error(`ab: no suite ${s}`);
912
+ }
859
913
  touchTree(checkout);
860
- const outPath = `${tmpDir}/${fp("ab-run", candSuites[s]!, spawned++)}.json`;
914
+ const outPath = `${tmpDir}/${fp("ab-run", candSuite, spawned++)}.json`;
861
915
  const runnerOpts: AbRunnerOpts = {
862
- filter: opts.filter,
916
+ ...definedFields({ filter: opts.filter }),
863
917
  rounds,
864
918
  thresholdPct,
865
919
  metric,
866
- preload: launches[s]!.preload,
920
+ preload: launch.preload,
867
921
  // Per task only on the first pass; repeats report themselves.
868
922
  progress:
869
923
  onProgress !== undefined && !extra.workloadIds && !extra.memoryFor,
@@ -874,20 +928,22 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
874
928
  ran = await runRunnerProcess(
875
929
  [
876
930
  "bun",
877
- ...launches[s]!.bunFlags,
931
+ ...launch.bunFlags,
878
932
  RUNNER_PATH,
879
- candSuites[s]!,
880
- baseSuites[s]!,
933
+ candSuite,
934
+ baseSuite,
881
935
  outPath,
882
936
  JSON.stringify(runnerOpts),
883
937
  ],
884
938
  {
885
939
  cwd,
886
940
  label: "A/B suite",
887
- name: opts.suites[s]!,
888
- timeoutMs: opts.timeoutMs,
889
- signal: opts.signal,
890
- env,
941
+ name: file,
942
+ ...definedFields({
943
+ timeoutMs: opts.timeoutMs,
944
+ signal: opts.signal,
945
+ env,
946
+ }),
891
947
  // The runner names the side that failed to load, when that's why.
892
948
  errorFile: `${outPath}.error`,
893
949
  ...(runnerOpts.progress && {
@@ -896,7 +952,7 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
896
952
  phase: "measure",
897
953
  suite: s + 1,
898
954
  suites: candSuites.length,
899
- file: opts.suites[s]!,
955
+ file,
900
956
  pass: extra.candFirst ? 2 : 1,
901
957
  passes: 2,
902
958
  ...message,
@@ -905,17 +961,16 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
905
961
  },
906
962
  );
907
963
  } catch (err) {
908
- const side = Bun.file(`${outPath}.side`);
909
- if (!(await side.exists())) throw err;
910
- throw new AbSuiteError(
911
- (err as Error).message,
912
- (await side.text()) as Side,
913
- );
964
+ const sideFile = Bun.file(`${outPath}.side`);
965
+ if (!(await sideFile.exists())) throw err;
966
+ const side = await sideFile.text();
967
+ if (!isSide(side)) throw err;
968
+ throw new AbSuiteError(errorMessage(err), side);
914
969
  }
915
970
  return ran ? outPath : undefined;
916
971
  };
917
- /** Runs suite `s` twice, base first and then candidate first, splitting
918
- * the rounds, and pools the two; undefined when cancelled. */
972
+ // Each order gets half the rounds, so the pooled run costs what one order
973
+ // alone would. Undefined only when cancelled.
919
974
  const runSuite = async (
920
975
  s: number,
921
976
  extra: Partial<AbRunnerOpts> = {},
@@ -925,9 +980,10 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
925
980
  rounds: Math.ceil(rounds / 2),
926
981
  });
927
982
  if (!first) return undefined;
983
+ // Only the first pass writes the plan, so the second drops `planPath`.
984
+ const { planPath: _planPath, ...secondExtra } = extra;
928
985
  const second = await runRunner(s, {
929
- ...extra,
930
- planPath: undefined,
986
+ ...secondExtra,
931
987
  rounds: Math.floor(rounds / 2),
932
988
  candFirst: true,
933
989
  });
@@ -947,15 +1003,17 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
947
1003
  const baseOnly: string[] = [];
948
1004
  const candOnly: string[] = [];
949
1005
  const wantsMemory: (AbMemoryTask & { suite: number })[] = [];
950
- for (let s = 0; s < candSuites.length; s++) {
951
- const planPath = `${tmpDir}/${fp("ab-plan", candSuites[s]!)}.json`;
1006
+ for (const [s, candSuite] of candSuites.entries()) {
1007
+ const planPath = `${tmpDir}/${fp("ab-plan", candSuite)}.json`;
952
1008
  const doc = await runSuite(s, {
953
- alloc: opts.alloc,
954
- peakMem: opts.peakMem,
1009
+ ...definedFields({ alloc: opts.alloc, peakMem: opts.peakMem }),
955
1010
  planPath,
956
1011
  });
957
1012
  if (!doc) break;
958
- const plan: AbRunnerPlan = await Bun.file(planPath).json();
1013
+ const plan: unknown = await Bun.file(planPath).json();
1014
+ if (!isRunnerPlan(plan)) {
1015
+ throw new Error(`ab: ${planPath} isn't a runner plan`);
1016
+ }
959
1017
  for (const m of plan.memory) wantsMemory.push({ ...m, suite: s });
960
1018
  workloads.push(...doc.workloads);
961
1019
  measurements.push(...doc.measurements);
@@ -975,16 +1033,20 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
975
1033
  candOnly.push(...(doc.unmatched?.candOnly ?? []));
976
1034
  }
977
1035
 
978
- const toConfirm = measurements.filter(
979
- (m) => m.paired?.flagged && confirm > 0 && comparable(m.paired),
980
- );
1036
+ const toConfirm = measurements.flatMap((m) => {
1037
+ const p = m.paired;
1038
+ return p?.flagged && confirm > 0 && comparable(p)
1039
+ ? [{ m, p, flagged: p.flagged }]
1040
+ : [];
1041
+ });
981
1042
  const labelOf = new Map(
982
1043
  workloads.map((w) => [w.id, w.entry?.task ?? w.id]),
983
1044
  );
984
1045
  let started = 0;
985
- for (const m of toConfirm) {
986
- const p = m.paired!;
987
- const flagged = p.flagged!;
1046
+ for (const { m, p, flagged } of toConfirm) {
1047
+ const s = suiteOf.get(m.workloadId);
1048
+ // invariant: every measurement's suite was recorded above.
1049
+ if (s === undefined) throw new Error(`ab: no suite for ${m.workloadId}`);
988
1050
  p.repeats = [];
989
1051
  for (let r = 0; r < confirm && !opts.signal?.aborted; r++) {
990
1052
  onProgress?.({
@@ -993,7 +1055,7 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
993
1055
  repeats: toConfirm.length * confirm,
994
1056
  label: labelOf.get(m.workloadId) ?? m.workloadId,
995
1057
  });
996
- const doc = await runSuite(suiteOf.get(m.workloadId)!, {
1058
+ const doc = await runSuite(s, {
997
1059
  workloadIds: [m.workloadId],
998
1060
  });
999
1061
  const run = doc?.measurements[0];
@@ -1036,12 +1098,12 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
1036
1098
  });
1037
1099
  const memoryRuns = memoryTasks.length * PEAK_MEM_PROCESSES * 2;
1038
1100
  let memoryRun = 0;
1039
- for (const task of memoryTasks) {
1101
+ const readMemory = async (task: (typeof memoryTasks)[number]) => {
1040
1102
  const { workloadId, suite, peakMem } = task;
1041
1103
  const readings: Record<Side, AbMemoryResult[]> = { base: [], cand: [] };
1042
- for (let r = 0; r < PEAK_MEM_PROCESSES && !opts.signal?.aborted; r++) {
1104
+ for (let r = 0; r < PEAK_MEM_PROCESSES; r++) {
1043
1105
  for (const side of ["base", "cand"] as const) {
1044
- if (opts.signal?.aborted) break;
1106
+ if (opts.signal?.aborted) return readings;
1045
1107
  onProgress?.({
1046
1108
  phase: "memory",
1047
1109
  run: ++memoryRun,
@@ -1056,11 +1118,23 @@ export async function ab(opts: AbOptions): Promise<ProfileDocument> {
1056
1118
  // before the measured call does.
1057
1119
  peakMem ? { OSTIA_PEAK_MEM: "1" } : undefined,
1058
1120
  );
1059
- if (outPath) readings[side].push(await Bun.file(outPath).json());
1121
+ if (!outPath) continue;
1122
+ const result: unknown = await Bun.file(outPath).json();
1123
+ if (!isMemoryResult(result)) {
1124
+ throw new Error(`ab: ${outPath} isn't a memory reading`);
1125
+ }
1126
+ readings[side].push(result);
1060
1127
  }
1061
1128
  }
1129
+ return readings;
1130
+ };
1131
+ for (const task of memoryTasks) {
1132
+ const readings = await readMemory(task);
1062
1133
  if (readings.base.length === 0 || readings.cand.length === 0) continue;
1063
- judgeMemory(byWorkload.get(workloadId)!, task, readings, memThresholdPct);
1134
+ const m = byWorkload.get(task.workloadId);
1135
+ // invariant: memoryTasks holds only tasks with a paired measurement.
1136
+ if (!m?.paired) continue;
1137
+ judgeMemory(m, m.paired, task, readings, memThresholdPct);
1064
1138
  }
1065
1139
 
1066
1140
  stampRunWarnings(
@@ -3,11 +3,8 @@ import { baselinePath, type OstiaConfig } from "../config/index.ts";
3
3
  import { createDocument, loadDocument, saveDocument } from "../ir/document.ts";
4
4
  import type { GitMetadata } from "../ir/types.ts";
5
5
 
6
- /**
7
- * Measures every configured workload and writes it to
8
- * `<baselineDir>/<name>.json` (default `config.baseline`); returns the
9
- * path. Always measures fresh: a baseline never holds a cached `ci` run.
10
- * */
6
+ // Writes to `<baselineDir>/<name>.json` (default `config.baseline`).
7
+ // Always measures fresh: a baseline never holds a cached `ci` run.
11
8
  export async function saveBaseline(
12
9
  config: OstiaConfig,
13
10
  name?: string,
@@ -26,7 +23,7 @@ export async function saveBaseline(
26
23
  return path;
27
24
  }
28
25
 
29
- export interface BaselineInfo {
26
+ interface BaselineInfo {
30
27
  name: string;
31
28
  path: string;
32
29
  createdAt: string;
@@ -36,9 +33,6 @@ export interface BaselineInfo {
36
33
  git?: GitMetadata;
37
34
  }
38
35
 
39
- /**
40
- * Every `<baselineDir>/*.json` that parses as a `ProfileDocument`, sorted
41
- * by name. A missing `baselineDir` yields an empty list. */
42
36
  export async function listBaselines(
43
37
  config: OstiaConfig,
44
38
  ): Promise<BaselineInfo[]> {