ostia 0.2.12 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +50 -358
  3. package/docs/agent-protocol.md +210 -0
  4. package/docs/cli.md +1196 -0
  5. package/docs/config.md +233 -0
  6. package/docs/document-schema.md +224 -0
  7. package/docs/library.md +421 -0
  8. package/docs/preload-recipes.md +169 -0
  9. package/docs/statistics.md +218 -0
  10. package/index.d.ts +894 -677
  11. package/package.json +16 -14
  12. package/src/ab/ab-runner.ts +474 -0
  13. package/src/ab/index.ts +1086 -0
  14. package/src/baseline/index.ts +75 -0
  15. package/src/bench/index.ts +462 -0
  16. package/src/bench/projects.ts +39 -0
  17. package/src/bench/range.ts +27 -0
  18. package/src/bench/registry.ts +424 -0
  19. package/src/bench/run-tasks.ts +176 -0
  20. package/src/bench/run.ts +51 -0
  21. package/src/bench/runner.ts +147 -0
  22. package/src/bench/support.ts +161 -0
  23. package/src/bench/sweep.ts +39 -0
  24. package/src/cache/fingerprint.ts +59 -0
  25. package/src/cache/store.ts +28 -0
  26. package/src/capture/bunflags.ts +91 -0
  27. package/src/capture/cpu-parse.ts +119 -0
  28. package/src/capture/cpu.ts +44 -0
  29. package/src/capture/frames.ts +54 -0
  30. package/src/capture/heap-parse.ts +86 -0
  31. package/src/capture/heap.ts +32 -0
  32. package/src/capture/inspector.ts +46 -0
  33. package/src/capture/jsc-parse.ts +167 -0
  34. package/src/capture/jsc.ts +35 -0
  35. package/src/capture/sampling.ts +5 -0
  36. package/src/ci/index.ts +416 -0
  37. package/src/cli/flags.ts +264 -0
  38. package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
  39. package/src/cli/main.ts +18 -0
  40. package/src/cli/output.ts +185 -0
  41. package/src/cli/run.ts +1110 -0
  42. package/src/compare/index.ts +617 -0
  43. package/src/config/index.ts +275 -0
  44. package/src/config/validate.ts +267 -0
  45. package/src/errors.ts +8 -0
  46. package/src/format.ts +36 -0
  47. package/src/glob.ts +48 -0
  48. package/src/index.ts +62 -0
  49. package/src/ir/cpu.ts +10 -0
  50. package/src/ir/document.ts +471 -0
  51. package/src/ir/fp.ts +31 -0
  52. package/src/ir/git.ts +36 -0
  53. package/src/ir/types.ts +615 -0
  54. package/src/measure/alloc.ts +57 -0
  55. package/src/measure/cpu.ts +99 -0
  56. package/src/measure/environment.ts +41 -0
  57. package/src/measure/inprocess.ts +191 -0
  58. package/src/measure/instructions.ts +133 -0
  59. package/src/measure/loop.ts +57 -0
  60. package/src/measure/noise.ts +55 -0
  61. package/src/measure/paired.ts +312 -0
  62. package/src/measure/peak.ts +202 -0
  63. package/src/measure/timing.ts +263 -0
  64. package/src/profile.ts +109 -0
  65. package/src/renderers/collapsed.ts +35 -0
  66. package/src/renderers/cpu-tree.ts +183 -0
  67. package/src/renderers/cpuprofile.ts +43 -0
  68. package/src/renderers/format.ts +142 -0
  69. package/src/renderers/index.ts +27 -0
  70. package/src/renderers/json.ts +10 -0
  71. package/src/renderers/jsonl.ts +15 -0
  72. package/src/renderers/markdown.ts +525 -0
  73. package/src/renderers/mermaid.ts +78 -0
  74. package/src/renderers/minimal.ts +602 -0
  75. package/src/renderers/paired.ts +229 -0
  76. package/src/renderers/relative.ts +64 -0
  77. package/src/renderers/select.ts +286 -0
  78. package/src/renderers/speedscope.ts +69 -0
  79. package/src/renderers/terminal.ts +466 -0
  80. package/src/renderers/types.ts +27 -0
  81. package/src/spawn/index.ts +396 -0
  82. package/src/stats/bootstrap.ts +153 -0
  83. package/src/stats/index.ts +140 -0
  84. package/src/stats/mannwhitney.ts +81 -0
  85. package/src/time.ts +325 -0
  86. package/src/version.ts +3 -0
  87. package/ab-runner.ts +0 -8
  88. package/chunk-05jfst35.js +0 -28
  89. package/chunk-1g1x9zz2.js +0 -15
  90. package/chunk-23g2rwrn.js +0 -3
  91. package/chunk-468h5412.js +0 -25
  92. package/chunk-4esjfc2m.js +0 -2
  93. package/chunk-ct2xsezd.js +0 -14
  94. package/cli.js +0 -3
  95. package/index.js +0 -2
  96. package/runner.ts +0 -7
@@ -0,0 +1,99 @@
1
+ import { captureJscProfile } from "../capture/jsc.ts";
2
+ import { cpuSampleCount } from "../ir/cpu.ts";
3
+ import type { CpuEvidence, JitTierBreakdown, Warning } from "../ir/types.ts";
4
+ import { isPromiseLike } from "./loop.ts";
5
+
6
+ /**
7
+ * JSC's 1000µs default gives a ~3ms task about three samples per call, too
8
+ * few for a top-frame table to hold still between runs. */
9
+ export const DEFAULT_TASK_CPU_INTERVAL_US = 100;
10
+ /**
11
+ * The sampler manages well under one sample per interval (about 0.6 at
12
+ * 100µs, 0.8 at 1000µs on an idle M2), hence the 2x slack on the window.
13
+ * */
14
+ const TARGET_SAMPLES = 2000;
15
+ const WINDOW_SLACK = 2;
16
+ const MIN_WINDOW_MS = 200;
17
+ const MAX_WINDOW_MS = 10_000;
18
+ const LOW_SAMPLES = TARGET_SAMPLES / 2;
19
+ const JIT_COLD_THRESHOLD_PCT = 20;
20
+
21
+ export interface TaskCpuCaptureOptions {
22
+ intervalUs?: number;
23
+ }
24
+
25
+ export interface TaskCpuCaptureResult {
26
+ cpu: CpuEvidence;
27
+ jit: JitTierBreakdown;
28
+ diagnosticWallNs: number;
29
+ warnings: Warning[];
30
+ }
31
+
32
+ /**
33
+ * Capture window, ms: about `TARGET_SAMPLES` at `intervalUs`, clamped to
34
+ * [200ms, 10s]. A task slower than the window still runs once, whole. */
35
+ export function cpuWindowMs(intervalUs: number): number {
36
+ const ms = (TARGET_SAMPLES * WINDOW_SLACK * intervalUs) / 1000;
37
+ return Math.min(MAX_WINDOW_MS, Math.max(MIN_WINDOW_MS, ms));
38
+ }
39
+
40
+ /**
41
+ * Loops `fn` under the JSC sampling profiler for `cpuWindowMs`; one call
42
+ * is usually gone before the first tick. Never feeds timing stats. */
43
+ export async function captureTaskCpuProfile(
44
+ fn: () => unknown | Promise<unknown>,
45
+ opts: TaskCpuCaptureOptions = {},
46
+ ): Promise<TaskCpuCaptureResult> {
47
+ const intervalUs = opts.intervalUs ?? DEFAULT_TASK_CPU_INTERVAL_US;
48
+ const budgetNs = cpuWindowMs(intervalUs) * 1e6;
49
+ const looped = async (): Promise<void> => {
50
+ const start = Bun.nanoseconds();
51
+ do {
52
+ const result = fn();
53
+ if (isPromiseLike(result)) await result;
54
+ } while (Bun.nanoseconds() - start < budgetNs);
55
+ };
56
+ const { cpu, jit, diagnosticWallNs } = await captureJscProfile(looped, {
57
+ intervalUs,
58
+ });
59
+ const warnings = [lowCpuSampleWarning(cpu), jitColdWarning(jit)].filter(
60
+ (w): w is Warning => w !== undefined,
61
+ );
62
+ return { cpu, jit, diagnosticWallNs, warnings };
63
+ }
64
+
65
+ function lowCpuSampleWarning(cpu: CpuEvidence): Warning | undefined {
66
+ const samples = cpuSampleCount(cpu);
67
+ if (samples >= LOW_SAMPLES) return undefined;
68
+ return {
69
+ code: "low-sample-count",
70
+ message: `Only ${samples} CPU sample(s) at ${cpu.samplingIntervalUs}µs (target ${TARGET_SAMPLES}); frame shares this thin move several points between runs. Lower --cpu-interval for more.`,
71
+ data: {
72
+ samples,
73
+ target: TARGET_SAMPLES,
74
+ intervalUs: cpu.samplingIntervalUs,
75
+ },
76
+ };
77
+ }
78
+
79
+ /**
80
+ * Warns when over `JIT_COLD_THRESHOLD_PCT`% of samples are still in
81
+ * llint/baseline.
82
+ */
83
+ export function jitColdWarning(jit: JitTierBreakdown): Warning | undefined {
84
+ const { llint, baseline, dfg, ftl } = jit.tiers;
85
+ const total = llint + baseline + dfg + ftl;
86
+ if (total === 0) return undefined;
87
+
88
+ const llintPct = (llint / total) * 100;
89
+ const baselinePct = (baseline / total) * 100;
90
+ const dfgPct = (dfg / total) * 100;
91
+ const ftlPct = (ftl / total) * 100;
92
+ if (llintPct + baselinePct <= JIT_COLD_THRESHOLD_PCT) return undefined;
93
+
94
+ return {
95
+ code: "jit-cold",
96
+ message: `${(llintPct + baselinePct).toFixed(1)}% of CPU samples were in the llint/baseline tiers: the JIT never warmed this task up.`,
97
+ data: { llintPct, baselinePct, dfgPct, ftlPct },
98
+ };
99
+ }
@@ -0,0 +1,41 @@
1
+ import os from "node:os";
2
+
3
+ import type { Environment, Warning } from "../ir/types.ts";
4
+ import { measureNoiseFloor } from "./noise.ts";
5
+
6
+ const LOAD_WARNING_FRACTION = 0.75;
7
+
8
+ /**
9
+ * Takes ~200ms (runs the noise-floor workload): call once per invocation,
10
+ * not per workload.
11
+ */
12
+ export function captureEnvironment(): Environment {
13
+ const [loadAvg1 = 0, loadAvg5 = 0] = os.loadavg();
14
+ return {
15
+ cpuModel: os.cpus()[0]?.model ?? "unknown",
16
+ cores: os.availableParallelism(),
17
+ loadAvg1,
18
+ loadAvg5,
19
+ noise: measureNoiseFloor(),
20
+ };
21
+ }
22
+
23
+ /**
24
+ * Re-runs the reference loop at the end of a run and stamps how much
25
+ * slower it ran than at the start on `env.noise.driftPct`: the machine's
26
+ * drift over the run, which `compare` adds to its timing threshold. */
27
+ export function stampDrift(env: Environment | undefined): void {
28
+ if (!env) return;
29
+ const start = env.noise.referenceMedianNs;
30
+ const end = measureNoiseFloor().referenceMedianNs;
31
+ env.noise.driftPct = start > 0 ? (end / start - 1) * 100 : 0;
32
+ }
33
+
34
+ export function noisyMachineWarning(env: Environment): Warning | undefined {
35
+ if (env.loadAvg1 <= env.cores * LOAD_WARNING_FRACTION) return undefined;
36
+ return {
37
+ code: "noisy-machine",
38
+ message: `Load average ${env.loadAvg1.toFixed(2)} exceeds ${LOAD_WARNING_FRACTION * 100}% of ${env.cores} available core(s); timing noise may be elevated.`,
39
+ data: { loadAvg1: env.loadAvg1, cores: env.cores },
40
+ };
41
+ }
@@ -0,0 +1,191 @@
1
+ import { formatDuration } from "../format.ts";
2
+ import type {
3
+ InstructionStats,
4
+ TimingStats,
5
+ Trial,
6
+ Warning,
7
+ } from "../ir/types.ts";
8
+ import {
9
+ computeTimingStats,
10
+ percentile,
11
+ sortedCopy,
12
+ timingWarnings,
13
+ } from "../stats/index.ts";
14
+ import { instructionCounter } from "./instructions.ts";
15
+ import { batchTimer, probeFirstCall, type TaskBody } from "./loop.ts";
16
+
17
+ export interface InprocessTimingOptions {
18
+ /** Wall-clock budget for the sampling loop, per task (default: 500). */
19
+ budgetMs?: number;
20
+ /** Exact trial count; the budget is ignored. */
21
+ samples?: number;
22
+ /** Keep sampling past the budget until this many trials exist. When unset
23
+ * the floor is cost-aware (see `defaultSampleFloor`). */
24
+ minSamples?: number;
25
+ /** Warmup budget as a fraction of `budgetMs` (default: 0.1); unlike
26
+ * `time()`'s `warmup`, which is a trial count. Always runs at least one
27
+ * call. */
28
+ warmup?: number;
29
+ gc?: boolean;
30
+ }
31
+
32
+ const DEFAULT_TIME_BUDGET_MS = 500;
33
+ // Upper bound only: a task cheap enough to fit 20 trials in the budget is
34
+ // time-bound.
35
+ const BUDGET_FLOOR_CAP = 20;
36
+ const RIGOR_FLOOR_MIN = 3;
37
+ const RIGOR_FLOOR_CAP = 10;
38
+ const RIGOR_SAMPLES_PER_DECADE = 2;
39
+ const DEFAULT_WARMUP_FRACTION = 0.1;
40
+ // Batch each trial to at least this long so timer resolution doesn't
41
+ // dominate.
42
+ const BATCH_THRESHOLD_NS = 1000;
43
+ // Batch further so a full budget yields about this many trials: every
44
+ // trial is sorted, serialized over IPC and parsed back, which costs
45
+ // seconds at millions.
46
+ const TRIALS_TARGET = 10_000;
47
+ // Hard stop for a task that got faster than its calibration predicted.
48
+ const MAX_TRIALS = 2 * TRIALS_TARGET;
49
+ // Warmup doubles its batch until one spans this long.
50
+ const WARMUP_CHUNK_NS = 1_000_000;
51
+ const CALIBRATION_ROUNDS = 5;
52
+
53
+ export interface InprocessTimingResult {
54
+ trials: Trial[];
55
+ timing: TimingStats;
56
+ /** Per trial, where the machine counts them. */
57
+ instructions?: InstructionStats;
58
+ warnings: Warning[];
59
+ }
60
+
61
+ /** Samples a task's per-trial cost earns regardless of budget: 3 at 1ms or
62
+ * less, two more per decade of cost, capped at 10 from about 3s up. Only
63
+ * expensive tasks ever hit it; the budget fills cheap ones with thousands.
64
+ * */
65
+ export function rigorFloor(trialCostNs: number): number {
66
+ const decadesAboveOneMs = Math.log10(Math.max(1, trialCostNs) / 1e6);
67
+ const floor = Math.round(
68
+ RIGOR_FLOOR_MIN + RIGOR_SAMPLES_PER_DECADE * decadesAboveOneMs,
69
+ );
70
+ return Math.min(RIGOR_FLOOR_CAP, Math.max(RIGOR_FLOOR_MIN, floor));
71
+ }
72
+
73
+ /** Default floor without `minSamples`: as many trials as fit in the budget
74
+ * (capped at 20), never fewer than `rigorFloor`. */
75
+ export function defaultSampleFloor(
76
+ trialCostNs: number,
77
+ timeBudgetNs: number,
78
+ ): number {
79
+ const fit = Math.floor(timeBudgetNs / trialCostNs);
80
+ return Math.min(BUDGET_FLOOR_CAP, Math.max(fit, rigorFloor(trialCostNs)));
81
+ }
82
+
83
+ // Write-only on purpose: a store to module state is never provably dead.
84
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- see above
85
+ let kept: unknown;
86
+
87
+ /** Pins `value` against dead-code elimination for an intermediate inside a
88
+ * task body. A task's own return value is already pinned by the timing
89
+ * loop. */
90
+ export function keep(value: unknown): void {
91
+ kept = value;
92
+ }
93
+
94
+ function sizeBatch(singleCallNs: number, timeBudgetNs: number): number {
95
+ return Math.max(
96
+ 1,
97
+ Math.ceil(BATCH_THRESHOLD_NS / singleCallNs),
98
+ Math.ceil(timeBudgetNs / (singleCallNs * TRIALS_TARGET)),
99
+ );
100
+ }
101
+
102
+ function medianOf(values: number[]): number {
103
+ const sorted = [...values].sort((a, b) => a - b);
104
+ return sorted[sorted.length >> 1]!;
105
+ }
106
+
107
+ export async function measureTask(
108
+ fn: TaskBody,
109
+ opts: InprocessTimingOptions = {},
110
+ ): Promise<InprocessTimingResult> {
111
+ const timeBudgetNs = (opts.budgetMs ?? DEFAULT_TIME_BUDGET_MS) * 1e6;
112
+ const warmupBudgetNs =
113
+ timeBudgetNs * (opts.warmup ?? DEFAULT_WARMUP_FRACTION);
114
+
115
+ // The first call picks the loop and is the cost estimate when warmup is
116
+ // off.
117
+ const first = await probeFirstCall(fn);
118
+ let singleCallNs = first.ns;
119
+ const timeBatch = batchTimer(fn, first.isAsync);
120
+
121
+ const warmupStart = Bun.nanoseconds();
122
+ let n = 1;
123
+ while (Bun.nanoseconds() - warmupStart < warmupBudgetNs) {
124
+ const ns = await timeBatch(n);
125
+ singleCallNs = Math.max(1, ns / n);
126
+ if (ns < WARMUP_CHUNK_NS) n *= 2;
127
+ }
128
+
129
+ // A single warmup batch can be inflated by a GC pause or tier-up compile
130
+ // and under-batch a fast task into a flood of trials; settle on the median
131
+ // of a few batches at the planned size instead.
132
+ let batchSize = sizeBatch(singleCallNs, timeBudgetNs);
133
+ if (batchSize > 1) {
134
+ const perCall: number[] = [];
135
+ for (let r = 0; r < CALIBRATION_ROUNDS; r++) {
136
+ perCall.push((await timeBatch(batchSize)) / batchSize);
137
+ }
138
+ singleCallNs = Math.max(1, medianOf(perCall));
139
+ batchSize = sizeBatch(singleCallNs, timeBudgetNs);
140
+ }
141
+ const trialCostNs = singleCallNs * batchSize;
142
+ const minSamples =
143
+ opts.samples ??
144
+ opts.minSamples ??
145
+ defaultSampleFloor(trialCostNs, timeBudgetNs);
146
+ const effectiveBudgetNs = opts.samples !== undefined ? 0 : timeBudgetNs;
147
+ const maxTrials = opts.samples ?? Math.max(MAX_TRIALS, minSamples);
148
+
149
+ // Read around each batch, outside the loop's own clock reads.
150
+ const count = instructionCounter().read;
151
+ const instructions: number[] = [];
152
+ const trials: Trial[] = [];
153
+ const start = Bun.nanoseconds();
154
+ let elapsed = 0;
155
+ let i = 0;
156
+ while (i < minSamples || (elapsed < effectiveBudgetNs && i < maxTrials)) {
157
+ const before = count?.() ?? 0;
158
+ const ns = await timeBatch(batchSize);
159
+ if (count) instructions.push((count() - before) / batchSize);
160
+ trials.push({ i, wallNs: ns / batchSize });
161
+ i++;
162
+ elapsed = Bun.nanoseconds() - start;
163
+ if (opts.gc) Bun.gc(true);
164
+ }
165
+
166
+ const timing = computeTimingStats(trials.map((t) => t.wallNs));
167
+ if (batchSize > 1) timing.batch = batchSize;
168
+ const warnings = timingWarnings(timing, [], "inprocess");
169
+
170
+ // Only fires when an explicit `minSamples` undercut the default floor.
171
+ const target = rigorFloor(trialCostNs);
172
+ if (trials.length < target) {
173
+ warnings.push({
174
+ code: "low-sample-count",
175
+ message: `Only ${trials.length} sample(s) at ~${formatDuration(trialCostNs)} per trial; ${target} is the floor for this cost class. Raise minSamples or the time budget for a steadier number.`,
176
+ data: { samples: trials.length, target, trialCostNs },
177
+ });
178
+ }
179
+
180
+ return {
181
+ trials,
182
+ timing,
183
+ ...(count && {
184
+ instructions: {
185
+ samples: instructions,
186
+ median: percentile(sortedCopy(instructions), 0.5),
187
+ },
188
+ }),
189
+ warnings,
190
+ };
191
+ }
@@ -0,0 +1,133 @@
1
+ import { dlopen, FFIType, ptr, read } from "bun:ffi";
2
+
3
+ /**
4
+ * Reads how many instructions the calling thread has retired in user mode.
5
+ * Only differences between two reads mean anything. */
6
+ type InstructionReader = () => number;
7
+
8
+ export type InstructionCounter =
9
+ | { read: InstructionReader; unavailable?: undefined }
10
+ /** Why this machine can't count instructions, for an error message. */
11
+ | { read?: undefined; unavailable: string };
12
+
13
+ let counter: InstructionCounter | undefined;
14
+
15
+ /**
16
+ * The calling thread's retired-instruction counter: steadier than wall
17
+ * time on a loaded machine, since another process taking the CPU doesn't
18
+ * change what this thread executes. Per thread, user mode only, so neither
19
+ * the kernel's work for a system call nor any other thread's (JIT
20
+ * compiler, GC helpers, I/O pool) counts. Reads the hardware counter
21
+ * through `thread_selfcounts` on macOS and `perf_event_open` on Linux. */
22
+ export function instructionCounter(): InstructionCounter {
23
+ counter ??= openCounter();
24
+ return counter;
25
+ }
26
+
27
+ function openCounter(): InstructionCounter {
28
+ try {
29
+ if (process.platform === "darwin") return darwinCounter();
30
+ if (process.platform === "linux") return linuxCounter();
31
+ } catch (err) {
32
+ return { unavailable: (err as Error).message };
33
+ }
34
+ return { unavailable: `not supported on ${process.platform}` };
35
+ }
36
+
37
+ // thread_selfcounts(1, ...) fills { instructions, cycles } for the calling
38
+ // thread: what `/usr/bin/time -l` totals over a process, read per thread.
39
+ function darwinCounter(): InstructionCounter {
40
+ const { symbols } = dlopen("/usr/lib/libSystem.B.dylib", {
41
+ thread_selfcounts: {
42
+ args: [FFIType.i32, FFIType.ptr, FFIType.u64],
43
+ returns: FFIType.i32,
44
+ },
45
+ });
46
+ const counts = new BigUint64Array(2);
47
+ const at = ptr(counts);
48
+ if (symbols.thread_selfcounts(1, at, 16) !== 0 || counts[0] === 0n) {
49
+ return {
50
+ unavailable:
51
+ "thread_selfcounts can't read this Mac's instruction counter (in a VM?)",
52
+ };
53
+ }
54
+ return {
55
+ read: () => {
56
+ symbols.thread_selfcounts(1, at, 16);
57
+ return Number(counts[0]);
58
+ },
59
+ };
60
+ }
61
+
62
+ const PERF_EVENT_OPEN: Partial<Record<string, number>> = {
63
+ x64: 298,
64
+ arm64: 241,
65
+ };
66
+ const PERF_TYPE_HARDWARE = 0;
67
+ const PERF_COUNT_HW_INSTRUCTIONS = 1;
68
+ // perf_event_attr's first version, which every kernel since takes.
69
+ const PERF_ATTR_SIZE_VER0 = 64;
70
+ // exclude_kernel | exclude_hv: what `perf_event_paranoid` 2 still allows.
71
+ const PERF_USER_ONLY = (1n << 5n) | (1n << 6n);
72
+
73
+ // An event opened with pid 0 and cpu -1 counts the calling thread, on any
74
+ // CPU, from the moment it's opened.
75
+ function linuxCounter(): InstructionCounter {
76
+ const nr = PERF_EVENT_OPEN[process.arch];
77
+ if (nr === undefined) {
78
+ return { unavailable: `not supported on linux/${process.arch}` };
79
+ }
80
+ const { symbols } = dlopen("libc.so.6", {
81
+ syscall: {
82
+ args: [
83
+ FFIType.i64,
84
+ FFIType.ptr,
85
+ FFIType.i64,
86
+ FFIType.i64,
87
+ FFIType.i64,
88
+ FFIType.i64,
89
+ ],
90
+ returns: FFIType.i64,
91
+ },
92
+ read: {
93
+ args: [FFIType.i32, FFIType.ptr, FFIType.u64],
94
+ returns: FFIType.i64,
95
+ },
96
+ __errno_location: { args: [], returns: FFIType.ptr },
97
+ });
98
+ const attr = new BigUint64Array(PERF_ATTR_SIZE_VER0 / 8);
99
+ const head = new Uint32Array(attr.buffer, 0, 2);
100
+ head[0] = PERF_TYPE_HARDWARE;
101
+ head[1] = PERF_ATTR_SIZE_VER0;
102
+ attr[1] = BigInt(PERF_COUNT_HW_INSTRUCTIONS);
103
+ attr[5] = PERF_USER_ONLY;
104
+ const fd = Number(symbols.syscall(nr, ptr(attr), 0, -1, -1, 0));
105
+ if (fd < 0) {
106
+ const errno = read.i32(symbols.__errno_location()!);
107
+ return { unavailable: perfError(errno) };
108
+ }
109
+ const count = new BigUint64Array(1);
110
+ const at = ptr(count);
111
+ if (Number(symbols.read(fd, at, 8)) !== 8) {
112
+ return { unavailable: "perf_event_open's counter couldn't be read" };
113
+ }
114
+ return {
115
+ read: () => {
116
+ symbols.read(fd, at, 8);
117
+ return Number(count[0]);
118
+ },
119
+ };
120
+ }
121
+
122
+ function perfError(errno: number): string {
123
+ const base = `perf_event_open failed (errno ${errno})`;
124
+ // EACCES, EPERM
125
+ if (errno === 13 || errno === 1) {
126
+ return `${base}: not permitted; set /proc/sys/kernel/perf_event_paranoid to 2 or lower (a container may also need CAP_PERFMON or a seccomp profile that allows it)`;
127
+ }
128
+ // ENOENT, ENODEV, EOPNOTSUPP
129
+ if (errno === 2 || errno === 19 || errno === 95) {
130
+ return `${base}: this machine exposes no instruction counter (many VMs and containers don't)`;
131
+ }
132
+ return base;
133
+ }
@@ -0,0 +1,57 @@
1
+ export type TaskBody = () => unknown | Promise<unknown>;
2
+
3
+ export function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
4
+ return (
5
+ value !== null &&
6
+ typeof value === "object" &&
7
+ typeof (value as PromiseLike<unknown>).then === "function"
8
+ );
9
+ }
10
+
11
+ type Loop = (
12
+ fn: TaskBody,
13
+ sink: unknown[],
14
+ n: number,
15
+ ) => number | Promise<number>;
16
+
17
+ const AsyncFunction = (async () => {}).constructor as FunctionConstructor;
18
+ let loopSerial = 0;
19
+ // Ring buffer every result is stored into: the JIT can't prove a stored
20
+ // value unused, so it can't elide the call or its allocations.
21
+ const SINK_SIZE = 256;
22
+
23
+ /** Times `n` back-to-back calls of `fn`, returning total ns, through a loop
24
+ * compiled for this task alone. JSC specializes compiled code per
25
+ * function: a shared loop gets its `fn()` call site tuned for whichever
26
+ * task ran first and measures every later task through a slower generic
27
+ * call. The serial in the source keeps JSC's code cache from handing two
28
+ * tasks the same compiled body. An async task gets an awaiting loop; a
29
+ * sync one never pays a microtask per call. */
30
+ export function batchTimer(
31
+ fn: TaskBody,
32
+ isAsync: boolean,
33
+ ): (n: number) => number | Promise<number> {
34
+ const body = `/* ostia task loop ${loopSerial++} */
35
+ const t0 = Bun.nanoseconds()
36
+ for (let b = 0; b < n; b++) sink[b & ${SINK_SIZE - 1}] = ${isAsync ? "await " : ""}fn()
37
+ return Bun.nanoseconds() - t0`;
38
+ const loop = (isAsync ? AsyncFunction : Function)(
39
+ "fn",
40
+ "sink",
41
+ "n",
42
+ body,
43
+ ) as Loop;
44
+ const sink: unknown[] = new Array(SINK_SIZE);
45
+ return (n) => loop(fn, sink, n);
46
+ }
47
+
48
+ /** Calls `fn` once, timed, to learn whether it is async. */
49
+ export async function probeFirstCall(
50
+ fn: TaskBody,
51
+ ): Promise<{ isAsync: boolean; result: unknown; ns: number }> {
52
+ const t0 = Bun.nanoseconds();
53
+ const value = fn();
54
+ const isAsync = isPromiseLike(value);
55
+ const result = isAsync ? await value : value;
56
+ return { isAsync, result, ns: Math.max(1, Bun.nanoseconds() - t0) };
57
+ }
@@ -0,0 +1,55 @@
1
+ import type { NoiseFloor } from "../ir/types.ts";
2
+ import { computeTimingStats } from "../stats/index.ts";
3
+
4
+ const DEFAULT_BUDGET_MS = 200;
5
+ // Keeps a trial in the microsecond range so timer resolution doesn't
6
+ // dominate.
7
+ const HASHES_PER_TRIAL = 64;
8
+
9
+ // Fixed, allocation-free workload: trial-to-trial variance is the
10
+ // machine's noise.
11
+ const REFERENCE_BUFFER = (() => {
12
+ const buf = new Uint8Array(4096);
13
+ for (let i = 0; i < buf.length; i++) buf[i] = (i * 2654435761) & 0xff;
14
+ return buf;
15
+ })();
16
+
17
+ function hashBuffer(buf: Uint8Array, seed: number): number {
18
+ let h = seed;
19
+ for (let i = 0; i < buf.length; i++) {
20
+ h ^= buf[i]!;
21
+ h = Math.imul(h, 16777619);
22
+ }
23
+ return h >>> 0;
24
+ }
25
+
26
+ /** `mad / median` of `samples`, as a percent. */
27
+ export function computeNoiseFloor(samples: number[]): NoiseFloor {
28
+ const stats = computeTimingStats(samples);
29
+ return {
30
+ floorPct: stats.median === 0 ? 0 : (stats.mad / stats.median) * 100,
31
+ referenceMedianNs: stats.median,
32
+ samples: samples.length,
33
+ };
34
+ }
35
+
36
+ /**
37
+ * Samples the reference hash loop for `budgetMs`; characterizes the
38
+ * machine, not any workload, so run it once per document. */
39
+ export function measureNoiseFloor(budgetMs = DEFAULT_BUDGET_MS): NoiseFloor {
40
+ const budgetNs = budgetMs * 1e6;
41
+ const trials: number[] = [];
42
+ let sink = 0;
43
+
44
+ const start = Bun.nanoseconds();
45
+ while (Bun.nanoseconds() - start < budgetNs) {
46
+ const trialStart = Bun.nanoseconds();
47
+ for (let i = 0; i < HASHES_PER_TRIAL; i++) {
48
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars -- write-only, defeats DCE
49
+ sink ^= hashBuffer(REFERENCE_BUFFER, i);
50
+ }
51
+ trials.push((Bun.nanoseconds() - trialStart) / HASHES_PER_TRIAL);
52
+ }
53
+
54
+ return computeNoiseFloor(trials);
55
+ }