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,312 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AbSummary,
|
|
3
|
+
MemoryChange,
|
|
4
|
+
PairedEvidence,
|
|
5
|
+
PairedInstructions,
|
|
6
|
+
} from "../ir/types.ts";
|
|
7
|
+
import { percentile, sortedCopy } from "../stats/index.ts";
|
|
8
|
+
import { instructionCounter } from "./instructions.ts";
|
|
9
|
+
import { batchTimer, probeFirstCall, type TaskBody } from "./loop.ts";
|
|
10
|
+
|
|
11
|
+
export type Side = "base" | "cand";
|
|
12
|
+
|
|
13
|
+
/** `"candidate"` for `"cand"`, for messages; other sides as they are. */
|
|
14
|
+
export function sideLabel(side: Side | "both"): string {
|
|
15
|
+
return side === "cand" ? "candidate" : side;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* What `measurePaired` throws when one side's task throws, naming the
|
|
20
|
+
* side; the task's own error is `cause`. */
|
|
21
|
+
export class PairedSideError extends Error {
|
|
22
|
+
constructor(
|
|
23
|
+
readonly side: Side,
|
|
24
|
+
cause: unknown,
|
|
25
|
+
) {
|
|
26
|
+
super(cause instanceof Error ? cause.message : String(cause), { cause });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Runs `fn`, rethrowing anything it throws as a `PairedSideError` for
|
|
32
|
+
* `side`. */
|
|
33
|
+
async function onSide<T>(
|
|
34
|
+
side: "base" | "cand",
|
|
35
|
+
fn: () => T | Promise<T>,
|
|
36
|
+
): Promise<T> {
|
|
37
|
+
try {
|
|
38
|
+
return await fn();
|
|
39
|
+
} catch (err) {
|
|
40
|
+
throw err instanceof PairedSideError ? err : new PairedSideError(side, err);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface PairedTimingOptions {
|
|
45
|
+
/** Rounds of one base batch and one candidate batch (default: 15). */
|
|
46
|
+
rounds?: number;
|
|
47
|
+
/**
|
|
48
|
+
* Aborting rejects `measurePaired` with the signal's reason at the next
|
|
49
|
+
* batch boundary; partial rounds are discarded. */
|
|
50
|
+
signal?: AbortSignal;
|
|
51
|
+
/**
|
|
52
|
+
* Give the candidate what the base gets first by default: the first
|
|
53
|
+
* call, warmup, the warm rounds and the first batch of even rounds. */
|
|
54
|
+
candFirst?: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface PairedTimingResult {
|
|
58
|
+
rounds: number;
|
|
59
|
+
/** Calls per side per round. */
|
|
60
|
+
batch: number;
|
|
61
|
+
/** Per-call time of each side in each round, ns, index-aligned. */
|
|
62
|
+
baseSamples: number[];
|
|
63
|
+
candSamples: number[];
|
|
64
|
+
/** `candSamples[i] / baseSamples[i]`. */
|
|
65
|
+
ratios: number[];
|
|
66
|
+
/**
|
|
67
|
+
* Instructions per call of each side in each round, index-aligned with
|
|
68
|
+
* the times; absent where the machine can't count them. */
|
|
69
|
+
instructions?: InstructionSamples;
|
|
70
|
+
/** Whether the two sides' first calls returned deep-equal values. */
|
|
71
|
+
sameOutput: boolean;
|
|
72
|
+
diagnosticWallNs: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface InstructionSamples {
|
|
76
|
+
baseSamples: number[];
|
|
77
|
+
candSamples: number[];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface RatioStats {
|
|
81
|
+
medianRatio: number;
|
|
82
|
+
ratioP25: number;
|
|
83
|
+
ratioP75: number;
|
|
84
|
+
flagged?: "regressed" | "improved";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const DEFAULT_ROUNDS = 15;
|
|
88
|
+
// Long enough that timer resolution vanishes, short enough that the
|
|
89
|
+
// machine barely changes between a round's two halves.
|
|
90
|
+
const ROUND_BATCH_NS = 10_000_000;
|
|
91
|
+
// Warmup doubles each side's batch until it spans this long.
|
|
92
|
+
const WARMUP_CHUNK_NS = 1_000_000;
|
|
93
|
+
const WARM_ROUNDS = 3;
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Whether two first-call results are deep-equal. A result too deeply
|
|
97
|
+
* nested to compare (a 10,000-level chain overflows the stack) counts as
|
|
98
|
+
* equal: the check is informational and must not take the run down. */
|
|
99
|
+
function sameResult(a: unknown, b: unknown): boolean {
|
|
100
|
+
try {
|
|
101
|
+
return Bun.deepEquals(a, b);
|
|
102
|
+
} catch (err) {
|
|
103
|
+
if (err instanceof RangeError) return true;
|
|
104
|
+
throw err;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Times `base` and `cand` against each other in one process: after warmup,
|
|
110
|
+
* `rounds` rounds of one ~10ms batch per side, alternating which goes
|
|
111
|
+
* first. Drift (load, thermal throttling) hits both halves of a round
|
|
112
|
+
* alike and cancels in that round's ratio, which a baseline measured
|
|
113
|
+
* minutes earlier can't do. A throw from either side rejects with a
|
|
114
|
+
* `PairedSideError` naming it. */
|
|
115
|
+
export async function measurePaired(
|
|
116
|
+
base: TaskBody,
|
|
117
|
+
cand: TaskBody,
|
|
118
|
+
opts: PairedTimingOptions = {},
|
|
119
|
+
): Promise<PairedTimingResult> {
|
|
120
|
+
const rounds = opts.rounds ?? DEFAULT_ROUNDS;
|
|
121
|
+
const { signal } = opts;
|
|
122
|
+
signal?.throwIfAborted();
|
|
123
|
+
const start = Bun.nanoseconds();
|
|
124
|
+
|
|
125
|
+
const order: Side[] = opts.candFirst ? ["cand", "base"] : ["base", "cand"];
|
|
126
|
+
const reversed = order.toReversed();
|
|
127
|
+
const fns = { base, cand };
|
|
128
|
+
const probes = {} as Record<Side, Awaited<ReturnType<typeof probeFirstCall>>>;
|
|
129
|
+
for (const name of order) {
|
|
130
|
+
probes[name] = await onSide(name, () => probeFirstCall(fns[name]));
|
|
131
|
+
}
|
|
132
|
+
const sameOutput = sameResult(probes.base.result, probes.cand.result);
|
|
133
|
+
|
|
134
|
+
const side = (name: Side) => {
|
|
135
|
+
const time = batchTimer(fns[name], probes[name].isAsync);
|
|
136
|
+
return (n: number): Promise<number> => onSide(name, () => time(n));
|
|
137
|
+
};
|
|
138
|
+
const timers = { base: side("base"), cand: side("cand") };
|
|
139
|
+
|
|
140
|
+
// Each side warms alone: sharing one doubling would run a slow side
|
|
141
|
+
// thousands of times just to get a fast side's batch past the chunk.
|
|
142
|
+
const warmUp = async (time: (n: number) => number | Promise<number>) => {
|
|
143
|
+
for (let n = 1; ; n *= 2) {
|
|
144
|
+
signal?.throwIfAborted();
|
|
145
|
+
const ns = await time(n);
|
|
146
|
+
if (ns >= WARMUP_CHUNK_NS) return Math.max(1, ns / n);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const callNs = { base: 0, cand: 0 };
|
|
150
|
+
for (const name of order) callNs[name] = await warmUp(timers[name]);
|
|
151
|
+
|
|
152
|
+
const batch = Math.max(
|
|
153
|
+
1,
|
|
154
|
+
Math.round(ROUND_BATCH_NS / Math.max(callNs.base, callNs.cand)),
|
|
155
|
+
);
|
|
156
|
+
for (let r = 0; r < WARM_ROUNDS; r++) {
|
|
157
|
+
signal?.throwIfAborted();
|
|
158
|
+
for (const name of order) await timers[name](batch);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Read around each batch, outside the loop's own clock reads.
|
|
162
|
+
const count = instructionCounter().read;
|
|
163
|
+
const instructions: InstructionSamples = { baseSamples: [], candSamples: [] };
|
|
164
|
+
const baseSamples: number[] = [];
|
|
165
|
+
const candSamples: number[] = [];
|
|
166
|
+
const ratios: number[] = [];
|
|
167
|
+
for (let r = 0; r < rounds; r++) {
|
|
168
|
+
signal?.throwIfAborted();
|
|
169
|
+
const ns = { base: 0, cand: 0 };
|
|
170
|
+
const ins = { base: 0, cand: 0 };
|
|
171
|
+
for (const name of r % 2 === 0 ? order : reversed) {
|
|
172
|
+
const before = count?.() ?? 0;
|
|
173
|
+
ns[name] = await timers[name](batch);
|
|
174
|
+
if (count) ins[name] = (count() - before) / batch;
|
|
175
|
+
}
|
|
176
|
+
const b = Math.max(1, ns.base);
|
|
177
|
+
const c = Math.max(1, ns.cand);
|
|
178
|
+
baseSamples.push(b / batch);
|
|
179
|
+
candSamples.push(c / batch);
|
|
180
|
+
ratios.push(c / b);
|
|
181
|
+
instructions.baseSamples.push(ins.base);
|
|
182
|
+
instructions.candSamples.push(ins.cand);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return {
|
|
186
|
+
rounds,
|
|
187
|
+
batch,
|
|
188
|
+
baseSamples,
|
|
189
|
+
candSamples,
|
|
190
|
+
ratios,
|
|
191
|
+
...(count && { instructions }),
|
|
192
|
+
sameOutput,
|
|
193
|
+
diagnosticWallNs: Bun.nanoseconds() - start,
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function median(values: number[]): number {
|
|
198
|
+
return percentile(sortedCopy(values), 0.5);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
type RatioQuartiles = Omit<RatioStats, "flagged">;
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* `metric`'s ratios of a paired task or one of its repeats; undefined when
|
|
205
|
+
* its instructions weren't counted. */
|
|
206
|
+
export function metricRatios(
|
|
207
|
+
r: RatioQuartiles & { instructions?: RatioQuartiles },
|
|
208
|
+
metric: AbSummary["metric"],
|
|
209
|
+
): RatioQuartiles | undefined {
|
|
210
|
+
return metric === "instructions" ? r.instructions : r;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* A paired task's evidence from its rounds (one process's, or several
|
|
215
|
+
* pooled), `flagged` by `metric`'s ratios. */
|
|
216
|
+
export function pairedEvidence(
|
|
217
|
+
input: Pick<
|
|
218
|
+
PairedTimingResult,
|
|
219
|
+
| "rounds"
|
|
220
|
+
| "batch"
|
|
221
|
+
| "baseSamples"
|
|
222
|
+
| "ratios"
|
|
223
|
+
| "instructions"
|
|
224
|
+
| "sameOutput"
|
|
225
|
+
>,
|
|
226
|
+
thresholdPct: number,
|
|
227
|
+
metric: AbSummary["metric"],
|
|
228
|
+
): PairedEvidence {
|
|
229
|
+
const { flagged: timeFlag, ...time } = ratioStats(input.ratios, thresholdPct);
|
|
230
|
+
let instructions: PairedInstructions | undefined;
|
|
231
|
+
let instructionFlag: RatioStats["flagged"];
|
|
232
|
+
if (input.instructions) {
|
|
233
|
+
const { baseSamples, candSamples } = input.instructions;
|
|
234
|
+
const ratios = candSamples.map((c, i) => c / Math.max(1, baseSamples[i]!));
|
|
235
|
+
const { flagged, ...stats } = ratioStats(ratios, thresholdPct);
|
|
236
|
+
instructionFlag = flagged;
|
|
237
|
+
instructions = {
|
|
238
|
+
baseSamples,
|
|
239
|
+
candSamples,
|
|
240
|
+
baseMedian: median(baseSamples),
|
|
241
|
+
candMedian: median(candSamples),
|
|
242
|
+
ratios,
|
|
243
|
+
...stats,
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
const flagged = metric === "instructions" ? instructionFlag : timeFlag;
|
|
247
|
+
return {
|
|
248
|
+
rounds: input.rounds,
|
|
249
|
+
batch: input.batch,
|
|
250
|
+
baseSamples: input.baseSamples,
|
|
251
|
+
baseMedianNs: median(input.baseSamples),
|
|
252
|
+
ratios: input.ratios,
|
|
253
|
+
...time,
|
|
254
|
+
...(instructions && { instructions }),
|
|
255
|
+
...(flagged && { flagged }),
|
|
256
|
+
verdict: flagged ?? "unchanged",
|
|
257
|
+
sameOutput: input.sameOutput,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* False when the suite file changed and the two sides' outputs differ:
|
|
263
|
+
* the sides then likely ran different benchmarks, and their time ratio
|
|
264
|
+
* says nothing about the code under test. */
|
|
265
|
+
export function comparable(p: {
|
|
266
|
+
suiteChanged?: true;
|
|
267
|
+
sameOutput: boolean;
|
|
268
|
+
}): boolean {
|
|
269
|
+
return !(p.suiteChanged && !p.sameOutput);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* `regressed` when the candidate exceeds the base by more than
|
|
274
|
+
* `thresholdPct` of the base and more than `floorBytes`; `improved` is the
|
|
275
|
+
* mirror. */
|
|
276
|
+
export function memoryChange(
|
|
277
|
+
baseBytes: number,
|
|
278
|
+
candBytes: number,
|
|
279
|
+
thresholdPct: number,
|
|
280
|
+
floorBytes: number,
|
|
281
|
+
): MemoryChange {
|
|
282
|
+
const diff = candBytes - baseBytes;
|
|
283
|
+
const counts =
|
|
284
|
+
Math.abs(diff) > Math.max(floorBytes, (baseBytes * thresholdPct) / 100);
|
|
285
|
+
return {
|
|
286
|
+
baseBytes,
|
|
287
|
+
candBytes,
|
|
288
|
+
verdict: !counts ? "unchanged" : diff > 0 ? "regressed" : "improved",
|
|
289
|
+
floorBytes,
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/**
|
|
294
|
+
* `regressed` when the median ratio is above `1 + thresholdPct/100` and
|
|
295
|
+
* the 25th percentile is above 1 (slower in at least three quarters of
|
|
296
|
+
* rounds); `improved` is the mirror. The quartile condition keeps a few
|
|
297
|
+
* wild rounds from flagging a workload whose typical round shows no
|
|
298
|
+
* change. */
|
|
299
|
+
export function ratioStats(ratios: number[], thresholdPct: number): RatioStats {
|
|
300
|
+
const sorted = sortedCopy(ratios);
|
|
301
|
+
const medianRatio = percentile(sorted, 0.5);
|
|
302
|
+
const ratioP25 = percentile(sorted, 0.25);
|
|
303
|
+
const ratioP75 = percentile(sorted, 0.75);
|
|
304
|
+
const t = thresholdPct / 100;
|
|
305
|
+
const flagged =
|
|
306
|
+
medianRatio > 1 + t && ratioP25 > 1
|
|
307
|
+
? "regressed"
|
|
308
|
+
: medianRatio < 1 - t && ratioP75 < 1
|
|
309
|
+
? "improved"
|
|
310
|
+
: undefined;
|
|
311
|
+
return { medianRatio, ratioP25, ratioP75, ...(flagged && { flagged }) };
|
|
312
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { dlopen, FFIType, ptr } from "bun:ffi";
|
|
2
|
+
import { heapStats } from "bun:jsc";
|
|
3
|
+
|
|
4
|
+
import { isPromiseLike } from "./loop.ts";
|
|
5
|
+
|
|
6
|
+
export interface MemorySnapshot {
|
|
7
|
+
rssBytes: number;
|
|
8
|
+
residentBytes: number;
|
|
9
|
+
liveBytes: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Taken before the suite loads so `measurePeakMem` can split the starting
|
|
14
|
+
* RSS into live data and memory setup freed that the allocator still
|
|
15
|
+
* holds. */
|
|
16
|
+
export function memorySnapshot(): MemorySnapshot {
|
|
17
|
+
const { heapSize, extraMemorySize } = heapStats();
|
|
18
|
+
const rssBytes = process.memoryUsage.rss();
|
|
19
|
+
return {
|
|
20
|
+
rssBytes,
|
|
21
|
+
residentBytes: residentBytes() ?? rssBytes,
|
|
22
|
+
liveBytes: heapSize + extraMemorySize,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Bun 1.4.3+ reports the physical footprint as RSS on macOS, which misses
|
|
27
|
+
// reused freed pages for a while (oven-sh/bun#44951). Resident size
|
|
28
|
+
// doesn't.
|
|
29
|
+
function residentBytes(): number | undefined {
|
|
30
|
+
if (process.platform !== "darwin") return undefined;
|
|
31
|
+
readResident ??= residentReader();
|
|
32
|
+
return readResident();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
let readResident: (() => number | undefined) | undefined;
|
|
36
|
+
|
|
37
|
+
// Asks the kernel directly: spawning `ps` costs a few ms a call.
|
|
38
|
+
function residentReader(): () => number | undefined {
|
|
39
|
+
const { symbols } = dlopen("/usr/lib/libSystem.B.dylib", {
|
|
40
|
+
proc_pid_rusage: {
|
|
41
|
+
args: [FFIType.i32, FFIType.i32, FFIType.ptr],
|
|
42
|
+
returns: FFIType.i32,
|
|
43
|
+
},
|
|
44
|
+
});
|
|
45
|
+
// rusage_info_v0: a 16-byte uuid, then u64s; ri_resident_size is at byte
|
|
46
|
+
// 64.
|
|
47
|
+
const info = new BigUint64Array(12);
|
|
48
|
+
return () =>
|
|
49
|
+
symbols.proc_pid_rusage(process.pid, 0, ptr(info)) === 0
|
|
50
|
+
? Number(info[8])
|
|
51
|
+
: undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Worker body: waits for `go`, then polls RSS flat out (~1µs) keeping the
|
|
55
|
+
// max in KiB in slot 1 until `stop`. Slot 0 is the CONTROL handshake.
|
|
56
|
+
const CONTROL = { ready: 1, go: 2, sampling: 3, stop: 4 } as const;
|
|
57
|
+
const SAMPLER_SOURCE = `self.onmessage = (event) => {
|
|
58
|
+
const slots = new Int32Array(event.data)
|
|
59
|
+
Atomics.store(slots, 0, ${CONTROL.ready})
|
|
60
|
+
Atomics.wait(slots, 0, ${CONTROL.ready})
|
|
61
|
+
if (Atomics.compareExchange(slots, 0, ${CONTROL.go}, ${CONTROL.sampling}) === ${CONTROL.go}) {
|
|
62
|
+
while (Atomics.load(slots, 0) === ${CONTROL.sampling}) {
|
|
63
|
+
const kib = (process.memoryUsage.rss() / 1024) | 0
|
|
64
|
+
if (kib > Atomics.load(slots, 1)) Atomics.store(slots, 1, kib)
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
postMessage(0)
|
|
68
|
+
}`;
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Start before taking the snapshots it's compared against, so the worker's
|
|
72
|
+
* own memory counts as setup. Single use: `during` terminates the worker.
|
|
73
|
+
* */
|
|
74
|
+
export interface RssSampler {
|
|
75
|
+
/** Runs `call`, returning the highest RSS seen meanwhile, bytes. */
|
|
76
|
+
during(call: () => Promise<void>): Promise<number>;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Generous: only a sampler that never answers (startup failure under heavy
|
|
80
|
+
// load aside) should hit it.
|
|
81
|
+
const HANDSHAKE_TIMEOUT_MS = 10_000;
|
|
82
|
+
|
|
83
|
+
export async function startRssSampler(
|
|
84
|
+
source: string = SAMPLER_SOURCE,
|
|
85
|
+
): Promise<RssSampler> {
|
|
86
|
+
const slots = new Int32Array(new SharedArrayBuffer(8));
|
|
87
|
+
const worker = new Worker(
|
|
88
|
+
URL.createObjectURL(new Blob([source], { type: "application/javascript" })),
|
|
89
|
+
);
|
|
90
|
+
// Rejects if the worker errors or exits before it finishes sampling, so a
|
|
91
|
+
// dead sampler fails the measurement instead of hanging it.
|
|
92
|
+
const died = new Promise<never>((_, reject) => {
|
|
93
|
+
const fail = (why: string) =>
|
|
94
|
+
reject(new Error(`RSS sampler worker failed: ${why}`));
|
|
95
|
+
worker.onerror = (event) => fail(event.message || "uncaught error");
|
|
96
|
+
worker.addEventListener("close", () => fail("worker exited unexpectedly"));
|
|
97
|
+
});
|
|
98
|
+
died.catch(() => {});
|
|
99
|
+
const stopped = new Promise((resolve) => {
|
|
100
|
+
worker.onmessage = resolve;
|
|
101
|
+
});
|
|
102
|
+
try {
|
|
103
|
+
worker.postMessage(slots.buffer);
|
|
104
|
+
const deadline = Date.now() + HANDSHAKE_TIMEOUT_MS;
|
|
105
|
+
while (Atomics.load(slots, 0) !== CONTROL.ready) {
|
|
106
|
+
if (Date.now() > deadline) {
|
|
107
|
+
throw new Error("RSS sampler worker failed: did not start in time");
|
|
108
|
+
}
|
|
109
|
+
await Promise.race([Bun.sleep(1), died]);
|
|
110
|
+
}
|
|
111
|
+
} catch (err) {
|
|
112
|
+
worker.terminate();
|
|
113
|
+
throw err;
|
|
114
|
+
}
|
|
115
|
+
return {
|
|
116
|
+
async during(call) {
|
|
117
|
+
try {
|
|
118
|
+
Atomics.store(slots, 0, CONTROL.go);
|
|
119
|
+
Atomics.notify(slots, 0);
|
|
120
|
+
// Spin first: the sampler must be polling before `call` starts, and
|
|
121
|
+
// it normally is within microseconds. Past that, yield so a dead
|
|
122
|
+
// worker's `died` can surface.
|
|
123
|
+
const spinUntil = Bun.nanoseconds() + 50e6;
|
|
124
|
+
while (
|
|
125
|
+
Atomics.load(slots, 0) !== CONTROL.sampling &&
|
|
126
|
+
Bun.nanoseconds() < spinUntil
|
|
127
|
+
) {
|
|
128
|
+
// Spin.
|
|
129
|
+
}
|
|
130
|
+
const deadline = Date.now() + HANDSHAKE_TIMEOUT_MS;
|
|
131
|
+
while (Atomics.load(slots, 0) !== CONTROL.sampling) {
|
|
132
|
+
if (Date.now() > deadline) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
"RSS sampler worker failed: did not start sampling",
|
|
135
|
+
);
|
|
136
|
+
}
|
|
137
|
+
await Promise.race([Bun.sleep(1), died]);
|
|
138
|
+
}
|
|
139
|
+
await call();
|
|
140
|
+
Atomics.store(slots, 0, CONTROL.stop);
|
|
141
|
+
await Promise.race([stopped, died]);
|
|
142
|
+
return Atomics.load(slots, 1) * 1024;
|
|
143
|
+
} finally {
|
|
144
|
+
worker.terminate();
|
|
145
|
+
}
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export interface PeakMemResult {
|
|
151
|
+
/** RSS rise above where it stood when the call started. */
|
|
152
|
+
peakBytes: number;
|
|
153
|
+
/**
|
|
154
|
+
* Setup-freed memory the allocator still held at call start (from
|
|
155
|
+
* `since`): the call can reuse it unseen, so `peakBytes` can be low by
|
|
156
|
+
* this much. */
|
|
157
|
+
slackBytes: number;
|
|
158
|
+
wallNs: number;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* How far one call of `fn` raises this process's RSS, garbage included:
|
|
163
|
+
* the higher of the worker-sampled peak and the `maxRSS` high-water mark
|
|
164
|
+
* (if the call moved it), after a full GC. Sampling alone can miss a spike
|
|
165
|
+
* between polls; the high-water mark alone misses any call peaking below
|
|
166
|
+
* an earlier peak (on Linux, every call smaller than process startup).
|
|
167
|
+
* Meant for the first call in a fresh process: memory an earlier call
|
|
168
|
+
* freed but the allocator holds (macOS returns it seconds later) is reused
|
|
169
|
+
* unseen. */
|
|
170
|
+
export async function measurePeakMem(
|
|
171
|
+
fn: () => unknown | Promise<unknown>,
|
|
172
|
+
since?: MemorySnapshot,
|
|
173
|
+
sampler?: RssSampler,
|
|
174
|
+
): Promise<PeakMemResult> {
|
|
175
|
+
const rss = sampler ?? (await startRssSampler());
|
|
176
|
+
Bun.gc(true);
|
|
177
|
+
const start = memorySnapshot();
|
|
178
|
+
const highWaterBefore = process.resourceUsage().maxRSS * 1024;
|
|
179
|
+
const startNs = Bun.nanoseconds();
|
|
180
|
+
let wallNs = 0;
|
|
181
|
+
const sampledMax = await rss.during(async () => {
|
|
182
|
+
const result = fn();
|
|
183
|
+
if (isPromiseLike(result)) await result;
|
|
184
|
+
wallNs = Bun.nanoseconds() - startNs;
|
|
185
|
+
});
|
|
186
|
+
const highWaterAfter = process.resourceUsage().maxRSS * 1024;
|
|
187
|
+
const peak = Math.max(
|
|
188
|
+
sampledMax,
|
|
189
|
+
highWaterAfter > highWaterBefore ? highWaterAfter : 0,
|
|
190
|
+
);
|
|
191
|
+
|
|
192
|
+
const residentFree = since
|
|
193
|
+
? start.residentBytes -
|
|
194
|
+
since.residentBytes -
|
|
195
|
+
(start.liveBytes - since.liveBytes)
|
|
196
|
+
: 0;
|
|
197
|
+
return {
|
|
198
|
+
peakBytes: Math.max(0, peak - start.rssBytes),
|
|
199
|
+
slackBytes: Math.max(0, residentFree),
|
|
200
|
+
wallNs,
|
|
201
|
+
};
|
|
202
|
+
}
|