ostia 0.2.11 → 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 -353
  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 +942 -642
  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-scvezzm9.js → src/cli/help.ts} +31 -15
  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-5m601yfv.js +0 -15
  89. package/chunk-82vs1rw1.js +0 -2
  90. package/chunk-dvqggjkn.js +0 -14
  91. package/chunk-fc36fd0b.js +0 -3
  92. package/chunk-pdv5zb3w.js +0 -27
  93. package/chunk-r6hwb84z.js +0 -25
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,75 @@
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
+ /**
7
+ * Measures every configured workload and writes it to
8
+ * `<baselineDir>/<name>.json` (default `config.baseline`); returns the
9
+ * path. Always measures fresh: a baseline never holds a cached `ci` run.
10
+ * */
11
+ export async function saveBaseline(
12
+ config: OstiaConfig,
13
+ name?: string,
14
+ ): Promise<string> {
15
+ const { results: measured, environment } = await measureConfigWorkloads(
16
+ config,
17
+ true,
18
+ );
19
+ const doc = createDocument(
20
+ measured.map((m) => m.workload),
21
+ measured.map((m) => m.run),
22
+ environment,
23
+ );
24
+ const path = baselinePath(config, name);
25
+ await saveDocument(doc, path);
26
+ return path;
27
+ }
28
+
29
+ export interface BaselineInfo {
30
+ name: string;
31
+ path: string;
32
+ createdAt: string;
33
+ toolVersion: string;
34
+ bunVersion: string;
35
+ workloads: number;
36
+ git?: GitMetadata;
37
+ }
38
+
39
+ /**
40
+ * Every `<baselineDir>/*.json` that parses as a `ProfileDocument`, sorted
41
+ * by name. A missing `baselineDir` yields an empty list. */
42
+ export async function listBaselines(
43
+ config: OstiaConfig,
44
+ ): Promise<BaselineInfo[]> {
45
+ let names: string[];
46
+ try {
47
+ const files = await Array.fromAsync(
48
+ new Bun.Glob("*.json").scan({ cwd: config.baselineDir }),
49
+ );
50
+ names = files.map((file) => file.replace(/\.json$/, "")).sort();
51
+ } catch {
52
+ return [];
53
+ }
54
+
55
+ const infos = await Promise.all(
56
+ names.map(async (name): Promise<BaselineInfo | undefined> => {
57
+ const path = baselinePath(config, name);
58
+ try {
59
+ const doc = await loadDocument(path);
60
+ return {
61
+ name,
62
+ path,
63
+ createdAt: doc.createdAt,
64
+ toolVersion: doc.toolVersion,
65
+ bunVersion: doc.bunVersion,
66
+ workloads: doc.workloads.length,
67
+ ...(doc.git !== undefined && { git: doc.git }),
68
+ };
69
+ } catch {
70
+ return undefined;
71
+ }
72
+ }),
73
+ );
74
+ return infos.filter((info) => info !== undefined);
75
+ }
@@ -0,0 +1,462 @@
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 { resolveSuiteLaunches } 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
+ /** Logical CPUs available to this process, for `--jobs auto`. */
112
+ export function availableJobs(): number {
113
+ return Math.max(1, navigator.hardwareConcurrency || 1);
114
+ }
115
+
116
+ /**
117
+ * The subset of `ostia bench`'s CLI flags that have a config-file
118
+ * counterpart in `BenchConfig`. */
119
+ export interface BenchCliOverrides {
120
+ suites: string[];
121
+ budgetMs?: number;
122
+ samples?: number;
123
+ minSamples?: number;
124
+ jobs?: number;
125
+ gc?: boolean;
126
+ cpu?: boolean;
127
+ cpuIntervalUs?: number;
128
+ alloc?: boolean;
129
+ peakMem?: boolean;
130
+ filter?: string;
131
+ isolate?: boolean;
132
+ preload: string[];
133
+ bunFlags: string[];
134
+ outDir?: string;
135
+ noiseCheck: boolean;
136
+ timeoutMs?: number;
137
+ }
138
+
139
+ /**
140
+ * Merges CLI flags with `ostia.config.json`'s `bench` section: a CLI value
141
+ * wins per field, then the config's, then `bench()`'s own defaults (left
142
+ * undefined). `suites`, `preload` and `bunFlags` are replaced wholesale,
143
+ * not merged. With no CLI suites, the files to run are the config's
144
+ * `suites` plus whatever its `projects` match. A CLI `preload` /
145
+ * `bunFlags` also replaces that field in every project. */
146
+ export async function resolveBenchOptions(
147
+ cli: BenchCliOverrides,
148
+ config: BenchConfig | undefined,
149
+ cwd: string = process.cwd(),
150
+ ): Promise<BenchOptions> {
151
+ const globs = [
152
+ ...(config?.suites ?? []),
153
+ ...(config?.projects?.flatMap((p) => p.suites) ?? []),
154
+ ];
155
+ const suites =
156
+ cli.suites.length > 0
157
+ ? cli.suites
158
+ : globs.length > 0
159
+ ? await scanGlobs(globs, cwd)
160
+ : [];
161
+
162
+ return {
163
+ suites,
164
+ budgetMs: cli.budgetMs ?? config?.budgetMs,
165
+ samples: cli.samples ?? config?.samples,
166
+ minSamples: cli.minSamples ?? config?.minSamples,
167
+ jobs:
168
+ cli.jobs ?? (config?.jobs === "auto" ? availableJobs() : config?.jobs),
169
+ gc: cli.gc ?? config?.gc ?? false,
170
+ cpu: cli.cpu ?? config?.cpu ?? false,
171
+ cpuIntervalUs: cli.cpuIntervalUs ?? config?.cpuIntervalUs,
172
+ alloc: cli.alloc ?? config?.alloc ?? false,
173
+ peakMem: cli.peakMem ?? config?.peakMem ?? false,
174
+ filter: cli.filter ?? config?.filter,
175
+ isolate: cli.isolate ?? config?.isolate ?? false,
176
+ preload: cli.preload.length > 0 ? cli.preload : (config?.preload ?? []),
177
+ bunFlags: cli.bunFlags.length > 0 ? cli.bunFlags : (config?.bunFlags ?? []),
178
+ projects: config?.projects?.map((project) => ({
179
+ ...project,
180
+ ...(cli.preload.length > 0 && { preload: undefined }),
181
+ ...(cli.bunFlags.length > 0 && { bunFlags: undefined }),
182
+ })),
183
+ outDir: cli.outDir ?? config?.outDir,
184
+ noiseCheck: cli.noiseCheck,
185
+ timeoutMs: cli.timeoutMs ?? config?.timeoutMs,
186
+ cwd,
187
+ };
188
+ }
189
+
190
+ interface PlannedTask {
191
+ workloadId: string;
192
+ isolate: boolean;
193
+ peakMem: boolean;
194
+ }
195
+
196
+ function peakMeasurement(
197
+ workload: Workload,
198
+ readings: PeakMemResult[] | undefined,
199
+ ): Measurement[] {
200
+ if (!readings?.length) return [];
201
+ const peak = median(readings.map((r) => r.peakBytes));
202
+ const warning = peakHiddenWarning(readings);
203
+ return [
204
+ makeInstrumentedMeasurement({
205
+ workload,
206
+ phase: "memstats",
207
+ configFingerprint: configFingerprint({ peakMem: true }),
208
+ diagnosticWallNs: median(readings.map((r) => r.wallNs)),
209
+ memory: { origin: "resourceUsage", kind: "peak", peakBytes: peak },
210
+ warnings: warning ? [warning] : [],
211
+ artifacts: [],
212
+ }),
213
+ ];
214
+ }
215
+
216
+ interface RunnerJob {
217
+ suiteIndex: number;
218
+ outPath: string;
219
+ runnerOpts: RunnerOpts;
220
+ }
221
+
222
+ export async function bench(opts: BenchOptions): Promise<ProfileDocument> {
223
+ assertSamplingOptions("bench", opts);
224
+ const jobs = opts.jobs ?? 1;
225
+ if (!Number.isInteger(jobs) || jobs < 1) {
226
+ throw new RangeError(`bench: jobs must be an integer >= 1, got ${jobs}`);
227
+ }
228
+
229
+ const cwd = opts.cwd ?? process.cwd();
230
+ // Against `cwd`, where the runner subprocesses write, not this process's
231
+ // cwd, where it reads their results back.
232
+ const tmpDir = uniqueTmpDir(
233
+ absolutePath(cwd, opts.outDir ?? DEFAULT_OUT_DIR),
234
+ "bench",
235
+ );
236
+ const suites = opts.suites.map((file) => absolutePath(cwd, file));
237
+ for (const [i, suite] of suites.entries()) {
238
+ assertSuiteExists(opts.suites[i]!, suite);
239
+ }
240
+ const launches = resolveSuiteLaunches(suites, cwd, opts, opts.projects);
241
+ const { environment, noiseWarning } = captureRunEnvironment(opts.noiseCheck);
242
+
243
+ const measureOpts = {
244
+ budgetMs: opts.budgetMs,
245
+ samples: opts.samples,
246
+ minSamples: opts.minSamples,
247
+ gc: opts.gc,
248
+ cpu: opts.cpu,
249
+ cpuIntervalUs: opts.cpuIntervalUs,
250
+ alloc: opts.alloc,
251
+ peakMem: opts.peakMem,
252
+ // Measured once here: every runner repeating the ~200ms reference
253
+ // measurement only to have all but the first discarded cost seconds.
254
+ noiseCheck: false,
255
+ };
256
+
257
+ const outPath = (tag: string, suiteIndex: number, ...rest: unknown[]) =>
258
+ `${tmpDir}/${fp(tag, suites[suiteIndex], ...rest)}.json`;
259
+
260
+ // `jobs` workers pull from a shared cursor. The first failure stops the
261
+ // pool: queued jobs are skipped and in-flight children killed, so a broken
262
+ // suite fails the run fast.
263
+ const runPool = async (
264
+ list: RunnerJob[],
265
+ env?: Record<string, string>,
266
+ ): Promise<void> => {
267
+ const inFlight = new Set<Bun.Subprocess>();
268
+ let next = 0;
269
+ let failure: Error | undefined;
270
+
271
+ const worker = async (): Promise<void> => {
272
+ while (
273
+ failure === undefined &&
274
+ !opts.signal?.aborted &&
275
+ next < list.length
276
+ ) {
277
+ const job = list[next++]!;
278
+ try {
279
+ const ran = await runRunnerProcess(
280
+ [
281
+ "bun",
282
+ ...launches[job.suiteIndex]!.bunFlags,
283
+ RUNNER_PATH,
284
+ suites[job.suiteIndex]!,
285
+ job.outPath,
286
+ JSON.stringify(job.runnerOpts),
287
+ ],
288
+ {
289
+ label: "Bench suite",
290
+ name: opts.suites[job.suiteIndex]!,
291
+ cwd,
292
+ env,
293
+ timeoutMs: opts.timeoutMs,
294
+ signal: opts.signal,
295
+ inFlight,
296
+ },
297
+ );
298
+ if (!ran) return;
299
+ } catch (err) {
300
+ failure ??= err instanceof Error ? err : new Error(String(err));
301
+ for (const proc of inFlight) proc.kill();
302
+ }
303
+ }
304
+ };
305
+
306
+ await Promise.all(
307
+ Array.from({ length: Math.min(jobs, list.length) }, worker),
308
+ );
309
+ if (failure) throw failure;
310
+ };
311
+
312
+ try {
313
+ // Phase 1: import each suite once. The same process records the plan
314
+ // (each task's effective isolate/peakMem) and runs the non-isolated
315
+ // tasks, so module-scope setup never runs twice just to learn the plan.
316
+ const primaries = suites.map((_, i) => ({
317
+ planPath: outPath("bench-plan", i),
318
+ outPath: outPath("bench-primary", i),
319
+ }));
320
+ await runPool(
321
+ primaries.map((p, i) => ({
322
+ suiteIndex: i,
323
+ outPath: p.outPath,
324
+ runnerOpts: {
325
+ ...measureOpts,
326
+ filter: opts.filter,
327
+ isolate: opts.isolate,
328
+ preload: launches[i]!.preload,
329
+ planPath: p.planPath,
330
+ },
331
+ })),
332
+ );
333
+
334
+ // A suite killed mid-run wrote neither file and contributes nothing.
335
+ const plans: PlannedTask[][] = await Promise.all(
336
+ primaries.map(async (p) =>
337
+ (await Bun.file(p.planPath).exists())
338
+ ? ((await Bun.file(p.planPath).json()) as { tasks: PlannedTask[] })
339
+ .tasks
340
+ : [],
341
+ ),
342
+ );
343
+ const primaryDocs = await Promise.all(
344
+ primaries.map((p) => loadIfExists(p.outPath)),
345
+ );
346
+
347
+ // Phase 2: each isolated task in its own subprocess.
348
+ const isolated = plans.flatMap((tasks, suiteIndex) =>
349
+ tasks
350
+ .filter((task) => task.isolate)
351
+ .map((task) => ({ task, suiteIndex })),
352
+ );
353
+ const isolatedPaths = isolated.map((item, i) =>
354
+ outPath("bench-item", item.suiteIndex, i),
355
+ );
356
+ await runPool(
357
+ isolated.map((item, i) => ({
358
+ suiteIndex: item.suiteIndex,
359
+ outPath: isolatedPaths[i]!,
360
+ runnerOpts: {
361
+ ...measureOpts,
362
+ workloadIds: [item.task.workloadId],
363
+ preload: launches[item.suiteIndex]!.preload,
364
+ markIsolated: true,
365
+ },
366
+ })),
367
+ );
368
+ const isolatedDocs = new Map<PlannedTask, ProfileDocument>();
369
+ await Promise.all(
370
+ isolated.map(async (item, i) => {
371
+ const doc = await loadIfExists(isolatedPaths[i]!);
372
+ if (doc) isolatedDocs.set(item.task, doc);
373
+ }),
374
+ );
375
+
376
+ // Phase 3: each `peakMem` task's first call, alone in a fresh process,
377
+ // PEAK_MEM_PROCESSES times.
378
+ const peakRuns = plans.flatMap((tasks, suiteIndex) =>
379
+ tasks
380
+ .filter((task) => task.peakMem)
381
+ .flatMap((task) =>
382
+ Array.from({ length: PEAK_MEM_PROCESSES }, () => ({
383
+ workloadId: task.workloadId,
384
+ suiteIndex,
385
+ })),
386
+ ),
387
+ );
388
+ const peakPaths = peakRuns.map((run, i) =>
389
+ outPath("bench-peak", run.suiteIndex, i),
390
+ );
391
+ await runPool(
392
+ peakRuns.map((run, i) => ({
393
+ suiteIndex: run.suiteIndex,
394
+ outPath: peakPaths[i]!,
395
+ runnerOpts: {
396
+ filter: opts.filter,
397
+ preload: launches[run.suiteIndex]!.preload,
398
+ peakMemFor: run.workloadId,
399
+ },
400
+ })),
401
+ // Lets a suite skip heavy module-scope work that would peak before the
402
+ // measured call does.
403
+ { OSTIA_PEAK_MEM: "1" },
404
+ );
405
+ const peakReadings = new Map<string, PeakMemResult[]>();
406
+ for (let i = 0; i < peakRuns.length; i++) {
407
+ const file = Bun.file(peakPaths[i]!);
408
+ if (!(await file.exists())) continue;
409
+ const id = peakRuns[i]!.workloadId;
410
+ const readings = peakReadings.get(id) ?? [];
411
+ readings.push((await file.json()) as PeakMemResult);
412
+ peakReadings.set(id, readings);
413
+ }
414
+
415
+ // Plan order (registration order, filtered) within a suite, suites in
416
+ // command-line order. Measurements are matched by workload id, not
417
+ // position: a task.skip()'d task has a workload but no measurement.
418
+ const workloads: Workload[] = [];
419
+ const measurements: Measurement[] = [];
420
+ plans.forEach((tasks, s) => {
421
+ // A cancelled suite wrote nothing and is absent, not empty.
422
+ const sharedDoc = primaryDocs[s];
423
+ if (!sharedDoc) return;
424
+ const sharedByWorkload = Map.groupBy(
425
+ sharedDoc.measurements,
426
+ (m) => m.workloadId,
427
+ );
428
+ let sharedPtr = 0;
429
+ for (const task of tasks) {
430
+ let workload: Workload;
431
+ let own: Measurement[];
432
+ if (task.isolate) {
433
+ // Cancelled before its subprocess finished: drop just this task.
434
+ const doc = isolatedDocs.get(task);
435
+ if (!doc) continue;
436
+ workload = doc.workloads[0]!;
437
+ own = doc.measurements.filter((m) => m.workloadId === workload.id);
438
+ } else {
439
+ workload = sharedDoc.workloads[sharedPtr++]!;
440
+ own = sharedByWorkload.get(workload.id) ?? [];
441
+ }
442
+ workloads.push(workload);
443
+ measurements.push(
444
+ ...own,
445
+ ...peakMeasurement(workload, peakReadings.get(workload.id)),
446
+ );
447
+ }
448
+ });
449
+
450
+ stampRunWarnings(
451
+ measurements,
452
+ noiseWarning,
453
+ opts.signal?.aborted
454
+ ? "Run was cancelled before it finished; this document holds whatever suites/tasks had already completed."
455
+ : undefined,
456
+ );
457
+ stampDrift(environment);
458
+ return createDocument(workloads, measurements, environment);
459
+ } finally {
460
+ await removeDir(tmpDir);
461
+ }
462
+ }
@@ -0,0 +1,39 @@
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
+ /** Launch settings for each of `suites`, in order: the first project whose
13
+ * globs match the file (against its path relative to `cwd`) overrides the
14
+ * top-level `preload` / `bunFlags` field by field; a field the project
15
+ * leaves unset, or a file no project matches, keeps the top-level value.
16
+ * */
17
+ export function resolveSuiteLaunches(
18
+ suites: string[],
19
+ cwd: string,
20
+ base: { preload?: string[]; bunFlags?: string[] },
21
+ projects: BenchProject[] = [],
22
+ ): SuiteLaunch[] {
23
+ const matchers = projects.map((project) =>
24
+ project.suites.map((pattern) => new Bun.Glob(pattern)),
25
+ );
26
+ return suites.map((file) => {
27
+ const rel = relative(cwd, absolutePath(cwd, file));
28
+ const index = matchers.findIndex((globs) =>
29
+ globs.some((g) => g.match(rel)),
30
+ );
31
+ const project = index < 0 ? undefined : projects[index];
32
+ return {
33
+ preload: (project?.preload ?? base.preload ?? []).map((p) =>
34
+ absolutePath(cwd, p),
35
+ ),
36
+ bunFlags: project?.bunFlags ?? base.bunFlags ?? [],
37
+ };
38
+ });
39
+ }
@@ -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
+ }