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,11 +1,11 @@
1
- /**
2
- * Appended to "registered no tasks": the usual cause besides a missing
3
- * `task()` call is a suite importing a different copy of ostia than the
4
- * CLI running it, so its calls register on that copy. */
1
+ // Appended to "registered no tasks": the usual cause besides a missing
2
+ // `task()` call is a suite importing a different copy of ostia than the
3
+ // CLI running it, so its calls register on that copy.
5
4
  export const NO_TASKS_HINT =
6
5
  " If the suite does call task(), it imports a different copy of ostia than the CLI running it (a global install, or another version): run the one from the project's node_modules.";
7
6
 
8
- type Hook = () => unknown | Promise<unknown>;
7
+ /** A task body or hook; it may return a promise, which the runner awaits. */
8
+ export type Hook = () => unknown;
9
9
 
10
10
  export interface TaskOptions {
11
11
  /**
@@ -117,45 +117,57 @@ export interface GroupOptions {
117
117
  interface GroupFrame {
118
118
  /** Slash-joined names from the outermost group down to this one. */
119
119
  path: string;
120
- before?: Hook;
121
- after?: Hook;
120
+ before?: Hook | undefined;
121
+ after?: Hook | undefined;
122
122
  }
123
123
 
124
124
  export interface RegisteredTask {
125
125
  /** The enclosing groups' names joined with "/", outermost first. */
126
- groupName?: string;
126
+ groupName?: string | undefined;
127
127
  /** Enclosing groups, outermost first. */
128
- groupChain?: readonly GroupFrame[];
129
- groupDescription?: string;
130
- groupIsolate?: boolean;
131
- groupGc?: boolean;
132
- groupCpu?: boolean;
133
- groupAlloc?: boolean;
134
- groupPeakMem?: boolean;
128
+ groupChain?: readonly GroupFrame[] | undefined;
129
+ groupDescription?: string | undefined;
130
+ groupIsolate?: boolean | undefined;
131
+ groupGc?: boolean | undefined;
132
+ groupCpu?: boolean | undefined;
133
+ groupAlloc?: boolean | undefined;
134
+ groupPeakMem?: boolean | undefined;
135
135
  name: string;
136
- fn: () => unknown | Promise<unknown>;
137
- baseline?: boolean;
138
- params?: Record<string, string | number | boolean>;
136
+ fn: Hook;
137
+ baseline?: boolean | undefined;
138
+ params?: Record<string, string | number | boolean> | undefined;
139
139
  /**
140
140
  * From `task.skip()` or a `group.skip()` this task is inside. The runner
141
141
  * never measures it; the document still carries its workload (marked
142
142
  * `Workload.skipped`) so a renderer or `compare` can say so explicitly. */
143
- skipped?: boolean;
143
+ skipped?: boolean | undefined;
144
144
  /**
145
145
  * From `task.only()` or a `group.only()` this task is inside. When any
146
146
  * registered task has this set, the runner restricts the whole suite file
147
147
  * to only those tasks (before `--filter` narrows further). */
148
- only?: boolean;
149
- opts?: TaskOptions;
148
+ only?: boolean | undefined;
149
+ opts?: TaskOptions | undefined;
150
150
  }
151
151
 
152
152
  type Flags = { skip?: boolean; only?: boolean };
153
153
 
154
+ interface GroupScope {
155
+ path: string;
156
+ chain: readonly GroupFrame[];
157
+ description: string | undefined;
158
+ isolate: boolean | undefined;
159
+ gc: boolean | undefined;
160
+ cpu: boolean | undefined;
161
+ alloc: boolean | undefined;
162
+ peakMem: boolean | undefined;
163
+ skip: boolean | undefined;
164
+ only: boolean | undefined;
165
+ }
166
+
154
167
  const tasks: RegisteredTask[] = [];
155
- let currentGroup:
156
- | (Omit<GroupOptions, "before" | "after"> &
157
- Flags & { path: string; chain: readonly GroupFrame[] })
158
- | undefined;
168
+ // eslint-disable-next-line no-restricted-syntax -- group() is a free function in the public API, so the enclosing group is module state
169
+ let currentGroup: GroupScope | undefined;
170
+ // eslint-disable-next-line no-restricted-syntax -- sweep() hands its point to task() calls inside it, which are free functions
159
171
  let currentParams: Record<string, string | number | boolean> | undefined;
160
172
 
161
173
  function registerGroup(
@@ -195,7 +207,7 @@ type GroupRegistrar = (
195
207
  opts?: GroupOptions,
196
208
  ) => void;
197
209
 
198
- interface GroupFn extends GroupRegistrar {
210
+ export interface GroupFn extends GroupRegistrar {
199
211
  /**
200
212
  * Registers every task inside as skipped: the runner never measures
201
213
  * them, but the document still carries their workloads (marked
@@ -208,19 +220,21 @@ interface GroupFn extends GroupRegistrar {
208
220
  only: GroupRegistrar;
209
221
  }
210
222
 
223
+ /** Registers the tasks `fn` declares under the group `name`. */
211
224
  export const group: GroupFn = Object.assign(
212
- ((name, fn, opts) => registerGroup(name, fn, opts, {})) as GroupRegistrar,
225
+ ((name, fn, opts) =>
226
+ registerGroup(name, fn, opts, {})) satisfies GroupRegistrar,
213
227
  {
214
228
  skip: ((name, fn, opts) =>
215
- registerGroup(name, fn, opts, { skip: true })) as GroupRegistrar,
229
+ registerGroup(name, fn, opts, { skip: true })) satisfies GroupRegistrar,
216
230
  only: ((name, fn, opts) =>
217
- registerGroup(name, fn, opts, { only: true })) as GroupRegistrar,
231
+ registerGroup(name, fn, opts, { only: true })) satisfies GroupRegistrar,
218
232
  },
219
233
  );
220
234
 
221
235
  function registerTask(
222
236
  name: string,
223
- fn: () => unknown | Promise<unknown>,
237
+ fn: Hook,
224
238
  opts: TaskOptions | undefined,
225
239
  flags: Flags,
226
240
  ): void {
@@ -247,13 +261,9 @@ function registerTask(
247
261
  });
248
262
  }
249
263
 
250
- type TaskRegistrar = (
251
- name: string,
252
- fn: () => unknown | Promise<unknown>,
253
- opts?: TaskOptions,
254
- ) => void;
264
+ type TaskRegistrar = (name: string, fn: Hook, opts?: TaskOptions) => void;
255
265
 
256
- interface TaskFn extends TaskRegistrar {
266
+ export interface TaskFn extends TaskRegistrar {
257
267
  /**
258
268
  * Registers the task as skipped: the runner never measures it, but the
259
269
  * document still carries its workload (marked `Workload.skipped`) so a
@@ -267,13 +277,15 @@ interface TaskFn extends TaskRegistrar {
267
277
  only: TaskRegistrar;
268
278
  }
269
279
 
280
+ /** Registers `fn` as a benchmark task named `name` in the current group. */
270
281
  export const task: TaskFn = Object.assign(
271
- ((name, fn, opts) => registerTask(name, fn, opts, {})) as TaskRegistrar,
282
+ ((name, fn, opts) =>
283
+ registerTask(name, fn, opts, {})) satisfies TaskRegistrar,
272
284
  {
273
285
  skip: ((name, fn, opts) =>
274
- registerTask(name, fn, opts, { skip: true })) as TaskRegistrar,
286
+ registerTask(name, fn, opts, { skip: true })) satisfies TaskRegistrar,
275
287
  only: ((name, fn, opts) =>
276
- registerTask(name, fn, opts, { only: true })) as TaskRegistrar,
288
+ registerTask(name, fn, opts, { only: true })) satisfies TaskRegistrar,
277
289
  },
278
290
  );
279
291
 
@@ -287,10 +299,8 @@ export function resetRegistry(): void {
287
299
  currentParams = undefined;
288
300
  }
289
301
 
290
- /**
291
- * Runs `fn` with `params` as the current sweep point: `task()` calls
292
- * inside inherit it as their params (explicit `TaskOptions.params` keys
293
- * win). */
302
+ // `task()` calls inside `fn` inherit `params` as theirs, unless their own
303
+ // `TaskOptions.params` sets the same key.
294
304
  export function withCurrentParams<T>(
295
305
  params: Record<string, string | number | boolean>,
296
306
  fn: () => T,
@@ -308,15 +318,12 @@ export function taskId(t: RegisteredTask): string {
308
318
  return t.groupName ? `${t.groupName}/${t.name}` : t.name;
309
319
  }
310
320
 
311
- /** `taskId` under each of the task's `aliases`. */
312
321
  export function formerTaskIds(t: RegisteredTask): string[] {
313
322
  return (t.opts?.aliases ?? []).map((alias) =>
314
323
  t.groupName ? `${t.groupName}/${alias}` : alias,
315
324
  );
316
325
  }
317
326
 
318
- // Effective per-task flags: the task's own value, then its group's, then
319
- // the suite-wide default.
320
327
  export function taskIsolate(t: RegisteredTask, suiteIsolate: boolean): boolean {
321
328
  return t.opts?.isolate ?? t.groupIsolate ?? suiteIsolate;
322
329
  }
@@ -337,26 +344,25 @@ export function taskPeakMem(t: RegisteredTask, suitePeakMem: boolean): boolean {
337
344
  return t.opts?.peakMem ?? t.groupPeakMem ?? suitePeakMem;
338
345
  }
339
346
 
340
- /**
341
- * For the task at an index, the paths of the groups it opens (it's the
342
- * first measured task inside them: outermost first) and closes (the last:
343
- * innermost first), so group hooks wrap measured tasks only (a group's
344
- * tasks needn't be contiguous) and an outer group's hooks run once around
345
- * its nested groups. */
347
+ // For the task at an index, the paths of the groups it opens (it's the
348
+ // first measured task inside them: outermost first) and closes (the last:
349
+ // innermost first), so group hooks wrap measured tasks only (a group's
350
+ // tasks needn't be contiguous) and an outer group's hooks run once around
351
+ // its nested groups.
346
352
  export function groupEdges(
347
353
  tasks: readonly RegisteredTask[],
348
354
  ): (index: number) => { enter: string[]; leave: string[] } {
349
355
  const first = new Map<string, number>();
350
356
  const last = new Map<string, number>();
351
- tasks.forEach((t, i) => {
352
- if (t.skipped) return;
357
+ for (const [i, t] of tasks.entries()) {
358
+ if (t.skipped) continue;
353
359
  for (const { path } of t.groupChain ?? []) {
354
360
  if (!first.has(path)) first.set(path, i);
355
361
  last.set(path, i);
356
362
  }
357
- });
363
+ }
358
364
  return (i) => {
359
- const paths = (tasks[i]!.groupChain ?? []).map((f) => f.path);
365
+ const paths = (tasks[i]?.groupChain ?? []).map((f) => f.path);
360
366
  return {
361
367
  enter: paths.filter((p) => first.get(p) === i),
362
368
  leave: paths.filter((p) => last.get(p) === i).reverse(),
@@ -364,10 +370,9 @@ export function groupEdges(
364
370
  };
365
371
  }
366
372
 
367
- /**
368
- * Runs the task's `before`/`after` hooks for the groups at `paths` (in the
369
- * order given; default: all its groups, outermost first for `before`,
370
- * innermost first for `after`). A path the task isn't in is skipped. */
373
+ // `paths` run in the order given; by default all the task's groups,
374
+ // outermost first for `before`, innermost first for `after`. A path the
375
+ // task isn't in is skipped.
371
376
  export async function runGroupHooks(
372
377
  t: RegisteredTask,
373
378
  kind: "before" | "after",
@@ -382,9 +387,8 @@ export async function runGroupHooks(
382
387
  }
383
388
  }
384
389
 
385
- /**
386
- * mitata-compatible: filter value is a JS regex source, substring-matched
387
- * (no anchoring), case-sensitive, against the "group/name" task id. */
390
+ // compat: as in mitata, the filter is a JS regex source, substring-matched
391
+ // (no anchoring), case-sensitive, against the "group/name" task id.
388
392
  export function filterTasks(
389
393
  tasks: readonly RegisteredTask[],
390
394
  filter?: string,
@@ -394,11 +398,9 @@ export function filterTasks(
394
398
  return tasks.filter((t) => re.test(taskId(t)));
395
399
  }
396
400
 
397
- /**
398
- * The tasks a run measures: `.only` tasks when any exist (with a stderr
399
- * notice, since a forgotten `.only` silently shrinks a suite), else every
400
- * registered task - then narrowed by `filter`. Throws when that leaves
401
- * nothing, naming how many tasks the filter was matched against. */
401
+ // `.only` tasks when any exist (with a stderr notice, since a forgotten
402
+ // `.only` silently shrinks a suite), else every registered task, then
403
+ // narrowed by `filter`.
402
404
  export function selectTasks(
403
405
  registered: readonly RegisteredTask[],
404
406
  filter: string | undefined,
@@ -49,35 +49,36 @@ export interface MeasureTasksOpts extends InprocessTimingOptions {
49
49
  noiseCheck?: boolean;
50
50
  }
51
51
 
52
- /**
53
- * Shared by every runner so a task has the same id under `bench()` and
54
- * `ab()`.
55
- */
52
+ // Shared by every runner so a task has the same id under `bench()` and
53
+ // `ab()`.
56
54
  export function taskWorkload(
57
55
  suiteFile: string,
58
56
  t: RegisteredTask,
59
57
  isolated?: boolean,
60
58
  ): Workload {
61
59
  const id = taskIdOf(t);
60
+ const params = t.params !== undefined && { params: t.params };
62
61
  const formerIds = formerTaskIds(t).map(
63
- (former) => makeEntryWorkload(suiteFile, former, { params: t.params }).id,
62
+ (former) => makeEntryWorkload(suiteFile, former, { ...params }).id,
64
63
  );
64
+ const description = t.opts?.description;
65
65
  return makeEntryWorkload(suiteFile, id, {
66
66
  label: id,
67
- formerIds: formerIds.length > 0 ? formerIds : undefined,
68
- baseline: t.baseline,
69
- group: t.groupName,
70
- description: t.opts?.description,
71
- groupDescription: t.groupDescription,
72
- isolated,
73
- params: t.params,
74
- skipped: t.skipped,
67
+ ...(formerIds.length > 0 && { formerIds }),
68
+ ...(t.baseline !== undefined && { baseline: t.baseline }),
69
+ ...(t.groupName !== undefined && { group: t.groupName }),
70
+ ...(description !== undefined && { description }),
71
+ ...(t.groupDescription !== undefined && {
72
+ groupDescription: t.groupDescription,
73
+ }),
74
+ ...(isolated !== undefined && { isolated }),
75
+ ...params,
76
+ ...(t.skipped !== undefined && { skipped: t.skipped }),
75
77
  });
76
78
  }
77
79
 
78
- /**
79
- * Measures exactly `tasks` (already selected by the caller) in this
80
- * process; isolation is the caller's concern. */
80
+ // The caller has already selected `tasks` and handled isolation, so
81
+ // neither happens here.
81
82
  export async function measureTasks(
82
83
  suiteFile: string,
83
84
  tasks: readonly RegisteredTask[],
@@ -91,8 +92,7 @@ export async function measureTasks(
91
92
 
92
93
  const workloads: Workload[] = [];
93
94
  const measurements: Measurement[] = [];
94
- for (let idx = 0; idx < tasks.length; idx++) {
95
- const t = tasks[idx]!;
95
+ for (const [idx, t] of tasks.entries()) {
96
96
  const workload = taskWorkload(suiteFile, t, opts.markIsolated);
97
97
  workloads.push(workload);
98
98
 
@@ -104,11 +104,14 @@ export async function measureTasks(
104
104
 
105
105
  // Per-task options win; the fingerprint is per task so two runs only
106
106
  // compare like-for-like when measured under the same effective settings.
107
+ const budgetMs = t.opts?.budgetMs ?? opts.budgetMs;
108
+ const samples = t.opts?.samples ?? opts.samples;
109
+ const minSamples = t.opts?.minSamples ?? opts.minSamples;
107
110
  const taskOpts: InprocessTimingOptions = {
108
- budgetMs: t.opts?.budgetMs ?? opts.budgetMs,
109
- samples: t.opts?.samples ?? opts.samples,
110
- minSamples: t.opts?.minSamples ?? opts.minSamples,
111
- warmup: opts.warmup,
111
+ ...(budgetMs !== undefined && { budgetMs }),
112
+ ...(samples !== undefined && { samples }),
113
+ ...(minSamples !== undefined && { minSamples }),
114
+ ...(opts.warmup !== undefined && { warmup: opts.warmup }),
112
115
  gc: taskGc(t, opts.gc ?? false),
113
116
  };
114
117
  // The heap as of its last GC, never forcing one: a forced GC would
@@ -128,7 +131,7 @@ export async function measureTasks(
128
131
  }),
129
132
  trials: result.trials,
130
133
  timing: result.timing,
131
- instructions: result.instructions,
134
+ ...(result.instructions && { instructions: result.instructions }),
132
135
  warnings:
133
136
  noiseWarning && measurements.length === 0
134
137
  ? [...result.warnings, noiseWarning]
package/src/bench/run.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { errorMessage } from "../errors.ts";
1
2
  import type { ProfileDocument } from "../ir/types.ts";
2
3
  import { renderers } from "../renderers/index.ts";
3
4
  import type { FormatName } from "../renderers/types.ts";
@@ -37,7 +38,7 @@ export async function run(opts: RunOptions = {}): Promise<ProfileDocument> {
37
38
  try {
38
39
  tasks = selectTasks(registered, opts.filter, suiteFile);
39
40
  } catch (err) {
40
- throw new Error(`run(): ${(err as Error).message}`, { cause: err });
41
+ throw new Error(`run(): ${errorMessage(err)}`, { cause: err });
41
42
  }
42
43
  const doc = await measureTasks(suiteFile, tasks, opts);
43
44
 
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
+ import { errorMessage } from "../errors.ts";
3
4
  import { saveDocument } from "../ir/document.ts";
4
5
  import {
5
6
  measurePeakMem,
@@ -56,6 +57,20 @@ export interface RunnerOpts extends MeasureTasksOpts {
56
57
  preload?: string[];
57
58
  }
58
59
 
60
+ // The parent serializes a `RunnerOpts`; only that it's an object is
61
+ // checked.
62
+ function isRunnerOpts(value: unknown): value is RunnerOpts {
63
+ return typeof value === "object" && value !== null && !Array.isArray(value);
64
+ }
65
+
66
+ function parseRunnerOpts(json: string): RunnerOpts {
67
+ const value: unknown = JSON.parse(json);
68
+ if (!isRunnerOpts(value)) {
69
+ throw new Error(`bench runner: options aren't an object: ${json}`);
70
+ }
71
+ return value;
72
+ }
73
+
59
74
  async function main(): Promise<number> {
60
75
  const [suiteFile, outputPath, optsJson] = process.argv.slice(2);
61
76
  if (!suiteFile || !outputPath) {
@@ -65,10 +80,10 @@ async function main(): Promise<number> {
65
80
  return 2;
66
81
  }
67
82
 
68
- const opts: RunnerOpts = optsJson ? JSON.parse(optsJson) : {};
83
+ const opts: RunnerOpts = optsJson ? parseRunnerOpts(optsJson) : {};
69
84
 
70
- // Baseline for `measurePeakMem`, taken once ostia (which the suite
71
- // imports) is loaded.
85
+ // The `measurePeakMem` baseline waits until ostia, which the suite
86
+ // imports, is loaded, so ostia's own load isn't counted in the peak.
72
87
  let launched: MemorySnapshot | undefined;
73
88
  let sampler: RssSampler | undefined;
74
89
  if (opts.peakMemFor) {
@@ -100,7 +115,7 @@ async function main(): Promise<number> {
100
115
  !opts.workloadIds && !opts.peakMemFor,
101
116
  );
102
117
  } catch (err) {
103
- process.stderr.write(`bench runner: ${(err as Error).message}\n`);
118
+ process.stderr.write(`bench runner: ${errorMessage(err)}\n`);
104
119
  return 2;
105
120
  }
106
121
  const workloadIdOf = (t: RegisteredTask) => taskWorkload(suiteFile, t).id;
@@ -144,4 +159,4 @@ async function main(): Promise<number> {
144
159
  return 0;
145
160
  }
146
161
 
147
- main().then((code) => process.exit(code));
162
+ process.exit(await main());
@@ -2,9 +2,15 @@ import { statSync } from "node:fs";
2
2
  import { rm } from "node:fs/promises";
3
3
  import { isAbsolute } from "node:path";
4
4
 
5
+ import { processEnv } from "../config/env.ts";
5
6
  import { OstiaUsageError } from "../errors.ts";
6
7
  import { loadDocument } from "../ir/document.ts";
7
- import type { Measurement, ProfileDocument, Warning } from "../ir/types.ts";
8
+ import type {
9
+ Environment,
10
+ Measurement,
11
+ ProfileDocument,
12
+ Warning,
13
+ } from "../ir/types.ts";
8
14
  import {
9
15
  captureEnvironment,
10
16
  noisyMachineWarning,
@@ -23,19 +29,14 @@ export function absolutePath(cwd: string, file: string): string {
23
29
  /** A suite file named on the command line or in config doesn't exist. */
24
30
  class SuiteNotFoundError extends OstiaUsageError {}
25
31
 
26
- /**
27
- * Throws `SuiteNotFoundError` unless `absolute` is a file; `given` is the
28
- * path as the caller wrote it, for the message. */
29
32
  export function assertSuiteExists(given: string, absolute: string): void {
30
33
  if (!statSync(absolute, { throwIfNoEntry: false })?.isFile()) {
31
34
  throw new SuiteNotFoundError(`Suite not found: ${given}`);
32
35
  }
33
36
  }
34
37
 
35
- /**
36
- * A scratch directory under `outDir` no other run shares, so concurrent
37
- * `bench()`/`ab()` calls (or a rerun after a crash) never delete each
38
- * other's files. */
38
+ // No other run shares the directory, so concurrent `bench()`/`ab()` calls
39
+ // (or a rerun after a crash) never delete each other's files.
39
40
  export function uniqueTmpDir(outDir: string, kind: "bench" | "ab"): string {
40
41
  return `${outDir}/${kind}-tmp-${process.pid}-${crypto.randomUUID().slice(0, 8)}`;
41
42
  }
@@ -48,22 +49,20 @@ export function removeDir(path: string): Promise<void> {
48
49
  return rm(path, { recursive: true, force: true });
49
50
  }
50
51
 
51
- /** `undefined` when a runner killed mid-run never wrote its output. */
52
+ // `undefined` when a runner killed mid-run never wrote its output.
52
53
  export async function loadIfExists(
53
54
  path: string,
54
55
  ): Promise<ProfileDocument | undefined> {
55
56
  return (await Bun.file(path).exists()) ? loadDocument(path) : undefined;
56
57
  }
57
58
 
58
- /** Fresh processes per `--peak-mem` reading; the median is reported. */
59
+ // invariant: a `--peak-mem` reading is the median of this many fresh
60
+ // processes.
59
61
  export const PEAK_MEM_PROCESSES = 3;
60
- // Below this, slack is what any suite that loads fixtures leaves behind
61
- // (8MB for caligula's) and too common to warn about.
62
+ // Slack below this is what any suite that loads fixtures leaves behind
63
+ // (8MB for caligula's), so it's too common to warn about.
62
64
  const PEAK_SLACK_NOISE_BYTES = 16 * 1024 * 1024;
63
65
 
64
- /**
65
- * A `peak-hidden` warning when memory freed before the call may have
66
- * hidden part of its peak in `readings` (one task's fresh processes). */
67
66
  export function peakHiddenWarning(
68
67
  readings: PeakMemResult[],
69
68
  ): Warning | undefined {
@@ -77,7 +76,10 @@ export function peakHiddenWarning(
77
76
  };
78
77
  }
79
78
 
80
- export function captureRunEnvironment(noiseCheck: boolean | undefined) {
79
+ export function captureRunEnvironment(noiseCheck: boolean | undefined): {
80
+ environment: Environment | undefined;
81
+ noiseWarning: Warning | undefined;
82
+ } {
81
83
  const environment = noiseCheck === false ? undefined : captureEnvironment();
82
84
  return {
83
85
  environment,
@@ -85,7 +87,6 @@ export function captureRunEnvironment(noiseCheck: boolean | undefined) {
85
87
  };
86
88
  }
87
89
 
88
- /** Noise warning on the first measurement, `aborted` message on the last. */
89
90
  export function stampRunWarnings(
90
91
  measurements: Measurement[],
91
92
  noiseWarning: Warning | undefined,
@@ -100,28 +101,27 @@ export function stampRunWarnings(
100
101
  }
101
102
  }
102
103
 
103
- export interface RunnerProcessOptions {
104
+ interface RunnerProcessOptions {
104
105
  /** Prefix for error messages, e.g. "Bench suite". */
105
106
  label: string;
106
107
  /** What the error messages name: the suite file. */
107
108
  name: string;
108
109
  cwd: string;
109
- env?: Record<string, string>;
110
- timeoutMs?: number;
111
- signal?: AbortSignal;
110
+ env?: Record<string, string> | undefined;
111
+ timeoutMs?: number | undefined;
112
+ signal?: AbortSignal | undefined;
112
113
  /** Children to SIGKILL if a sibling fails. */
113
114
  inFlight?: Set<Bun.Subprocess>;
114
115
  /** Receives the runner's IPC messages. */
115
- ipc?: (message: never) => void;
116
+ ipc?: ((message: never) => void) | undefined;
116
117
  /**
117
118
  * Where the runner writes why it failed; its text, when present, goes in
118
119
  * the error for a non-zero exit. */
119
120
  errorFile?: string;
120
121
  }
121
122
 
122
- /**
123
- * Runs one runner subprocess to completion. Resolves `false` when the
124
- * caller's signal cancelled it (not a failure), `true` on a clean exit. */
123
+ // A cancel resolves `false` instead of rejecting, since it isn't a
124
+ // failure; a clean exit resolves `true`.
125
125
  export async function runRunnerProcess(
126
126
  argv: string[],
127
127
  opts: RunnerProcessOptions,
@@ -129,7 +129,7 @@ export async function runRunnerProcess(
129
129
  const kill = killSwitch(opts.timeoutMs, opts.signal);
130
130
  const proc = Bun.spawn(argv, {
131
131
  cwd: opts.cwd,
132
- ...(opts.env && { env: { ...process.env, ...opts.env } }),
132
+ ...(opts.env && { env: { ...processEnv(), ...opts.env } }),
133
133
  stdout: "inherit",
134
134
  stderr: "inherit",
135
135
  stdin: "ignore",
@@ -1,6 +1,6 @@
1
1
  import { withCurrentParams } from "./registry.ts";
2
2
 
3
- type SweepPoint<T extends Record<string, readonly unknown[]>> = {
3
+ export type SweepPoint<T extends Record<string, readonly unknown[]>> = {
4
4
  [K in keyof T]: T[K][number];
5
5
  };
6
6
 
@@ -19,18 +19,20 @@ export function sweep<T extends Record<string, readonly unknown[]>>(
19
19
  dims: T,
20
20
  fn: (point: SweepPoint<T>) => void,
21
21
  ): void {
22
- const keys = Object.keys(dims) as (keyof T)[];
22
+ const keys = Object.keys(dims);
23
23
 
24
24
  const go = (index: number, point: Record<string, unknown>): void => {
25
- if (index === keys.length) {
25
+ const key = keys[index];
26
+ if (key === undefined) {
26
27
  withCurrentParams(
28
+ // eslint-disable-next-line typescript/consistent-type-assertions, no-restricted-syntax -- `dims` may hold any value, and params carry the point as given
27
29
  point as Record<string, string | number | boolean>,
30
+ // eslint-disable-next-line typescript/consistent-type-assertions, no-restricted-syntax -- every key of `dims` is set by now, which TS can't follow through a mapped type
28
31
  () => fn(point as SweepPoint<T>),
29
32
  );
30
33
  return;
31
34
  }
32
- const key = keys[index]!;
33
- for (const value of dims[key]!) {
35
+ for (const value of dims[key] ?? []) {
34
36
  go(index + 1, { ...point, [key]: value });
35
37
  }
36
38
  };
@@ -4,14 +4,14 @@ import { scanGlobs } from "../glob.ts";
4
4
  import { fp } from "../ir/fp.ts";
5
5
  import type { Phase } from "../ir/types.ts";
6
6
 
7
- export interface CacheKeyInput {
7
+ interface CacheKeyInput {
8
8
  workloadId: string;
9
9
  phase: Phase;
10
10
  configFingerprint: string;
11
11
  bunVersion: string;
12
12
  toolVersion: string;
13
13
  instrumented: boolean;
14
- inputsDigest?: string;
14
+ inputsDigest?: string | undefined;
15
15
  }
16
16
 
17
17
  export function computeCacheKey(input: CacheKeyInput): string {
@@ -27,7 +27,8 @@ export function computeCacheKey(input: CacheKeyInput): string {
27
27
  );
28
28
  }
29
29
 
30
- // Keeps a large glob under the process's open-file limit (EMFILE).
30
+ // Caps parallel reads because a large glob would otherwise pass the
31
+ // process's open-file limit (EMFILE).
31
32
  const READ_CONCURRENCY = 32;
32
33
 
33
34
  export async function computeInputsDigest(
@@ -37,13 +38,15 @@ export async function computeInputsDigest(
37
38
  if (globs.length === 0) return undefined;
38
39
 
39
40
  const paths = await scanGlobs(globs, cwd);
40
- const entries: { path: string; sha256: string }[] = new Array(paths.length);
41
+ const entries = new Array<{ path: string; sha256: string }>(paths.length);
41
42
  let next = 0;
42
43
  const worker = async () => {
43
44
  while (next < paths.length) {
44
45
  const k = next++;
45
- const path = paths[k]!;
46
- // Absolute patterns scan to absolute paths; `resolve` handles both.
46
+ const path = paths[k];
47
+ if (path === undefined) continue;
48
+ // `resolve`, not a join, since absolute patterns scan to absolute
49
+ // paths.
47
50
  const buf = await Bun.file(resolve(cwd, path)).arrayBuffer();
48
51
  entries[k] = {
49
52
  path,