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/index.d.ts CHANGED
@@ -106,25 +106,7 @@ export type AbProgress = {
106
106
  side: Side;
107
107
  label: string;
108
108
  };
109
- type Side = "base" | "cand";
110
- /** `ab()` can't run: not in a git repository, or `base` isn't a commit. */
111
- export declare class AbBaseError extends OstiaUsageError {
112
- }
113
- /** The caller's input can't be run as given (missing suite, bad ref, absent
114
- * baseline): the CLI reports it as a usage error (exit 2) rather than an
115
- * internal failure. */
116
- declare class OstiaUsageError extends Error {
117
- }
118
- /** A `baseSetup` command exited non-zero or timed out. The message names
119
- * the command and ends with the tail of its output. */
120
- export declare class AbSetupError extends Error {
121
- }
122
- /** One side's suite failed outside any task: on import, with no tasks, or
123
- * while a task's memory was measured. */
124
- export declare class AbSuiteError extends Error {
125
- readonly side: Side;
126
- constructor(message: string, side: Side);
127
- }
109
+ export type Side = "base" | "cand";
128
110
  /** Paired A/B timing of suite files against a git ref: every task runs on
129
111
  * the ref's committed tree (base) and the working tree (candidate) in one
130
112
  * process, alternating short batches, and is judged on the per-round time
@@ -230,7 +212,7 @@ export interface Workload {
230
212
  * `unchanged` with a `skipped` warning. */
231
213
  skipped?: boolean;
232
214
  }
233
- interface Measurement {
215
+ export interface Measurement {
234
216
  id: string;
235
217
  workloadId: string;
236
218
  phase: Phase;
@@ -403,7 +385,7 @@ interface InstructionStats {
403
385
  /**
404
386
  * Evidence of a `phase: "paired"` measurement: base and candidate
405
387
  * alternate in batches in one process, so drift cancels in the ratio. */
406
- interface PairedEvidence {
388
+ export interface PairedEvidence {
407
389
  /** One base batch and one candidate batch per round, alternating order. */
408
390
  rounds: number;
409
391
  /** Calls per side per round. */
@@ -503,7 +485,7 @@ export type WarningCode = (typeof WARNING_CODES)[number];
503
485
  * Every `Warning.code`. A runtime array so a test can assert each is
504
486
  * emitted.
505
487
  */
506
- declare const WARNING_CODES: readonly [
488
+ export declare const WARNING_CODES: readonly [
507
489
  "slow-first-run",
508
490
  "outliers-detected",
509
491
  "fast-command",
@@ -582,7 +564,7 @@ export interface Comparison {
582
564
  verdict: "pass" | "fail";
583
565
  }
584
566
  /** Aggregate view over a `compareDocuments` call's `Comparison[]`. */
585
- interface ComparisonSummary {
567
+ export interface ComparisonSummary {
586
568
  /** `comparisons.length`. */
587
569
  matched: number;
588
570
  regressed: number;
@@ -609,7 +591,7 @@ interface ComparisonSummary {
609
591
  * One task of a `compare`/`ci` run: matched on both sides, or present on
610
592
  * only one (`missing-base`: new, or renamed without an alias;
611
593
  * `missing-cand`: removed, or renamed). Times in ns, memory in bytes. */
612
- interface ComparedTask {
594
+ export interface ComparedTask {
613
595
  /** The candidate's workload id; the base's on a `missing-cand` task. */
614
596
  workloadId: string;
615
597
  /** Display name: the label, else the command, else the id. */
@@ -660,7 +642,7 @@ interface MemoryDelta {
660
642
  candBytes: number;
661
643
  deltaPct: number;
662
644
  }
663
- interface Environment {
645
+ export interface Environment {
664
646
  cpuModel: string;
665
647
  cores: number;
666
648
  loadAvg1: number;
@@ -681,7 +663,7 @@ interface NoiseFloor {
681
663
  driftPct?: number;
682
664
  }
683
665
  /** Run-level result of `ab()`, stamped on the document as `ab`. */
684
- interface AbSummary {
666
+ export interface AbSummary {
685
667
  base: {
686
668
  ref: string;
687
669
  sha: string;
@@ -737,11 +719,29 @@ interface AbSummary {
737
719
  * any task's memory regressed. */
738
720
  verdict: "pass" | "fail";
739
721
  }
740
- interface GitMetadata {
722
+ export interface GitMetadata {
741
723
  sha: string;
742
724
  branch: string;
743
725
  dirty: boolean;
744
726
  }
727
+ /** `ab()` can't run: not in a git repository, or `base` isn't a commit. */
728
+ export declare class AbBaseError extends OstiaUsageError {
729
+ }
730
+ /** The caller's input can't be run as given (missing suite, bad ref, absent
731
+ * baseline): the CLI reports it as a usage error (exit 2) rather than an
732
+ * internal failure. */
733
+ export declare class OstiaUsageError extends Error {
734
+ }
735
+ /** A `baseSetup` command exited non-zero or timed out. The message names
736
+ * the command and ends with the tail of its output. */
737
+ export declare class AbSetupError extends Error {
738
+ }
739
+ /** One side's suite failed outside any task: on import, with no tasks, or
740
+ * while a task's memory was measured. */
741
+ export declare class AbSuiteError extends Error {
742
+ readonly side: Side;
743
+ constructor(message: string, side: Side);
744
+ }
745
745
  export interface BenchOptions {
746
746
  suites: string[];
747
747
  /** Wall-clock sampling budget per task, ms (default 500). */
@@ -817,6 +817,7 @@ export interface BenchOptions {
817
817
  * dropped entirely: it only writes its result once, at the end. */
818
818
  signal?: AbortSignal;
819
819
  }
820
+ /** Measures the tasks each of `suites` registers, one subprocess per file. */
820
821
  export declare function bench(opts: BenchOptions): Promise<ProfileDocument>;
821
822
  /**
822
823
  * Geometric sweep points from `start` to `end`, growing by `multiplier`
@@ -867,7 +868,8 @@ export interface GroupOptions {
867
868
  /** Runs once, unmeasured, after the group's last task's last trial. */
868
869
  after?: Hook;
869
870
  }
870
- type Hook = () => unknown | Promise<unknown>;
871
+ /** A task body or hook; it may return a promise, which the runner awaits. */
872
+ export type Hook = () => unknown;
871
873
  export interface TaskOptions {
872
874
  /**
873
875
  * Marks this task as the Relative reference for its group in the table
@@ -939,8 +941,7 @@ export interface TaskOptions {
939
941
  * process/no-per-trial caveats as `before`. */
940
942
  after?: Hook;
941
943
  }
942
- export declare const group: GroupFn;
943
- interface GroupFn extends GroupRegistrar {
944
+ export interface GroupFn extends GroupRegistrar {
944
945
  /**
945
946
  * Registers every task inside as skipped: the runner never measures
946
947
  * them, but the document still carries their workloads (marked
@@ -953,8 +954,7 @@ interface GroupFn extends GroupRegistrar {
953
954
  only: GroupRegistrar;
954
955
  }
955
956
  type GroupRegistrar = (name: string, fn: () => void, opts?: GroupOptions) => void;
956
- export declare const task: TaskFn;
957
- interface TaskFn extends TaskRegistrar {
957
+ export interface TaskFn extends TaskRegistrar {
958
958
  /**
959
959
  * Registers the task as skipped: the runner never measures it, but the
960
960
  * document still carries its workload (marked `Workload.skipped`) so a
@@ -967,16 +967,12 @@ interface TaskFn extends TaskRegistrar {
967
967
  * further) and prints a one-line notice to stderr. */
968
968
  only: TaskRegistrar;
969
969
  }
970
- type TaskRegistrar = (name: string, fn: () => unknown | Promise<unknown>, opts?: TaskOptions) => void;
971
- export interface RunOptions extends MeasureTasksOpts {
972
- /** Regex matched against "group/name" task ids, as in `bench({ filter })`. */
973
- filter?: string;
974
- /** Skip printing the report to stdout; still returns the document. */
975
- quiet?: boolean;
976
- /** Renderer used for the printed report (default: `"table"`). */
977
- format?: FormatName;
978
- }
979
- interface MeasureTasksOpts extends InprocessTimingOptions {
970
+ type TaskRegistrar = (name: string, fn: Hook, opts?: TaskOptions) => void;
971
+ /** Registers the tasks `fn` declares under the group `name`. */
972
+ export declare const group: GroupFn;
973
+ /** Registers `fn` as a benchmark task named `name` in the current group. */
974
+ export declare const task: TaskFn;
975
+ export interface MeasureTasksOpts extends InprocessTimingOptions {
980
976
  /**
981
977
  * Suite-wide default for capturing an extra `phase: "cpu"` measurement per
982
978
  * task (task/group `cpu` still wins). */
@@ -1008,7 +1004,15 @@ interface InprocessTimingOptions {
1008
1004
  warmup?: number;
1009
1005
  gc?: boolean;
1010
1006
  }
1011
- type FormatName = "table" | "json" | "markdown" | "jsonl" | "minimal" | "collapsed" | "mermaid" | "speedscope" | "cpuprofile";
1007
+ export interface RunOptions extends MeasureTasksOpts {
1008
+ /** Regex matched against "group/name" task ids, as in `bench({ filter })`. */
1009
+ filter?: string;
1010
+ /** Skip printing the report to stdout; still returns the document. */
1011
+ quiet?: boolean;
1012
+ /** Renderer used for the printed report (default: `"table"`). */
1013
+ format?: FormatName;
1014
+ }
1015
+ export type FormatName = "table" | "json" | "markdown" | "jsonl" | "minimal" | "collapsed" | "mermaid" | "speedscope" | "cpuprofile";
1012
1016
  /** In-file entrypoint: call at the bottom of a suite file run directly with
1013
1017
  * `bun suite.ts` to measure every registered `group()`/`task()`, print a
1014
1018
  * report, and return the document.
@@ -1017,6 +1021,9 @@ type FormatName = "table" | "json" | "markdown" | "jsonl" | "minimal" | "collaps
1017
1021
  * ignored. Prefer `ostia bench`/`bench()` for numbers you'll
1018
1022
  * `compare`/`ci` against. */
1019
1023
  export declare function run(opts?: RunOptions): Promise<ProfileDocument>;
1024
+ export type SweepPoint<T extends Record<string, readonly unknown[]>> = {
1025
+ [K in keyof T]: T[K][number];
1026
+ };
1020
1027
  /** Cartesian product over `dims`, calling `fn` once per point. Inside `fn`,
1021
1028
  * `task()` calls automatically inherit the point as their params (an
1022
1029
  * explicit `TaskOptions.params` merges over it, explicit keys win):
@@ -1029,9 +1036,6 @@ export declare function run(opts?: RunOptions): Promise<ProfileDocument>;
1029
1036
  * })
1030
1037
  */
1031
1038
  export declare function sweep<T extends Record<string, readonly unknown[]>>(dims: T, fn: (point: SweepPoint<T>) => void): void;
1032
- type SweepPoint<T extends Record<string, readonly unknown[]>> = {
1033
- [K in keyof T]: T[K][number];
1034
- };
1035
1039
  export interface CompareResult {
1036
1040
  comparisons: Comparison[];
1037
1041
  unmatched: {
@@ -1060,6 +1064,10 @@ export interface Thresholds {
1060
1064
  * candidate order, as `ostia ci` does), and reports what matched only one
1061
1065
  * side in `unmatched` rather than dropping it. */
1062
1066
  export declare function compareDocuments(base: ProfileDocument, cand: ProfileDocument, thresholds?: Thresholds): CompareResult;
1067
+ /**
1068
+ * The thresholds `compareDocuments` uses when given none; spread over it
1069
+ * to change one field.
1070
+ */
1063
1071
  export declare const DEFAULT_THRESHOLDS: Thresholds;
1064
1072
  /**
1065
1073
  * Settings for `ostia ab` only; it reads the rest (suites, filter,
@@ -1092,6 +1100,41 @@ export interface AbConfig {
1092
1100
  * `--mem-threshold` overrides. Default: 10. */
1093
1101
  memThresholdPct?: number;
1094
1102
  }
1103
+ export interface BenchConfig {
1104
+ /**
1105
+ * Suite file globs, resolved against the config's directory (e.g.
1106
+ * "bench/**\/*.bench.ts"). Suite files given on the command line replace
1107
+ * this list. */
1108
+ suites?: string[];
1109
+ /**
1110
+ * Per-suite `preload`/`bunFlags`, so one tier (e.g. DOM-dependent suites)
1111
+ * can pay for a setup the others don't need. The first project whose
1112
+ * `suites` match a file wins; a file no project matches gets the top-level
1113
+ * `preload`/`bunFlags`. `--preload` / `--bun-flags` replace the matching
1114
+ * field for every file. */
1115
+ projects?: BenchProject[];
1116
+ preload?: string[];
1117
+ /**
1118
+ * Extra flags for the `bun` process that runs each suite file; see
1119
+ * `BenchOptions.bunFlags`. `--bun-flags` replaces this list. */
1120
+ bunFlags?: string[];
1121
+ jobs?: number | "auto";
1122
+ budgetMs?: number;
1123
+ samples?: number;
1124
+ minSamples?: number;
1125
+ gc?: boolean;
1126
+ cpu?: boolean;
1127
+ cpuIntervalUs?: number;
1128
+ alloc?: boolean;
1129
+ peakMem?: boolean;
1130
+ filter?: string;
1131
+ isolate?: boolean;
1132
+ outDir?: string;
1133
+ /**
1134
+ * Kills a suite file's (or isolated task's) subprocess after this many
1135
+ * ms; overrides `ostia ci`'s 10-minute default. */
1136
+ timeoutMs?: number;
1137
+ }
1095
1138
  export interface OstiaConfig {
1096
1139
  /** `command` workloads: exact trial count; see `time()`. */
1097
1140
  samples?: number;
@@ -1184,46 +1227,23 @@ export interface TimeSource {
1184
1227
  unit?: TimeUnit;
1185
1228
  }
1186
1229
  export type TimeUnit = "ns" | "us" | "ms" | "s";
1187
- interface BenchConfig {
1188
- /**
1189
- * Suite file globs, resolved against the config's directory (e.g.
1190
- * "bench/**\/*.bench.ts"). Suite files given on the command line replace
1191
- * this list. */
1192
- suites?: string[];
1193
- /**
1194
- * Per-suite `preload`/`bunFlags`, so one tier (e.g. DOM-dependent suites)
1195
- * can pay for a setup the others don't need. The first project whose
1196
- * `suites` match a file wins; a file no project matches gets the top-level
1197
- * `preload`/`bunFlags`. `--preload` / `--bun-flags` replace the matching
1198
- * field for every file. */
1199
- projects?: BenchProject[];
1200
- preload?: string[];
1201
- /**
1202
- * Extra flags for the `bun` process that runs each suite file; see
1203
- * `BenchOptions.bunFlags`. `--bun-flags` replaces this list. */
1204
- bunFlags?: string[];
1205
- jobs?: number | "auto";
1206
- budgetMs?: number;
1207
- samples?: number;
1208
- minSamples?: number;
1209
- gc?: boolean;
1210
- cpu?: boolean;
1211
- cpuIntervalUs?: number;
1212
- alloc?: boolean;
1213
- peakMem?: boolean;
1214
- filter?: string;
1215
- isolate?: boolean;
1216
- outDir?: string;
1217
- /**
1218
- * Kills a suite file's (or isolated task's) subprocess after this many
1219
- * ms; overrides `ostia ci`'s 10-minute default. */
1220
- timeoutMs?: number;
1221
- }
1222
1230
  export type OstiaConfigInput = Omit<Partial<OstiaConfig>, "thresholds"> & {
1223
1231
  thresholds?: Partial<Thresholds>;
1224
1232
  };
1233
+ /**
1234
+ * Builds a document from workloads and their measurements, stamped with
1235
+ * versions, platform, timestamp and git metadata.
1236
+ */
1225
1237
  export declare function createDocument(workloads: Workload[], measurements: Measurement[], environment?: Environment): ProfileDocument;
1238
+ /**
1239
+ * Reads a document `saveDocument` wrote; throws `OstiaDocumentError`
1240
+ * unless it's valid JSON with `schemaVersion: 2`.
1241
+ */
1226
1242
  export declare function loadDocument(path: string): Promise<ProfileDocument>;
1243
+ /**
1244
+ * What `loadDocument` throws for a file that isn't JSON, isn't a document,
1245
+ * or has a `schemaVersion` this ostia doesn't read.
1246
+ */
1227
1247
  export declare class OstiaDocumentError extends Error {
1228
1248
  readonly code: "invalid-json" | "not-a-document" | "unsupported-schema";
1229
1249
  readonly path?: string;
@@ -1233,6 +1253,10 @@ export declare class OstiaDocumentError extends Error {
1233
1253
  schemaVersion?: unknown;
1234
1254
  });
1235
1255
  }
1256
+ /**
1257
+ * Writes a document to `path` atomically: a killed process never leaves a
1258
+ * truncated file.
1259
+ */
1236
1260
  export declare function saveDocument(doc: ProfileDocument, path: string): Promise<void>;
1237
1261
  /** Pins `value` against dead-code elimination for an intermediate inside a
1238
1262
  * task body. A task's own return value is already pinned by the timing
@@ -1266,21 +1290,33 @@ export interface ProfileResult<T> {
1266
1290
  measurement: Measurement;
1267
1291
  document: ProfileDocument;
1268
1292
  }
1293
+ /** Captures a CPU profile of `fn` in the current process. */
1269
1294
  export declare function profile<T>(fn: () => T | Promise<T>, opts?: ProfileOptions): Promise<ProfileResult<T>>;
1270
1295
  /** Each format's renderer, typed with its own options. `Renderer<never>` is
1271
1296
  * the top type, so `satisfies` checks every format is present without
1272
1297
  * widening the options. */
1273
1298
  export declare const renderers: {
1274
- table: Renderer<unknown>;
1275
- json: Renderer<unknown>;
1276
- markdown: Renderer<unknown>;
1277
- jsonl: Renderer<unknown>;
1299
+ table: Renderer;
1300
+ json: Renderer;
1301
+ markdown: Renderer;
1302
+ jsonl: Renderer;
1278
1303
  minimal: Renderer<MinimalRenderOptions>;
1279
1304
  collapsed: Renderer<VizOptions>;
1280
1305
  mermaid: Renderer<MermaidOptions>;
1281
1306
  speedscope: Renderer<VizOptions>;
1282
1307
  cpuprofile: Renderer<VizOptions>;
1283
1308
  };
1309
+ export interface Renderer<O = unknown> {
1310
+ name: FormatName;
1311
+ render(doc: ProfileDocument, options: O): Promise<RenderResult>;
1312
+ }
1313
+ interface RenderResult {
1314
+ text?: string;
1315
+ files?: {
1316
+ path?: string;
1317
+ content: string;
1318
+ }[];
1319
+ }
1284
1320
  export interface MinimalRenderOptions {
1285
1321
  protocol?: MinimalProtocolContext;
1286
1322
  }
@@ -1315,22 +1351,12 @@ export interface VizOptions {
1315
1351
  export interface MermaidOptions extends VizOptions {
1316
1352
  topN?: number;
1317
1353
  }
1318
- interface Renderer<O = unknown> {
1319
- name: FormatName;
1320
- render(doc: ProfileDocument, options: O): Promise<RenderResult>;
1321
- }
1322
- interface RenderResult {
1323
- text?: string;
1324
- files?: {
1325
- path?: string;
1326
- content: string;
1327
- }[];
1328
- }
1354
+ /** One parsed line of `--format minimal` output; narrow on `event`. */
1329
1355
  export type MinimalEvent = MinimalRunLine | MinimalUnmatchedLine | MinimalSummaryLine;
1330
1356
  /**
1331
1357
  * One per timing run, for piping into an agent's context in place of the
1332
1358
  * full `ProfileDocument`. Numbers stay in the IR's units (ns). */
1333
- interface MinimalRunLine {
1359
+ export interface MinimalRunLine {
1334
1360
  event: "run";
1335
1361
  protocolVersion: typeof MINIMAL_PROTOCOL_VERSION;
1336
1362
  schemaVersion: ProfileDocument["schemaVersion"];
@@ -1469,7 +1495,7 @@ interface MinimalMemoryChange {
1469
1495
  floor: number;
1470
1496
  }
1471
1497
  /** A workload present on only one side of a `compare`/`ci` run. */
1472
- interface MinimalUnmatchedLine {
1498
+ export interface MinimalUnmatchedLine {
1473
1499
  event: "unmatched";
1474
1500
  protocolVersion: typeof MINIMAL_PROTOCOL_VERSION;
1475
1501
  workloadId: string;
@@ -1479,7 +1505,7 @@ interface MinimalUnmatchedLine {
1479
1505
  /**
1480
1506
  * The last line of a `compare`/`ci`/`ab` run; never emitted for a bare
1481
1507
  * `time`/`bench` document. */
1482
- interface MinimalSummaryLine {
1508
+ export interface MinimalSummaryLine {
1483
1509
  event: "summary";
1484
1510
  protocolVersion: typeof MINIMAL_PROTOCOL_VERSION;
1485
1511
  command: "compare" | "ci" | "ab";
@@ -1611,6 +1637,8 @@ export interface TimeOptions {
1611
1637
  * */
1612
1638
  ignoreExitCodes?: number[];
1613
1639
  }
1640
+ /** Times each of `commands` as a subprocess, as `ostia time` does. */
1614
1641
  export declare function time(opts: TimeOptions): Promise<ProfileDocument>;
1615
1642
  /** Identity function that types an `ostia.config.ts` default export. */
1616
1643
  export declare function defineConfig(config: OstiaConfigInput): OstiaConfigInput;
1644
+ export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ostia",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Fast profiling and benchmarking for Bun.",
5
5
  "license": "MIT",
6
6
  "author": "Eric Liu (https://github.com/metonym)",
@@ -15,6 +15,7 @@ import {
15
15
  taskPeakMem,
16
16
  } from "../bench/registry.ts";
17
17
  import { taskWorkload } from "../bench/run-tasks.ts";
18
+ import { errorMessage } from "../errors.ts";
18
19
  import {
19
20
  configFingerprint,
20
21
  createDocument,
@@ -93,18 +94,14 @@ export interface AbRunnerProgress {
93
94
  label: string;
94
95
  }
95
96
 
96
- /**
97
- * Tasks pair across sides by "group/name" plus `params`, the workload id's
98
- * identity.
99
- */
97
+ // invariant: tasks pair across sides by "group/name" plus `params`, the
98
+ // workload id's identity.
100
99
  function pairKey(t: RegisteredTask, id: string = taskId(t)): string {
101
100
  return `${id}\u0000${canonicalJSON(t.params ?? null)}`;
102
101
  }
103
102
 
104
- /**
105
- * The task's own key, then one per alias: a base task under any of them
106
- * pairs.
107
- */
103
+ // A base task pairs under the task's id or any former one, so a rename
104
+ // doesn't break the pair.
108
105
  function pairKeys(t: RegisteredTask): string[] {
109
106
  return [taskId(t), ...formerTaskIds(t)].map((id) => pairKey(t, id));
110
107
  }
@@ -115,18 +112,30 @@ async function importTasks(suiteFile: string): Promise<RegisteredTask[]> {
115
112
  return [...getRegisteredTasks()];
116
113
  }
117
114
 
115
+ // The parent writes optsJson, so this checks only the fields every run
116
+ // reads.
117
+ function isRunnerOpts(v: unknown): v is AbRunnerOpts {
118
+ return (
119
+ typeof v === "object" &&
120
+ v !== null &&
121
+ "rounds" in v &&
122
+ typeof v.rounds === "number" &&
123
+ "thresholdPct" in v &&
124
+ typeof v.thresholdPct === "number" &&
125
+ "metric" in v &&
126
+ (v.metric === "time" || v.metric === "instructions")
127
+ );
128
+ }
129
+
118
130
  const ERROR_LINES = 5;
119
131
 
120
- /** An error's message, cut to its first few lines. */
121
132
  function errorText(err: unknown): string {
122
133
  const text = err instanceof Error ? err.message : String(err);
123
134
  return text.split("\n").slice(0, ERROR_LINES).join("\n");
124
135
  }
125
136
 
126
- /**
127
- * Reports a failure that stops the whole suite: on stderr, and in
128
- * `<outputPath>.error` (and `.side`, when it's one side's) for `ab()` to
129
- * put in the error it throws. */
137
+ // For a failure that stops the whole suite. The `.error` and `.side` files
138
+ // exist because `ab()` reads them back for the error it throws.
130
139
  async function fail(
131
140
  outputPath: string,
132
141
  message: string,
@@ -142,15 +151,14 @@ type MeasureOutcome =
142
151
  | { result: Awaited<ReturnType<typeof measurePaired>> }
143
152
  | { threw: NonNullable<Measurement["threw"]> };
144
153
 
145
- /**
146
- * One pair's `before` hooks, paired timing and `after` hooks. A throw from
147
- * either side's task or hooks doesn't stop the suite; it's reported with
148
- * its side instead. Each `before` runs once, in `order`, and a side whose
149
- * `before` threw isn't timed or torn down. Every side that was set up is
150
- * torn down once, in reverse order, even when a hook throws. When only one
151
- * side has thrown, the other side's task is called once more, before
152
- * teardown and only if that side is set up, to tell whether it throws too
153
- * (`"both"`). */
154
+ // One pair's `before` hooks, paired timing and `after` hooks. A throw from
155
+ // either side's task or hooks doesn't stop the suite; it's reported with
156
+ // its side instead. Each `before` runs once, in `order`, and a side whose
157
+ // `before` threw isn't timed or torn down. Every side that was set up is
158
+ // torn down once, in reverse order, even when a hook throws. When only one
159
+ // side has thrown, the other side's task is called once more, before
160
+ // teardown and only if that side is set up, to tell whether it throws too
161
+ // (`"both"`).
154
162
  async function measureTask(
155
163
  base: RegisteredTask,
156
164
  cand: RegisteredTask,
@@ -158,7 +166,6 @@ async function measureTask(
158
166
  order: Side[],
159
167
  ): Promise<MeasureOutcome> {
160
168
  const tasks = { base, cand };
161
- // The first error from each side.
162
169
  const errors = new Map<Side, unknown>();
163
170
  const record = (side: Side, err: unknown) => {
164
171
  if (!errors.has(side)) errors.set(side, err);
@@ -224,14 +231,15 @@ async function measureTask(
224
231
  if (errors.has("cand")) {
225
232
  return { threw: { side: "cand", message: errorText(candErr) } };
226
233
  }
227
- return { result: result! };
234
+ // invariant: with no errors, both sides were set up and timed.
235
+ if (!result) throw new Error("ab runner: a pair finished untimed");
236
+ return { result };
228
237
  }
229
238
 
230
- /**
231
- * A `memoryFor` process. Only one side's suite loads, so the other side's
232
- * setup and the packages both sides share can't move the readings. Peak is
233
- * the first call; retained follows a warmup batch, as `bench --alloc`
234
- * follows timing. */
239
+ // A `memoryFor` process. Only one side's suite loads, so the other side's
240
+ // setup and the packages both sides share can't move the readings. Peak is
241
+ // the first call; retained follows a warmup batch, as `bench --alloc`
242
+ // follows timing.
235
243
  async function measureMemory(
236
244
  suite: string,
237
245
  candSuite: string,
@@ -240,8 +248,8 @@ async function measureMemory(
240
248
  preload: string[],
241
249
  ): Promise<number> {
242
250
  const { workloadId, side } = memoryFor;
243
- // Baseline for `measurePeakMem`, taken once ostia (which the suite
244
- // imports) is loaded.
251
+ // The `measurePeakMem` baseline waits until ostia, which the suite
252
+ // imports, is loaded, so ostia's own load isn't counted in the peak.
245
253
  const sampler = memoryFor.peakMem ? await startRssSampler() : undefined;
246
254
  await import("../index.ts");
247
255
  const launched = memorySnapshot();
@@ -272,7 +280,10 @@ async function measureMemory(
272
280
  if (memoryFor.alloc) {
273
281
  await measureAllocPerOp(t.fn);
274
282
  const { memory, calls } = await measureAllocPerOp(t.fn);
275
- result.alloc = { bytesPerOp: memory.bytesPerOp!, calls };
283
+ if (memory.bytesPerOp === undefined) {
284
+ throw new Error("measureAllocPerOp returned no bytesPerOp");
285
+ }
286
+ result.alloc = { bytesPerOp: memory.bytesPerOp, calls };
276
287
  }
277
288
  await t.opts?.after?.();
278
289
  await runGroupHooks(t, "after");
@@ -287,13 +298,12 @@ async function measureMemory(
287
298
  }
288
299
  }
289
300
 
290
- /**
291
- * Pairs one suite file's tasks against the same file at the base checkout,
292
- * in this process. Each side is imported from its own path so its relative
293
- * imports resolve within its own tree, while bare imports (including
294
- * `ostia`, hence the shared registry) share `node_modules`. `baseSuite` is
295
- * "" when the file doesn't exist at the base ref: every task is
296
- * candidate-only. */
301
+ // Pairs one suite file's tasks against the same file at the base checkout,
302
+ // in this process. Each side is imported from its own path so its relative
303
+ // imports resolve within its own tree, while bare imports (including
304
+ // `ostia`, hence the shared registry) share `node_modules`. `baseSuite` is
305
+ // "" when the file doesn't exist at the base ref: every task is
306
+ // candidate-only.
297
307
  async function main(): Promise<number> {
298
308
  const [candSuite, baseSuite, outputPath, optsJson] = process.argv.slice(2);
299
309
  if (!candSuite || baseSuite === undefined || !outputPath || !optsJson) {
@@ -302,7 +312,11 @@ async function main(): Promise<number> {
302
312
  );
303
313
  return 2;
304
314
  }
305
- const opts: AbRunnerOpts = JSON.parse(optsJson);
315
+ const opts: unknown = JSON.parse(optsJson);
316
+ if (!isRunnerOpts(opts)) {
317
+ process.stderr.write(`ab runner: malformed optsJson: ${optsJson}\n`);
318
+ return 2;
319
+ }
306
320
 
307
321
  if (opts.memoryFor) {
308
322
  return measureMemory(
@@ -359,7 +373,7 @@ async function main(): Promise<number> {
359
373
  !opts.workloadIds,
360
374
  );
361
375
  } catch (err) {
362
- return fail(outputPath, (err as Error).message);
376
+ return fail(outputPath, errorMessage(err));
363
377
  }
364
378
 
365
379
  const wanted = opts.workloadIds && new Set(opts.workloadIds);
@@ -419,8 +433,7 @@ async function main(): Promise<number> {
419
433
  metric: opts.metric,
420
434
  });
421
435
  const measurements: Measurement[] = [];
422
- for (let i = 0; i < pairs.length; i++) {
423
- const { workload, base, cand } = pairs[i]!;
436
+ for (const [i, { workload, base, cand }] of pairs.entries()) {
424
437
  const { enter, leave } = edges(i);
425
438
  if (opts.progress) {
426
439
  process.send?.({
@@ -471,4 +484,4 @@ async function main(): Promise<number> {
471
484
  return 0;
472
485
  }
473
486
 
474
- main().then((code) => process.exit(code));
487
+ process.exit(await main());