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,263 @@
1
+ import type { Measurement, TimingStats, Trial, Warning } from "../ir/types.ts";
2
+ import {
3
+ assertReusableTimeSource,
4
+ type PrepareHook,
5
+ runPrepare,
6
+ runTrial,
7
+ type SpawnTrialOptions,
8
+ } from "../spawn/index.ts";
9
+ import { computeTimingStats, timingWarnings } from "../stats/index.ts";
10
+
11
+ interface TimingPhaseOptions extends SpawnTrialOptions {
12
+ /** Exact trial count; the budget is ignored. */
13
+ samples?: number;
14
+ /** Warmup trial count, discarded before sampling. */
15
+ warmup?: number;
16
+ /** Floor on trials when `samples` is unset. */
17
+ minSamples?: number;
18
+ /** Wall-clock budget for the sampling loop, ms. */
19
+ budgetMs?: number;
20
+ /** Runs unmeasured before every trial, warmup included. */
21
+ prepare?: PrepareHook;
22
+ /**
23
+ * Exit codes treated as success (hyperfine's `--ignore-failure`): such a
24
+ * trial still contributes its sample and never triggers `nonzero-exit`. */
25
+ ignoreExitCodes?: number[];
26
+ }
27
+
28
+ const DEFAULT_MIN_SAMPLES = 10;
29
+ const DEFAULT_BUDGET_MS = 3000;
30
+ const DEFAULT_WARMUP = 3;
31
+
32
+ interface TimingPhaseResult {
33
+ trials: Trial[];
34
+ /** Absent when no trial produced a sample (e.g. all timed out). */
35
+ timing?: TimingStats;
36
+ warnings: Warning[];
37
+ }
38
+
39
+ /**
40
+ * One command's trial loop, a trial at a time so `time()` can round-robin
41
+ * several commands (`--interleave`). `warmup()` first, then `step()` until
42
+ * it returns false. */
43
+ interface TimingPhaseIterator {
44
+ warmup(): Promise<void>;
45
+ /**
46
+ * Runs one more trial unless the stopping criterion is met; returns
47
+ * whether one ran.
48
+ */
49
+ step(): Promise<boolean>;
50
+ done(): boolean;
51
+ result(): TimingPhaseResult;
52
+ }
53
+
54
+ // `undefined` is a timed-out trial: killed, so it has no exit code to fail
55
+ // on.
56
+ function isFailedExit(code: number | undefined, ignored: Set<number>): boolean {
57
+ return code !== undefined && code !== 0 && !ignored.has(code);
58
+ }
59
+
60
+ export function createTimingPhase(
61
+ opts: TimingPhaseOptions,
62
+ ): TimingPhaseIterator {
63
+ // Fail fast on bad options, before any trial runs.
64
+ assertSamplingOptions("time", opts);
65
+ if (opts.timeSource) assertReusableTimeSource(opts.timeSource);
66
+ const warmupCount = opts.warmup ?? DEFAULT_WARMUP;
67
+ const samples = opts.samples;
68
+ const minSamples = opts.minSamples ?? DEFAULT_MIN_SAMPLES;
69
+ const budgetNs =
70
+ samples !== undefined ? 0 : (opts.budgetMs ?? DEFAULT_BUDGET_MS) * 1e6;
71
+ const reported = opts.timeSource !== undefined;
72
+ const ignoreExitCodes = opts.ignoreExitCodes ?? [];
73
+ const ignored = new Set(ignoreExitCodes);
74
+
75
+ const trials: Trial[] = [];
76
+ let totalNs = 0;
77
+ let i = 0;
78
+ let failedEarly = false;
79
+ // Only the first, since one representative excerpt is enough for the
80
+ // aggregate warning.
81
+ let firstNoMatchOutput: string | undefined;
82
+
83
+ function done(): boolean {
84
+ if (failedEarly) return true;
85
+ if (samples !== undefined) return i >= samples;
86
+ return i >= minSamples && totalNs >= budgetNs;
87
+ }
88
+
89
+ async function trial(phase: "warmup" | "timing", index: number) {
90
+ if (opts.prepare) {
91
+ await runPrepare(
92
+ opts.prepare,
93
+ { phase, index },
94
+ {
95
+ ...(opts.cwd !== undefined && { cwd: opts.cwd }),
96
+ ...(opts.env !== undefined && { env: opts.env }),
97
+ ...(opts.timeoutMs !== undefined && { timeoutMs: opts.timeoutMs }),
98
+ ...(opts.signal !== undefined && { signal: opts.signal }),
99
+ },
100
+ );
101
+ }
102
+ return runTrial(opts);
103
+ }
104
+
105
+ return {
106
+ async warmup() {
107
+ for (let w = 0; w < warmupCount; w++) {
108
+ if (opts.signal?.aborted) return;
109
+ await trial("warmup", w);
110
+ }
111
+ },
112
+ async step() {
113
+ if (done() || opts.signal?.aborted) return false;
114
+ const result = await trial("timing", i);
115
+ // Killed by cancellation mid-trial: drop the truncated sample.
116
+ if (opts.signal?.aborted) return false;
117
+ if (result.timeSourceNoMatch) {
118
+ firstNoMatchOutput ??= result.timeSourceMissOutput;
119
+ }
120
+ const exitCode = result.exitCode ?? undefined;
121
+ trials.push({
122
+ i,
123
+ wallNs: result.wallNs,
124
+ ...(exitCode !== undefined && { exitCode }),
125
+ ...(result.userNs !== undefined && { userNs: result.userNs }),
126
+ ...(result.systemNs !== undefined && { systemNs: result.systemNs }),
127
+ ...(result.maxRssBytes !== undefined && {
128
+ maxRssBytes: result.maxRssBytes,
129
+ }),
130
+ ...(result.reportedNs !== undefined && {
131
+ reportedNs: result.reportedNs,
132
+ }),
133
+ ...(result.timedOut && { timedOut: true as const }),
134
+ ...(result.timeSourceNoMatch && { timeSourceNoMatch: true as const }),
135
+ });
136
+ // The budget bounds the loop's wall time even for reported-time samples.
137
+ totalNs += result.wallNs;
138
+ i++;
139
+ // A failing exit already makes this a harness failure; more trials can't
140
+ // change that.
141
+ if (isFailedExit(exitCode, ignored)) failedEarly = true;
142
+ return true;
143
+ },
144
+ done,
145
+ result(): TimingPhaseResult {
146
+ // Excluded, never a `wallNs` fallback: that would mix wall time into a
147
+ // reported-time series.
148
+ const sampled = trials.filter((t) => !t.timedOut && !t.timeSourceNoMatch);
149
+ const timingSamples = sampled.map((t) =>
150
+ reported ? (t.reportedNs ?? Number.NaN) : t.wallNs,
151
+ );
152
+
153
+ const warnings: Warning[] = [];
154
+ const timedOutCount = trials.filter((t) => t.timedOut).length;
155
+ if (timedOutCount > 0) {
156
+ warnings.push({
157
+ code: "timeout",
158
+ message: `${timedOutCount} of ${trials.length} trial(s) timed out after ${opts.timeoutMs}ms.`,
159
+ data: { timeoutMs: opts.timeoutMs, trials: timedOutCount },
160
+ });
161
+ }
162
+
163
+ const noMatchCount = trials.filter((t) => t.timeSourceNoMatch).length;
164
+ if (noMatchCount > 0 && opts.timeSource) {
165
+ const { pattern } = opts.timeSource;
166
+ warnings.push({
167
+ code: "time-source-no-match",
168
+ message: `${noMatchCount} of ${trials.length} trial(s) didn't match the timeSource pattern.`,
169
+ data: {
170
+ pattern: typeof pattern === "string" ? pattern : pattern.source,
171
+ trials: noMatchCount,
172
+ ...(firstNoMatchOutput !== undefined && {
173
+ output: firstNoMatchOutput,
174
+ }),
175
+ },
176
+ });
177
+ }
178
+
179
+ if (timingSamples.length === 0) return { trials, warnings };
180
+
181
+ const timing = computeTimingStats(timingSamples);
182
+ warnings.push(
183
+ ...timingWarnings(
184
+ timing,
185
+ sampled.map((t) => t.exitCode),
186
+ reported ? "reported" : "subprocess",
187
+ ignoreExitCodes,
188
+ ),
189
+ );
190
+ return { trials, timing, warnings };
191
+ },
192
+ };
193
+ }
194
+
195
+ export async function drainTimingPhase(
196
+ phase: TimingPhaseIterator,
197
+ ): Promise<void> {
198
+ await phase.warmup();
199
+ while (await phase.step()) {
200
+ // Each step runs one trial.
201
+ }
202
+ }
203
+
204
+ export async function runTimingPhase(
205
+ opts: TimingPhaseOptions,
206
+ ): Promise<TimingPhaseResult> {
207
+ const phase = createTimingPhase(opts);
208
+ await drainTimingPhase(phase);
209
+ return phase.result();
210
+ }
211
+
212
+ // True when some trial exited non-zero (outside `ignoreExitCodes`) or none
213
+ // produced a sample. Not a regression: `ostia time` and `ostia ci` both
214
+ // exit 2. A timed-out trial has no exit code, so it fails the run only
215
+ // when no trial is left to sample (the `timeout` warning covers the
216
+ // partial case).
217
+ export function isHarnessFailure(
218
+ measurement: Pick<Measurement, "trials" | "timing">,
219
+ ignoreExitCodes: number[] = [],
220
+ ): boolean {
221
+ if (!measurement.timing) return true;
222
+ const ignored = new Set(ignoreExitCodes);
223
+ return measurement.trials.some((t) => isFailedExit(t.exitCode, ignored));
224
+ }
225
+
226
+ export function assertSamplingOptions(
227
+ fnName: string,
228
+ opts: {
229
+ samples?: number;
230
+ minSamples?: number;
231
+ budgetMs?: number;
232
+ warmup?: number;
233
+ timeoutMs?: number;
234
+ },
235
+ ): void {
236
+ for (const [key, value] of Object.entries({
237
+ samples: opts.samples,
238
+ minSamples: opts.minSamples,
239
+ })) {
240
+ if (value !== undefined && (!Number.isFinite(value) || value < 1)) {
241
+ throw new RangeError(`${fnName}: ${key} must be >= 1, got ${value}`);
242
+ }
243
+ }
244
+ if (opts.budgetMs !== undefined && !Number.isFinite(opts.budgetMs)) {
245
+ throw new RangeError(
246
+ `${fnName}: budgetMs must be finite, got ${opts.budgetMs}`,
247
+ );
248
+ }
249
+ if (
250
+ opts.warmup !== undefined &&
251
+ (!Number.isFinite(opts.warmup) || opts.warmup < 0)
252
+ ) {
253
+ throw new RangeError(`${fnName}: warmup must be >= 0, got ${opts.warmup}`);
254
+ }
255
+ if (
256
+ opts.timeoutMs !== undefined &&
257
+ (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs <= 0)
258
+ ) {
259
+ throw new RangeError(
260
+ `${fnName}: timeoutMs must be > 0, got ${opts.timeoutMs}`,
261
+ );
262
+ }
263
+ }
package/src/profile.ts ADDED
@@ -0,0 +1,110 @@
1
+ import { captureInspectorProfile } from "./capture/inspector.ts";
2
+ import { captureJscProfile } from "./capture/jsc.ts";
3
+ import {
4
+ configFingerprint,
5
+ createDocument,
6
+ makeInprocessWorkload,
7
+ makeInstrumentedMeasurement,
8
+ } from "./ir/document.ts";
9
+ import type { Measurement, ProfileDocument, Warning } from "./ir/types.ts";
10
+ import { abortedWarning, DEFAULT_CPU_INTERVAL_US } from "./time.ts";
11
+
12
+ export interface ProfileOptions {
13
+ /**
14
+ * Sampling interval in µs; default 1000. Named like `time()`'s and
15
+ * `bench()`'s option, the config key and `--cpu-interval`. */
16
+ cpuIntervalUs?: number;
17
+ /**
18
+ * Names the workload: it becomes the label and, instead of the function's
19
+ * name and source, what the id hashes, so closures that differ only in
20
+ * captured values get distinct ids and the id survives editing the
21
+ * function. */
22
+ name?: string;
23
+ /**
24
+ * `"inspector"` (default) captures through CDP and writes a portable
25
+ * .cpuprofile; `"jsc"` uses `bun:jsc.profile` and adds
26
+ * LLInt/Baseline/DFG/FTL tier data. */
27
+ origin?: "inspector" | "jsc";
28
+ /**
29
+ * There's no child to kill, so an already-aborted signal skips the
30
+ * profiler, calls `fn` plain (still returning its `result`) and records an
31
+ * `aborted` warning instead of CPU evidence. It can't interrupt a running
32
+ * `fn`. */
33
+ signal?: AbortSignal;
34
+ }
35
+
36
+ export interface ProfileResult<T> {
37
+ result: T;
38
+ measurement: Measurement;
39
+ document: ProfileDocument;
40
+ }
41
+
42
+ /** Captures a CPU profile of `fn` in the current process. */
43
+ export async function profile<T>(
44
+ fn: () => T | Promise<T>,
45
+ opts: ProfileOptions = {},
46
+ ): Promise<ProfileResult<T>> {
47
+ if (
48
+ opts.name !== undefined &&
49
+ (typeof opts.name !== "string" || !opts.name)
50
+ ) {
51
+ throw new TypeError("profile(): name must be a non-empty string");
52
+ }
53
+ const workload = makeInprocessWorkload(fn, opts.name);
54
+ const intervalUs = opts.cpuIntervalUs ?? DEFAULT_CPU_INTERVAL_US;
55
+ const configFp = configFingerprint({
56
+ intervalUs,
57
+ origin: opts.origin ?? "inspector",
58
+ });
59
+ const result = (result: T, measurement: Measurement) => ({
60
+ result,
61
+ measurement,
62
+ document: createDocument([workload], [measurement]),
63
+ });
64
+
65
+ if (opts.signal?.aborted) {
66
+ const start = Bun.nanoseconds();
67
+ const value = await fn();
68
+ return result(
69
+ value,
70
+ makeInstrumentedMeasurement({
71
+ workload,
72
+ phase: "cpu",
73
+ configFingerprint: configFp,
74
+ diagnosticWallNs: Bun.nanoseconds() - start,
75
+ warnings: [abortedWarning()],
76
+ artifacts: [],
77
+ }),
78
+ );
79
+ }
80
+
81
+ const captured =
82
+ opts.origin === "jsc"
83
+ ? await captureJscProfile(fn, { intervalUs })
84
+ : {
85
+ ...(await captureInspectorProfile(fn, { intervalUs })),
86
+ jit: undefined,
87
+ };
88
+ const warnings: Warning[] =
89
+ captured.cpu.samples?.nodeIds.length === 0
90
+ ? [
91
+ {
92
+ code: "empty-profile",
93
+ message: "In-process capture produced zero samples.",
94
+ },
95
+ ]
96
+ : [];
97
+ return result(
98
+ captured.result,
99
+ makeInstrumentedMeasurement({
100
+ workload,
101
+ phase: "cpu",
102
+ configFingerprint: configFp,
103
+ diagnosticWallNs: captured.diagnosticWallNs,
104
+ cpu: captured.cpu,
105
+ ...(captured.jit && { jit: captured.jit }),
106
+ warnings,
107
+ artifacts: [],
108
+ }),
109
+ );
110
+ }
@@ -0,0 +1,42 @@
1
+ import type { ProfileDocument } from "../ir/types.ts";
2
+ import { buildDenseTree, renderCpuFiles } from "./cpu-tree.ts";
3
+ import { frameName } from "./format.ts";
4
+ import type { Renderer, RenderResult, VizOptions } from "./types.ts";
5
+
6
+ export const collapsedRenderer: Renderer<VizOptions> = {
7
+ name: "collapsed",
8
+ render(
9
+ doc: ProfileDocument,
10
+ options: VizOptions = {},
11
+ ): Promise<RenderResult> {
12
+ return Promise.try(() =>
13
+ renderCpuFiles(doc, options, "collapsed.txt", ({ cpu }) => {
14
+ const { nodes, frames } = cpu;
15
+ const tree = buildDenseTree(cpu);
16
+
17
+ const pathOf = new Array<string>(tree.count);
18
+ for (const i of tree.order) {
19
+ const node = nodes[i];
20
+ if (node === undefined) continue;
21
+ const name = frameName(frames[node.frameIx]);
22
+ const p = tree.parentIx[i] ?? -1;
23
+ pathOf[i] = p === -1 ? name : `${pathOf[p]};${name}`;
24
+ }
25
+
26
+ // Typed counts plus a first-seen list, because this runs over every
27
+ // sample.
28
+ const counts = new Float64Array(tree.count);
29
+ const seen: number[] = [];
30
+ for (const id of cpu.samples?.nodeIds ?? []) {
31
+ const ix = tree.indexOf(id);
32
+ if (ix === -1) continue;
33
+ const count = counts[ix] ?? 0;
34
+ counts[ix] = count + 1;
35
+ if (count === 0) seen.push(ix);
36
+ }
37
+ const lines = seen.map((ix) => `${pathOf[ix]} ${counts[ix]}`);
38
+ return lines.length > 0 ? `${lines.join("\n")}\n` : "";
39
+ }),
40
+ );
41
+ },
42
+ };
@@ -0,0 +1,191 @@
1
+ import type { CpuEvidence, Measurement, ProfileDocument } from "../ir/types.ts";
2
+ import type { RenderResult, VizOptions } from "./types.ts";
3
+
4
+ type CpuRun = Measurement & { cpu: CpuEvidence };
5
+
6
+ function hasCpu(m: Measurement): m is CpuRun {
7
+ return m.cpu !== undefined;
8
+ }
9
+
10
+ export function selectCpuRuns(
11
+ doc: ProfileDocument,
12
+ measurementId?: string,
13
+ ): CpuRun[] {
14
+ if (measurementId) {
15
+ const run = doc.measurements.find((r) => r.id === measurementId);
16
+ return run && hasCpu(run) ? [run] : [];
17
+ }
18
+ return doc.measurements.filter(
19
+ (r): r is CpuRun => r.phase === "cpu" && hasCpu(r),
20
+ );
21
+ }
22
+
23
+ export function renderCpuFiles(
24
+ doc: ProfileDocument,
25
+ options: VizOptions,
26
+ ext: string,
27
+ build: (run: CpuRun) => string,
28
+ ): RenderResult {
29
+ return {
30
+ files: selectCpuRuns(doc, options.measurementId).map((run) => ({
31
+ path: `${run.id}.${ext}`,
32
+ content: build(run),
33
+ })),
34
+ };
35
+ }
36
+
37
+ export function buildParentMap(cpu: CpuEvidence): Map<number, number> {
38
+ const parentOf = new Map<number, number>();
39
+ for (const node of cpu.nodes) {
40
+ for (const childId of node.children) parentOf.set(childId, node.id);
41
+ }
42
+ return parentOf;
43
+ }
44
+
45
+ export function findRootId(cpu: CpuEvidence): number | undefined {
46
+ const tree = buildDenseTree(cpu);
47
+ const rootIx = tree.roots[0];
48
+ return rootIx === undefined ? undefined : cpu.nodes[rootIx]?.id;
49
+ }
50
+
51
+ export function pathToRoot(
52
+ nodeId: number,
53
+ parentOf: Map<number, number>,
54
+ ): number[] {
55
+ const path = [nodeId];
56
+ for (
57
+ let parent = parentOf.get(nodeId);
58
+ parent !== undefined;
59
+ parent = parentOf.get(parent)
60
+ ) {
61
+ path.push(parent);
62
+ }
63
+ return path.reverse();
64
+ }
65
+
66
+ interface NodeTimes {
67
+ selfUs: number;
68
+ totalUs: number;
69
+ samples: number;
70
+ }
71
+
72
+ interface DenseTree {
73
+ count: number;
74
+ indexOf: (id: number) => number;
75
+ parentIx: Int32Array;
76
+ roots: number[];
77
+ order: number[];
78
+ }
79
+
80
+ export function buildDenseTree(cpu: CpuEvidence): DenseTree {
81
+ const nodes = cpu.nodes;
82
+ const count = nodes.length;
83
+ const indexOf = makeIndexer(cpu);
84
+
85
+ const parentIx = new Int32Array(count).fill(-1);
86
+ let ix = 0;
87
+ for (const node of nodes) {
88
+ for (const childId of node.children) {
89
+ const c = indexOf(childId);
90
+ if (c !== -1) parentIx[c] = ix;
91
+ }
92
+ ix++;
93
+ }
94
+
95
+ const roots: number[] = [];
96
+ for (let i = 0; i < count; i++) if (parentIx[i] === -1) roots.push(i);
97
+
98
+ const order: number[] = [];
99
+ const stack = roots.toReversed();
100
+ for (let i = stack.pop(); i !== undefined; i = stack.pop()) {
101
+ order.push(i);
102
+ for (const childId of nodes[i]?.children ?? []) {
103
+ const c = indexOf(childId);
104
+ if (c !== -1 && parentIx[c] === i) stack.push(c);
105
+ }
106
+ }
107
+
108
+ return { count, indexOf, parentIx, roots, order };
109
+ }
110
+
111
+ function makeIndexer(cpu: CpuEvidence): (id: number) => number {
112
+ const nodes = cpu.nodes;
113
+ const count = nodes.length;
114
+ let min = Infinity;
115
+ let max = -Infinity;
116
+ let integral = true;
117
+ for (const { id } of nodes) {
118
+ if (!Number.isInteger(id)) {
119
+ integral = false;
120
+ break;
121
+ }
122
+ if (id < min) min = id;
123
+ if (id > max) max = id;
124
+ }
125
+ if (integral && count > 0 && max - min < count * 4 + 64) {
126
+ const span = max - min + 1;
127
+ const table = new Int32Array(span).fill(-1);
128
+ let ix = 0;
129
+ for (const node of nodes) table[node.id - min] = ix++;
130
+ return (id) => {
131
+ const k = id - min;
132
+ return k >= 0 && k < span ? (table[k] ?? -1) : -1;
133
+ };
134
+ }
135
+ const byId = new Map<number, number>();
136
+ let ix = 0;
137
+ for (const node of nodes) byId.set(node.id, ix++);
138
+ return (id) => byId.get(id) ?? -1;
139
+ }
140
+
141
+ interface DenseNodeTimes {
142
+ selfUs: Float64Array;
143
+ totalUs: Float64Array;
144
+ samples: Float64Array;
145
+ }
146
+
147
+ export function computeDenseNodeTimes(
148
+ cpu: CpuEvidence,
149
+ tree: DenseTree,
150
+ ): DenseNodeTimes {
151
+ const { count, indexOf, parentIx, order } = tree;
152
+ const selfUs = new Float64Array(count);
153
+ const samples = new Float64Array(count);
154
+ const nodeIds = cpu.samples?.nodeIds ?? [];
155
+ const deltas = cpu.samples?.timeDeltasUs ?? [];
156
+ for (let i = 0; i < nodeIds.length; i++) {
157
+ const id = nodeIds[i];
158
+ if (id === undefined) continue;
159
+ const ix = indexOf(id);
160
+ if (ix === -1) continue;
161
+ selfUs[ix] = (selfUs[ix] ?? 0) + (deltas[i] ?? 0);
162
+ samples[ix] = (samples[ix] ?? 0) + 1;
163
+ }
164
+
165
+ const totalUs = new Float64Array(count);
166
+ for (let k = order.length - 1; k >= 0; k--) {
167
+ const i = order[k];
168
+ if (i === undefined) continue;
169
+ const total = (totalUs[i] ?? 0) + (selfUs[i] ?? 0);
170
+ totalUs[i] = total;
171
+ const p = parentIx[i] ?? -1;
172
+ if (p >= 0) totalUs[p] = (totalUs[p] ?? 0) + total;
173
+ }
174
+ return { selfUs, totalUs, samples };
175
+ }
176
+
177
+ export function computeNodeTimes(cpu: CpuEvidence): Map<number, NodeTimes> {
178
+ const tree = buildDenseTree(cpu);
179
+ const { selfUs, totalUs, samples } = computeDenseNodeTimes(cpu, tree);
180
+ const times = new Map<number, NodeTimes>();
181
+ let i = 0;
182
+ for (const node of cpu.nodes) {
183
+ times.set(node.id, {
184
+ selfUs: selfUs[i] ?? 0,
185
+ totalUs: totalUs[i] ?? 0,
186
+ samples: samples[i] ?? 0,
187
+ });
188
+ i++;
189
+ }
190
+ return times;
191
+ }
@@ -0,0 +1,43 @@
1
+ import type { ProfileDocument } from "../ir/types.ts";
2
+ import { selectCpuRuns } from "./cpu-tree.ts";
3
+ import type { Renderer, RenderResult, VizOptions } from "./types.ts";
4
+
5
+ export const cpuprofileRenderer: Renderer<VizOptions> = {
6
+ name: "cpuprofile",
7
+ async render(
8
+ doc: ProfileDocument,
9
+ options: VizOptions = {},
10
+ ): Promise<RenderResult> {
11
+ const files: NonNullable<RenderResult["files"]> = [];
12
+ const skipped: string[] = [];
13
+
14
+ for (const run of selectCpuRuns(doc, options.measurementId)) {
15
+ const { origin } = run.cpu;
16
+ if (origin !== "cpu-prof" && origin !== "inspector") {
17
+ skipped.push(
18
+ `${run.id} (origin ${origin} has no .cpuprofile artifact to pass through)`,
19
+ );
20
+ continue;
21
+ }
22
+ const artifact = run.artifacts.find((a) => a.kind === "cpuprofile");
23
+ if (!artifact) {
24
+ skipped.push(`${run.id} (no cpuprofile artifact recorded on this run)`);
25
+ continue;
26
+ }
27
+ const file = Bun.file(artifact.path);
28
+ if (!(await file.exists())) {
29
+ skipped.push(`${run.id} (artifact missing on disk: ${artifact.path})`);
30
+ continue;
31
+ }
32
+ files.push({ path: `${run.id}.cpuprofile`, content: await file.text() });
33
+ }
34
+
35
+ if (files.length === 0 && skipped.length > 0) {
36
+ return {
37
+ text: `No .cpuprofile artifacts available:\n${skipped.map((s) => ` - ${s}`).join("\n")}\n`,
38
+ };
39
+ }
40
+
41
+ return { files };
42
+ },
43
+ };