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