ostia 0.2.12 → 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 (98) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -358
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +923 -679
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +487 -0
  13. package/src/ab/index.ts +1160 -0
  14. package/src/baseline/index.ts +69 -0
  15. package/src/bench/index.ts +516 -0
  16. package/src/bench/projects.ts +43 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +426 -0
  19. package/src/bench/run-tasks.ts +179 -0
  20. package/src/bench/run.ts +52 -0
  21. package/src/bench/runner.ts +162 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +41 -0
  24. package/src/cache/fingerprint.ts +62 -0
  25. package/src/cache/store.ts +40 -0
  26. package/src/capture/bunflags.ts +92 -0
  27. package/src/capture/cpu-parse.ts +131 -0
  28. package/src/capture/cpu.ts +47 -0
  29. package/src/capture/frames.ts +60 -0
  30. package/src/capture/heap-parse.ts +111 -0
  31. package/src/capture/heap.ts +36 -0
  32. package/src/capture/inspector.ts +47 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +440 -0
  37. package/src/cli/flags.ts +263 -0
  38. package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +179 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +624 -0
  43. package/src/config/env.ts +13 -0
  44. package/src/config/index.ts +283 -0
  45. package/src/config/validate.ts +273 -0
  46. package/src/errors.ts +8 -0
  47. package/src/format.ts +35 -0
  48. package/src/glob.ts +45 -0
  49. package/src/index.ts +60 -0
  50. package/src/ir/cpu.ts +10 -0
  51. package/src/ir/defined.ts +12 -0
  52. package/src/ir/document.ts +491 -0
  53. package/src/ir/fp.ts +28 -0
  54. package/src/ir/git.ts +37 -0
  55. package/src/ir/types.ts +615 -0
  56. package/src/measure/alloc.ts +56 -0
  57. package/src/measure/cpu.ts +91 -0
  58. package/src/measure/environment.ts +38 -0
  59. package/src/measure/inprocess.ts +191 -0
  60. package/src/measure/instructions.ts +139 -0
  61. package/src/measure/loop.ts +64 -0
  62. package/src/measure/noise.ts +55 -0
  63. package/src/measure/paired.ts +304 -0
  64. package/src/measure/peak.ts +201 -0
  65. package/src/measure/timing.ts +263 -0
  66. package/src/profile.ts +110 -0
  67. package/src/renderers/collapsed.ts +42 -0
  68. package/src/renderers/cpu-tree.ts +191 -0
  69. package/src/renderers/cpuprofile.ts +43 -0
  70. package/src/renderers/format.ts +132 -0
  71. package/src/renderers/index.ts +37 -0
  72. package/src/renderers/json.ts +10 -0
  73. package/src/renderers/jsonl.ts +19 -0
  74. package/src/renderers/markdown.ts +543 -0
  75. package/src/renderers/mermaid.ts +90 -0
  76. package/src/renderers/minimal.ts +602 -0
  77. package/src/renderers/paired.ts +223 -0
  78. package/src/renderers/relative.ts +60 -0
  79. package/src/renderers/select.ts +264 -0
  80. package/src/renderers/speedscope.ts +73 -0
  81. package/src/renderers/terminal.ts +470 -0
  82. package/src/renderers/types.ts +27 -0
  83. package/src/spawn/index.ts +387 -0
  84. package/src/stats/bootstrap.ts +151 -0
  85. package/src/stats/index.ts +144 -0
  86. package/src/stats/mannwhitney.ts +82 -0
  87. package/src/time.ts +337 -0
  88. package/src/version.ts +3 -0
  89. package/ab-runner.ts +0 -8
  90. package/chunk-05jfst35.js +0 -28
  91. package/chunk-1g1x9zz2.js +0 -15
  92. package/chunk-23g2rwrn.js +0 -3
  93. package/chunk-468h5412.js +0 -25
  94. package/chunk-4esjfc2m.js +0 -2
  95. package/chunk-ct2xsezd.js +0 -14
  96. package/cli.js +0 -3
  97. package/index.js +0 -2
  98. package/runner.ts +0 -7
@@ -0,0 +1,426 @@
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.
4
+ export const NO_TASKS_HINT =
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.";
6
+
7
+ /** A task body or hook; it may return a promise, which the runner awaits. */
8
+ type Hook = () => unknown;
9
+
10
+ export interface TaskOptions {
11
+ /**
12
+ * Marks this task as the Relative reference for its group in the table
13
+ * renderer, mirroring mitata's `baseline()`. At most one per group. */
14
+ baseline?: boolean;
15
+ /** Per-task time budget; overrides the suite-wide `--budget` / `budgetMs`. */
16
+ budgetMs?: number;
17
+ /**
18
+ * Per-task exact trial count; overrides the suite-wide `--samples` /
19
+ * `samples`. When set, the budget is ignored for this task. */
20
+ samples?: number;
21
+ /**
22
+ * Per-task hard floor on trials; overrides the suite-wide `--min-samples`
23
+ * / `minSamples`. */
24
+ minSamples?: number;
25
+ /**
26
+ * Former names of this task in the same group, so `compare` and `ab`
27
+ * match a base measured before a rename instead of reporting the old name
28
+ * as removed and the new one as new. */
29
+ aliases?: string[];
30
+ /**
31
+ * What this task measures and why. Flows into `Workload.description` so
32
+ * the intent travels with the numbers instead of living only in a source
33
+ * comment. */
34
+ description?: string;
35
+ /**
36
+ * Give this task its own subprocess instead of sharing its suite file's,
37
+ * isolating its JIT tier state and heap shape from every other task in the
38
+ * run. Overrides the group's and the suite-wide `bench({ isolate })` /
39
+ * `--isolate` default for this task only. */
40
+ isolate?: boolean;
41
+ /**
42
+ * Overrides the suite-wide `bench({ gc })` / `--gc` (and any
43
+ * `GroupOptions.gc`) for this task only. */
44
+ gc?: boolean;
45
+ /**
46
+ * Overrides the suite-wide `bench({ cpu })` / `--cpu` (and any
47
+ * `GroupOptions.cpu`) for this task only: after the timing measurement,
48
+ * capture one extra `phase: "cpu"` measurement (JIT tiers included) on
49
+ * the same workload, never mixed into the timing numbers. */
50
+ cpu?: boolean;
51
+ /**
52
+ * Overrides the suite-wide `bench({ alloc })` / `--alloc` (and any
53
+ * `GroupOptions.alloc`) for this task only: after the timing measurement,
54
+ * capture one extra `phase: "memstats"` measurement of the heap each call
55
+ * retains (what survives a full GC, not what it allocates). */
56
+ alloc?: boolean;
57
+ /**
58
+ * Overrides the suite-wide `bench({ peakMem })` / `--peak-mem` (and any
59
+ * `GroupOptions.peakMem`) for this task only: capture one extra
60
+ * `phase: "memstats"` measurement of how far one call raises the
61
+ * process's peak RSS, in fresh processes. */
62
+ peakMem?: boolean;
63
+ /**
64
+ * Structured parameters this task represents (e.g. `{ size: 800, impl:
65
+ * "fast" }`), written to `Workload.params` and folded into the workload id
66
+ * so points with the same task name don't collide. Inside `sweep()`, the
67
+ * current point is inherited automatically; an explicit `params` here
68
+ * merges over it (explicit keys win). */
69
+ params?: Record<string, string | number | boolean>;
70
+ /**
71
+ * Runs once, unmeasured, immediately before this task's warmup - in the
72
+ * task's own process, so it works with `isolate`. No per-trial hook: that
73
+ * would defeat batching. Use `gc` (Bun.gc between trials) or `isolate`
74
+ * (a fresh process per task) for per-trial concerns instead. */
75
+ before?: Hook;
76
+ /**
77
+ * Runs once, unmeasured, immediately after this task's last trial. Same
78
+ * process/no-per-trial caveats as `before`. */
79
+ after?: Hook;
80
+ }
81
+
82
+ export interface GroupOptions {
83
+ /**
84
+ * What this group measures and why. Flows into `Workload.groupDescription`
85
+ * on every task in the group. */
86
+ description?: string;
87
+ /**
88
+ * Default `isolate` for every task in this group, unless a task overrides
89
+ * it with its own `TaskOptions.isolate`. */
90
+ isolate?: boolean;
91
+ /**
92
+ * Default `gc` for every task in this group, unless a task overrides it
93
+ * with its own `TaskOptions.gc`. */
94
+ gc?: boolean;
95
+ /**
96
+ * Default `cpu` for every task in this group, unless a task overrides it
97
+ * with its own `TaskOptions.cpu`. */
98
+ cpu?: boolean;
99
+ /**
100
+ * Default `alloc` for every task in this group, unless a task overrides
101
+ * it with its own `TaskOptions.alloc`. */
102
+ alloc?: boolean;
103
+ /**
104
+ * Default `peakMem` for every task in this group, unless a task
105
+ * overrides it with its own `TaskOptions.peakMem`. */
106
+ peakMem?: boolean;
107
+ /**
108
+ * Runs once, unmeasured, before the group's first task's warmup (not
109
+ * before every task) - in whichever process runs that task, so it works
110
+ * with `isolate`. */
111
+ before?: Hook;
112
+ /** Runs once, unmeasured, after the group's last task's last trial. */
113
+ after?: Hook;
114
+ }
115
+
116
+ /** One enclosing group of a task, with the hooks it declared. */
117
+ interface GroupFrame {
118
+ /** Slash-joined names from the outermost group down to this one. */
119
+ path: string;
120
+ before?: Hook | undefined;
121
+ after?: Hook | undefined;
122
+ }
123
+
124
+ export interface RegisteredTask {
125
+ /** The enclosing groups' names joined with "/", outermost first. */
126
+ groupName?: string | undefined;
127
+ /** Enclosing groups, outermost first. */
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
+ name: string;
136
+ fn: Hook;
137
+ baseline?: boolean | undefined;
138
+ params?: Record<string, string | number | boolean> | undefined;
139
+ /**
140
+ * From `task.skip()` or a `group.skip()` this task is inside. The runner
141
+ * never measures it; the document still carries its workload (marked
142
+ * `Workload.skipped`) so a renderer or `compare` can say so explicitly. */
143
+ skipped?: boolean | undefined;
144
+ /**
145
+ * From `task.only()` or a `group.only()` this task is inside. When any
146
+ * registered task has this set, the runner restricts the whole suite file
147
+ * to only those tasks (before `--filter` narrows further). */
148
+ only?: boolean | undefined;
149
+ opts?: TaskOptions | undefined;
150
+ }
151
+
152
+ type Flags = { skip?: boolean; only?: boolean };
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
+
167
+ const tasks: RegisteredTask[] = [];
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
171
+ let currentParams: Record<string, string | number | boolean> | undefined;
172
+
173
+ function registerGroup(
174
+ name: string,
175
+ fn: () => void,
176
+ opts: GroupOptions | undefined,
177
+ flags: Flags,
178
+ ): void {
179
+ const previous = currentGroup;
180
+ // An inner group inherits what it doesn't set, and skip/only from outside.
181
+ const path = previous ? `${previous.path}/${name}` : name;
182
+ currentGroup = {
183
+ path,
184
+ chain: [
185
+ ...(previous?.chain ?? []),
186
+ { path, before: opts?.before, after: opts?.after },
187
+ ],
188
+ description: opts?.description ?? previous?.description,
189
+ isolate: opts?.isolate ?? previous?.isolate,
190
+ gc: opts?.gc ?? previous?.gc,
191
+ cpu: opts?.cpu ?? previous?.cpu,
192
+ alloc: opts?.alloc ?? previous?.alloc,
193
+ peakMem: opts?.peakMem ?? previous?.peakMem,
194
+ skip: flags.skip || previous?.skip,
195
+ only: flags.only || previous?.only,
196
+ };
197
+ try {
198
+ fn();
199
+ } finally {
200
+ currentGroup = previous;
201
+ }
202
+ }
203
+
204
+ type GroupRegistrar = (
205
+ name: string,
206
+ fn: () => void,
207
+ opts?: GroupOptions,
208
+ ) => void;
209
+
210
+ interface GroupFn extends GroupRegistrar {
211
+ /**
212
+ * Registers every task inside as skipped: the runner never measures
213
+ * them, but the document still carries their workloads (marked
214
+ * `Workload.skipped`). */
215
+ skip: GroupRegistrar;
216
+ /**
217
+ * When any task or group in the suite uses `.only`, the runner restricts
218
+ * the whole suite file to only those tasks (before `--filter` narrows
219
+ * further) and prints a one-line notice to stderr. */
220
+ only: GroupRegistrar;
221
+ }
222
+
223
+ /** Registers the tasks `fn` declares under the group `name`. */
224
+ export const group: GroupFn = Object.assign(
225
+ ((name, fn, opts) =>
226
+ registerGroup(name, fn, opts, {})) satisfies GroupRegistrar,
227
+ {
228
+ skip: ((name, fn, opts) =>
229
+ registerGroup(name, fn, opts, { skip: true })) satisfies GroupRegistrar,
230
+ only: ((name, fn, opts) =>
231
+ registerGroup(name, fn, opts, { only: true })) satisfies GroupRegistrar,
232
+ },
233
+ );
234
+
235
+ function registerTask(
236
+ name: string,
237
+ fn: Hook,
238
+ opts: TaskOptions | undefined,
239
+ flags: Flags,
240
+ ): void {
241
+ const params =
242
+ currentParams !== undefined || opts?.params !== undefined
243
+ ? { ...currentParams, ...opts?.params }
244
+ : undefined;
245
+ tasks.push({
246
+ groupName: currentGroup?.path,
247
+ groupChain: currentGroup?.chain,
248
+ groupDescription: currentGroup?.description,
249
+ groupIsolate: currentGroup?.isolate,
250
+ groupGc: currentGroup?.gc,
251
+ groupCpu: currentGroup?.cpu,
252
+ groupAlloc: currentGroup?.alloc,
253
+ groupPeakMem: currentGroup?.peakMem,
254
+ name,
255
+ fn,
256
+ baseline: opts?.baseline,
257
+ params,
258
+ skipped: flags.skip || currentGroup?.skip,
259
+ only: flags.only || currentGroup?.only,
260
+ opts,
261
+ });
262
+ }
263
+
264
+ type TaskRegistrar = (name: string, fn: Hook, opts?: TaskOptions) => void;
265
+
266
+ interface TaskFn extends TaskRegistrar {
267
+ /**
268
+ * Registers the task as skipped: the runner never measures it, but the
269
+ * document still carries its workload (marked `Workload.skipped`) so a
270
+ * renderer or `compare` can say so explicitly instead of the task simply
271
+ * being absent. */
272
+ skip: TaskRegistrar;
273
+ /**
274
+ * When any task or group in the suite uses `.only`, the runner restricts
275
+ * the whole suite file to only those tasks (before `--filter` narrows
276
+ * further) and prints a one-line notice to stderr. */
277
+ only: TaskRegistrar;
278
+ }
279
+
280
+ /** Registers `fn` as a benchmark task named `name` in the current group. */
281
+ export const task: TaskFn = Object.assign(
282
+ ((name, fn, opts) =>
283
+ registerTask(name, fn, opts, {})) satisfies TaskRegistrar,
284
+ {
285
+ skip: ((name, fn, opts) =>
286
+ registerTask(name, fn, opts, { skip: true })) satisfies TaskRegistrar,
287
+ only: ((name, fn, opts) =>
288
+ registerTask(name, fn, opts, { only: true })) satisfies TaskRegistrar,
289
+ },
290
+ );
291
+
292
+ export function getRegisteredTasks(): readonly RegisteredTask[] {
293
+ return tasks;
294
+ }
295
+
296
+ export function resetRegistry(): void {
297
+ tasks.length = 0;
298
+ currentGroup = undefined;
299
+ currentParams = undefined;
300
+ }
301
+
302
+ // `task()` calls inside `fn` inherit `params` as theirs, unless their own
303
+ // `TaskOptions.params` sets the same key.
304
+ export function withCurrentParams<T>(
305
+ params: Record<string, string | number | boolean>,
306
+ fn: () => T,
307
+ ): T {
308
+ const previous = currentParams;
309
+ currentParams = params;
310
+ try {
311
+ return fn();
312
+ } finally {
313
+ currentParams = previous;
314
+ }
315
+ }
316
+
317
+ export function taskId(t: RegisteredTask): string {
318
+ return t.groupName ? `${t.groupName}/${t.name}` : t.name;
319
+ }
320
+
321
+ export function formerTaskIds(t: RegisteredTask): string[] {
322
+ return (t.opts?.aliases ?? []).map((alias) =>
323
+ t.groupName ? `${t.groupName}/${alias}` : alias,
324
+ );
325
+ }
326
+
327
+ export function taskIsolate(t: RegisteredTask, suiteIsolate: boolean): boolean {
328
+ return t.opts?.isolate ?? t.groupIsolate ?? suiteIsolate;
329
+ }
330
+
331
+ export function taskGc(t: RegisteredTask, suiteGc: boolean): boolean {
332
+ return t.opts?.gc ?? t.groupGc ?? suiteGc;
333
+ }
334
+
335
+ export function taskCpu(t: RegisteredTask, suiteCpu: boolean): boolean {
336
+ return t.opts?.cpu ?? t.groupCpu ?? suiteCpu;
337
+ }
338
+
339
+ export function taskAlloc(t: RegisteredTask, suiteAlloc: boolean): boolean {
340
+ return t.opts?.alloc ?? t.groupAlloc ?? suiteAlloc;
341
+ }
342
+
343
+ export function taskPeakMem(t: RegisteredTask, suitePeakMem: boolean): boolean {
344
+ return t.opts?.peakMem ?? t.groupPeakMem ?? suitePeakMem;
345
+ }
346
+
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.
352
+ export function groupEdges(
353
+ tasks: readonly RegisteredTask[],
354
+ ): (index: number) => { enter: string[]; leave: string[] } {
355
+ const first = new Map<string, number>();
356
+ const last = new Map<string, number>();
357
+ for (const [i, t] of tasks.entries()) {
358
+ if (t.skipped) continue;
359
+ for (const { path } of t.groupChain ?? []) {
360
+ if (!first.has(path)) first.set(path, i);
361
+ last.set(path, i);
362
+ }
363
+ }
364
+ return (i) => {
365
+ const paths = (tasks[i]?.groupChain ?? []).map((f) => f.path);
366
+ return {
367
+ enter: paths.filter((p) => first.get(p) === i),
368
+ leave: paths.filter((p) => last.get(p) === i).reverse(),
369
+ };
370
+ };
371
+ }
372
+
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.
376
+ export async function runGroupHooks(
377
+ t: RegisteredTask,
378
+ kind: "before" | "after",
379
+ paths?: readonly string[],
380
+ ): Promise<void> {
381
+ const chain = t.groupChain ?? [];
382
+ const order =
383
+ paths ??
384
+ (kind === "before" ? chain : [...chain].reverse()).map((f) => f.path);
385
+ for (const path of order) {
386
+ await chain.find((f) => f.path === path)?.[kind]?.();
387
+ }
388
+ }
389
+
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.
392
+ export function filterTasks(
393
+ tasks: readonly RegisteredTask[],
394
+ filter?: string,
395
+ ): RegisteredTask[] {
396
+ if (!filter) return [...tasks];
397
+ const re = new RegExp(filter);
398
+ return tasks.filter((t) => re.test(taskId(t)));
399
+ }
400
+
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`.
404
+ export function selectTasks(
405
+ registered: readonly RegisteredTask[],
406
+ filter: string | undefined,
407
+ where: string,
408
+ // False in the follow-up processes of one run (isolated tasks, peak-memory
409
+ // readings, ab repeats), so the notice prints once per suite file.
410
+ announce = true,
411
+ ): RegisteredTask[] {
412
+ const onlyTasks = registered.filter((t) => t.only);
413
+ const candidates = onlyTasks.length > 0 ? onlyTasks : registered;
414
+ if (announce && onlyTasks.length > 0) {
415
+ process.stderr.write(
416
+ `bench: ${onlyTasks.length} task(s) selected by .only\n`,
417
+ );
418
+ }
419
+ const tasks = filterTasks(candidates, filter);
420
+ if (tasks.length === 0) {
421
+ throw new Error(
422
+ `filter ${JSON.stringify(filter)} matched zero of ${candidates.length} registered task(s) in ${where}.`,
423
+ );
424
+ }
425
+ return tasks;
426
+ }
@@ -0,0 +1,179 @@
1
+ import { heapSize } from "bun:jsc";
2
+
3
+ import {
4
+ configFingerprint,
5
+ createDocument,
6
+ makeEntryWorkload,
7
+ makeInstrumentedMeasurement,
8
+ makeTimingMeasurement,
9
+ } from "../ir/document.ts";
10
+ import type { Measurement, ProfileDocument, Workload } from "../ir/types.ts";
11
+ import { measureAllocPerOp } from "../measure/alloc.ts";
12
+ import {
13
+ captureTaskCpuProfile,
14
+ DEFAULT_TASK_CPU_INTERVAL_US,
15
+ } from "../measure/cpu.ts";
16
+ import { stampDrift } from "../measure/environment.ts";
17
+ import {
18
+ type InprocessTimingOptions,
19
+ measureTask,
20
+ } from "../measure/inprocess.ts";
21
+ import {
22
+ formerTaskIds,
23
+ groupEdges,
24
+ type RegisteredTask,
25
+ runGroupHooks,
26
+ taskAlloc,
27
+ taskCpu,
28
+ taskGc,
29
+ taskId as taskIdOf,
30
+ } from "./registry.ts";
31
+ import { captureRunEnvironment } from "./support.ts";
32
+
33
+ export interface MeasureTasksOpts extends InprocessTimingOptions {
34
+ /**
35
+ * Suite-wide default for capturing an extra `phase: "cpu"` measurement per
36
+ * task (task/group `cpu` still wins). */
37
+ cpu?: boolean;
38
+ /** `cpu`'s sampling interval, µs (default: 100). */
39
+ cpuIntervalUs?: number;
40
+ /**
41
+ * Suite-wide default for capturing an extra `phase: "memstats"`
42
+ * measurement per task (task/group `alloc` still wins). */
43
+ alloc?: boolean;
44
+ /** Stamped onto every workload: it ran in a subprocess dedicated to it. */
45
+ markIsolated?: boolean;
46
+ /**
47
+ * Measure this machine's noise floor before the first task (default:
48
+ * true) and stamp it on the document as `environment`. */
49
+ noiseCheck?: boolean;
50
+ }
51
+
52
+ // Shared by every runner so a task has the same id under `bench()` and
53
+ // `ab()`.
54
+ export function taskWorkload(
55
+ suiteFile: string,
56
+ t: RegisteredTask,
57
+ isolated?: boolean,
58
+ ): Workload {
59
+ const id = taskIdOf(t);
60
+ const params = t.params !== undefined && { params: t.params };
61
+ const formerIds = formerTaskIds(t).map(
62
+ (former) => makeEntryWorkload(suiteFile, former, { ...params }).id,
63
+ );
64
+ const description = t.opts?.description;
65
+ return makeEntryWorkload(suiteFile, id, {
66
+ label: id,
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 }),
77
+ });
78
+ }
79
+
80
+ // The caller has already selected `tasks` and handled isolation, so
81
+ // neither happens here.
82
+ export async function measureTasks(
83
+ suiteFile: string,
84
+ tasks: readonly RegisteredTask[],
85
+ opts: MeasureTasksOpts,
86
+ ): Promise<ProfileDocument> {
87
+ const willMeasure = tasks.some((t) => !t.skipped);
88
+ const { environment, noiseWarning } = captureRunEnvironment(
89
+ willMeasure ? opts.noiseCheck : false,
90
+ );
91
+ const edges = groupEdges(tasks);
92
+
93
+ const workloads: Workload[] = [];
94
+ const measurements: Measurement[] = [];
95
+ for (const [idx, t] of tasks.entries()) {
96
+ const workload = taskWorkload(suiteFile, t, opts.markIsolated);
97
+ workloads.push(workload);
98
+
99
+ if (t.skipped) continue;
100
+
101
+ const { enter, leave } = edges(idx);
102
+ await runGroupHooks(t, "before", enter);
103
+ if (t.opts?.before) await t.opts.before();
104
+
105
+ // Per-task options win; the fingerprint is per task so two runs only
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;
110
+ const taskOpts: InprocessTimingOptions = {
111
+ ...(budgetMs !== undefined && { budgetMs }),
112
+ ...(samples !== undefined && { samples }),
113
+ ...(minSamples !== undefined && { minSamples }),
114
+ ...(opts.warmup !== undefined && { warmup: opts.warmup }),
115
+ gc: taskGc(t, opts.gc ?? false),
116
+ };
117
+ // The heap as of its last GC, never forcing one: a forced GC would
118
+ // change the timing it brackets.
119
+ const heapBefore = heapSize();
120
+ const result = await measureTask(t.fn, taskOpts);
121
+ const heapAfter = heapSize();
122
+ measurements.push(
123
+ makeTimingMeasurement({
124
+ workload,
125
+ heapUsed: { beforeBytes: heapBefore, afterBytes: heapAfter },
126
+ configFingerprint: configFingerprint({
127
+ budgetMs: taskOpts.budgetMs ?? null,
128
+ samples: taskOpts.samples ?? null,
129
+ minSamples: taskOpts.minSamples ?? null,
130
+ gc: taskOpts.gc ?? false,
131
+ }),
132
+ trials: result.trials,
133
+ timing: result.timing,
134
+ ...(result.instructions && { instructions: result.instructions }),
135
+ warnings:
136
+ noiseWarning && measurements.length === 0
137
+ ? [...result.warnings, noiseWarning]
138
+ : result.warnings,
139
+ }),
140
+ );
141
+
142
+ if (taskCpu(t, opts.cpu ?? false)) {
143
+ const intervalUs = opts.cpuIntervalUs ?? DEFAULT_TASK_CPU_INTERVAL_US;
144
+ const cpuResult = await captureTaskCpuProfile(t.fn, { intervalUs });
145
+ measurements.push(
146
+ makeInstrumentedMeasurement({
147
+ workload,
148
+ phase: "cpu",
149
+ configFingerprint: configFingerprint({ cpu: true, intervalUs }),
150
+ diagnosticWallNs: cpuResult.diagnosticWallNs,
151
+ cpu: cpuResult.cpu,
152
+ jit: cpuResult.jit,
153
+ warnings: cpuResult.warnings,
154
+ artifacts: [],
155
+ }),
156
+ );
157
+ }
158
+ if (taskAlloc(t, opts.alloc ?? false)) {
159
+ const allocResult = await measureAllocPerOp(t.fn);
160
+ measurements.push(
161
+ makeInstrumentedMeasurement({
162
+ workload,
163
+ phase: "memstats",
164
+ configFingerprint: configFingerprint({ alloc: true }),
165
+ diagnosticWallNs: allocResult.diagnosticWallNs,
166
+ memory: allocResult.memory,
167
+ warnings: [],
168
+ artifacts: [],
169
+ }),
170
+ );
171
+ }
172
+
173
+ if (t.opts?.after) await t.opts.after();
174
+ await runGroupHooks(t, "after", leave);
175
+ }
176
+
177
+ stampDrift(environment);
178
+ return createDocument(workloads, measurements, environment);
179
+ }
@@ -0,0 +1,52 @@
1
+ import { errorMessage } from "../errors.ts";
2
+ import type { ProfileDocument } from "../ir/types.ts";
3
+ import { renderers } from "../renderers/index.ts";
4
+ import type { FormatName } from "../renderers/types.ts";
5
+ import {
6
+ getRegisteredTasks,
7
+ type RegisteredTask,
8
+ selectTasks,
9
+ } from "./registry.ts";
10
+ import { measureTasks, type MeasureTasksOpts } from "./run-tasks.ts";
11
+
12
+ export interface RunOptions extends MeasureTasksOpts {
13
+ /** Regex matched against "group/name" task ids, as in `bench({ filter })`. */
14
+ filter?: string;
15
+ /** Skip printing the report to stdout; still returns the document. */
16
+ quiet?: boolean;
17
+ /** Renderer used for the printed report (default: `"table"`). */
18
+ format?: FormatName;
19
+ }
20
+
21
+ /** In-file entrypoint: call at the bottom of a suite file run directly with
22
+ * `bun suite.ts` to measure every registered `group()`/`task()`, print a
23
+ * report, and return the document.
24
+ *
25
+ * Everything runs in the current process, so `TaskOptions.isolate` is
26
+ * ignored. Prefer `ostia bench`/`bench()` for numbers you'll
27
+ * `compare`/`ci` against. */
28
+ export async function run(opts: RunOptions = {}): Promise<ProfileDocument> {
29
+ const registered = getRegisteredTasks();
30
+ if (registered.length === 0) {
31
+ throw new Error(
32
+ "run(): no tasks registered - call group()/task() before run() in the same file.",
33
+ );
34
+ }
35
+
36
+ const suiteFile = Bun.main;
37
+ let tasks: RegisteredTask[];
38
+ try {
39
+ tasks = selectTasks(registered, opts.filter, suiteFile);
40
+ } catch (err) {
41
+ throw new Error(`run(): ${errorMessage(err)}`, { cause: err });
42
+ }
43
+ const doc = await measureTasks(suiteFile, tasks, opts);
44
+
45
+ if (!opts.quiet) {
46
+ const format = opts.format ?? "table";
47
+ const { text } = await renderers[format].render(doc, {});
48
+ if (text) process.stdout.write(text);
49
+ }
50
+
51
+ return doc;
52
+ }