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,91 @@
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
+ // JSC's 1000µs default would give a ~3ms task about three samples per
7
+ // call, too few for a top-frame table to hold still between runs.
8
+ export const DEFAULT_TASK_CPU_INTERVAL_US = 100;
9
+ // perf: the sampler manages well under one sample per interval (about 0.6
10
+ // at 100µs, 0.8 at 1000µs on an idle M2), hence the 2x slack on the
11
+ // window.
12
+ const TARGET_SAMPLES = 2000;
13
+ const WINDOW_SLACK = 2;
14
+ const MIN_WINDOW_MS = 200;
15
+ const MAX_WINDOW_MS = 10_000;
16
+ const LOW_SAMPLES = TARGET_SAMPLES / 2;
17
+ const JIT_COLD_THRESHOLD_PCT = 20;
18
+
19
+ interface TaskCpuCaptureOptions {
20
+ intervalUs?: number;
21
+ }
22
+
23
+ interface TaskCpuCaptureResult {
24
+ cpu: CpuEvidence;
25
+ jit: JitTierBreakdown;
26
+ diagnosticWallNs: number;
27
+ warnings: Warning[];
28
+ }
29
+
30
+ // In ms. A task slower than the window still runs once, whole: the window
31
+ // never cuts a call short.
32
+ export function cpuWindowMs(intervalUs: number): number {
33
+ const ms = (TARGET_SAMPLES * WINDOW_SLACK * intervalUs) / 1000;
34
+ return Math.min(MAX_WINDOW_MS, Math.max(MIN_WINDOW_MS, ms));
35
+ }
36
+
37
+ // Loops `fn` under the JSC sampling profiler for `cpuWindowMs`; one call
38
+ // is usually gone before the first tick. Never feeds timing stats.
39
+ export async function captureTaskCpuProfile(
40
+ fn: () => unknown,
41
+ opts: TaskCpuCaptureOptions = {},
42
+ ): Promise<TaskCpuCaptureResult> {
43
+ const intervalUs = opts.intervalUs ?? DEFAULT_TASK_CPU_INTERVAL_US;
44
+ const budgetNs = cpuWindowMs(intervalUs) * 1e6;
45
+ const looped = async (): Promise<void> => {
46
+ const start = Bun.nanoseconds();
47
+ do {
48
+ const result = fn();
49
+ if (isPromiseLike(result)) await result;
50
+ } while (Bun.nanoseconds() - start < budgetNs);
51
+ };
52
+ const { cpu, jit, diagnosticWallNs } = await captureJscProfile(looped, {
53
+ intervalUs,
54
+ });
55
+ const warnings = [lowCpuSampleWarning(cpu), jitColdWarning(jit)].filter(
56
+ (w): w is Warning => w !== undefined,
57
+ );
58
+ return { cpu, jit, diagnosticWallNs, warnings };
59
+ }
60
+
61
+ function lowCpuSampleWarning(cpu: CpuEvidence): Warning | undefined {
62
+ const samples = cpuSampleCount(cpu);
63
+ if (samples >= LOW_SAMPLES) return undefined;
64
+ return {
65
+ code: "low-sample-count",
66
+ 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.`,
67
+ data: {
68
+ samples,
69
+ target: TARGET_SAMPLES,
70
+ intervalUs: cpu.samplingIntervalUs,
71
+ },
72
+ };
73
+ }
74
+
75
+ export function jitColdWarning(jit: JitTierBreakdown): Warning | undefined {
76
+ const { llint, baseline, dfg, ftl } = jit.tiers;
77
+ const total = llint + baseline + dfg + ftl;
78
+ if (total === 0) return undefined;
79
+
80
+ const llintPct = (llint / total) * 100;
81
+ const baselinePct = (baseline / total) * 100;
82
+ const dfgPct = (dfg / total) * 100;
83
+ const ftlPct = (ftl / total) * 100;
84
+ if (llintPct + baselinePct <= JIT_COLD_THRESHOLD_PCT) return undefined;
85
+
86
+ return {
87
+ code: "jit-cold",
88
+ message: `${(llintPct + baselinePct).toFixed(1)}% of CPU samples were in the llint/baseline tiers: the JIT never warmed this task up.`,
89
+ data: { llintPct, baselinePct, dfgPct, ftlPct },
90
+ };
91
+ }
@@ -0,0 +1,38 @@
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
+ // perf: takes ~200ms (runs the noise-floor workload), so call it once per
9
+ // invocation, never per workload.
10
+ export function captureEnvironment(): Environment {
11
+ const [loadAvg1 = 0, loadAvg5 = 0] = os.loadavg();
12
+ return {
13
+ cpuModel: os.cpus()[0]?.model ?? "unknown",
14
+ cores: os.availableParallelism(),
15
+ loadAvg1,
16
+ loadAvg5,
17
+ noise: measureNoiseFloor(),
18
+ };
19
+ }
20
+
21
+ // Run at the end of a run, because `compare` adds the machine's drift
22
+ // over the run (how much slower the reference loop ran than at the start)
23
+ // to its timing threshold.
24
+ export function stampDrift(env: Environment | undefined): void {
25
+ if (!env) return;
26
+ const start = env.noise.referenceMedianNs;
27
+ const end = measureNoiseFloor().referenceMedianNs;
28
+ env.noise.driftPct = start > 0 ? (end / start - 1) * 100 : 0;
29
+ }
30
+
31
+ export function noisyMachineWarning(env: Environment): Warning | undefined {
32
+ if (env.loadAvg1 <= env.cores * LOAD_WARNING_FRACTION) return undefined;
33
+ return {
34
+ code: "noisy-machine",
35
+ message: `Load average ${env.loadAvg1.toFixed(2)} exceeds ${LOAD_WARNING_FRACTION * 100}% of ${env.cores} available core(s); timing noise may be elevated.`,
36
+ data: { loadAvg1: env.loadAvg1, cores: env.cores },
37
+ };
38
+ }
@@ -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
+ // A hard stop, since a task that got faster than its calibration predicted
48
+ // would otherwise run far past `TRIALS_TARGET`.
49
+ const MAX_TRIALS = 2 * TRIALS_TARGET;
50
+ // Warmup doubles its batch until one spans this long.
51
+ const WARMUP_CHUNK_NS = 1_000_000;
52
+ const CALIBRATION_ROUNDS = 5;
53
+
54
+ interface InprocessTimingResult {
55
+ trials: Trial[];
56
+ timing: TimingStats;
57
+ /** Per trial, where the machine counts them. */
58
+ instructions?: InstructionStats;
59
+ warnings: Warning[];
60
+ }
61
+
62
+ // Samples a task's per-trial cost earns regardless of budget: 3 at 1ms or
63
+ // less, two more per decade of cost, capped at 10 from about 3s up. Only
64
+ // expensive tasks ever hit it; the budget fills cheap ones with thousands.
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
+ const kept: { value?: unknown } = {};
85
+
86
+ /** Pins `value` against dead-code elimination for an intermediate inside a
87
+ * task body. A task's own return value is already pinned by the timing
88
+ * loop. */
89
+ export function keep(value: unknown): void {
90
+ kept.value = value;
91
+ }
92
+
93
+ function sizeBatch(singleCallNs: number, timeBudgetNs: number): number {
94
+ return Math.max(
95
+ 1,
96
+ Math.ceil(BATCH_THRESHOLD_NS / singleCallNs),
97
+ Math.ceil(timeBudgetNs / (singleCallNs * TRIALS_TARGET)),
98
+ );
99
+ }
100
+
101
+ function medianOf(values: number[]): number {
102
+ const sorted = [...values].sort((a, b) => a - b);
103
+ return sorted[sorted.length >> 1] ?? 0;
104
+ }
105
+
106
+ export async function measureTask(
107
+ fn: TaskBody,
108
+ opts: InprocessTimingOptions = {},
109
+ ): Promise<InprocessTimingResult> {
110
+ const timeBudgetNs = (opts.budgetMs ?? DEFAULT_TIME_BUDGET_MS) * 1e6;
111
+ const warmupBudgetNs =
112
+ timeBudgetNs * (opts.warmup ?? DEFAULT_WARMUP_FRACTION);
113
+
114
+ // The first call picks the loop, and is the only cost estimate when
115
+ // warmup is off.
116
+ const first = await probeFirstCall(fn);
117
+ let singleCallNs = first.ns;
118
+ const timeBatch = batchTimer(fn, first.isAsync);
119
+
120
+ const warmupStart = Bun.nanoseconds();
121
+ let n = 1;
122
+ while (Bun.nanoseconds() - warmupStart < warmupBudgetNs) {
123
+ const ns = await timeBatch(n);
124
+ singleCallNs = Math.max(1, ns / n);
125
+ if (ns < WARMUP_CHUNK_NS) n *= 2;
126
+ }
127
+
128
+ // A single warmup batch can be inflated by a GC pause or tier-up compile
129
+ // and under-batch a fast task into a flood of trials; settle on the median
130
+ // of a few batches at the planned size instead.
131
+ let batchSize = sizeBatch(singleCallNs, timeBudgetNs);
132
+ if (batchSize > 1) {
133
+ const perCall: number[] = [];
134
+ for (let r = 0; r < CALIBRATION_ROUNDS; r++) {
135
+ perCall.push((await timeBatch(batchSize)) / batchSize);
136
+ }
137
+ singleCallNs = Math.max(1, medianOf(perCall));
138
+ batchSize = sizeBatch(singleCallNs, timeBudgetNs);
139
+ }
140
+ const trialCostNs = singleCallNs * batchSize;
141
+ const minSamples =
142
+ opts.samples ??
143
+ opts.minSamples ??
144
+ defaultSampleFloor(trialCostNs, timeBudgetNs);
145
+ const effectiveBudgetNs = opts.samples !== undefined ? 0 : timeBudgetNs;
146
+ const maxTrials = opts.samples ?? Math.max(MAX_TRIALS, minSamples);
147
+
148
+ // Read around each batch, outside the loop's own clock reads, so reading
149
+ // the counter never adds to the measured time.
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,139 @@
1
+ import { dlopen, FFIType, ptr, read } from "bun:ffi";
2
+
3
+ import { errorMessage } from "../errors.ts";
4
+
5
+ /**
6
+ * Reads how many instructions the calling thread has retired in user mode.
7
+ * Only differences between two reads mean anything. */
8
+ type InstructionReader = () => number;
9
+
10
+ type InstructionCounter =
11
+ | { read: InstructionReader; unavailable?: undefined }
12
+ /** Why this machine can't count instructions, for an error message. */
13
+ | { read?: undefined; unavailable: string };
14
+
15
+ // One counter per process: each Linux open holds a perf event fd.
16
+ // eslint-disable-next-line no-restricted-syntax -- a lazy cache, opened once
17
+ let counter: InstructionCounter | undefined;
18
+
19
+ // The calling thread's retired-instruction counter: steadier than wall
20
+ // time on a loaded machine, since another process taking the CPU doesn't
21
+ // change what this thread executes. Per thread, user mode only, so neither
22
+ // the kernel's work for a system call nor any other thread's (JIT
23
+ // compiler, GC helpers, I/O pool) counts. Reads the hardware counter
24
+ // through `thread_selfcounts` on macOS and `perf_event_open` on Linux.
25
+ export function instructionCounter(): InstructionCounter {
26
+ counter ??= openCounter();
27
+ return counter;
28
+ }
29
+
30
+ function openCounter(): InstructionCounter {
31
+ try {
32
+ if (process.platform === "darwin") return darwinCounter();
33
+ if (process.platform === "linux") return linuxCounter();
34
+ } catch (err) {
35
+ return { unavailable: errorMessage(err) };
36
+ }
37
+ return { unavailable: `not supported on ${process.platform}` };
38
+ }
39
+
40
+ // spec: thread_selfcounts(1, ...) fills { instructions, cycles } for the
41
+ // calling thread: what `/usr/bin/time -l` totals over a process, read per
42
+ // thread.
43
+ function darwinCounter(): InstructionCounter {
44
+ const { symbols } = dlopen("/usr/lib/libSystem.B.dylib", {
45
+ thread_selfcounts: {
46
+ args: [FFIType.i32, FFIType.ptr, FFIType.u64],
47
+ returns: FFIType.i32,
48
+ },
49
+ });
50
+ const counts = new BigUint64Array(2);
51
+ const at = ptr(counts);
52
+ if (symbols.thread_selfcounts(1, at, 16) !== 0 || counts[0] === 0n) {
53
+ return {
54
+ unavailable:
55
+ "thread_selfcounts can't read this Mac's instruction counter (in a VM?)",
56
+ };
57
+ }
58
+ return {
59
+ read: () => {
60
+ symbols.thread_selfcounts(1, at, 16);
61
+ return Number(counts[0]);
62
+ },
63
+ };
64
+ }
65
+
66
+ const PERF_EVENT_OPEN: Partial<Record<string, number>> = {
67
+ x64: 298,
68
+ arm64: 241,
69
+ };
70
+ const PERF_TYPE_HARDWARE = 0;
71
+ const PERF_COUNT_HW_INSTRUCTIONS = 1;
72
+ // perf_event_attr's first version, which every kernel since takes.
73
+ const PERF_ATTR_SIZE_VER0 = 64;
74
+ // spec: exclude_kernel | exclude_hv, because `perf_event_paranoid` 2 still
75
+ // allows that much.
76
+ const PERF_USER_ONLY = (1n << 5n) | (1n << 6n);
77
+
78
+ // spec: an event opened with pid 0 and cpu -1 counts the calling thread,
79
+ // on any CPU, from the moment it's opened.
80
+ function linuxCounter(): InstructionCounter {
81
+ const nr = PERF_EVENT_OPEN[process.arch];
82
+ if (nr === undefined) {
83
+ return { unavailable: `not supported on linux/${process.arch}` };
84
+ }
85
+ const { symbols } = dlopen("libc.so.6", {
86
+ syscall: {
87
+ args: [
88
+ FFIType.i64,
89
+ FFIType.ptr,
90
+ FFIType.i64,
91
+ FFIType.i64,
92
+ FFIType.i64,
93
+ FFIType.i64,
94
+ ],
95
+ returns: FFIType.i64,
96
+ },
97
+ read: {
98
+ args: [FFIType.i32, FFIType.ptr, FFIType.u64],
99
+ returns: FFIType.i64,
100
+ },
101
+ __errno_location: { args: [], returns: FFIType.ptr },
102
+ });
103
+ const attr = new BigUint64Array(PERF_ATTR_SIZE_VER0 / 8);
104
+ const head = new Uint32Array(attr.buffer, 0, 2);
105
+ head[0] = PERF_TYPE_HARDWARE;
106
+ head[1] = PERF_ATTR_SIZE_VER0;
107
+ attr[1] = BigInt(PERF_COUNT_HW_INSTRUCTIONS);
108
+ attr[5] = PERF_USER_ONLY;
109
+ const fd = Number(symbols.syscall(nr, ptr(attr), 0, -1, -1, 0));
110
+ if (fd < 0) {
111
+ const errnoAt = symbols.__errno_location();
112
+ if (errnoAt === null) throw new Error("__errno_location returned null");
113
+ return { unavailable: perfError(read.i32(errnoAt)) };
114
+ }
115
+ const count = new BigUint64Array(1);
116
+ const at = ptr(count);
117
+ if (Number(symbols.read(fd, at, 8)) !== 8) {
118
+ return { unavailable: "perf_event_open's counter couldn't be read" };
119
+ }
120
+ return {
121
+ read: () => {
122
+ symbols.read(fd, at, 8);
123
+ return Number(count[0]);
124
+ },
125
+ };
126
+ }
127
+
128
+ function perfError(errno: number): string {
129
+ const base = `perf_event_open failed (errno ${errno})`;
130
+ // EACCES, EPERM
131
+ if (errno === 13 || errno === 1) {
132
+ 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)`;
133
+ }
134
+ // ENOENT, ENODEV, EOPNOTSUPP
135
+ if (errno === 2 || errno === 19 || errno === 95) {
136
+ return `${base}: this machine exposes no instruction counter (many VMs and containers don't)`;
137
+ }
138
+ return base;
139
+ }
@@ -0,0 +1,64 @@
1
+ export type TaskBody = () => unknown;
2
+
3
+ export function isPromiseLike(value: unknown): value is PromiseLike<unknown> {
4
+ return (
5
+ value !== null &&
6
+ typeof value === "object" &&
7
+ "then" in value &&
8
+ typeof value.then === "function"
9
+ );
10
+ }
11
+
12
+ // What `Function` and AsyncFunction build at runtime: a callable whose
13
+ // signature only the source text knows.
14
+ function isCallable<T>(f: unknown): f is T {
15
+ return typeof f === "function";
16
+ }
17
+
18
+ type Loop = (
19
+ fn: TaskBody,
20
+ sink: unknown[],
21
+ n: number,
22
+ ) => number | Promise<number>;
23
+
24
+ const AsyncFunction: unknown = (async () => {}).constructor;
25
+ // eslint-disable-next-line no-restricted-syntax -- gives each compiled loop its own source; see batchTimer
26
+ let loopSerial = 0;
27
+ // Ring buffer every result is stored into: the JIT can't prove a stored
28
+ // value unused, so it can't elide the call or its allocations.
29
+ const SINK_SIZE = 256;
30
+
31
+ // Times `n` back-to-back calls of `fn`, returning total ns, through a loop
32
+ // compiled for this task alone. JSC specializes compiled code per
33
+ // function: a shared loop gets its `fn()` call site tuned for whichever
34
+ // task ran first and measures every later task through a slower generic
35
+ // call. The serial in the source keeps JSC's code cache from handing two
36
+ // tasks the same compiled body. An async task gets an awaiting loop; a
37
+ // sync one never pays a microtask per call.
38
+ export function batchTimer(
39
+ fn: TaskBody,
40
+ isAsync: boolean,
41
+ ): (n: number) => number | Promise<number> {
42
+ const body = `/* ostia task loop ${loopSerial++} */
43
+ const t0 = Bun.nanoseconds()
44
+ for (let b = 0; b < n; b++) sink[b & ${SINK_SIZE - 1}] = ${isAsync ? "await " : ""}fn()
45
+ return Bun.nanoseconds() - t0`;
46
+ const make = isAsync ? AsyncFunction : Function;
47
+ const loop = isCallable<FunctionConstructor>(make)
48
+ ? make("fn", "sink", "n", body)
49
+ : undefined;
50
+ if (!isCallable<Loop>(loop))
51
+ throw new Error("ostia: can't compile a task loop");
52
+ const sink: unknown[] = new Array(SINK_SIZE);
53
+ return (n) => loop(fn, sink, n);
54
+ }
55
+
56
+ export async function probeFirstCall(
57
+ fn: TaskBody,
58
+ ): Promise<{ isAsync: boolean; result: unknown; ns: number }> {
59
+ const t0 = Bun.nanoseconds();
60
+ const value = fn();
61
+ const isAsync = isPromiseLike(value);
62
+ const result = isAsync ? await value : value;
63
+ return { isAsync, result, ns: Math.max(1, Bun.nanoseconds() - t0) };
64
+ }
@@ -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 and allocation-free, so trial-to-trial variance is the machine's
10
+ // 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] ?? 0;
21
+ h = Math.imul(h, 16777619);
22
+ }
23
+ return h >>> 0;
24
+ }
25
+
26
+ export function computeNoiseFloor(samples: number[]): NoiseFloor {
27
+ const stats = computeTimingStats(samples);
28
+ return {
29
+ floorPct: stats.median === 0 ? 0 : (stats.mad / stats.median) * 100,
30
+ referenceMedianNs: stats.median,
31
+ samples: samples.length,
32
+ };
33
+ }
34
+
35
+ // Samples the reference hash loop for `budgetMs`; characterizes the
36
+ // machine, not any workload, so run it once per document.
37
+ export function measureNoiseFloor(
38
+ budgetMs: number = DEFAULT_BUDGET_MS,
39
+ ): 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
+ }