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
@@ -1,3 +1,5 @@
1
+ import { errorMessage } from "../errors.ts";
2
+
1
3
  /**
2
4
  * A config file that exists but can't be used; the CLI reports it as
3
5
  * `config-invalid`.
@@ -5,21 +7,23 @@
5
7
  export class ConfigError extends Error {}
6
8
 
7
9
  type Rule = (v: unknown) => boolean;
10
+ type Guard<T> = (v: unknown) => v is T;
8
11
 
9
12
  const isObject = (v: unknown): v is Record<string, unknown> =>
10
13
  typeof v === "object" && v !== null && !Array.isArray(v);
11
14
 
12
15
  const isInt =
13
- (min: number): Rule =>
14
- (v) =>
16
+ (min: number): Guard<number> =>
17
+ (v): v is number =>
15
18
  typeof v === "number" && Number.isInteger(v) && v >= min;
16
19
  const isNum =
17
- (min: number): Rule =>
18
- (v) =>
20
+ (min: number): Guard<number> =>
21
+ (v): v is number =>
19
22
  typeof v === "number" && Number.isFinite(v) && v >= min;
20
- const isString: Rule = (v) => typeof v === "string";
23
+ const isString: Guard<string> = (v) => typeof v === "string";
21
24
  const isBool: Rule = (v) => typeof v === "boolean";
22
- const isStringArray: Rule = (v) => Array.isArray(v) && v.every(isString);
25
+ const isStringArray: Guard<string[]> = (v): v is string[] =>
26
+ Array.isArray(v) && v.every(isString);
23
27
  const oneOf =
24
28
  (...values: unknown[]): Rule =>
25
29
  (v) =>
@@ -42,13 +46,13 @@ const THRESHOLD_FIELDS: Record<string, Field> = {
42
46
  frameSelfPct: field(isNum(0), "a non-negative number"),
43
47
  heapTypePct: field(isNum(0), "a non-negative number"),
44
48
  minFrameSelfUs: field(isNum(0), "a non-negative number"),
45
- alpha: field((v) => isNum(0)(v) && (v as number) <= 1, "a number in [0, 1]"),
49
+ alpha: field((v) => isNum(0)(v) && v <= 1, "a number in [0, 1]"),
46
50
  bootstrapIterations: posInt,
47
51
  };
48
52
 
49
53
  const PROJECT_FIELDS: Record<string, Field> = {
50
54
  suites: field(
51
- (v) => isStringArray(v) && (v as string[]).length > 0,
55
+ (v) => isStringArray(v) && v.length > 0,
52
56
  "a non-empty array of glob strings",
53
57
  ),
54
58
  preload: strings,
@@ -95,11 +99,11 @@ const COMMAND_ONLY = ["inputs", "prepare", "timeSource", "ignoreExitCodes"];
95
99
  const WORKLOAD_FIELDS: Record<string, Field> = {
96
100
  label: text,
97
101
  command: field(
98
- (v) => isStringArray(v) && (v as string[]).length > 0,
102
+ (v) => isStringArray(v) && v.length > 0,
99
103
  "a non-empty array of strings (argv, no shell)",
100
104
  ),
101
105
  suites: field(
102
- (v) => isStringArray(v) && (v as string[]).length > 0,
106
+ (v) => isStringArray(v) && v.length > 0,
103
107
  "a non-empty array of glob strings",
104
108
  ),
105
109
  inputs: strings,
@@ -117,8 +121,7 @@ const WORKLOAD_FIELDS: Record<string, Field> = {
117
121
  ),
118
122
  timeoutMs: posInt,
119
123
  ignoreExitCodes: field(
120
- (v) =>
121
- Array.isArray(v) && v.every((c) => isInt(0)(c) && (c as number) <= 255),
124
+ (v) => Array.isArray(v) && v.every((c) => isInt(0)(c) && c <= 255),
122
125
  "an array of exit codes 0-255",
123
126
  ),
124
127
  };
@@ -142,10 +145,9 @@ const describe = (v: unknown): string =>
142
145
  ? String(v)
143
146
  : (JSON.stringify(v) ?? String(v));
144
147
 
145
- /**
146
- * Checks each present (non-`undefined`) key of `obj` against `fields`;
147
- * unknown keys are reported to `warn` rather than failing, as they always
148
- * were ignored. A `$`-prefixed key (`"$schema"`) is never reported. */
148
+ // Checks each present (non-`undefined`) key of `obj` against `fields`;
149
+ // unknown keys are reported to `warn` rather than failing, as they always
150
+ // were ignored. A `$`-prefixed key (`"$schema"`) is never reported.
149
151
  function checkFields(
150
152
  obj: Record<string, unknown>,
151
153
  fields: Record<string, Field>,
@@ -206,23 +208,22 @@ function checkWorkload(
206
208
  }
207
209
  }
208
210
  }
209
- const source = (obj.timeSource as { pattern?: unknown } | undefined)?.pattern;
211
+ const source = isObject(obj.timeSource) ? obj.timeSource.pattern : undefined;
210
212
  if (typeof source === "string") {
211
213
  try {
212
214
  new RegExp(source);
213
215
  } catch (err) {
214
216
  throw new ConfigError(
215
- `${file}: "${where}.timeSource.pattern" is not a valid regex: ${(err as Error).message}`,
217
+ `${file}: "${where}.timeSource.pattern" is not a valid regex: ${errorMessage(err)}`,
216
218
  );
217
219
  }
218
220
  }
219
221
  }
220
222
 
221
- /**
222
- * Throws `ConfigError` naming the offending key for a wrong type or value;
223
- * `warn` gets keys that are unknown (or inapplicable) and so ignored.
224
- * `raw` is the already-object-checked config with `undefined` values still
225
- * present. */
223
+ // Throws `ConfigError` naming the offending key for a wrong type or value;
224
+ // `warn` gets keys that are unknown (or inapplicable) and so ignored.
225
+ // `raw` is the already-object-checked config with `undefined` values still
226
+ // present.
226
227
  export function validateConfig(
227
228
  raw: Record<string, unknown>,
228
229
  file: string,
@@ -242,14 +243,19 @@ export function validateConfig(
242
243
  if (bench !== undefined) {
243
244
  const benchObj = checkObject(bench, "bench", file);
244
245
  checkFields(benchObj, BENCH_FIELDS, "bench", file, warn);
245
- (benchObj.projects as unknown[] | undefined)?.forEach((project, i) => {
246
+ // invariant: checkFields has made `projects` an array when present.
247
+ const projects: unknown = benchObj.projects;
248
+ for (const [i, project] of (Array.isArray(projects)
249
+ ? projects
250
+ : []
251
+ ).entries()) {
246
252
  const where = `bench.projects[${i}]`;
247
253
  const obj = checkObject(project, where, file);
248
254
  if (obj.suites === undefined) {
249
255
  throw new ConfigError(`${file}: "${where}" needs "suites".`);
250
256
  }
251
257
  checkFields(obj, PROJECT_FIELDS, where, file, warn);
252
- });
258
+ }
253
259
  }
254
260
  if (ab !== undefined) {
255
261
  checkFields(checkObject(ab, "ab", file), AB_FIELDS, "ab", file, warn);
@@ -260,8 +266,8 @@ export function validateConfig(
260
266
  `${file}: "workloads" must be an array, got ${describe(workloads)}.`,
261
267
  );
262
268
  }
263
- workloads.forEach((wc, i) => {
269
+ for (const [i, wc] of workloads.entries()) {
264
270
  checkWorkload(wc, i, file, warn);
265
- });
271
+ }
266
272
  }
267
273
  }
package/src/format.ts CHANGED
@@ -1,6 +1,6 @@
1
- /**
2
- * Duration formatting shared by the stats warnings and every renderer; a
3
- * leaf module so neither imports the other. */
1
+ // Duration formatting shared by the stats warnings and every renderer; a
2
+ // leaf module so neither imports the other.
3
+
4
4
  export type DurationUnit = "ns" | "µs" | "ms" | "s";
5
5
 
6
6
  const UNIT_DIVISORS: Record<DurationUnit, number> = {
@@ -24,9 +24,8 @@ function sigFigDecimals(value: number): number {
24
24
  return Math.max(1, 3 - intDigits);
25
25
  }
26
26
 
27
- /**
28
- * Adaptive-unit duration, e.g. `3.02 ns`, `12.4 µs`, `275.8 ms`. Pass
29
- * `unit` to keep a row's columns in one unit. */
27
+ // Pass `unit` so a row's columns share one unit instead of each picking
28
+ // its own.
30
29
  export function formatDuration(
31
30
  ns: number,
32
31
  unit: DurationUnit = pickDurationUnit(ns),
package/src/glob.ts CHANGED
@@ -1,16 +1,15 @@
1
1
  import { resolve } from "node:path";
2
2
 
3
3
  const SKIPPED_DIRS = ["node_modules", ".git"];
4
- // Where `ostia ab` extracts base trees: copies of the project.
4
+ // Wildcards skip it because `ostia ab` extracts copies of the project
5
+ // there.
5
6
  const AB_TREES = ".ostia/ab";
6
- // `@(` and `+(` open extglobs (Bun 1.4.4+); a bare `(` stays literal, as
7
- // in `app/(marketing)`.
7
+ // compat: `@(` and `+(` open extglobs since Bun 1.4.4; a bare `(` isn't a
8
+ // glob character, so `app/(marketing)` stays literal.
8
9
  const GLOB_CHARS = /[*?[\]{}!]|[@+]\(/;
9
10
 
10
- /**
11
- * Segments after the pattern's literal prefix, i.e. the part the wildcards
12
- * chose.
13
- */
11
+ // Only the segments past the pattern's literal prefix were chosen by a
12
+ // wildcard, so only those can wander into a skipped directory.
14
13
  function wildcardSegments(pattern: string, path: string): [string[], string[]] {
15
14
  const patternSegs = pattern.split("/");
16
15
  const literal = patternSegs.findIndex((s) => GLOB_CHARS.test(s));
@@ -18,11 +17,9 @@ function wildcardSegments(pattern: string, path: string): [string[], string[]] {
18
17
  return [patternSegs.slice(from), path.split("/").slice(from)];
19
18
  }
20
19
 
21
- /**
22
- * Paths under `cwd` matching any of `patterns`, relative to `cwd`, deduped
23
- * and sorted. Dotfiles match (`.github/**`), but wildcards never descend
24
- * into `node_modules`, `.git` or `.ostia/ab` unless the pattern names that
25
- * directory itself. */
20
+ // Relative to `cwd`, deduped and sorted. Dotfiles match (`.github/**`),
21
+ // but wildcards never descend into `node_modules`, `.git` or `.ostia/ab`
22
+ // unless the pattern names that directory itself.
26
23
  export async function scanGlobs(
27
24
  patterns: string[],
28
25
  cwd: string,
package/src/index.ts CHANGED
@@ -1,24 +1,29 @@
1
1
  import type { OstiaConfigInput } from "./config/index.ts";
2
2
 
3
3
  export type { AbOptions, AbProgress } from "./ab/index.ts";
4
- export { AbBaseError, AbSetupError, AbSuiteError, ab } from "./ab/index.ts";
4
+ export { ab, AbBaseError, AbSetupError, AbSuiteError } from "./ab/index.ts";
5
5
  export type { BenchOptions } from "./bench/index.ts";
6
6
  export { bench } from "./bench/index.ts";
7
7
  export { range } from "./bench/range.ts";
8
8
  export type { GroupOptions, TaskOptions } from "./bench/registry.ts";
9
+ export type { GroupFn, Hook, TaskFn } from "./bench/registry.ts";
9
10
  export { group, task } from "./bench/registry.ts";
11
+ export type { MeasureTasksOpts } from "./bench/run-tasks.ts";
10
12
  export type { RunOptions } from "./bench/run.ts";
11
13
  export { run } from "./bench/run.ts";
14
+ export type { SweepPoint } from "./bench/sweep.ts";
12
15
  export { sweep } from "./bench/sweep.ts";
13
16
  export type { CompareResult, Thresholds } from "./compare/index.ts";
14
17
  export { compareDocuments, DEFAULT_THRESHOLDS } from "./compare/index.ts";
15
18
  export type {
16
19
  AbConfig,
20
+ BenchConfig,
17
21
  BenchProject,
18
22
  OstiaConfig,
19
23
  OstiaConfigInput,
20
24
  WorkloadConfig,
21
25
  } from "./config/index.ts";
26
+ export { OstiaUsageError } from "./errors.ts";
22
27
  export {
23
28
  createDocument,
24
29
  loadDocument,
@@ -26,26 +31,36 @@ export {
26
31
  saveDocument,
27
32
  } from "./ir/document.ts";
28
33
  export type {
34
+ AbSummary,
35
+ ComparedTask,
29
36
  Comparison,
37
+ ComparisonSummary,
38
+ Environment,
39
+ GitMetadata,
40
+ Measurement,
41
+ PairedEvidence,
30
42
  ProfileDocument,
31
43
  Warning,
32
44
  WarningCode,
33
45
  Workload,
34
46
  } from "./ir/types.ts";
47
+ export { WARNING_CODES } from "./ir/types.ts";
35
48
  export { keep } from "./measure/inprocess.ts";
49
+ export type { Side } from "./measure/paired.ts";
36
50
  export type { ProfileOptions, ProfileResult } from "./profile.ts";
37
51
  export { profile } from "./profile.ts";
38
52
  export { renderers } from "./renderers/index.ts";
39
53
  export type { MermaidOptions } from "./renderers/mermaid.ts";
40
- // `MinimalEvent` is one parsed line of `--format minimal` output; narrow
41
- // on `event`.
42
54
  export type {
43
55
  MinimalEvent,
44
56
  MinimalProtocolContext,
45
57
  MinimalRenderOptions,
58
+ MinimalRunLine,
59
+ MinimalSummaryLine,
60
+ MinimalUnmatchedLine,
46
61
  } from "./renderers/minimal.ts";
47
62
  export { MINIMAL_PROTOCOL_VERSION } from "./renderers/minimal.ts";
48
- export type { VizOptions } from "./renderers/types.ts";
63
+ export type { FormatName, Renderer, VizOptions } from "./renderers/types.ts";
49
64
  export type {
50
65
  PrepareFn,
51
66
  PrepareHook,
package/src/ir/cpu.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { CpuEvidence } from "./types.ts";
2
2
 
3
- /** The sample stream's length when the capture kept one, else the summed
4
- * per-frame self counts. */
3
+ // The sample stream's length when the capture kept one, else the summed
4
+ // per-frame self counts.
5
5
  export function cpuSampleCount(cpu: CpuEvidence): number {
6
6
  return (
7
7
  cpu.samples?.nodeIds.length ??
@@ -0,0 +1,12 @@
1
+ // The fields of `fields` that aren't undefined, so an optional property is
2
+ // absent rather than present and undefined (exactOptionalPropertyTypes).
3
+ export function definedFields<T extends object>(
4
+ fields: T,
5
+ ): { [K in keyof T]?: NonNullable<T[K]> | (T[K] & null) } {
6
+ const out: { [K in keyof T]?: NonNullable<T[K]> | (T[K] & null) } = {};
7
+ for (const key in fields) {
8
+ const value = fields[key];
9
+ if (value !== undefined) out[key] = value;
10
+ }
11
+ return out;
12
+ }
@@ -11,6 +11,7 @@ import {
11
11
  } from "../spawn/index.ts";
12
12
  import { computeTimingStats } from "../stats/index.ts";
13
13
  import { TOOL_VERSION } from "../version.ts";
14
+ import { definedFields } from "./defined.ts";
14
15
  import { canonicalJSON, fp } from "./fp.ts";
15
16
  import { captureGitMetadata } from "./git.ts";
16
17
  import type {
@@ -31,12 +32,6 @@ import type {
31
32
  Workload,
32
33
  } from "./types.ts";
33
34
 
34
- function definedFields<T extends object>(fields: T): Partial<T> {
35
- return Object.fromEntries(
36
- Object.entries(fields).filter(([, v]) => v !== undefined),
37
- ) as Partial<T>;
38
- }
39
-
40
35
  function measurementId(
41
36
  workloadId: string,
42
37
  phase: Phase,
@@ -52,6 +47,10 @@ function measurementId(
52
47
  );
53
48
  }
54
49
 
50
+ /**
51
+ * Builds a document from workloads and their measurements, stamped with
52
+ * versions, platform, timestamp and git metadata.
53
+ */
55
54
  export function createDocument(
56
55
  workloads: Workload[],
57
56
  measurements: Measurement[],
@@ -70,16 +69,15 @@ export function createDocument(
70
69
  };
71
70
  }
72
71
 
73
- export interface SubprocessWorkloadOptions {
72
+ interface SubprocessWorkloadOptions {
74
73
  prepare?: PrepareHook;
75
74
  timeSource?: TimeSource;
76
75
  }
77
76
 
78
- /**
79
- * `prepare` and `timeSource` join the id only when given, so commands
80
- * without them keep their old id. A function `prepare` hashes by source
81
- * text. The id excludes `process.cwd()` so baselines match across
82
- * checkouts. */
77
+ // `prepare` and `timeSource` join the id only when given, so commands
78
+ // without them keep their old id. A function `prepare` hashes by source
79
+ // text. The id excludes `process.cwd()` so baselines match across
80
+ // checkouts.
83
81
  export function makeSubprocessWorkload(
84
82
  command: string[],
85
83
  label?: string,
@@ -102,14 +100,12 @@ export function makeSubprocessWorkload(
102
100
  id,
103
101
  kind: "subprocess",
104
102
  command,
105
- label,
106
- ...definedFields({ prepare, timeSource }),
103
+ ...definedFields({ label, prepare, timeSource }),
107
104
  };
108
105
  }
109
106
 
110
- /**
111
- * Without `name` the id hashes the function's name and source, not the
112
- * values it closes over; `name` replaces both and is the label. */
107
+ // Without `name` the id hashes the function's name and source, not the
108
+ // values it closes over; `name` replaces both and is the label.
113
109
  export function makeInprocessWorkload(
114
110
  fn: (...args: unknown[]) => unknown,
115
111
  name?: string,
@@ -118,10 +114,10 @@ export function makeInprocessWorkload(
118
114
  name === undefined
119
115
  ? fp("wl", "inprocess", fn.name, fn.toString())
120
116
  : fp("wl", "inprocess-named", name);
121
- return { id, kind: "inprocess", label: name };
117
+ return { id, kind: "inprocess", ...definedFields({ label: name }) };
122
118
  }
123
119
 
124
- export interface EntryWorkloadOptions {
120
+ interface EntryWorkloadOptions {
125
121
  label?: string;
126
122
  baseline?: boolean;
127
123
  group?: string;
@@ -133,12 +129,11 @@ export interface EntryWorkloadOptions {
133
129
  skipped?: boolean;
134
130
  }
135
131
 
136
- /**
137
- * The id hashes the file (cwd-relative, so checkouts match), `taskName`
138
- * (the registry's "group/name") and `params` when present; `params` joins
139
- * only when given so tasks without it keep their old id, and a `sweep()`
140
- * reuses one task name across points. Everything else is annotation and
141
- * never orphans a baseline. */
132
+ // The id hashes the file (cwd-relative, so checkouts match), `taskName`
133
+ // (the registry's "group/name") and `params` when present; `params` joins
134
+ // only when given so tasks without it keep their old id, and a `sweep()`
135
+ // reuses one task name across points. Everything else is annotation and
136
+ // never orphans a baseline.
142
137
  export function makeEntryWorkload(
143
138
  file: string,
144
139
  taskName: string,
@@ -158,7 +153,7 @@ export function makeEntryWorkload(
158
153
  };
159
154
  }
160
155
 
161
- export interface TimingMeasurementInput {
156
+ interface TimingMeasurementInput {
162
157
  workload: Workload;
163
158
  configFingerprint: string;
164
159
  trials: Trial[];
@@ -183,16 +178,18 @@ export function makeTimingMeasurement(
183
178
  instrumented: false,
184
179
  configFingerprint: input.configFingerprint,
185
180
  trials: input.trials,
186
- timing: input.timing,
181
+ ...definedFields({ timing: input.timing }),
187
182
  warnings: input.warnings,
188
183
  artifacts: [],
189
- memory: input.heapUsed
190
- ? {
191
- origin: "heapStats",
192
- heapUsedBeforeBytes: input.heapUsed.beforeBytes,
193
- heapUsedAfterBytes: input.heapUsed.afterBytes,
194
- }
195
- : memoryFromTrials(input.trials),
184
+ ...definedFields({
185
+ memory: input.heapUsed
186
+ ? {
187
+ origin: "heapStats" as const,
188
+ heapUsedBeforeBytes: input.heapUsed.beforeBytes,
189
+ heapUsedAfterBytes: input.heapUsed.afterBytes,
190
+ }
191
+ : memoryFromTrials(input.trials),
192
+ }),
196
193
  ...definedFields({
197
194
  instructions: input.instructions,
198
195
  interleaved: input.interleaved,
@@ -235,19 +232,25 @@ export function makeInstrumentedMeasurement(
235
232
  instrumented: true,
236
233
  configFingerprint: input.configFingerprint,
237
234
  trials: [
238
- { i: 0, wallNs: input.diagnosticWallNs, exitCode: input.exitCode },
235
+ {
236
+ i: 0,
237
+ wallNs: input.diagnosticWallNs,
238
+ ...definedFields({ exitCode: input.exitCode }),
239
+ },
239
240
  ],
240
241
  diagnosticWallNs: input.diagnosticWallNs,
241
- cpu: input.cpu,
242
- heap: input.heap,
243
- memory: input.memory,
244
- jit: input.jit,
242
+ ...definedFields({
243
+ cpu: input.cpu,
244
+ heap: input.heap,
245
+ memory: input.memory,
246
+ jit: input.jit,
247
+ }),
245
248
  warnings: input.warnings,
246
249
  artifacts: input.artifacts,
247
250
  };
248
251
  }
249
252
 
250
- export type PairedMeasurementInput = {
253
+ type PairedMeasurementInput = {
251
254
  workload: Workload;
252
255
  configFingerprint: string;
253
256
  diagnosticWallNs: number;
@@ -264,10 +267,8 @@ export type PairedMeasurementInput = {
264
267
  }
265
268
  );
266
269
 
267
- /**
268
- * `timing` is the candidate side; `paired` holds the base side and the
269
- * ratios.
270
- */
270
+ // invariant: `timing` is the candidate side; `paired` holds the base side
271
+ // and the ratios.
271
272
  export function makePairedMeasurement(
272
273
  input: PairedMeasurementInput,
273
274
  ): Measurement {
@@ -310,11 +311,10 @@ export function serializeDocument(doc: ProfileDocument): string {
310
311
  return `${canonicalJSON(doc, 2)}\n`;
311
312
  }
312
313
 
313
- /**
314
- * Writes to a unique temp file then renames, so a killed process never
315
- * leaves a truncated document at `path` and concurrent saves of one path
316
- * don't share a temp file. Takes serialized text so a caller that already
317
- * has it can skip `serializeDocument`. */
314
+ // Writes to a unique temp file then renames, so a killed process never
315
+ // leaves a truncated document at `path` and concurrent saves of one path
316
+ // don't share a temp file. Takes serialized text so a caller that already
317
+ // has it can skip `serializeDocument`.
318
318
  export async function saveDocumentText(
319
319
  text: string,
320
320
  path: string,
@@ -329,6 +329,10 @@ export async function saveDocumentText(
329
329
  }
330
330
  }
331
331
 
332
+ /**
333
+ * Writes a document to `path` atomically: a killed process never leaves a
334
+ * truncated file.
335
+ */
332
336
  export async function saveDocument(
333
337
  doc: ProfileDocument,
334
338
  path: string,
@@ -336,6 +340,10 @@ export async function saveDocument(
336
340
  await saveDocumentText(serializeDocument(doc), path);
337
341
  }
338
342
 
343
+ /**
344
+ * What `loadDocument` throws for a file that isn't JSON, isn't a document,
345
+ * or has a `schemaVersion` this ostia doesn't read.
346
+ */
339
347
  export class OstiaDocumentError extends Error {
340
348
  readonly code: "invalid-json" | "not-a-document" | "unsupported-schema";
341
349
  readonly path?: string;
@@ -349,11 +357,15 @@ export class OstiaDocumentError extends Error {
349
357
  super(message);
350
358
  this.name = "OstiaDocumentError";
351
359
  this.code = code;
352
- this.path = opts.path;
360
+ if (opts.path !== undefined) this.path = opts.path;
353
361
  this.schemaVersion = opts.schemaVersion;
354
362
  }
355
363
  }
356
364
 
365
+ /**
366
+ * Reads a document `saveDocument` wrote; throws `OstiaDocumentError`
367
+ * unless it's valid JSON with `schemaVersion: 2`.
368
+ */
357
369
  export async function loadDocument(path: string): Promise<ProfileDocument> {
358
370
  const text = await Bun.file(path).text();
359
371
  let raw: unknown;
@@ -368,8 +380,8 @@ export async function loadDocument(path: string): Promise<ProfileDocument> {
368
380
  );
369
381
  }
370
382
  const schemaVersion =
371
- raw !== null && typeof raw === "object"
372
- ? (raw as { schemaVersion?: unknown }).schemaVersion
383
+ raw !== null && typeof raw === "object" && "schemaVersion" in raw
384
+ ? raw.schemaVersion
373
385
  : undefined;
374
386
  if (typeof schemaVersion !== "number") {
375
387
  throw new OstiaDocumentError(
@@ -385,17 +397,19 @@ export async function loadDocument(path: string): Promise<ProfileDocument> {
385
397
  { path, schemaVersion },
386
398
  );
387
399
  }
388
- assertDocumentShape(raw as Record<string, unknown>, path);
389
- return renamePairedRatioFields(backfillTimingStats(raw as ProfileDocument));
400
+ assertDocumentShape(raw, path);
401
+ return renamePairedRatioFields(backfillTimingStats(raw));
390
402
  }
391
403
 
392
404
  const isObject = (v: unknown): v is Record<string, unknown> =>
393
405
  typeof v === "object" && v !== null && !Array.isArray(v);
394
406
 
395
- /**
396
- * Cheap structural check, so a hand-edited or truncated document fails
397
- * here with a path and index instead of a TypeError deep in a renderer. */
398
- function assertDocumentShape(doc: Record<string, unknown>, path: string): void {
407
+ // Cheap structural check, so a hand-edited or truncated document fails
408
+ // here with a path and index instead of a TypeError deep in a renderer.
409
+ function assertDocumentShape(
410
+ doc: unknown,
411
+ path: string,
412
+ ): asserts doc is ProfileDocument {
399
413
  const bad = (what: string) =>
400
414
  new OstiaDocumentError(
401
415
  "not-a-document",
@@ -404,16 +418,18 @@ function assertDocumentShape(doc: Record<string, unknown>, path: string): void {
404
418
  path,
405
419
  },
406
420
  );
421
+ // invariant: loadDocument passes an object with a `schemaVersion`.
422
+ if (!isObject(doc)) throw bad("not an object");
407
423
  if (!Array.isArray(doc.workloads)) throw bad(`"workloads" must be an array`);
408
424
  if (!Array.isArray(doc.measurements)) {
409
425
  throw bad(`"measurements" must be an array`);
410
426
  }
411
- doc.workloads.forEach((w, i) => {
427
+ for (const [i, w] of doc.workloads.entries()) {
412
428
  if (!isObject(w) || typeof w.id !== "string") {
413
429
  throw bad(`workloads[${i}] must be an object with a string "id"`);
414
430
  }
415
- });
416
- doc.measurements.forEach((m, i) => {
431
+ }
432
+ for (const [i, m] of doc.measurements.entries()) {
417
433
  if (
418
434
  !isObject(m) ||
419
435
  typeof m.id !== "string" ||
@@ -429,15 +445,21 @@ function assertDocumentShape(doc: Record<string, unknown>, path: string): void {
429
445
  throw bad(`measurements[${i}].${key} must be an array`);
430
446
  }
431
447
  }
432
- });
448
+ }
449
+ }
450
+
451
+ // `ab` documents from ostia 0.2.8-0.2.9 name the ratio quartiles
452
+ // `p25`/`p75`, now `ratioP25`/`ratioP75`; read the old names so saved
453
+ // documents still render. Those from before 0.2.12 lack `ab.metric`.
454
+ interface LegacyRatioFields {
455
+ ratioP25?: unknown;
456
+ ratioP75?: unknown;
457
+ p25?: unknown;
458
+ p75?: unknown;
433
459
  }
434
460
 
435
- /**
436
- * `ab` documents from ostia 0.2.8-0.2.9 name the ratio quartiles
437
- * `p25`/`p75`, now `ratioP25`/`ratioP75`; read the old names so saved
438
- * documents still render. Those from before 0.2.12 lack `ab.metric`. */
439
461
  function renamePairedRatioFields(doc: ProfileDocument): ProfileDocument {
440
- const rename = (r: Record<string, unknown>) => {
462
+ const rename = (r: LegacyRatioFields) => {
441
463
  if (r.ratioP25 !== undefined || r.p25 === undefined) return;
442
464
  r.ratioP25 = r.p25;
443
465
  r.ratioP75 = r.p75;
@@ -446,18 +468,16 @@ function renamePairedRatioFields(doc: ProfileDocument): ProfileDocument {
446
468
  };
447
469
  for (const m of doc.measurements) {
448
470
  if (!m.paired) continue;
449
- rename(m.paired as unknown as Record<string, unknown>);
450
- for (const r of m.paired.repeats ?? [])
451
- rename(r as unknown as Record<string, unknown>);
471
+ rename(m.paired);
472
+ for (const r of m.paired.repeats ?? []) rename(r);
452
473
  }
453
474
  // Before 0.2.12, `ab` judged by time alone.
454
475
  if (doc.ab) doc.ab.metric ??= "time";
455
476
  return doc;
456
477
  }
457
478
 
458
- /**
459
- * Documents from before ostia 0.2.4 lack `p25`/`p75`/`p99`/`mad`;
460
- * recompute them so every consumer sees the full `TimingStats`. */
479
+ // Documents from before ostia 0.2.4 lack `p25`/`p75`/`p99`/`mad`;
480
+ // recompute them so every consumer sees the full `TimingStats`.
461
481
  function backfillTimingStats(doc: ProfileDocument): ProfileDocument {
462
482
  for (const m of doc.measurements) {
463
483
  const t = m.timing;