ostia 0.2.12 → 0.3.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 (96) 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 +894 -677
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -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 +416 -0
  37. package/src/cli/flags.ts +264 -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 +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-05jfst35.js +0 -28
  89. package/chunk-1g1x9zz2.js +0 -15
  90. package/chunk-23g2rwrn.js +0 -3
  91. package/chunk-468h5412.js +0 -25
  92. package/chunk-4esjfc2m.js +0 -2
  93. package/chunk-ct2xsezd.js +0 -14
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,424 @@
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. */
5
+ export const NO_TASKS_HINT =
6
+ " 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
+
8
+ type Hook = () => unknown | Promise<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;
121
+ after?: Hook;
122
+ }
123
+
124
+ export interface RegisteredTask {
125
+ /** The enclosing groups' names joined with "/", outermost first. */
126
+ groupName?: string;
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;
135
+ name: string;
136
+ fn: () => unknown | Promise<unknown>;
137
+ baseline?: boolean;
138
+ params?: Record<string, string | number | boolean>;
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;
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;
149
+ opts?: TaskOptions;
150
+ }
151
+
152
+ type Flags = { skip?: boolean; only?: boolean };
153
+
154
+ const tasks: RegisteredTask[] = [];
155
+ let currentGroup:
156
+ | (Omit<GroupOptions, "before" | "after"> &
157
+ Flags & { path: string; chain: readonly GroupFrame[] })
158
+ | undefined;
159
+ let currentParams: Record<string, string | number | boolean> | undefined;
160
+
161
+ function registerGroup(
162
+ name: string,
163
+ fn: () => void,
164
+ opts: GroupOptions | undefined,
165
+ flags: Flags,
166
+ ): void {
167
+ const previous = currentGroup;
168
+ // An inner group inherits what it doesn't set, and skip/only from outside.
169
+ const path = previous ? `${previous.path}/${name}` : name;
170
+ currentGroup = {
171
+ path,
172
+ chain: [
173
+ ...(previous?.chain ?? []),
174
+ { path, before: opts?.before, after: opts?.after },
175
+ ],
176
+ description: opts?.description ?? previous?.description,
177
+ isolate: opts?.isolate ?? previous?.isolate,
178
+ gc: opts?.gc ?? previous?.gc,
179
+ cpu: opts?.cpu ?? previous?.cpu,
180
+ alloc: opts?.alloc ?? previous?.alloc,
181
+ peakMem: opts?.peakMem ?? previous?.peakMem,
182
+ skip: flags.skip || previous?.skip,
183
+ only: flags.only || previous?.only,
184
+ };
185
+ try {
186
+ fn();
187
+ } finally {
188
+ currentGroup = previous;
189
+ }
190
+ }
191
+
192
+ type GroupRegistrar = (
193
+ name: string,
194
+ fn: () => void,
195
+ opts?: GroupOptions,
196
+ ) => void;
197
+
198
+ interface GroupFn extends GroupRegistrar {
199
+ /**
200
+ * Registers every task inside as skipped: the runner never measures
201
+ * them, but the document still carries their workloads (marked
202
+ * `Workload.skipped`). */
203
+ skip: GroupRegistrar;
204
+ /**
205
+ * When any task or group in the suite uses `.only`, the runner restricts
206
+ * the whole suite file to only those tasks (before `--filter` narrows
207
+ * further) and prints a one-line notice to stderr. */
208
+ only: GroupRegistrar;
209
+ }
210
+
211
+ export const group: GroupFn = Object.assign(
212
+ ((name, fn, opts) => registerGroup(name, fn, opts, {})) as GroupRegistrar,
213
+ {
214
+ skip: ((name, fn, opts) =>
215
+ registerGroup(name, fn, opts, { skip: true })) as GroupRegistrar,
216
+ only: ((name, fn, opts) =>
217
+ registerGroup(name, fn, opts, { only: true })) as GroupRegistrar,
218
+ },
219
+ );
220
+
221
+ function registerTask(
222
+ name: string,
223
+ fn: () => unknown | Promise<unknown>,
224
+ opts: TaskOptions | undefined,
225
+ flags: Flags,
226
+ ): void {
227
+ const params =
228
+ currentParams !== undefined || opts?.params !== undefined
229
+ ? { ...currentParams, ...opts?.params }
230
+ : undefined;
231
+ tasks.push({
232
+ groupName: currentGroup?.path,
233
+ groupChain: currentGroup?.chain,
234
+ groupDescription: currentGroup?.description,
235
+ groupIsolate: currentGroup?.isolate,
236
+ groupGc: currentGroup?.gc,
237
+ groupCpu: currentGroup?.cpu,
238
+ groupAlloc: currentGroup?.alloc,
239
+ groupPeakMem: currentGroup?.peakMem,
240
+ name,
241
+ fn,
242
+ baseline: opts?.baseline,
243
+ params,
244
+ skipped: flags.skip || currentGroup?.skip,
245
+ only: flags.only || currentGroup?.only,
246
+ opts,
247
+ });
248
+ }
249
+
250
+ type TaskRegistrar = (
251
+ name: string,
252
+ fn: () => unknown | Promise<unknown>,
253
+ opts?: TaskOptions,
254
+ ) => void;
255
+
256
+ interface TaskFn extends TaskRegistrar {
257
+ /**
258
+ * Registers the task as skipped: the runner never measures it, but the
259
+ * document still carries its workload (marked `Workload.skipped`) so a
260
+ * renderer or `compare` can say so explicitly instead of the task simply
261
+ * being absent. */
262
+ skip: TaskRegistrar;
263
+ /**
264
+ * When any task or group in the suite uses `.only`, the runner restricts
265
+ * the whole suite file to only those tasks (before `--filter` narrows
266
+ * further) and prints a one-line notice to stderr. */
267
+ only: TaskRegistrar;
268
+ }
269
+
270
+ export const task: TaskFn = Object.assign(
271
+ ((name, fn, opts) => registerTask(name, fn, opts, {})) as TaskRegistrar,
272
+ {
273
+ skip: ((name, fn, opts) =>
274
+ registerTask(name, fn, opts, { skip: true })) as TaskRegistrar,
275
+ only: ((name, fn, opts) =>
276
+ registerTask(name, fn, opts, { only: true })) as TaskRegistrar,
277
+ },
278
+ );
279
+
280
+ export function getRegisteredTasks(): readonly RegisteredTask[] {
281
+ return tasks;
282
+ }
283
+
284
+ export function resetRegistry(): void {
285
+ tasks.length = 0;
286
+ currentGroup = undefined;
287
+ currentParams = undefined;
288
+ }
289
+
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). */
294
+ export function withCurrentParams<T>(
295
+ params: Record<string, string | number | boolean>,
296
+ fn: () => T,
297
+ ): T {
298
+ const previous = currentParams;
299
+ currentParams = params;
300
+ try {
301
+ return fn();
302
+ } finally {
303
+ currentParams = previous;
304
+ }
305
+ }
306
+
307
+ export function taskId(t: RegisteredTask): string {
308
+ return t.groupName ? `${t.groupName}/${t.name}` : t.name;
309
+ }
310
+
311
+ /** `taskId` under each of the task's `aliases`. */
312
+ export function formerTaskIds(t: RegisteredTask): string[] {
313
+ return (t.opts?.aliases ?? []).map((alias) =>
314
+ t.groupName ? `${t.groupName}/${alias}` : alias,
315
+ );
316
+ }
317
+
318
+ // Effective per-task flags: the task's own value, then its group's, then
319
+ // the suite-wide default.
320
+ export function taskIsolate(t: RegisteredTask, suiteIsolate: boolean): boolean {
321
+ return t.opts?.isolate ?? t.groupIsolate ?? suiteIsolate;
322
+ }
323
+
324
+ export function taskGc(t: RegisteredTask, suiteGc: boolean): boolean {
325
+ return t.opts?.gc ?? t.groupGc ?? suiteGc;
326
+ }
327
+
328
+ export function taskCpu(t: RegisteredTask, suiteCpu: boolean): boolean {
329
+ return t.opts?.cpu ?? t.groupCpu ?? suiteCpu;
330
+ }
331
+
332
+ export function taskAlloc(t: RegisteredTask, suiteAlloc: boolean): boolean {
333
+ return t.opts?.alloc ?? t.groupAlloc ?? suiteAlloc;
334
+ }
335
+
336
+ export function taskPeakMem(t: RegisteredTask, suitePeakMem: boolean): boolean {
337
+ return t.opts?.peakMem ?? t.groupPeakMem ?? suitePeakMem;
338
+ }
339
+
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. */
346
+ export function groupEdges(
347
+ tasks: readonly RegisteredTask[],
348
+ ): (index: number) => { enter: string[]; leave: string[] } {
349
+ const first = new Map<string, number>();
350
+ const last = new Map<string, number>();
351
+ tasks.forEach((t, i) => {
352
+ if (t.skipped) return;
353
+ for (const { path } of t.groupChain ?? []) {
354
+ if (!first.has(path)) first.set(path, i);
355
+ last.set(path, i);
356
+ }
357
+ });
358
+ return (i) => {
359
+ const paths = (tasks[i]!.groupChain ?? []).map((f) => f.path);
360
+ return {
361
+ enter: paths.filter((p) => first.get(p) === i),
362
+ leave: paths.filter((p) => last.get(p) === i).reverse(),
363
+ };
364
+ };
365
+ }
366
+
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. */
371
+ export async function runGroupHooks(
372
+ t: RegisteredTask,
373
+ kind: "before" | "after",
374
+ paths?: readonly string[],
375
+ ): Promise<void> {
376
+ const chain = t.groupChain ?? [];
377
+ const order =
378
+ paths ??
379
+ (kind === "before" ? chain : [...chain].reverse()).map((f) => f.path);
380
+ for (const path of order) {
381
+ await chain.find((f) => f.path === path)?.[kind]?.();
382
+ }
383
+ }
384
+
385
+ /**
386
+ * mitata-compatible: filter value is a JS regex source, substring-matched
387
+ * (no anchoring), case-sensitive, against the "group/name" task id. */
388
+ export function filterTasks(
389
+ tasks: readonly RegisteredTask[],
390
+ filter?: string,
391
+ ): RegisteredTask[] {
392
+ if (!filter) return [...tasks];
393
+ const re = new RegExp(filter);
394
+ return tasks.filter((t) => re.test(taskId(t)));
395
+ }
396
+
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. */
402
+ export function selectTasks(
403
+ registered: readonly RegisteredTask[],
404
+ filter: string | undefined,
405
+ where: string,
406
+ // False in the follow-up processes of one run (isolated tasks, peak-memory
407
+ // readings, ab repeats), so the notice prints once per suite file.
408
+ announce = true,
409
+ ): RegisteredTask[] {
410
+ const onlyTasks = registered.filter((t) => t.only);
411
+ const candidates = onlyTasks.length > 0 ? onlyTasks : registered;
412
+ if (announce && onlyTasks.length > 0) {
413
+ process.stderr.write(
414
+ `bench: ${onlyTasks.length} task(s) selected by .only\n`,
415
+ );
416
+ }
417
+ const tasks = filterTasks(candidates, filter);
418
+ if (tasks.length === 0) {
419
+ throw new Error(
420
+ `filter ${JSON.stringify(filter)} matched zero of ${candidates.length} registered task(s) in ${where}.`,
421
+ );
422
+ }
423
+ return tasks;
424
+ }
@@ -0,0 +1,176 @@
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
+ /**
53
+ * Shared by every runner so a task has the same id under `bench()` and
54
+ * `ab()`.
55
+ */
56
+ export function taskWorkload(
57
+ suiteFile: string,
58
+ t: RegisteredTask,
59
+ isolated?: boolean,
60
+ ): Workload {
61
+ const id = taskIdOf(t);
62
+ const formerIds = formerTaskIds(t).map(
63
+ (former) => makeEntryWorkload(suiteFile, former, { params: t.params }).id,
64
+ );
65
+ return makeEntryWorkload(suiteFile, id, {
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,
75
+ });
76
+ }
77
+
78
+ /**
79
+ * Measures exactly `tasks` (already selected by the caller) in this
80
+ * process; isolation is the caller's concern. */
81
+ export async function measureTasks(
82
+ suiteFile: string,
83
+ tasks: readonly RegisteredTask[],
84
+ opts: MeasureTasksOpts,
85
+ ): Promise<ProfileDocument> {
86
+ const willMeasure = tasks.some((t) => !t.skipped);
87
+ const { environment, noiseWarning } = captureRunEnvironment(
88
+ willMeasure ? opts.noiseCheck : false,
89
+ );
90
+ const edges = groupEdges(tasks);
91
+
92
+ const workloads: Workload[] = [];
93
+ const measurements: Measurement[] = [];
94
+ for (let idx = 0; idx < tasks.length; idx++) {
95
+ const t = tasks[idx]!;
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 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,
112
+ gc: taskGc(t, opts.gc ?? false),
113
+ };
114
+ // The heap as of its last GC, never forcing one: a forced GC would
115
+ // change the timing it brackets.
116
+ const heapBefore = heapSize();
117
+ const result = await measureTask(t.fn, taskOpts);
118
+ const heapAfter = heapSize();
119
+ measurements.push(
120
+ makeTimingMeasurement({
121
+ workload,
122
+ heapUsed: { beforeBytes: heapBefore, afterBytes: heapAfter },
123
+ configFingerprint: configFingerprint({
124
+ budgetMs: taskOpts.budgetMs ?? null,
125
+ samples: taskOpts.samples ?? null,
126
+ minSamples: taskOpts.minSamples ?? null,
127
+ gc: taskOpts.gc ?? false,
128
+ }),
129
+ trials: result.trials,
130
+ timing: result.timing,
131
+ instructions: result.instructions,
132
+ warnings:
133
+ noiseWarning && measurements.length === 0
134
+ ? [...result.warnings, noiseWarning]
135
+ : result.warnings,
136
+ }),
137
+ );
138
+
139
+ if (taskCpu(t, opts.cpu ?? false)) {
140
+ const intervalUs = opts.cpuIntervalUs ?? DEFAULT_TASK_CPU_INTERVAL_US;
141
+ const cpuResult = await captureTaskCpuProfile(t.fn, { intervalUs });
142
+ measurements.push(
143
+ makeInstrumentedMeasurement({
144
+ workload,
145
+ phase: "cpu",
146
+ configFingerprint: configFingerprint({ cpu: true, intervalUs }),
147
+ diagnosticWallNs: cpuResult.diagnosticWallNs,
148
+ cpu: cpuResult.cpu,
149
+ jit: cpuResult.jit,
150
+ warnings: cpuResult.warnings,
151
+ artifacts: [],
152
+ }),
153
+ );
154
+ }
155
+ if (taskAlloc(t, opts.alloc ?? false)) {
156
+ const allocResult = await measureAllocPerOp(t.fn);
157
+ measurements.push(
158
+ makeInstrumentedMeasurement({
159
+ workload,
160
+ phase: "memstats",
161
+ configFingerprint: configFingerprint({ alloc: true }),
162
+ diagnosticWallNs: allocResult.diagnosticWallNs,
163
+ memory: allocResult.memory,
164
+ warnings: [],
165
+ artifacts: [],
166
+ }),
167
+ );
168
+ }
169
+
170
+ if (t.opts?.after) await t.opts.after();
171
+ await runGroupHooks(t, "after", leave);
172
+ }
173
+
174
+ stampDrift(environment);
175
+ return createDocument(workloads, measurements, environment);
176
+ }
@@ -0,0 +1,51 @@
1
+ import type { ProfileDocument } from "../ir/types.ts";
2
+ import { renderers } from "../renderers/index.ts";
3
+ import type { FormatName } from "../renderers/types.ts";
4
+ import {
5
+ getRegisteredTasks,
6
+ type RegisteredTask,
7
+ selectTasks,
8
+ } from "./registry.ts";
9
+ import { measureTasks, type MeasureTasksOpts } from "./run-tasks.ts";
10
+
11
+ export interface RunOptions extends MeasureTasksOpts {
12
+ /** Regex matched against "group/name" task ids, as in `bench({ filter })`. */
13
+ filter?: string;
14
+ /** Skip printing the report to stdout; still returns the document. */
15
+ quiet?: boolean;
16
+ /** Renderer used for the printed report (default: `"table"`). */
17
+ format?: FormatName;
18
+ }
19
+
20
+ /** In-file entrypoint: call at the bottom of a suite file run directly with
21
+ * `bun suite.ts` to measure every registered `group()`/`task()`, print a
22
+ * report, and return the document.
23
+ *
24
+ * Everything runs in the current process, so `TaskOptions.isolate` is
25
+ * ignored. Prefer `ostia bench`/`bench()` for numbers you'll
26
+ * `compare`/`ci` against. */
27
+ export async function run(opts: RunOptions = {}): Promise<ProfileDocument> {
28
+ const registered = getRegisteredTasks();
29
+ if (registered.length === 0) {
30
+ throw new Error(
31
+ "run(): no tasks registered - call group()/task() before run() in the same file.",
32
+ );
33
+ }
34
+
35
+ const suiteFile = Bun.main;
36
+ let tasks: RegisteredTask[];
37
+ try {
38
+ tasks = selectTasks(registered, opts.filter, suiteFile);
39
+ } catch (err) {
40
+ throw new Error(`run(): ${(err as Error).message}`, { cause: err });
41
+ }
42
+ const doc = await measureTasks(suiteFile, tasks, opts);
43
+
44
+ if (!opts.quiet) {
45
+ const format = opts.format ?? "table";
46
+ const { text } = await renderers[format].render(doc, {});
47
+ if (text) process.stdout.write(text);
48
+ }
49
+
50
+ return doc;
51
+ }