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,147 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import { saveDocument } from "../ir/document.ts";
4
+ import {
5
+ measurePeakMem,
6
+ type MemorySnapshot,
7
+ memorySnapshot,
8
+ type RssSampler,
9
+ startRssSampler,
10
+ } from "../measure/peak.ts";
11
+ import {
12
+ getRegisteredTasks,
13
+ NO_TASKS_HINT,
14
+ type RegisteredTask,
15
+ resetRegistry,
16
+ runGroupHooks,
17
+ selectTasks,
18
+ taskIsolate,
19
+ taskPeakMem,
20
+ } from "./registry.ts";
21
+ import {
22
+ measureTasks,
23
+ type MeasureTasksOpts,
24
+ taskWorkload,
25
+ } from "./run-tasks.ts";
26
+
27
+ export interface RunnerOpts extends MeasureTasksOpts {
28
+ /** Regex matched against "group/name" task ids. */
29
+ filter?: string;
30
+ /**
31
+ * Run exactly these workloads (after `filter`): a dedicated process for an
32
+ * isolated task the whole-file pass already planned. */
33
+ workloadIds?: string[];
34
+ /** Suite-wide isolate default (task/group `isolate` still wins). */
35
+ isolate?: boolean;
36
+ /**
37
+ * Suite-wide `peakMem` default (task/group `peakMem` still wins); only
38
+ * written into the plan, since the measurement runs in fresh processes
39
+ * (see `peakMemFor`). */
40
+ peakMem?: boolean;
41
+ /**
42
+ * A peak-memory process: measure this one workload's first call (after its
43
+ * group's and its own `before` hooks) and write the `PeakMemResult` to the
44
+ * output path instead of a document. Nothing else runs, so no other task's
45
+ * peak can hide this one's. */
46
+ peakMemFor?: string;
47
+ /**
48
+ * The suite's whole-file pass (without `workloadIds`): write every
49
+ * filtered task's id and effective isolate to this path, then run only the
50
+ * non-isolated ones in this process. Isolated tasks are left to dedicated
51
+ * subprocesses, so the suite is never imported twice to learn the plan. */
52
+ planPath?: string;
53
+ /**
54
+ * Scripts imported, in order, before the suite file, in this same process
55
+ * (so globals or `Bun.plugin()` loaders they install reach the suite). */
56
+ preload?: string[];
57
+ }
58
+
59
+ async function main(): Promise<number> {
60
+ const [suiteFile, outputPath, optsJson] = process.argv.slice(2);
61
+ if (!suiteFile || !outputPath) {
62
+ process.stderr.write(
63
+ "bench runner: usage: runner.ts <suiteFile> <outputPath> [optsJson]\n",
64
+ );
65
+ return 2;
66
+ }
67
+
68
+ const opts: RunnerOpts = optsJson ? JSON.parse(optsJson) : {};
69
+
70
+ // Baseline for `measurePeakMem`, taken once ostia (which the suite
71
+ // imports) is loaded.
72
+ let launched: MemorySnapshot | undefined;
73
+ let sampler: RssSampler | undefined;
74
+ if (opts.peakMemFor) {
75
+ sampler = await startRssSampler();
76
+ await import("../index.ts");
77
+ launched = memorySnapshot();
78
+ }
79
+
80
+ for (const preloadFile of opts.preload ?? []) {
81
+ await import(preloadFile);
82
+ }
83
+
84
+ resetRegistry();
85
+ await import(suiteFile);
86
+ const registered = getRegisteredTasks();
87
+ if (registered.length === 0) {
88
+ process.stderr.write(
89
+ `bench runner: ${suiteFile} registered no tasks (no task() calls found).${NO_TASKS_HINT}\n`,
90
+ );
91
+ return 2;
92
+ }
93
+
94
+ let tasks: RegisteredTask[];
95
+ try {
96
+ tasks = selectTasks(
97
+ registered,
98
+ opts.filter,
99
+ suiteFile,
100
+ !opts.workloadIds && !opts.peakMemFor,
101
+ );
102
+ } catch (err) {
103
+ process.stderr.write(`bench runner: ${(err as Error).message}\n`);
104
+ return 2;
105
+ }
106
+ const workloadIdOf = (t: RegisteredTask) => taskWorkload(suiteFile, t).id;
107
+ if (opts.workloadIds) {
108
+ const wanted = new Set(opts.workloadIds);
109
+ tasks = tasks.filter((t) => wanted.has(workloadIdOf(t)));
110
+ }
111
+
112
+ if (opts.peakMemFor) {
113
+ const t = tasks.find((t) => workloadIdOf(t) === opts.peakMemFor);
114
+ if (!t) {
115
+ process.stderr.write(
116
+ `bench runner: no task with workload id ${opts.peakMemFor} in ${suiteFile}.\n`,
117
+ );
118
+ return 2;
119
+ }
120
+ await runGroupHooks(t, "before");
121
+ await t.opts?.before?.();
122
+ const result = await measurePeakMem(t.fn, launched, sampler);
123
+ await t.opts?.after?.();
124
+ await runGroupHooks(t, "after");
125
+ await Bun.write(outputPath, JSON.stringify(result));
126
+ return 0;
127
+ }
128
+
129
+ if (opts.planPath) {
130
+ const plan = tasks.map((t) => ({
131
+ workloadId: workloadIdOf(t),
132
+ isolate: taskIsolate(t, opts.isolate ?? false),
133
+ peakMem: !t.skipped && taskPeakMem(t, opts.peakMem ?? false),
134
+ }));
135
+ await Bun.write(opts.planPath, JSON.stringify({ tasks: plan }));
136
+ }
137
+
138
+ const toRun = opts.workloadIds
139
+ ? tasks
140
+ : tasks.filter((t) => !taskIsolate(t, opts.isolate ?? false));
141
+
142
+ const doc = await measureTasks(suiteFile, toRun, opts);
143
+ await saveDocument(doc, outputPath);
144
+ return 0;
145
+ }
146
+
147
+ main().then((code) => process.exit(code));
@@ -0,0 +1,161 @@
1
+ import { statSync } from "node:fs";
2
+ import { rm } from "node:fs/promises";
3
+ import { isAbsolute } from "node:path";
4
+
5
+ import { OstiaUsageError } from "../errors.ts";
6
+ import { loadDocument } from "../ir/document.ts";
7
+ import type { Measurement, ProfileDocument, Warning } from "../ir/types.ts";
8
+ import {
9
+ captureEnvironment,
10
+ noisyMachineWarning,
11
+ } from "../measure/environment.ts";
12
+ import type { PeakMemResult } from "../measure/peak.ts";
13
+ import { formatBytes } from "../renderers/format.ts";
14
+ import { killSwitch } from "../spawn/index.ts";
15
+ import { percentile } from "../stats/index.ts";
16
+
17
+ // A plain join, not path.resolve: the path is hashed into workload ids, so
18
+ // normalizing "./x" would orphan existing baselines.
19
+ export function absolutePath(cwd: string, file: string): string {
20
+ return isAbsolute(file) ? file : `${cwd}/${file}`;
21
+ }
22
+
23
+ /** A suite file named on the command line or in config doesn't exist. */
24
+ class SuiteNotFoundError extends OstiaUsageError {}
25
+
26
+ /**
27
+ * Throws `SuiteNotFoundError` unless `absolute` is a file; `given` is the
28
+ * path as the caller wrote it, for the message. */
29
+ export function assertSuiteExists(given: string, absolute: string): void {
30
+ if (!statSync(absolute, { throwIfNoEntry: false })?.isFile()) {
31
+ throw new SuiteNotFoundError(`Suite not found: ${given}`);
32
+ }
33
+ }
34
+
35
+ /**
36
+ * A scratch directory under `outDir` no other run shares, so concurrent
37
+ * `bench()`/`ab()` calls (or a rerun after a crash) never delete each
38
+ * other's files. */
39
+ export function uniqueTmpDir(outDir: string, kind: "bench" | "ab"): string {
40
+ return `${outDir}/${kind}-tmp-${process.pid}-${crypto.randomUUID().slice(0, 8)}`;
41
+ }
42
+
43
+ export function median(values: number[]): number {
44
+ return percentile(Float64Array.from(values).sort(), 0.5);
45
+ }
46
+
47
+ export function removeDir(path: string): Promise<void> {
48
+ return rm(path, { recursive: true, force: true });
49
+ }
50
+
51
+ /** `undefined` when a runner killed mid-run never wrote its output. */
52
+ export async function loadIfExists(
53
+ path: string,
54
+ ): Promise<ProfileDocument | undefined> {
55
+ return (await Bun.file(path).exists()) ? loadDocument(path) : undefined;
56
+ }
57
+
58
+ /** Fresh processes per `--peak-mem` reading; the median is reported. */
59
+ export const PEAK_MEM_PROCESSES = 3;
60
+ // Below this, slack is what any suite that loads fixtures leaves behind
61
+ // (8MB for caligula's) and too common to warn about.
62
+ const PEAK_SLACK_NOISE_BYTES = 16 * 1024 * 1024;
63
+
64
+ /**
65
+ * A `peak-hidden` warning when memory freed before the call may have
66
+ * hidden part of its peak in `readings` (one task's fresh processes). */
67
+ export function peakHiddenWarning(
68
+ readings: PeakMemResult[],
69
+ ): Warning | undefined {
70
+ const peak = median(readings.map((r) => r.peakBytes));
71
+ const slack = Math.max(...readings.map((r) => r.slackBytes));
72
+ if (slack < PEAK_SLACK_NOISE_BYTES || slack <= peak / 4) return undefined;
73
+ return {
74
+ code: "peak-hidden",
75
+ message: `Before the call, earlier work in the process had freed up to ${formatBytes(slack)} the allocator still held (module-scope setup or before hooks that allocate), which the call could reuse without RSS rising: this reading can be low by up to that much. Skip that work when process.env.OSTIA_PEAK_MEM is set.`,
76
+ data: { slackBytes: slack, processes: readings.length },
77
+ };
78
+ }
79
+
80
+ export function captureRunEnvironment(noiseCheck: boolean | undefined) {
81
+ const environment = noiseCheck === false ? undefined : captureEnvironment();
82
+ return {
83
+ environment,
84
+ noiseWarning: environment && noisyMachineWarning(environment),
85
+ };
86
+ }
87
+
88
+ /** Noise warning on the first measurement, `aborted` message on the last. */
89
+ export function stampRunWarnings(
90
+ measurements: Measurement[],
91
+ noiseWarning: Warning | undefined,
92
+ abortedMessage: string | undefined,
93
+ ): void {
94
+ const first = measurements[0];
95
+ const last = measurements[measurements.length - 1];
96
+ if (!first || !last) return;
97
+ if (noiseWarning) first.warnings.push(noiseWarning);
98
+ if (abortedMessage) {
99
+ last.warnings.push({ code: "aborted", message: abortedMessage });
100
+ }
101
+ }
102
+
103
+ export interface RunnerProcessOptions {
104
+ /** Prefix for error messages, e.g. "Bench suite". */
105
+ label: string;
106
+ /** What the error messages name: the suite file. */
107
+ name: string;
108
+ cwd: string;
109
+ env?: Record<string, string>;
110
+ timeoutMs?: number;
111
+ signal?: AbortSignal;
112
+ /** Children to SIGKILL if a sibling fails. */
113
+ inFlight?: Set<Bun.Subprocess>;
114
+ /** Receives the runner's IPC messages. */
115
+ ipc?: (message: never) => void;
116
+ /**
117
+ * Where the runner writes why it failed; its text, when present, goes in
118
+ * the error for a non-zero exit. */
119
+ errorFile?: string;
120
+ }
121
+
122
+ /**
123
+ * Runs one runner subprocess to completion. Resolves `false` when the
124
+ * caller's signal cancelled it (not a failure), `true` on a clean exit. */
125
+ export async function runRunnerProcess(
126
+ argv: string[],
127
+ opts: RunnerProcessOptions,
128
+ ): Promise<boolean> {
129
+ const kill = killSwitch(opts.timeoutMs, opts.signal);
130
+ const proc = Bun.spawn(argv, {
131
+ cwd: opts.cwd,
132
+ ...(opts.env && { env: { ...process.env, ...opts.env } }),
133
+ stdout: "inherit",
134
+ stderr: "inherit",
135
+ stdin: "ignore",
136
+ ...(opts.ipc && { ipc: opts.ipc }),
137
+ ...kill.spawn,
138
+ });
139
+ opts.inFlight?.add(proc);
140
+ let exitCode: number;
141
+ try {
142
+ exitCode = await proc.exited;
143
+ } finally {
144
+ opts.inFlight?.delete(proc);
145
+ }
146
+ if (opts.signal?.aborted) return false;
147
+ if (kill.timedOut()) {
148
+ throw new Error(
149
+ `${opts.label} timed out after ${opts.timeoutMs}ms: ${opts.name}`,
150
+ );
151
+ }
152
+ if (exitCode !== 0) {
153
+ const reason = opts.errorFile && Bun.file(opts.errorFile);
154
+ throw new Error(
155
+ reason && (await reason.exists())
156
+ ? `${opts.label} failed: ${opts.name}: ${await reason.text()}`
157
+ : `${opts.label} failed: ${opts.name} (runner exited ${exitCode})`,
158
+ );
159
+ }
160
+ return true;
161
+ }
@@ -0,0 +1,39 @@
1
+ import { withCurrentParams } from "./registry.ts";
2
+
3
+ type SweepPoint<T extends Record<string, readonly unknown[]>> = {
4
+ [K in keyof T]: T[K][number];
5
+ };
6
+
7
+ /** Cartesian product over `dims`, calling `fn` once per point. Inside `fn`,
8
+ * `task()` calls automatically inherit the point as their params (an
9
+ * explicit `TaskOptions.params` merges over it, explicit keys win):
10
+ *
11
+ * group("parse", () => {
12
+ * sweep({ size: range(100, 10_000), impl: ["current", "fast"] }, ({ size, impl }) => {
13
+ * const input = build(size)
14
+ * task(`${impl}`, () => impls[impl](input))
15
+ * })
16
+ * })
17
+ */
18
+ export function sweep<T extends Record<string, readonly unknown[]>>(
19
+ dims: T,
20
+ fn: (point: SweepPoint<T>) => void,
21
+ ): void {
22
+ const keys = Object.keys(dims) as (keyof T)[];
23
+
24
+ const go = (index: number, point: Record<string, unknown>): void => {
25
+ if (index === keys.length) {
26
+ withCurrentParams(
27
+ point as Record<string, string | number | boolean>,
28
+ () => fn(point as SweepPoint<T>),
29
+ );
30
+ return;
31
+ }
32
+ const key = keys[index]!;
33
+ for (const value of dims[key]!) {
34
+ go(index + 1, { ...point, [key]: value });
35
+ }
36
+ };
37
+
38
+ go(0, {});
39
+ }
@@ -0,0 +1,59 @@
1
+ import { resolve } from "node:path";
2
+
3
+ import { scanGlobs } from "../glob.ts";
4
+ import { fp } from "../ir/fp.ts";
5
+ import type { Phase } from "../ir/types.ts";
6
+
7
+ export interface CacheKeyInput {
8
+ workloadId: string;
9
+ phase: Phase;
10
+ configFingerprint: string;
11
+ bunVersion: string;
12
+ toolVersion: string;
13
+ instrumented: boolean;
14
+ inputsDigest?: string;
15
+ }
16
+
17
+ export function computeCacheKey(input: CacheKeyInput): string {
18
+ return fp(
19
+ "cache",
20
+ input.workloadId,
21
+ input.phase,
22
+ input.configFingerprint,
23
+ input.bunVersion,
24
+ input.toolVersion,
25
+ input.instrumented,
26
+ input.inputsDigest ?? null,
27
+ );
28
+ }
29
+
30
+ // Keeps a large glob under the process's open-file limit (EMFILE).
31
+ const READ_CONCURRENCY = 32;
32
+
33
+ export async function computeInputsDigest(
34
+ globs: string[],
35
+ cwd: string = process.cwd(),
36
+ ): Promise<string | undefined> {
37
+ if (globs.length === 0) return undefined;
38
+
39
+ const paths = await scanGlobs(globs, cwd);
40
+ const entries: { path: string; sha256: string }[] = new Array(paths.length);
41
+ let next = 0;
42
+ const worker = async () => {
43
+ while (next < paths.length) {
44
+ const k = next++;
45
+ const path = paths[k]!;
46
+ // Absolute patterns scan to absolute paths; `resolve` handles both.
47
+ const buf = await Bun.file(resolve(cwd, path)).arrayBuffer();
48
+ entries[k] = {
49
+ path,
50
+ sha256: Bun.CryptoHasher.hash("sha256", buf, "hex"),
51
+ };
52
+ }
53
+ };
54
+ await Promise.all(
55
+ Array.from({ length: Math.min(READ_CONCURRENCY, paths.length) }, worker),
56
+ );
57
+
58
+ return fp("inputs", entries);
59
+ }
@@ -0,0 +1,28 @@
1
+ import type { Measurement } from "../ir/types.ts";
2
+
3
+ function cachePath(outDir: string, key: string): string {
4
+ return `${outDir}/cache/${key}.json`;
5
+ }
6
+
7
+ /**
8
+ * A missing or unreadable (e.g. truncated by an interrupted write) entry
9
+ * is a miss.
10
+ */
11
+ export async function readCachedRun(
12
+ outDir: string,
13
+ key: string,
14
+ ): Promise<Measurement | undefined> {
15
+ try {
16
+ return (await Bun.file(cachePath(outDir, key)).json()) as Measurement;
17
+ } catch {
18
+ return undefined;
19
+ }
20
+ }
21
+
22
+ export async function writeCachedRun(
23
+ outDir: string,
24
+ key: string,
25
+ run: Measurement,
26
+ ): Promise<void> {
27
+ await Bun.write(cachePath(outDir, key), `${JSON.stringify(run, null, 2)}\n`);
28
+ }
@@ -0,0 +1,91 @@
1
+ import type { Warning } from "../ir/types.ts";
2
+
3
+ // BUN_OPTIONS is split on whitespace; a backslash escapes a space or quote
4
+ // (Bun doesn't honour quoting, and a literal backslash can't be
5
+ // expressed).
6
+ function escapeBunOption(flag: string): string {
7
+ return flag.replace(/[\s"']/g, "\\$&");
8
+ }
9
+
10
+ export function withBunFlags(
11
+ argv: string[],
12
+ flags: string[],
13
+ env: Record<string, string> | undefined,
14
+ ): { argv: string[]; env: Record<string, string> | undefined } {
15
+ const bin = argv[0];
16
+ if (bin && /(^|[\\/])bun(\.exe)?$/.test(bin)) {
17
+ return { argv: [bin, ...flags, ...argv.slice(1)], env };
18
+ }
19
+ // A wrapper script that eventually execs bun still picks the flags up.
20
+ // Ours go last so they win over any the caller already set.
21
+ const merged = { ...process.env, ...env } as Record<string, string>;
22
+ const ours = flags.map(escapeBunOption).join(" ");
23
+ return {
24
+ argv,
25
+ env: {
26
+ ...merged,
27
+ BUN_OPTIONS: merged.BUN_OPTIONS ? `${merged.BUN_OPTIONS} ${ours}` : ours,
28
+ },
29
+ };
30
+ }
31
+
32
+ export interface ProfiledRunOptions {
33
+ argv: string[];
34
+ cwd?: string;
35
+ env?: Record<string, string>;
36
+ artifactDir: string;
37
+ fileName: string;
38
+ }
39
+
40
+ export interface ProfiledRun<T> {
41
+ diagnosticWallNs: number;
42
+ exitCode: number;
43
+ artifactPath?: string;
44
+ raw?: T;
45
+ warnings: Warning[];
46
+ }
47
+
48
+ /** Runs the workload under bun with profiler `flags` and loads the JSON
49
+ * artifact it wrote; `raw` is absent (with an `artifact-missing` warning)
50
+ * when none appeared. */
51
+ export async function runProfiled<T>(
52
+ opts: ProfiledRunOptions,
53
+ flags: string[],
54
+ artifact: { what: string; kind: string },
55
+ ): Promise<ProfiledRun<T>> {
56
+ const artifactPath = `${opts.artifactDir}/${opts.fileName}`;
57
+ const { argv, env } = withBunFlags(opts.argv, flags, opts.env);
58
+
59
+ const start = Bun.nanoseconds();
60
+ const proc = Bun.spawn(argv, {
61
+ cwd: opts.cwd,
62
+ env,
63
+ stdout: "ignore",
64
+ stderr: "ignore",
65
+ stdin: "ignore",
66
+ });
67
+ const exitCode = await proc.exited;
68
+ const diagnosticWallNs = Bun.nanoseconds() - start;
69
+
70
+ const file = Bun.file(artifactPath);
71
+ if (!(await file.exists())) {
72
+ return {
73
+ diagnosticWallNs,
74
+ exitCode,
75
+ warnings: [
76
+ {
77
+ code: "artifact-missing",
78
+ message: `Expected ${artifact.what} at ${artifactPath} after exit ${exitCode}, found nothing. The workload's argv[0] must be a \`bun\` binary for ${artifact.kind} capture.`,
79
+ data: { artifactPath, argv: opts.argv },
80
+ },
81
+ ],
82
+ };
83
+ }
84
+ return {
85
+ diagnosticWallNs,
86
+ exitCode,
87
+ artifactPath,
88
+ raw: (await file.json()) as T,
89
+ warnings: [],
90
+ };
91
+ }
@@ -0,0 +1,119 @@
1
+ import type { CallNode, CpuEvidence, FrameTotal } from "../ir/types.ts";
2
+ import { addFrameTotal, createFrameTable, sortedTotals } from "./frames.ts";
3
+
4
+ interface RawCallFrame {
5
+ functionName: string;
6
+ scriptId?: string;
7
+ url: string;
8
+ lineNumber: number;
9
+ columnNumber: number;
10
+ }
11
+
12
+ interface RawCpuNode {
13
+ id: number;
14
+ callFrame: RawCallFrame;
15
+ hitCount?: number;
16
+ children?: number[];
17
+ }
18
+
19
+ export interface RawCpuProfile {
20
+ nodes: RawCpuNode[];
21
+ startTime: number;
22
+ endTime: number;
23
+ samples: number[];
24
+ timeDeltas: number[];
25
+ }
26
+
27
+ // cpu-prof/inspector: sourcemapped file:// URLs, 0-based lines (jsc is
28
+ // 1-based).
29
+ function normalizeUrl(url: string): string {
30
+ return url.startsWith("file://") ? url.slice("file://".length) : url;
31
+ }
32
+
33
+ export function parseCpuProfile(
34
+ raw: RawCpuProfile,
35
+ origin: CpuEvidence["origin"],
36
+ samplingIntervalUs: number,
37
+ ): CpuEvidence {
38
+ const rawNodes = raw.nodes;
39
+ const count = rawNodes.length;
40
+
41
+ const { frames, intern } = createFrameTable();
42
+ const indexById = new Map<number, number>();
43
+ const nodes: CallNode[] = new Array(count);
44
+
45
+ for (let i = 0; i < count; i++) {
46
+ const node = rawNodes[i]!;
47
+ const cf = node.callFrame;
48
+ const frameIx = intern(
49
+ cf.functionName,
50
+ normalizeUrl(cf.url) || undefined,
51
+ cf.lineNumber >= 0 ? cf.lineNumber : undefined,
52
+ cf.columnNumber >= 0 ? cf.columnNumber : undefined,
53
+ );
54
+ nodes[i] = { id: node.id, frameIx, children: node.children ?? [] };
55
+ indexById.set(node.id, i);
56
+ }
57
+
58
+ const selfUs = new Float64Array(count);
59
+ const sampleCount = new Float64Array(count);
60
+ const sampleIds = raw.samples;
61
+ const deltas = raw.timeDeltas;
62
+ for (let i = 0; i < sampleIds.length; i++) {
63
+ const ix = indexById.get(sampleIds[i]!);
64
+ if (ix === undefined) continue;
65
+ selfUs[ix]! += deltas[i] ?? 0;
66
+ sampleCount[ix]! += 1;
67
+ }
68
+
69
+ const parentIx = new Int32Array(count).fill(-1);
70
+ for (let i = 0; i < count; i++) {
71
+ const children = rawNodes[i]!.children;
72
+ if (!children) continue;
73
+ for (const childId of children) {
74
+ const c = indexById.get(childId);
75
+ if (c !== undefined) parentIx[c] = i;
76
+ }
77
+ }
78
+ // Parents-before-children order, so walking it backwards rolls totals up.
79
+ const order: number[] = [];
80
+ const stack: number[] = [];
81
+ for (let i = count - 1; i >= 0; i--) if (parentIx[i] === -1) stack.push(i);
82
+ while (stack.length > 0) {
83
+ const i = stack.pop()!;
84
+ order.push(i);
85
+ const children = rawNodes[i]!.children;
86
+ if (!children) continue;
87
+ for (const childId of children) {
88
+ const c = indexById.get(childId);
89
+ if (c !== undefined && parentIx[c] === i) stack.push(c);
90
+ }
91
+ }
92
+ const totalUs = new Float64Array(count);
93
+ for (let k = order.length - 1; k >= 0; k--) {
94
+ const i = order[k]!;
95
+ totalUs[i]! += selfUs[i]!;
96
+ const p = parentIx[i]!;
97
+ if (p >= 0) totalUs[p]! += totalUs[i]!;
98
+ }
99
+
100
+ const totals = new Map<number, FrameTotal>();
101
+ for (let i = 0; i < count; i++) {
102
+ addFrameTotal(
103
+ totals,
104
+ nodes[i]!.frameIx,
105
+ selfUs[i]!,
106
+ totalUs[i]!,
107
+ sampleCount[i]!,
108
+ );
109
+ }
110
+
111
+ return {
112
+ origin,
113
+ samplingIntervalUs,
114
+ frames,
115
+ nodes,
116
+ totals: sortedTotals(totals),
117
+ samples: { nodeIds: raw.samples, timeDeltasUs: raw.timeDeltas },
118
+ };
119
+ }
@@ -0,0 +1,44 @@
1
+ import type { CpuEvidence, Warning } from "../ir/types.ts";
2
+ import { type ProfiledRunOptions, runProfiled } from "./bunflags.ts";
3
+ import { parseCpuProfile, type RawCpuProfile } from "./cpu-parse.ts";
4
+
5
+ export interface CpuCaptureOptions extends ProfiledRunOptions {
6
+ intervalUs: number;
7
+ }
8
+
9
+ export interface CpuCaptureResult {
10
+ diagnosticWallNs: number;
11
+ exitCode: number;
12
+ artifactPath?: string;
13
+ cpu?: CpuEvidence;
14
+ warnings: Warning[];
15
+ }
16
+
17
+ // BUN_CPU_PROFILE is documented but doesn't work on Bun 1.4.0, hence
18
+ // flags/BUN_OPTIONS.
19
+ export async function runCpuCapture(
20
+ opts: CpuCaptureOptions,
21
+ ): Promise<CpuCaptureResult> {
22
+ const { raw, ...run } = await runProfiled<RawCpuProfile>(
23
+ opts,
24
+ [
25
+ "--cpu-prof",
26
+ "--cpu-prof-dir",
27
+ opts.artifactDir,
28
+ "--cpu-prof-name",
29
+ opts.fileName,
30
+ "--cpu-prof-interval",
31
+ String(opts.intervalUs),
32
+ ],
33
+ { what: "a .cpuprofile", kind: "CPU" },
34
+ );
35
+ if (!raw) return run;
36
+
37
+ if (raw.samples.length === 0) {
38
+ run.warnings.push({
39
+ code: "empty-profile",
40
+ message: "CPU capture produced zero samples.",
41
+ });
42
+ }
43
+ return { ...run, cpu: parseCpuProfile(raw, "cpu-prof", opts.intervalUs) };
44
+ }