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/index.d.ts CHANGED
@@ -107,24 +107,6 @@ export type AbProgress = {
107
107
  label: string;
108
108
  };
109
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
- }
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
@@ -742,6 +724,24 @@ interface GitMetadata {
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
+ 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
+ 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,6 +941,7 @@ export interface TaskOptions {
939
941
  * process/no-per-trial caveats as `before`. */
940
942
  after?: Hook;
941
943
  }
944
+ /** Registers the tasks `fn` declares under the group `name`. */
942
945
  export declare const group: GroupFn;
943
946
  interface GroupFn extends GroupRegistrar {
944
947
  /**
@@ -953,6 +956,7 @@ interface GroupFn extends GroupRegistrar {
953
956
  only: GroupRegistrar;
954
957
  }
955
958
  type GroupRegistrar = (name: string, fn: () => void, opts?: GroupOptions) => void;
959
+ /** Registers `fn` as a benchmark task named `name` in the current group. */
956
960
  export declare const task: TaskFn;
957
961
  interface TaskFn extends TaskRegistrar {
958
962
  /**
@@ -967,7 +971,7 @@ interface TaskFn extends TaskRegistrar {
967
971
  * further) and prints a one-line notice to stderr. */
968
972
  only: TaskRegistrar;
969
973
  }
970
- type TaskRegistrar = (name: string, fn: () => unknown | Promise<unknown>, opts?: TaskOptions) => void;
974
+ type TaskRegistrar = (name: string, fn: Hook, opts?: TaskOptions) => void;
971
975
  export interface RunOptions extends MeasureTasksOpts {
972
976
  /** Regex matched against "group/name" task ids, as in `bench({ filter })`. */
973
977
  filter?: string;
@@ -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,
@@ -1222,8 +1230,20 @@ interface BenchConfig {
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
+ 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,17 +1351,7 @@ 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
@@ -1611,6 +1637,7 @@ 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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ostia",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
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());