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.
- package/LICENSE +21 -0
- package/README.md +50 -358
- package/docs/agent-protocol.md +210 -0
- package/docs/cli.md +1196 -0
- package/docs/config.md +233 -0
- package/docs/document-schema.md +224 -0
- package/docs/library.md +421 -0
- package/docs/preload-recipes.md +169 -0
- package/docs/statistics.md +218 -0
- package/index.d.ts +894 -677
- package/package.json +16 -14
- package/src/ab/ab-runner.ts +474 -0
- package/src/ab/index.ts +1086 -0
- package/src/baseline/index.ts +75 -0
- package/src/bench/index.ts +462 -0
- package/src/bench/projects.ts +39 -0
- package/src/bench/range.ts +27 -0
- package/src/bench/registry.ts +424 -0
- package/src/bench/run-tasks.ts +176 -0
- package/src/bench/run.ts +51 -0
- package/src/bench/runner.ts +147 -0
- package/src/bench/support.ts +161 -0
- package/src/bench/sweep.ts +39 -0
- package/src/cache/fingerprint.ts +59 -0
- package/src/cache/store.ts +28 -0
- package/src/capture/bunflags.ts +91 -0
- package/src/capture/cpu-parse.ts +119 -0
- package/src/capture/cpu.ts +44 -0
- package/src/capture/frames.ts +54 -0
- package/src/capture/heap-parse.ts +86 -0
- package/src/capture/heap.ts +32 -0
- package/src/capture/inspector.ts +46 -0
- package/src/capture/jsc-parse.ts +167 -0
- package/src/capture/jsc.ts +35 -0
- package/src/capture/sampling.ts +5 -0
- package/src/ci/index.ts +416 -0
- package/src/cli/flags.ts +264 -0
- package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
- package/src/cli/main.ts +18 -0
- package/src/cli/output.ts +185 -0
- package/src/cli/run.ts +1110 -0
- package/src/compare/index.ts +617 -0
- package/src/config/index.ts +275 -0
- package/src/config/validate.ts +267 -0
- package/src/errors.ts +8 -0
- package/src/format.ts +36 -0
- package/src/glob.ts +48 -0
- package/src/index.ts +62 -0
- package/src/ir/cpu.ts +10 -0
- package/src/ir/document.ts +471 -0
- package/src/ir/fp.ts +31 -0
- package/src/ir/git.ts +36 -0
- package/src/ir/types.ts +615 -0
- package/src/measure/alloc.ts +57 -0
- package/src/measure/cpu.ts +99 -0
- package/src/measure/environment.ts +41 -0
- package/src/measure/inprocess.ts +191 -0
- package/src/measure/instructions.ts +133 -0
- package/src/measure/loop.ts +57 -0
- package/src/measure/noise.ts +55 -0
- package/src/measure/paired.ts +312 -0
- package/src/measure/peak.ts +202 -0
- package/src/measure/timing.ts +263 -0
- package/src/profile.ts +109 -0
- package/src/renderers/collapsed.ts +35 -0
- package/src/renderers/cpu-tree.ts +183 -0
- package/src/renderers/cpuprofile.ts +43 -0
- package/src/renderers/format.ts +142 -0
- package/src/renderers/index.ts +27 -0
- package/src/renderers/json.ts +10 -0
- package/src/renderers/jsonl.ts +15 -0
- package/src/renderers/markdown.ts +525 -0
- package/src/renderers/mermaid.ts +78 -0
- package/src/renderers/minimal.ts +602 -0
- package/src/renderers/paired.ts +229 -0
- package/src/renderers/relative.ts +64 -0
- package/src/renderers/select.ts +286 -0
- package/src/renderers/speedscope.ts +69 -0
- package/src/renderers/terminal.ts +466 -0
- package/src/renderers/types.ts +27 -0
- package/src/spawn/index.ts +396 -0
- package/src/stats/bootstrap.ts +153 -0
- package/src/stats/index.ts +140 -0
- package/src/stats/mannwhitney.ts +81 -0
- package/src/time.ts +325 -0
- package/src/version.ts +3 -0
- package/ab-runner.ts +0 -8
- package/chunk-05jfst35.js +0 -28
- package/chunk-1g1x9zz2.js +0 -15
- package/chunk-23g2rwrn.js +0 -3
- package/chunk-468h5412.js +0 -25
- package/chunk-4esjfc2m.js +0 -2
- package/chunk-ct2xsezd.js +0 -14
- package/cli.js +0 -3
- package/index.js +0 -2
- 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
|
+
export 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
|
+
export 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
|
+
export 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
|
+
/**
|
|
55
|
+
* `undefined` is a timed-out trial: killed, so it has no exit code to fail
|
|
56
|
+
* on.
|
|
57
|
+
*/
|
|
58
|
+
function isFailedExit(code: number | undefined, ignored: Set<number>): boolean {
|
|
59
|
+
return code !== undefined && code !== 0 && !ignored.has(code);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function createTimingPhase(
|
|
63
|
+
opts: TimingPhaseOptions,
|
|
64
|
+
): TimingPhaseIterator {
|
|
65
|
+
// Fail fast on bad options, before any trial runs.
|
|
66
|
+
assertSamplingOptions("time", opts);
|
|
67
|
+
if (opts.timeSource) assertReusableTimeSource(opts.timeSource);
|
|
68
|
+
const warmupCount = opts.warmup ?? DEFAULT_WARMUP;
|
|
69
|
+
const samples = opts.samples;
|
|
70
|
+
const minSamples = opts.minSamples ?? DEFAULT_MIN_SAMPLES;
|
|
71
|
+
const budgetNs =
|
|
72
|
+
samples !== undefined ? 0 : (opts.budgetMs ?? DEFAULT_BUDGET_MS) * 1e6;
|
|
73
|
+
const reported = opts.timeSource !== undefined;
|
|
74
|
+
const ignoreExitCodes = opts.ignoreExitCodes ?? [];
|
|
75
|
+
const ignored = new Set(ignoreExitCodes);
|
|
76
|
+
|
|
77
|
+
const trials: Trial[] = [];
|
|
78
|
+
let totalNs = 0;
|
|
79
|
+
let i = 0;
|
|
80
|
+
let failedEarly = false;
|
|
81
|
+
// One representative excerpt is enough for the aggregate warning.
|
|
82
|
+
let firstNoMatchOutput: string | undefined;
|
|
83
|
+
|
|
84
|
+
function done(): boolean {
|
|
85
|
+
if (failedEarly) return true;
|
|
86
|
+
if (samples !== undefined) return i >= samples;
|
|
87
|
+
return i >= minSamples && totalNs >= budgetNs;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function trial(phase: "warmup" | "timing", index: number) {
|
|
91
|
+
if (opts.prepare) {
|
|
92
|
+
await runPrepare(
|
|
93
|
+
opts.prepare,
|
|
94
|
+
{ phase, index },
|
|
95
|
+
{
|
|
96
|
+
cwd: opts.cwd,
|
|
97
|
+
env: opts.env,
|
|
98
|
+
timeoutMs: opts.timeoutMs,
|
|
99
|
+
signal: opts.signal,
|
|
100
|
+
},
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
return runTrial(opts);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
async warmup() {
|
|
108
|
+
for (let w = 0; w < warmupCount; w++) {
|
|
109
|
+
if (opts.signal?.aborted) return;
|
|
110
|
+
await trial("warmup", w);
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
async step() {
|
|
114
|
+
if (done() || opts.signal?.aborted) return false;
|
|
115
|
+
const result = await trial("timing", i);
|
|
116
|
+
// Killed by cancellation mid-trial: drop the truncated sample.
|
|
117
|
+
if (opts.signal?.aborted) return false;
|
|
118
|
+
if (result.timeSourceNoMatch) {
|
|
119
|
+
firstNoMatchOutput ??= result.timeSourceMissOutput;
|
|
120
|
+
}
|
|
121
|
+
const exitCode = result.exitCode ?? undefined;
|
|
122
|
+
trials.push({
|
|
123
|
+
i,
|
|
124
|
+
wallNs: result.wallNs,
|
|
125
|
+
exitCode,
|
|
126
|
+
userNs: result.userNs,
|
|
127
|
+
systemNs: result.systemNs,
|
|
128
|
+
maxRssBytes: result.maxRssBytes,
|
|
129
|
+
...(result.reportedNs !== undefined && {
|
|
130
|
+
reportedNs: result.reportedNs,
|
|
131
|
+
}),
|
|
132
|
+
...(result.timedOut && { timedOut: true as const }),
|
|
133
|
+
...(result.timeSourceNoMatch && { timeSourceNoMatch: true as const }),
|
|
134
|
+
});
|
|
135
|
+
// The budget bounds the loop's wall time even for reported-time samples.
|
|
136
|
+
totalNs += result.wallNs;
|
|
137
|
+
i++;
|
|
138
|
+
// A failing exit already makes this a harness failure; more trials can't
|
|
139
|
+
// change that.
|
|
140
|
+
if (isFailedExit(exitCode, ignored)) failedEarly = true;
|
|
141
|
+
return true;
|
|
142
|
+
},
|
|
143
|
+
done,
|
|
144
|
+
result(): TimingPhaseResult {
|
|
145
|
+
// Excluded, never a `wallNs` fallback: that would mix wall time into a
|
|
146
|
+
// reported-time series.
|
|
147
|
+
const sampled = trials.filter((t) => !t.timedOut && !t.timeSourceNoMatch);
|
|
148
|
+
const timingSamples = sampled.map((t) =>
|
|
149
|
+
reported ? t.reportedNs! : t.wallNs,
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
const warnings: Warning[] = [];
|
|
153
|
+
const timedOutCount = trials.filter((t) => t.timedOut).length;
|
|
154
|
+
if (timedOutCount > 0) {
|
|
155
|
+
warnings.push({
|
|
156
|
+
code: "timeout",
|
|
157
|
+
message: `${timedOutCount} of ${trials.length} trial(s) timed out after ${opts.timeoutMs}ms.`,
|
|
158
|
+
data: { timeoutMs: opts.timeoutMs, trials: timedOutCount },
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const noMatchCount = trials.filter((t) => t.timeSourceNoMatch).length;
|
|
163
|
+
if (noMatchCount > 0 && opts.timeSource) {
|
|
164
|
+
const { pattern } = opts.timeSource;
|
|
165
|
+
warnings.push({
|
|
166
|
+
code: "time-source-no-match",
|
|
167
|
+
message: `${noMatchCount} of ${trials.length} trial(s) didn't match the timeSource pattern.`,
|
|
168
|
+
data: {
|
|
169
|
+
pattern: typeof pattern === "string" ? pattern : pattern.source,
|
|
170
|
+
trials: noMatchCount,
|
|
171
|
+
...(firstNoMatchOutput !== undefined && {
|
|
172
|
+
output: firstNoMatchOutput,
|
|
173
|
+
}),
|
|
174
|
+
},
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (timingSamples.length === 0) return { trials, warnings };
|
|
179
|
+
|
|
180
|
+
const timing = computeTimingStats(timingSamples);
|
|
181
|
+
warnings.push(
|
|
182
|
+
...timingWarnings(
|
|
183
|
+
timing,
|
|
184
|
+
sampled.map((t) => t.exitCode),
|
|
185
|
+
reported ? "reported" : "subprocess",
|
|
186
|
+
ignoreExitCodes,
|
|
187
|
+
),
|
|
188
|
+
);
|
|
189
|
+
return { trials, timing, warnings };
|
|
190
|
+
},
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
export async function drainTimingPhase(
|
|
195
|
+
phase: TimingPhaseIterator,
|
|
196
|
+
): Promise<void> {
|
|
197
|
+
await phase.warmup();
|
|
198
|
+
while (await phase.step()) {
|
|
199
|
+
// Each step runs one trial.
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
export async function runTimingPhase(
|
|
204
|
+
opts: TimingPhaseOptions,
|
|
205
|
+
): Promise<TimingPhaseResult> {
|
|
206
|
+
const phase = createTimingPhase(opts);
|
|
207
|
+
await drainTimingPhase(phase);
|
|
208
|
+
return phase.result();
|
|
209
|
+
}
|
|
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,109 @@
|
|
|
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
|
+
export async function profile<T>(
|
|
43
|
+
fn: () => T | Promise<T>,
|
|
44
|
+
opts: ProfileOptions = {},
|
|
45
|
+
): Promise<ProfileResult<T>> {
|
|
46
|
+
if (
|
|
47
|
+
opts.name !== undefined &&
|
|
48
|
+
(typeof opts.name !== "string" || !opts.name)
|
|
49
|
+
) {
|
|
50
|
+
throw new TypeError("profile(): name must be a non-empty string");
|
|
51
|
+
}
|
|
52
|
+
const workload = makeInprocessWorkload(fn, opts.name);
|
|
53
|
+
const intervalUs = opts.cpuIntervalUs ?? DEFAULT_CPU_INTERVAL_US;
|
|
54
|
+
const configFp = configFingerprint({
|
|
55
|
+
intervalUs,
|
|
56
|
+
origin: opts.origin ?? "inspector",
|
|
57
|
+
});
|
|
58
|
+
const result = (result: T, measurement: Measurement) => ({
|
|
59
|
+
result,
|
|
60
|
+
measurement,
|
|
61
|
+
document: createDocument([workload], [measurement]),
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
if (opts.signal?.aborted) {
|
|
65
|
+
const start = Bun.nanoseconds();
|
|
66
|
+
const value = await fn();
|
|
67
|
+
return result(
|
|
68
|
+
value,
|
|
69
|
+
makeInstrumentedMeasurement({
|
|
70
|
+
workload,
|
|
71
|
+
phase: "cpu",
|
|
72
|
+
configFingerprint: configFp,
|
|
73
|
+
diagnosticWallNs: Bun.nanoseconds() - start,
|
|
74
|
+
warnings: [abortedWarning()],
|
|
75
|
+
artifacts: [],
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
const captured =
|
|
81
|
+
opts.origin === "jsc"
|
|
82
|
+
? await captureJscProfile(fn, { intervalUs })
|
|
83
|
+
: {
|
|
84
|
+
...(await captureInspectorProfile(fn, { intervalUs })),
|
|
85
|
+
jit: undefined,
|
|
86
|
+
};
|
|
87
|
+
const warnings: Warning[] =
|
|
88
|
+
captured.cpu.samples?.nodeIds.length === 0
|
|
89
|
+
? [
|
|
90
|
+
{
|
|
91
|
+
code: "empty-profile",
|
|
92
|
+
message: "In-process capture produced zero samples.",
|
|
93
|
+
},
|
|
94
|
+
]
|
|
95
|
+
: [];
|
|
96
|
+
return result(
|
|
97
|
+
captured.result,
|
|
98
|
+
makeInstrumentedMeasurement({
|
|
99
|
+
workload,
|
|
100
|
+
phase: "cpu",
|
|
101
|
+
configFingerprint: configFp,
|
|
102
|
+
diagnosticWallNs: captured.diagnosticWallNs,
|
|
103
|
+
cpu: captured.cpu,
|
|
104
|
+
jit: captured.jit,
|
|
105
|
+
warnings,
|
|
106
|
+
artifacts: [],
|
|
107
|
+
}),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
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
|
+
async render(
|
|
9
|
+
doc: ProfileDocument,
|
|
10
|
+
options: VizOptions = {},
|
|
11
|
+
): Promise<RenderResult> {
|
|
12
|
+
return renderCpuFiles(doc, options, "collapsed.txt", ({ cpu }) => {
|
|
13
|
+
const { nodes, frames } = cpu;
|
|
14
|
+
const tree = buildDenseTree(cpu);
|
|
15
|
+
|
|
16
|
+
const pathOf: string[] = new Array(tree.count);
|
|
17
|
+
for (const i of tree.order) {
|
|
18
|
+
const name = frameName(frames[nodes[i]!.frameIx]);
|
|
19
|
+
const p = tree.parentIx[i]!;
|
|
20
|
+
pathOf[i] = p === -1 ? name : `${pathOf[p]};${name}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Typed counts plus a first-seen list: this runs over every sample.
|
|
24
|
+
const counts = new Float64Array(tree.count);
|
|
25
|
+
const seen: number[] = [];
|
|
26
|
+
for (const id of cpu.samples?.nodeIds ?? []) {
|
|
27
|
+
const ix = tree.indexOf(id);
|
|
28
|
+
if (ix === -1) continue;
|
|
29
|
+
if (counts[ix]!++ === 0) seen.push(ix);
|
|
30
|
+
}
|
|
31
|
+
const lines = seen.map((ix) => `${pathOf[ix]} ${counts[ix]}`);
|
|
32
|
+
return lines.length > 0 ? `${lines.join("\n")}\n` : "";
|
|
33
|
+
});
|
|
34
|
+
},
|
|
35
|
+
};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import type { CpuEvidence, Measurement, ProfileDocument } from "../ir/types.ts";
|
|
2
|
+
import type { RenderResult, VizOptions } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
export 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
|
+
/** One file per selected CPU run, named `<measurement id>.<ext>`. */
|
|
24
|
+
export function renderCpuFiles(
|
|
25
|
+
doc: ProfileDocument,
|
|
26
|
+
options: VizOptions,
|
|
27
|
+
ext: string,
|
|
28
|
+
build: (run: CpuRun) => string,
|
|
29
|
+
): RenderResult {
|
|
30
|
+
return {
|
|
31
|
+
files: selectCpuRuns(doc, options.measurementId).map((run) => ({
|
|
32
|
+
path: `${run.id}.${ext}`,
|
|
33
|
+
content: build(run),
|
|
34
|
+
})),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function buildParentMap(cpu: CpuEvidence): Map<number, number> {
|
|
39
|
+
const parentOf = new Map<number, number>();
|
|
40
|
+
for (const node of cpu.nodes) {
|
|
41
|
+
for (const childId of node.children) parentOf.set(childId, node.id);
|
|
42
|
+
}
|
|
43
|
+
return parentOf;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function findRootId(cpu: CpuEvidence): number | undefined {
|
|
47
|
+
const tree = buildDenseTree(cpu);
|
|
48
|
+
const rootIx = tree.roots[0];
|
|
49
|
+
return rootIx === undefined ? undefined : cpu.nodes[rootIx]!.id;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function pathToRoot(
|
|
53
|
+
nodeId: number,
|
|
54
|
+
parentOf: Map<number, number>,
|
|
55
|
+
): number[] {
|
|
56
|
+
const path = [nodeId];
|
|
57
|
+
let current = nodeId;
|
|
58
|
+
while (parentOf.has(current)) {
|
|
59
|
+
current = parentOf.get(current)!;
|
|
60
|
+
path.push(current);
|
|
61
|
+
}
|
|
62
|
+
return path.reverse();
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface NodeTimes {
|
|
66
|
+
selfUs: number;
|
|
67
|
+
totalUs: number;
|
|
68
|
+
samples: number;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface DenseTree {
|
|
72
|
+
count: number;
|
|
73
|
+
indexOf: (id: number) => number;
|
|
74
|
+
parentIx: Int32Array;
|
|
75
|
+
roots: number[];
|
|
76
|
+
order: number[];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function buildDenseTree(cpu: CpuEvidence): DenseTree {
|
|
80
|
+
const nodes = cpu.nodes;
|
|
81
|
+
const count = nodes.length;
|
|
82
|
+
const indexOf = makeIndexer(cpu);
|
|
83
|
+
|
|
84
|
+
const parentIx = new Int32Array(count).fill(-1);
|
|
85
|
+
for (let i = 0; i < count; i++) {
|
|
86
|
+
for (const childId of nodes[i]!.children) {
|
|
87
|
+
const c = indexOf(childId);
|
|
88
|
+
if (c !== -1) parentIx[c] = i;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const roots: number[] = [];
|
|
93
|
+
for (let i = 0; i < count; i++) if (parentIx[i] === -1) roots.push(i);
|
|
94
|
+
|
|
95
|
+
const order: number[] = [];
|
|
96
|
+
const stack: number[] = [];
|
|
97
|
+
for (let r = roots.length - 1; r >= 0; r--) stack.push(roots[r]!);
|
|
98
|
+
while (stack.length > 0) {
|
|
99
|
+
const i = stack.pop()!;
|
|
100
|
+
order.push(i);
|
|
101
|
+
for (const childId of nodes[i]!.children) {
|
|
102
|
+
const c = indexOf(childId);
|
|
103
|
+
if (c !== -1 && parentIx[c] === i) stack.push(c);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
return { count, indexOf, parentIx, roots, order };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function makeIndexer(cpu: CpuEvidence): (id: number) => number {
|
|
111
|
+
const nodes = cpu.nodes;
|
|
112
|
+
const count = nodes.length;
|
|
113
|
+
let min = Infinity;
|
|
114
|
+
let max = -Infinity;
|
|
115
|
+
let integral = true;
|
|
116
|
+
for (let i = 0; i < count; i++) {
|
|
117
|
+
const id = nodes[i]!.id;
|
|
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
|
+
for (let i = 0; i < count; i++) table[nodes[i]!.id - min] = i;
|
|
129
|
+
return (id) => {
|
|
130
|
+
const k = id - min;
|
|
131
|
+
return k >= 0 && k < span ? table[k]! : -1;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
const byId = new Map<number, number>();
|
|
135
|
+
for (let i = 0; i < count; i++) byId.set(nodes[i]!.id, i);
|
|
136
|
+
return (id) => byId.get(id) ?? -1;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export interface DenseNodeTimes {
|
|
140
|
+
selfUs: Float64Array;
|
|
141
|
+
totalUs: Float64Array;
|
|
142
|
+
samples: Float64Array;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function computeDenseNodeTimes(
|
|
146
|
+
cpu: CpuEvidence,
|
|
147
|
+
tree: DenseTree,
|
|
148
|
+
): DenseNodeTimes {
|
|
149
|
+
const { count, indexOf, parentIx, order } = tree;
|
|
150
|
+
const selfUs = new Float64Array(count);
|
|
151
|
+
const samples = new Float64Array(count);
|
|
152
|
+
const nodeIds = cpu.samples?.nodeIds ?? [];
|
|
153
|
+
const deltas = cpu.samples?.timeDeltasUs ?? [];
|
|
154
|
+
for (let i = 0; i < nodeIds.length; i++) {
|
|
155
|
+
const ix = indexOf(nodeIds[i]!);
|
|
156
|
+
if (ix === -1) continue;
|
|
157
|
+
selfUs[ix]! += deltas[i] ?? 0;
|
|
158
|
+
samples[ix]! += 1;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const totalUs = new Float64Array(count);
|
|
162
|
+
for (let k = order.length - 1; k >= 0; k--) {
|
|
163
|
+
const i = order[k]!;
|
|
164
|
+
totalUs[i]! += selfUs[i]!;
|
|
165
|
+
const p = parentIx[i]!;
|
|
166
|
+
if (p >= 0) totalUs[p]! += totalUs[i]!;
|
|
167
|
+
}
|
|
168
|
+
return { selfUs, totalUs, samples };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function computeNodeTimes(cpu: CpuEvidence): Map<number, NodeTimes> {
|
|
172
|
+
const tree = buildDenseTree(cpu);
|
|
173
|
+
const { selfUs, totalUs, samples } = computeDenseNodeTimes(cpu, tree);
|
|
174
|
+
const times = new Map<number, NodeTimes>();
|
|
175
|
+
for (let i = 0; i < tree.count; i++) {
|
|
176
|
+
times.set(cpu.nodes[i]!.id, {
|
|
177
|
+
selfUs: selfUs[i]!,
|
|
178
|
+
totalUs: totalUs[i]!,
|
|
179
|
+
samples: samples[i]!,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
return times;
|
|
183
|
+
}
|
|
@@ -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
|
+
};
|