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,69 @@
1
+ import { measureConfigWorkloads } from "../ci/index.ts";
2
+ import { baselinePath, type OstiaConfig } from "../config/index.ts";
3
+ import { createDocument, loadDocument, saveDocument } from "../ir/document.ts";
4
+ import type { GitMetadata } from "../ir/types.ts";
5
+
6
+ // Writes to `<baselineDir>/<name>.json` (default `config.baseline`).
7
+ // Always measures fresh: a baseline never holds a cached `ci` run.
8
+ export async function saveBaseline(
9
+ config: OstiaConfig,
10
+ name?: string,
11
+ ): Promise<string> {
12
+ const { results: measured, environment } = await measureConfigWorkloads(
13
+ config,
14
+ true,
15
+ );
16
+ const doc = createDocument(
17
+ measured.map((m) => m.workload),
18
+ measured.map((m) => m.run),
19
+ environment,
20
+ );
21
+ const path = baselinePath(config, name);
22
+ await saveDocument(doc, path);
23
+ return path;
24
+ }
25
+
26
+ interface BaselineInfo {
27
+ name: string;
28
+ path: string;
29
+ createdAt: string;
30
+ toolVersion: string;
31
+ bunVersion: string;
32
+ workloads: number;
33
+ git?: GitMetadata;
34
+ }
35
+
36
+ export async function listBaselines(
37
+ config: OstiaConfig,
38
+ ): Promise<BaselineInfo[]> {
39
+ let names: string[];
40
+ try {
41
+ const files = await Array.fromAsync(
42
+ new Bun.Glob("*.json").scan({ cwd: config.baselineDir }),
43
+ );
44
+ names = files.map((file) => file.replace(/\.json$/, "")).sort();
45
+ } catch {
46
+ return [];
47
+ }
48
+
49
+ const infos = await Promise.all(
50
+ names.map(async (name): Promise<BaselineInfo | undefined> => {
51
+ const path = baselinePath(config, name);
52
+ try {
53
+ const doc = await loadDocument(path);
54
+ return {
55
+ name,
56
+ path,
57
+ createdAt: doc.createdAt,
58
+ toolVersion: doc.toolVersion,
59
+ bunVersion: doc.bunVersion,
60
+ workloads: doc.workloads.length,
61
+ ...(doc.git !== undefined && { git: doc.git }),
62
+ };
63
+ } catch {
64
+ return undefined;
65
+ }
66
+ }),
67
+ );
68
+ return infos.filter((info) => info !== undefined);
69
+ }
@@ -0,0 +1,516 @@
1
+ import {
2
+ type BenchConfig,
3
+ type BenchProject,
4
+ DEFAULT_OUT_DIR,
5
+ } from "../config/index.ts";
6
+ import { scanGlobs } from "../glob.ts";
7
+ import {
8
+ configFingerprint,
9
+ createDocument,
10
+ makeInstrumentedMeasurement,
11
+ } from "../ir/document.ts";
12
+ import { fp } from "../ir/fp.ts";
13
+ import type { Measurement, ProfileDocument, Workload } from "../ir/types.ts";
14
+ import { stampDrift } from "../measure/environment.ts";
15
+ import type { PeakMemResult } from "../measure/peak.ts";
16
+ import { assertSamplingOptions } from "../measure/timing.ts";
17
+ import { type SuiteLaunch, suiteLauncher } from "./projects.ts";
18
+ import type { RunnerOpts } from "./runner.ts";
19
+ import {
20
+ absolutePath,
21
+ assertSuiteExists,
22
+ captureRunEnvironment,
23
+ loadIfExists,
24
+ median,
25
+ PEAK_MEM_PROCESSES,
26
+ peakHiddenWarning,
27
+ removeDir,
28
+ runRunnerProcess,
29
+ stampRunWarnings,
30
+ uniqueTmpDir,
31
+ } from "./support.ts";
32
+
33
+ export interface BenchOptions {
34
+ suites: string[];
35
+ /** Wall-clock sampling budget per task, ms (default 500). */
36
+ budgetMs?: number;
37
+ /** Exact trial count per task; the budget is ignored when set. */
38
+ samples?: number;
39
+ minSamples?: number;
40
+ gc?: boolean;
41
+ /**
42
+ * Capture one extra `phase: "cpu"` measurement per task (the task looped
43
+ * under the JSC sampling profiler for ~2,000 samples, JIT tiers included),
44
+ * never mixed into the timing numbers. Task/group `cpu` overrides this. */
45
+ cpu?: boolean;
46
+ /**
47
+ * `cpu`'s sampling interval, µs (default: 100). A coarser interval
48
+ * lengthens the capture to keep the sample count, up to 10s per task. */
49
+ cpuIntervalUs?: number;
50
+ /**
51
+ * Capture one extra `phase: "memstats"` measurement per task: retained
52
+ * heap growth per call, from a batch with `Bun.gc(true)` on both sides.
53
+ * What the calls keep alive, not what they allocate. Task/group `alloc`
54
+ * overrides this. */
55
+ alloc?: boolean;
56
+ /**
57
+ * Capture one extra `phase: "memstats"` measurement per task: how far the
58
+ * task's first call raises RSS, garbage included. Median of 3 fresh
59
+ * processes, each run with `OSTIA_PEAK_MEM=1` in its environment (see
60
+ * `measurePeakMem`). Task/group `peakMem` overrides this. */
61
+ peakMem?: boolean;
62
+ filter?: string;
63
+ /**
64
+ * Suite files (or isolated tasks) to run at once, each in its own child
65
+ * process (default: 1). Concurrent CPU-bound processes contend for cores,
66
+ * caches and turbo headroom, so timings under `jobs > 1` are noisier and
67
+ * not like-for-like with a baseline measured at 1. */
68
+ jobs?: number;
69
+ outDir?: string;
70
+ cwd?: string;
71
+ /**
72
+ * Give every task its own subprocess instead of sharing its suite file's,
73
+ * isolating JIT tier state, inline caches and heap shape between tasks.
74
+ * Task/group `isolate` overrides this. Multiplies spawn overhead by task
75
+ * count instead of file count. */
76
+ isolate?: boolean;
77
+ /**
78
+ * Scripts run, in order, before each suite file loads, in the same
79
+ * subprocess: install globals (jsdom) or a `Bun.plugin()` loader ahead of
80
+ * the suite's top-level code. */
81
+ preload?: string[];
82
+ /**
83
+ * Extra flags for the `bun` invocation that runs each suite file (e.g.
84
+ * `["--conditions", "browser"]`), placed before the runner script path. */
85
+ bunFlags?: string[];
86
+ /**
87
+ * Per-suite `preload` / `bunFlags`: the first project whose `suites` globs
88
+ * match a suite file (by its path relative to `cwd`) replaces those two
89
+ * fields for that file, so suites that need no setup don't pay for the
90
+ * others'. A field a project leaves unset keeps the top-level value above;
91
+ * `[]` clears it. */
92
+ projects?: BenchProject[];
93
+ /**
94
+ * Measure this machine's noise floor once, before any suite runs
95
+ * (default: true), and stamp it on the document as `environment`. */
96
+ noiseCheck?: boolean;
97
+ /**
98
+ * SIGKILLs a suite file's subprocess (or, under `isolate`, one task's)
99
+ * that hasn't finished after this many ms. No default. */
100
+ timeoutMs?: number;
101
+ /**
102
+ * Aborting kills in-flight subprocesses, starts no new ones, and resolves
103
+ * (never rejects) with whatever suites/tasks had finished, plus an
104
+ * `aborted` warning on the last measurement. A suite killed mid-run is
105
+ * dropped entirely: it only writes its result once, at the end. */
106
+ signal?: AbortSignal;
107
+ }
108
+
109
+ const RUNNER_PATH = new URL("./runner.ts", import.meta.url).pathname;
110
+
111
+ export function availableJobs(): number {
112
+ return Math.max(1, navigator.hardwareConcurrency || 1);
113
+ }
114
+
115
+ /**
116
+ * The subset of `ostia bench`'s CLI flags that have a config-file
117
+ * counterpart in `BenchConfig`. */
118
+ export interface BenchCliOverrides {
119
+ suites: string[];
120
+ budgetMs?: number;
121
+ samples?: number;
122
+ minSamples?: number;
123
+ jobs?: number;
124
+ gc?: boolean;
125
+ cpu?: boolean;
126
+ cpuIntervalUs?: number;
127
+ alloc?: boolean;
128
+ peakMem?: boolean;
129
+ filter?: string;
130
+ isolate?: boolean;
131
+ preload: string[];
132
+ bunFlags: string[];
133
+ outDir?: string;
134
+ noiseCheck: boolean;
135
+ timeoutMs?: number;
136
+ }
137
+
138
+ // A CLI value wins per field, then the config's, then `bench()`'s own
139
+ // defaults (left undefined). `suites`, `preload` and `bunFlags` are
140
+ // replaced wholesale, never merged. With no CLI suites, the files to run
141
+ // are the config's `suites` plus whatever its `projects` match. A CLI
142
+ // `preload` / `bunFlags` also replaces that field in every project.
143
+ export async function resolveBenchOptions(
144
+ cli: BenchCliOverrides,
145
+ config: BenchConfig | undefined,
146
+ cwd: string = process.cwd(),
147
+ ): Promise<BenchOptions> {
148
+ const globs = [
149
+ ...(config?.suites ?? []),
150
+ ...(config?.projects?.flatMap((p) => p.suites) ?? []),
151
+ ];
152
+ const suites =
153
+ cli.suites.length > 0
154
+ ? cli.suites
155
+ : globs.length > 0
156
+ ? await scanGlobs(globs, cwd)
157
+ : [];
158
+
159
+ const budgetMs = cli.budgetMs ?? config?.budgetMs;
160
+ const samples = cli.samples ?? config?.samples;
161
+ const minSamples = cli.minSamples ?? config?.minSamples;
162
+ const jobs =
163
+ cli.jobs ?? (config?.jobs === "auto" ? availableJobs() : config?.jobs);
164
+ const cpuIntervalUs = cli.cpuIntervalUs ?? config?.cpuIntervalUs;
165
+ const filter = cli.filter ?? config?.filter;
166
+ const projects = config?.projects?.map(
167
+ ({ preload, bunFlags, ...project }) => ({
168
+ ...project,
169
+ ...(cli.preload.length === 0 && preload !== undefined && { preload }),
170
+ ...(cli.bunFlags.length === 0 && bunFlags !== undefined && { bunFlags }),
171
+ }),
172
+ );
173
+ const outDir = cli.outDir ?? config?.outDir;
174
+ const timeoutMs = cli.timeoutMs ?? config?.timeoutMs;
175
+ return {
176
+ suites,
177
+ ...(budgetMs !== undefined && { budgetMs }),
178
+ ...(samples !== undefined && { samples }),
179
+ ...(minSamples !== undefined && { minSamples }),
180
+ ...(jobs !== undefined && { jobs }),
181
+ gc: cli.gc ?? config?.gc ?? false,
182
+ cpu: cli.cpu ?? config?.cpu ?? false,
183
+ ...(cpuIntervalUs !== undefined && { cpuIntervalUs }),
184
+ alloc: cli.alloc ?? config?.alloc ?? false,
185
+ peakMem: cli.peakMem ?? config?.peakMem ?? false,
186
+ ...(filter !== undefined && { filter }),
187
+ isolate: cli.isolate ?? config?.isolate ?? false,
188
+ preload: cli.preload.length > 0 ? cli.preload : (config?.preload ?? []),
189
+ bunFlags: cli.bunFlags.length > 0 ? cli.bunFlags : (config?.bunFlags ?? []),
190
+ ...(projects !== undefined && { projects }),
191
+ ...(outDir !== undefined && { outDir }),
192
+ noiseCheck: cli.noiseCheck,
193
+ ...(timeoutMs !== undefined && { timeoutMs }),
194
+ cwd,
195
+ };
196
+ }
197
+
198
+ interface PlannedTask {
199
+ workloadId: string;
200
+ isolate: boolean;
201
+ peakMem: boolean;
202
+ }
203
+
204
+ function peakMeasurement(
205
+ workload: Workload,
206
+ readings: PeakMemResult[] | undefined,
207
+ ): Measurement[] {
208
+ if (!readings?.length) return [];
209
+ const peak = median(readings.map((r) => r.peakBytes));
210
+ const warning = peakHiddenWarning(readings);
211
+ return [
212
+ makeInstrumentedMeasurement({
213
+ workload,
214
+ phase: "memstats",
215
+ configFingerprint: configFingerprint({ peakMem: true }),
216
+ diagnosticWallNs: median(readings.map((r) => r.wallNs)),
217
+ memory: { origin: "resourceUsage", kind: "peak", peakBytes: peak },
218
+ warnings: warning ? [warning] : [],
219
+ artifacts: [],
220
+ }),
221
+ ];
222
+ }
223
+
224
+ interface Suite extends SuiteLaunch {
225
+ // As the caller wrote it, for messages.
226
+ given: string;
227
+ path: string;
228
+ }
229
+
230
+ interface RunnerJob {
231
+ suite: Suite;
232
+ outPath: string;
233
+ runnerOpts: RunnerOpts;
234
+ }
235
+
236
+ function isPlan(value: unknown): value is { tasks: PlannedTask[] } {
237
+ return (
238
+ typeof value === "object" &&
239
+ value !== null &&
240
+ "tasks" in value &&
241
+ Array.isArray(value.tasks)
242
+ );
243
+ }
244
+
245
+ function isPeakMemResult(value: unknown): value is PeakMemResult {
246
+ return (
247
+ typeof value === "object" &&
248
+ value !== null &&
249
+ "peakBytes" in value &&
250
+ typeof value.peakBytes === "number"
251
+ );
252
+ }
253
+
254
+ /** Measures the tasks each of `suites` registers, one subprocess per file. */
255
+ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
256
+ assertSamplingOptions("bench", opts);
257
+ const jobs = opts.jobs ?? 1;
258
+ if (!Number.isInteger(jobs) || jobs < 1) {
259
+ throw new RangeError(`bench: jobs must be an integer >= 1, got ${jobs}`);
260
+ }
261
+
262
+ const cwd = opts.cwd ?? process.cwd();
263
+ // Resolved against `cwd` because the runner subprocesses write there;
264
+ // this process's own cwd may differ.
265
+ const tmpDir = uniqueTmpDir(
266
+ absolutePath(cwd, opts.outDir ?? DEFAULT_OUT_DIR),
267
+ "bench",
268
+ );
269
+ for (const given of opts.suites) {
270
+ assertSuiteExists(given, absolutePath(cwd, given));
271
+ }
272
+ const launch = suiteLauncher(cwd, opts, opts.projects);
273
+ const suites = opts.suites.map((given): Suite => {
274
+ const path = absolutePath(cwd, given);
275
+ return { given, path, ...launch(path) };
276
+ });
277
+ const { environment, noiseWarning } = captureRunEnvironment(opts.noiseCheck);
278
+
279
+ const measureOpts: RunnerOpts = {
280
+ ...(opts.budgetMs !== undefined && { budgetMs: opts.budgetMs }),
281
+ ...(opts.samples !== undefined && { samples: opts.samples }),
282
+ ...(opts.minSamples !== undefined && { minSamples: opts.minSamples }),
283
+ ...(opts.gc !== undefined && { gc: opts.gc }),
284
+ ...(opts.cpu !== undefined && { cpu: opts.cpu }),
285
+ ...(opts.cpuIntervalUs !== undefined && {
286
+ cpuIntervalUs: opts.cpuIntervalUs,
287
+ }),
288
+ ...(opts.alloc !== undefined && { alloc: opts.alloc }),
289
+ ...(opts.peakMem !== undefined && { peakMem: opts.peakMem }),
290
+ // Measured once here: every runner repeating the ~200ms reference
291
+ // measurement only to have all but the first discarded cost seconds.
292
+ noiseCheck: false,
293
+ };
294
+ const filter = opts.filter !== undefined && { filter: opts.filter };
295
+
296
+ const outPath = (tag: string, suite: Suite, ...rest: unknown[]) =>
297
+ `${tmpDir}/${fp(tag, suite.path, ...rest)}.json`;
298
+
299
+ // `jobs` workers pull from a shared cursor. The first failure stops the
300
+ // pool: queued jobs are skipped and in-flight children killed, so a broken
301
+ // suite fails the run fast.
302
+ const runPool = async (
303
+ list: RunnerJob[],
304
+ env?: Record<string, string>,
305
+ ): Promise<void> => {
306
+ const inFlight = new Set<Bun.Subprocess>();
307
+ let next = 0;
308
+ let failure: Error | undefined;
309
+
310
+ const worker = async (): Promise<void> => {
311
+ while (failure === undefined && !opts.signal?.aborted) {
312
+ const job = list[next++];
313
+ if (job === undefined) return;
314
+ try {
315
+ const ran = await runRunnerProcess(
316
+ [
317
+ "bun",
318
+ ...job.suite.bunFlags,
319
+ RUNNER_PATH,
320
+ job.suite.path,
321
+ job.outPath,
322
+ JSON.stringify(job.runnerOpts),
323
+ ],
324
+ {
325
+ label: "Bench suite",
326
+ name: job.suite.given,
327
+ cwd,
328
+ env,
329
+ timeoutMs: opts.timeoutMs,
330
+ signal: opts.signal,
331
+ inFlight,
332
+ },
333
+ );
334
+ if (!ran) return;
335
+ } catch (err) {
336
+ failure ??= err instanceof Error ? err : new Error(String(err));
337
+ for (const proc of inFlight) proc.kill();
338
+ }
339
+ }
340
+ };
341
+
342
+ await Promise.all(
343
+ Array.from({ length: Math.min(jobs, list.length) }, worker),
344
+ );
345
+ if (failure) throw failure;
346
+ };
347
+
348
+ try {
349
+ // Phase 1: import each suite once. The same process records the plan
350
+ // (each task's effective isolate/peakMem) and runs the non-isolated
351
+ // tasks, so module-scope setup never runs twice just to learn the plan.
352
+ const primaries = suites.map((suite) => ({
353
+ suite,
354
+ planPath: outPath("bench-plan", suite),
355
+ outPath: outPath("bench-primary", suite),
356
+ }));
357
+ await runPool(
358
+ primaries.map((p) => ({
359
+ suite: p.suite,
360
+ outPath: p.outPath,
361
+ runnerOpts: {
362
+ ...measureOpts,
363
+ ...filter,
364
+ ...(opts.isolate !== undefined && { isolate: opts.isolate }),
365
+ preload: p.suite.preload,
366
+ planPath: p.planPath,
367
+ },
368
+ })),
369
+ );
370
+
371
+ // A suite killed mid-run wrote neither file, so it contributes no tasks.
372
+ const planTasks = await Promise.all(
373
+ primaries.map(async (p): Promise<PlannedTask[]> => {
374
+ if (!(await Bun.file(p.planPath).exists())) return [];
375
+ const plan: unknown = await Bun.file(p.planPath).json();
376
+ if (!isPlan(plan)) {
377
+ throw new Error(`bench: unreadable plan for ${p.suite.given}`);
378
+ }
379
+ return plan.tasks;
380
+ }),
381
+ );
382
+ const primaryDocs = await Promise.all(
383
+ primaries.map((p) => loadIfExists(p.outPath)),
384
+ );
385
+ const plans = primaries.map((p, i) => ({
386
+ suite: p.suite,
387
+ tasks: planTasks[i] ?? [],
388
+ doc: primaryDocs[i],
389
+ }));
390
+
391
+ // Phase 2: each isolated task in its own subprocess, so its JIT state
392
+ // and heap are its own.
393
+ const isolated = plans
394
+ .flatMap(({ suite, tasks }) =>
395
+ tasks.filter((task) => task.isolate).map((task) => ({ task, suite })),
396
+ )
397
+ .map((item, i) => ({
398
+ ...item,
399
+ outPath: outPath("bench-item", item.suite, i),
400
+ }));
401
+ await runPool(
402
+ isolated.map((item) => ({
403
+ suite: item.suite,
404
+ outPath: item.outPath,
405
+ runnerOpts: {
406
+ ...measureOpts,
407
+ workloadIds: [item.task.workloadId],
408
+ preload: item.suite.preload,
409
+ markIsolated: true,
410
+ },
411
+ })),
412
+ );
413
+ const isolatedDocs = new Map<PlannedTask, ProfileDocument>();
414
+ await Promise.all(
415
+ isolated.map(async (item) => {
416
+ const doc = await loadIfExists(item.outPath);
417
+ if (doc) isolatedDocs.set(item.task, doc);
418
+ }),
419
+ );
420
+
421
+ // Phase 3: each `peakMem` task's first call, alone in a fresh process,
422
+ // since memory an earlier call freed would hide part of its peak.
423
+ const peakRuns = plans
424
+ .flatMap(({ suite, tasks }) =>
425
+ tasks
426
+ .filter((task) => task.peakMem)
427
+ .flatMap((task) =>
428
+ Array.from({ length: PEAK_MEM_PROCESSES }, () => ({
429
+ workloadId: task.workloadId,
430
+ suite,
431
+ })),
432
+ ),
433
+ )
434
+ .map((run, i) => ({
435
+ ...run,
436
+ outPath: outPath("bench-peak", run.suite, i),
437
+ }));
438
+ await runPool(
439
+ peakRuns.map((run) => ({
440
+ suite: run.suite,
441
+ outPath: run.outPath,
442
+ runnerOpts: {
443
+ ...filter,
444
+ preload: run.suite.preload,
445
+ peakMemFor: run.workloadId,
446
+ },
447
+ })),
448
+ // Lets a suite skip heavy module-scope work that would peak before the
449
+ // measured call does.
450
+ { OSTIA_PEAK_MEM: "1" },
451
+ );
452
+ const peakReadings = new Map<string, PeakMemResult[]>();
453
+ for (const run of peakRuns) {
454
+ const file = Bun.file(run.outPath);
455
+ if (!(await file.exists())) continue;
456
+ const reading: unknown = await file.json();
457
+ if (!isPeakMemResult(reading)) {
458
+ throw new Error(
459
+ `bench: unreadable peak-memory reading: ${run.outPath}`,
460
+ );
461
+ }
462
+ const readings = peakReadings.get(run.workloadId) ?? [];
463
+ readings.push(reading);
464
+ peakReadings.set(run.workloadId, readings);
465
+ }
466
+
467
+ // Plan order (registration order, filtered) within a suite, suites in
468
+ // command-line order. Measurements are matched by workload id, not
469
+ // position, because a task.skip()'d task has a workload but no
470
+ // measurement.
471
+ const workloads: Workload[] = [];
472
+ const measurements: Measurement[] = [];
473
+ for (const { suite, tasks, doc: sharedDoc } of plans) {
474
+ // A cancelled suite wrote nothing and is absent, not empty.
475
+ if (!sharedDoc) continue;
476
+ const sharedByWorkload = Map.groupBy(
477
+ sharedDoc.measurements,
478
+ (m) => m.workloadId,
479
+ );
480
+ const sharedWorkloads = sharedDoc.workloads.values();
481
+ for (const task of tasks) {
482
+ const doc = task.isolate ? isolatedDocs.get(task) : sharedDoc;
483
+ // Cancelled before its subprocess finished: drop just this task.
484
+ if (!doc) continue;
485
+ const workload = task.isolate
486
+ ? doc.workloads[0]
487
+ : sharedWorkloads.next().value;
488
+ if (workload === undefined) {
489
+ throw new Error(
490
+ `bench: ${suite.given} wrote fewer workloads than its plan`,
491
+ );
492
+ }
493
+ const own = task.isolate
494
+ ? doc.measurements.filter((m) => m.workloadId === workload.id)
495
+ : (sharedByWorkload.get(workload.id) ?? []);
496
+ workloads.push(workload);
497
+ measurements.push(
498
+ ...own,
499
+ ...peakMeasurement(workload, peakReadings.get(workload.id)),
500
+ );
501
+ }
502
+ }
503
+
504
+ stampRunWarnings(
505
+ measurements,
506
+ noiseWarning,
507
+ opts.signal?.aborted
508
+ ? "Run was cancelled before it finished; this document holds whatever suites/tasks had already completed."
509
+ : undefined,
510
+ );
511
+ stampDrift(environment);
512
+ return createDocument(workloads, measurements, environment);
513
+ } finally {
514
+ await removeDir(tmpDir);
515
+ }
516
+ }
@@ -0,0 +1,43 @@
1
+ import { relative } from "node:path";
2
+
3
+ import type { BenchProject } from "../config/index.ts";
4
+ import { absolutePath } from "./support.ts";
5
+
6
+ export interface SuiteLaunch {
7
+ /** Absolute paths, imported in order before the suite file. */
8
+ preload: string[];
9
+ bunFlags: string[];
10
+ }
11
+
12
+ export function suiteLauncher(
13
+ cwd: string,
14
+ base: { preload?: string[]; bunFlags?: string[] },
15
+ projects: BenchProject[] = [],
16
+ ): (file: string) => SuiteLaunch {
17
+ const matchers = projects.map((project) =>
18
+ project.suites.map((pattern) => new Bun.Glob(pattern)),
19
+ );
20
+ return (file) => {
21
+ const rel = relative(cwd, absolutePath(cwd, file));
22
+ const index = matchers.findIndex((globs) =>
23
+ globs.some((g) => g.match(rel)),
24
+ );
25
+ const project = index < 0 ? undefined : projects[index];
26
+ return {
27
+ preload: (project?.preload ?? base.preload ?? []).map((p) =>
28
+ absolutePath(cwd, p),
29
+ ),
30
+ bunFlags: project?.bunFlags ?? base.bunFlags ?? [],
31
+ };
32
+ };
33
+ }
34
+
35
+ export function resolveSuiteLaunches(
36
+ suites: string[],
37
+ cwd: string,
38
+ base: { preload?: string[]; bunFlags?: string[] },
39
+ projects: BenchProject[] = [],
40
+ ): SuiteLaunch[] {
41
+ const launch = suiteLauncher(cwd, base, projects);
42
+ return suites.map((file) => launch(file));
43
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Geometric sweep points from `start` to `end`, growing by `multiplier`
3
+ * each step and always ending on `end` even if the last step overshot it.
4
+ * Mirrors mitata's `.range(name, start, end, multiplier)` point generation
5
+ * exactly, minus the name templating - build the task name yourself in the
6
+ * loop:
7
+ *
8
+ * for (const size of range(100, 10_000)) {
9
+ * const input = buildInput(size)
10
+ * task(`${size} items`, () => parse(input))
11
+ * }
12
+ *
13
+ * range(100, 10_000) -> [100, 800, 6400, 10000]
14
+ * range(100, 100_000) -> [100, 800, 6400, 51200, 100000]
15
+ */
16
+ export function range(start: number, end: number, multiplier = 8): number[] {
17
+ if (multiplier <= 1) {
18
+ throw new RangeError(`range: multiplier must be > 1, got ${multiplier}`);
19
+ }
20
+ if (start <= 0) {
21
+ throw new RangeError(`range: start must be > 0, got ${start}`);
22
+ }
23
+ const points: number[] = [];
24
+ for (let v = start; v <= end; v *= multiplier) points.push(v);
25
+ if (!points.includes(end)) points.push(end);
26
+ return points;
27
+ }