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.
- 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 +923 -679
- package/package.json +16 -14
- package/src/ab/ab-runner.ts +487 -0
- package/src/ab/index.ts +1160 -0
- package/src/baseline/index.ts +69 -0
- package/src/bench/index.ts +516 -0
- package/src/bench/projects.ts +43 -0
- package/src/bench/range.ts +27 -0
- package/src/bench/registry.ts +426 -0
- package/src/bench/run-tasks.ts +179 -0
- package/src/bench/run.ts +52 -0
- package/src/bench/runner.ts +162 -0
- package/src/bench/support.ts +161 -0
- package/src/bench/sweep.ts +41 -0
- package/src/cache/fingerprint.ts +62 -0
- package/src/cache/store.ts +40 -0
- package/src/capture/bunflags.ts +92 -0
- package/src/capture/cpu-parse.ts +131 -0
- package/src/capture/cpu.ts +47 -0
- package/src/capture/frames.ts +60 -0
- package/src/capture/heap-parse.ts +111 -0
- package/src/capture/heap.ts +36 -0
- package/src/capture/inspector.ts +47 -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 +440 -0
- package/src/cli/flags.ts +263 -0
- package/{chunk-9sx15b08.js → src/cli/help.ts} +23 -11
- package/src/cli/main.ts +18 -0
- package/src/cli/output.ts +179 -0
- package/src/cli/run.ts +1110 -0
- package/src/compare/index.ts +624 -0
- package/src/config/env.ts +13 -0
- package/src/config/index.ts +283 -0
- package/src/config/validate.ts +273 -0
- package/src/errors.ts +8 -0
- package/src/format.ts +35 -0
- package/src/glob.ts +45 -0
- package/src/index.ts +60 -0
- package/src/ir/cpu.ts +10 -0
- package/src/ir/defined.ts +12 -0
- package/src/ir/document.ts +491 -0
- package/src/ir/fp.ts +28 -0
- package/src/ir/git.ts +37 -0
- package/src/ir/types.ts +615 -0
- package/src/measure/alloc.ts +56 -0
- package/src/measure/cpu.ts +91 -0
- package/src/measure/environment.ts +38 -0
- package/src/measure/inprocess.ts +191 -0
- package/src/measure/instructions.ts +139 -0
- package/src/measure/loop.ts +64 -0
- package/src/measure/noise.ts +55 -0
- package/src/measure/paired.ts +304 -0
- package/src/measure/peak.ts +201 -0
- package/src/measure/timing.ts +263 -0
- package/src/profile.ts +110 -0
- package/src/renderers/collapsed.ts +42 -0
- package/src/renderers/cpu-tree.ts +191 -0
- package/src/renderers/cpuprofile.ts +43 -0
- package/src/renderers/format.ts +132 -0
- package/src/renderers/index.ts +37 -0
- package/src/renderers/json.ts +10 -0
- package/src/renderers/jsonl.ts +19 -0
- package/src/renderers/markdown.ts +543 -0
- package/src/renderers/mermaid.ts +90 -0
- package/src/renderers/minimal.ts +602 -0
- package/src/renderers/paired.ts +223 -0
- package/src/renderers/relative.ts +60 -0
- package/src/renderers/select.ts +264 -0
- package/src/renderers/speedscope.ts +73 -0
- package/src/renderers/terminal.ts +470 -0
- package/src/renderers/types.ts +27 -0
- package/src/spawn/index.ts +387 -0
- package/src/stats/bootstrap.ts +151 -0
- package/src/stats/index.ts +144 -0
- package/src/stats/mannwhitney.ts +82 -0
- package/src/time.ts +337 -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
package/src/index.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { OstiaConfigInput } from "./config/index.ts";
|
|
2
|
+
|
|
3
|
+
export type { AbOptions, AbProgress } from "./ab/index.ts";
|
|
4
|
+
export { ab, AbBaseError, AbSetupError, AbSuiteError } from "./ab/index.ts";
|
|
5
|
+
export type { BenchOptions } from "./bench/index.ts";
|
|
6
|
+
export { bench } from "./bench/index.ts";
|
|
7
|
+
export { range } from "./bench/range.ts";
|
|
8
|
+
export type { GroupOptions, TaskOptions } from "./bench/registry.ts";
|
|
9
|
+
export { group, task } from "./bench/registry.ts";
|
|
10
|
+
export type { RunOptions } from "./bench/run.ts";
|
|
11
|
+
export { run } from "./bench/run.ts";
|
|
12
|
+
export { sweep } from "./bench/sweep.ts";
|
|
13
|
+
export type { CompareResult, Thresholds } from "./compare/index.ts";
|
|
14
|
+
export { compareDocuments, DEFAULT_THRESHOLDS } from "./compare/index.ts";
|
|
15
|
+
export type {
|
|
16
|
+
AbConfig,
|
|
17
|
+
BenchProject,
|
|
18
|
+
OstiaConfig,
|
|
19
|
+
OstiaConfigInput,
|
|
20
|
+
WorkloadConfig,
|
|
21
|
+
} from "./config/index.ts";
|
|
22
|
+
export {
|
|
23
|
+
createDocument,
|
|
24
|
+
loadDocument,
|
|
25
|
+
OstiaDocumentError,
|
|
26
|
+
saveDocument,
|
|
27
|
+
} from "./ir/document.ts";
|
|
28
|
+
export type {
|
|
29
|
+
Comparison,
|
|
30
|
+
ProfileDocument,
|
|
31
|
+
Warning,
|
|
32
|
+
WarningCode,
|
|
33
|
+
Workload,
|
|
34
|
+
} from "./ir/types.ts";
|
|
35
|
+
export { keep } from "./measure/inprocess.ts";
|
|
36
|
+
export type { ProfileOptions, ProfileResult } from "./profile.ts";
|
|
37
|
+
export { profile } from "./profile.ts";
|
|
38
|
+
export { renderers } from "./renderers/index.ts";
|
|
39
|
+
export type { MermaidOptions } from "./renderers/mermaid.ts";
|
|
40
|
+
export type {
|
|
41
|
+
MinimalEvent,
|
|
42
|
+
MinimalProtocolContext,
|
|
43
|
+
MinimalRenderOptions,
|
|
44
|
+
} from "./renderers/minimal.ts";
|
|
45
|
+
export { MINIMAL_PROTOCOL_VERSION } from "./renderers/minimal.ts";
|
|
46
|
+
export type { VizOptions } from "./renderers/types.ts";
|
|
47
|
+
export type {
|
|
48
|
+
PrepareFn,
|
|
49
|
+
PrepareHook,
|
|
50
|
+
PrepareRun,
|
|
51
|
+
TimeSource,
|
|
52
|
+
TimeUnit,
|
|
53
|
+
} from "./spawn/index.ts";
|
|
54
|
+
export type { CommandSpec, TimeOptions } from "./time.ts";
|
|
55
|
+
export { time } from "./time.ts";
|
|
56
|
+
|
|
57
|
+
/** Identity function that types an `ostia.config.ts` default export. */
|
|
58
|
+
export function defineConfig(config: OstiaConfigInput): OstiaConfigInput {
|
|
59
|
+
return config;
|
|
60
|
+
}
|
package/src/ir/cpu.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { CpuEvidence } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
// The sample stream's length when the capture kept one, else the summed
|
|
4
|
+
// per-frame self counts.
|
|
5
|
+
export function cpuSampleCount(cpu: CpuEvidence): number {
|
|
6
|
+
return (
|
|
7
|
+
cpu.samples?.nodeIds.length ??
|
|
8
|
+
cpu.totals.reduce((sum, t) => sum + t.samples, 0)
|
|
9
|
+
);
|
|
10
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// The fields of `fields` that aren't undefined, so an optional property is
|
|
2
|
+
// absent rather than present and undefined (exactOptionalPropertyTypes).
|
|
3
|
+
export function definedFields<T extends object>(
|
|
4
|
+
fields: T,
|
|
5
|
+
): { [K in keyof T]?: NonNullable<T[K]> | (T[K] & null) } {
|
|
6
|
+
const out: { [K in keyof T]?: NonNullable<T[K]> | (T[K] & null) } = {};
|
|
7
|
+
for (const key in fields) {
|
|
8
|
+
const value = fields[key];
|
|
9
|
+
if (value !== undefined) out[key] = value;
|
|
10
|
+
}
|
|
11
|
+
return out;
|
|
12
|
+
}
|
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
import { rename, rm } from "node:fs/promises";
|
|
2
|
+
import { isAbsolute, relative } from "node:path";
|
|
3
|
+
|
|
4
|
+
import { errorMessage } from "../errors.ts";
|
|
5
|
+
import {
|
|
6
|
+
assertReusableTimeSource,
|
|
7
|
+
prepareArgv,
|
|
8
|
+
type PrepareHook,
|
|
9
|
+
type TimeSource,
|
|
10
|
+
timeSourceSpec,
|
|
11
|
+
} from "../spawn/index.ts";
|
|
12
|
+
import { computeTimingStats } from "../stats/index.ts";
|
|
13
|
+
import { TOOL_VERSION } from "../version.ts";
|
|
14
|
+
import { definedFields } from "./defined.ts";
|
|
15
|
+
import { canonicalJSON, fp } from "./fp.ts";
|
|
16
|
+
import { captureGitMetadata } from "./git.ts";
|
|
17
|
+
import type {
|
|
18
|
+
ArtifactRef,
|
|
19
|
+
CpuEvidence,
|
|
20
|
+
Environment,
|
|
21
|
+
HeapEvidence,
|
|
22
|
+
InstructionStats,
|
|
23
|
+
JitTierBreakdown,
|
|
24
|
+
Measurement,
|
|
25
|
+
MemoryEvidence,
|
|
26
|
+
PairedEvidence,
|
|
27
|
+
Phase,
|
|
28
|
+
ProfileDocument,
|
|
29
|
+
TimingStats,
|
|
30
|
+
Trial,
|
|
31
|
+
Warning,
|
|
32
|
+
Workload,
|
|
33
|
+
} from "./types.ts";
|
|
34
|
+
|
|
35
|
+
function measurementId(
|
|
36
|
+
workloadId: string,
|
|
37
|
+
phase: Phase,
|
|
38
|
+
configFingerprint: string,
|
|
39
|
+
): string {
|
|
40
|
+
return fp(
|
|
41
|
+
"run",
|
|
42
|
+
workloadId,
|
|
43
|
+
phase,
|
|
44
|
+
configFingerprint,
|
|
45
|
+
Bun.version,
|
|
46
|
+
TOOL_VERSION,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Builds a document from workloads and their measurements, stamped with
|
|
52
|
+
* versions, platform, timestamp and git metadata.
|
|
53
|
+
*/
|
|
54
|
+
export function createDocument(
|
|
55
|
+
workloads: Workload[],
|
|
56
|
+
measurements: Measurement[],
|
|
57
|
+
environment?: Environment,
|
|
58
|
+
): ProfileDocument {
|
|
59
|
+
const git = captureGitMetadata();
|
|
60
|
+
return {
|
|
61
|
+
schemaVersion: 2,
|
|
62
|
+
toolVersion: TOOL_VERSION,
|
|
63
|
+
bunVersion: Bun.version,
|
|
64
|
+
platform: { os: process.platform, arch: process.arch },
|
|
65
|
+
createdAt: new Date().toISOString(),
|
|
66
|
+
workloads,
|
|
67
|
+
measurements,
|
|
68
|
+
...definedFields({ environment, git }),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface SubprocessWorkloadOptions {
|
|
73
|
+
prepare?: PrepareHook;
|
|
74
|
+
timeSource?: TimeSource;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// `prepare` and `timeSource` join the id only when given, so commands
|
|
78
|
+
// without them keep their old id. A function `prepare` hashes by source
|
|
79
|
+
// text. The id excludes `process.cwd()` so baselines match across
|
|
80
|
+
// checkouts.
|
|
81
|
+
export function makeSubprocessWorkload(
|
|
82
|
+
command: string[],
|
|
83
|
+
label?: string,
|
|
84
|
+
opts: SubprocessWorkloadOptions = {},
|
|
85
|
+
): Workload {
|
|
86
|
+
if (opts.timeSource) assertReusableTimeSource(opts.timeSource);
|
|
87
|
+
const prepare = prepareArgv(opts.prepare);
|
|
88
|
+
const timeSource = timeSourceSpec(opts.timeSource);
|
|
89
|
+
const prepareKey =
|
|
90
|
+
typeof opts.prepare === "function" ? opts.prepare.toString() : prepare;
|
|
91
|
+
const id = fp(
|
|
92
|
+
"wl",
|
|
93
|
+
"subprocess",
|
|
94
|
+
command,
|
|
95
|
+
...(prepareKey !== undefined || timeSource !== undefined
|
|
96
|
+
? [prepareKey ?? null, timeSource ?? null]
|
|
97
|
+
: []),
|
|
98
|
+
);
|
|
99
|
+
return {
|
|
100
|
+
id,
|
|
101
|
+
kind: "subprocess",
|
|
102
|
+
command,
|
|
103
|
+
...definedFields({ label, prepare, timeSource }),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Without `name` the id hashes the function's name and source, not the
|
|
108
|
+
// values it closes over; `name` replaces both and is the label.
|
|
109
|
+
export function makeInprocessWorkload(
|
|
110
|
+
fn: (...args: unknown[]) => unknown,
|
|
111
|
+
name?: string,
|
|
112
|
+
): Workload {
|
|
113
|
+
const id =
|
|
114
|
+
name === undefined
|
|
115
|
+
? fp("wl", "inprocess", fn.name, fn.toString())
|
|
116
|
+
: fp("wl", "inprocess-named", name);
|
|
117
|
+
return { id, kind: "inprocess", ...definedFields({ label: name }) };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
interface EntryWorkloadOptions {
|
|
121
|
+
label?: string;
|
|
122
|
+
baseline?: boolean;
|
|
123
|
+
group?: string;
|
|
124
|
+
description?: string;
|
|
125
|
+
groupDescription?: string;
|
|
126
|
+
isolated?: boolean;
|
|
127
|
+
params?: Record<string, string | number | boolean>;
|
|
128
|
+
formerIds?: string[];
|
|
129
|
+
skipped?: boolean;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// The id hashes the file (cwd-relative, so checkouts match), `taskName`
|
|
133
|
+
// (the registry's "group/name") and `params` when present; `params` joins
|
|
134
|
+
// only when given so tasks without it keep their old id, and a `sweep()`
|
|
135
|
+
// reuses one task name across points. Everything else is annotation and
|
|
136
|
+
// never orphans a baseline.
|
|
137
|
+
export function makeEntryWorkload(
|
|
138
|
+
file: string,
|
|
139
|
+
taskName: string,
|
|
140
|
+
opts: EntryWorkloadOptions = {},
|
|
141
|
+
): Workload {
|
|
142
|
+
const idPath = isAbsolute(file) ? relative(process.cwd(), file) : file;
|
|
143
|
+
const id =
|
|
144
|
+
opts.params !== undefined
|
|
145
|
+
? fp("wl", "inprocess-entry", idPath, taskName, opts.params)
|
|
146
|
+
: fp("wl", "inprocess-entry", idPath, taskName);
|
|
147
|
+
const { group, ...annotations } = opts;
|
|
148
|
+
return {
|
|
149
|
+
id,
|
|
150
|
+
kind: "inprocess",
|
|
151
|
+
entry: { file, task: taskName, ...definedFields({ group }) },
|
|
152
|
+
...definedFields(annotations),
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
interface TimingMeasurementInput {
|
|
157
|
+
workload: Workload;
|
|
158
|
+
configFingerprint: string;
|
|
159
|
+
trials: Trial[];
|
|
160
|
+
/**
|
|
161
|
+
* Absent when no trial produced a sample (all timed out or missed the
|
|
162
|
+
* `timeSource` pattern); renderers then skip the measurement. */
|
|
163
|
+
timing?: TimingStats;
|
|
164
|
+
warnings: Warning[];
|
|
165
|
+
interleaved?: boolean;
|
|
166
|
+
/** In-process heap readings around the run; see `MemoryEvidence`. */
|
|
167
|
+
heapUsed?: { beforeBytes: number; afterBytes: number };
|
|
168
|
+
instructions?: InstructionStats;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export function makeTimingMeasurement(
|
|
172
|
+
input: TimingMeasurementInput,
|
|
173
|
+
): Measurement {
|
|
174
|
+
return {
|
|
175
|
+
id: measurementId(input.workload.id, "timing", input.configFingerprint),
|
|
176
|
+
workloadId: input.workload.id,
|
|
177
|
+
phase: "timing",
|
|
178
|
+
instrumented: false,
|
|
179
|
+
configFingerprint: input.configFingerprint,
|
|
180
|
+
trials: input.trials,
|
|
181
|
+
...definedFields({ timing: input.timing }),
|
|
182
|
+
warnings: input.warnings,
|
|
183
|
+
artifacts: [],
|
|
184
|
+
...definedFields({
|
|
185
|
+
memory: input.heapUsed
|
|
186
|
+
? {
|
|
187
|
+
origin: "heapStats" as const,
|
|
188
|
+
heapUsedBeforeBytes: input.heapUsed.beforeBytes,
|
|
189
|
+
heapUsedAfterBytes: input.heapUsed.afterBytes,
|
|
190
|
+
}
|
|
191
|
+
: memoryFromTrials(input.trials),
|
|
192
|
+
}),
|
|
193
|
+
...definedFields({
|
|
194
|
+
instructions: input.instructions,
|
|
195
|
+
interleaved: input.interleaved,
|
|
196
|
+
}),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function memoryFromTrials(trials: Trial[]): MemoryEvidence | undefined {
|
|
201
|
+
const rss = trials
|
|
202
|
+
.map((t) => t.maxRssBytes)
|
|
203
|
+
.filter((v): v is number => v !== undefined);
|
|
204
|
+
if (rss.length === 0) return undefined;
|
|
205
|
+
return {
|
|
206
|
+
origin: "resourceUsage",
|
|
207
|
+
maxRssBytes: Math.max(...rss),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export interface InstrumentedMeasurementInput {
|
|
212
|
+
workload: Workload;
|
|
213
|
+
phase: Extract<Phase, "cpu" | "heap" | "memstats">;
|
|
214
|
+
configFingerprint: string;
|
|
215
|
+
diagnosticWallNs: number;
|
|
216
|
+
exitCode?: number;
|
|
217
|
+
cpu?: CpuEvidence;
|
|
218
|
+
heap?: HeapEvidence;
|
|
219
|
+
memory?: MemoryEvidence;
|
|
220
|
+
jit?: JitTierBreakdown;
|
|
221
|
+
warnings: Warning[];
|
|
222
|
+
artifacts: ArtifactRef[];
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function makeInstrumentedMeasurement(
|
|
226
|
+
input: InstrumentedMeasurementInput,
|
|
227
|
+
): Measurement {
|
|
228
|
+
return {
|
|
229
|
+
id: measurementId(input.workload.id, input.phase, input.configFingerprint),
|
|
230
|
+
workloadId: input.workload.id,
|
|
231
|
+
phase: input.phase,
|
|
232
|
+
instrumented: true,
|
|
233
|
+
configFingerprint: input.configFingerprint,
|
|
234
|
+
trials: [
|
|
235
|
+
{
|
|
236
|
+
i: 0,
|
|
237
|
+
wallNs: input.diagnosticWallNs,
|
|
238
|
+
...definedFields({ exitCode: input.exitCode }),
|
|
239
|
+
},
|
|
240
|
+
],
|
|
241
|
+
diagnosticWallNs: input.diagnosticWallNs,
|
|
242
|
+
...definedFields({
|
|
243
|
+
cpu: input.cpu,
|
|
244
|
+
heap: input.heap,
|
|
245
|
+
memory: input.memory,
|
|
246
|
+
jit: input.jit,
|
|
247
|
+
}),
|
|
248
|
+
warnings: input.warnings,
|
|
249
|
+
artifacts: input.artifacts,
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
type PairedMeasurementInput = {
|
|
254
|
+
workload: Workload;
|
|
255
|
+
configFingerprint: string;
|
|
256
|
+
diagnosticWallNs: number;
|
|
257
|
+
warnings: Warning[];
|
|
258
|
+
} & (
|
|
259
|
+
| {
|
|
260
|
+
/** The candidate side's per-call timing over the rounds. */
|
|
261
|
+
timing: TimingStats;
|
|
262
|
+
paired: PairedEvidence;
|
|
263
|
+
}
|
|
264
|
+
| {
|
|
265
|
+
/** A task that threw, so wasn't timed. */
|
|
266
|
+
threw: NonNullable<Measurement["threw"]>;
|
|
267
|
+
}
|
|
268
|
+
);
|
|
269
|
+
|
|
270
|
+
// invariant: `timing` is the candidate side; `paired` holds the base side
|
|
271
|
+
// and the ratios.
|
|
272
|
+
export function makePairedMeasurement(
|
|
273
|
+
input: PairedMeasurementInput,
|
|
274
|
+
): Measurement {
|
|
275
|
+
return {
|
|
276
|
+
id: measurementId(input.workload.id, "paired", input.configFingerprint),
|
|
277
|
+
workloadId: input.workload.id,
|
|
278
|
+
phase: "paired",
|
|
279
|
+
instrumented: false,
|
|
280
|
+
configFingerprint: input.configFingerprint,
|
|
281
|
+
trials: [],
|
|
282
|
+
...("threw" in input
|
|
283
|
+
? { threw: input.threw }
|
|
284
|
+
: { timing: input.timing, paired: input.paired }),
|
|
285
|
+
diagnosticWallNs: input.diagnosticWallNs,
|
|
286
|
+
warnings: input.warnings,
|
|
287
|
+
artifacts: [],
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
export async function makeArtifactRef(
|
|
292
|
+
ownerId: string,
|
|
293
|
+
kind: ArtifactRef["kind"],
|
|
294
|
+
path: string,
|
|
295
|
+
): Promise<ArtifactRef> {
|
|
296
|
+
const buf = await Bun.file(path).arrayBuffer();
|
|
297
|
+
return {
|
|
298
|
+
id: fp("art", ownerId, kind, path),
|
|
299
|
+
kind,
|
|
300
|
+
path,
|
|
301
|
+
sha256: Bun.CryptoHasher.hash("sha256", buf, "hex"),
|
|
302
|
+
bytes: buf.byteLength,
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
export function configFingerprint(opts: Record<string, unknown>): string {
|
|
307
|
+
return fp("cfg", opts);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
export function serializeDocument(doc: ProfileDocument): string {
|
|
311
|
+
return `${canonicalJSON(doc, 2)}\n`;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Writes to a unique temp file then renames, so a killed process never
|
|
315
|
+
// leaves a truncated document at `path` and concurrent saves of one path
|
|
316
|
+
// don't share a temp file. Takes serialized text so a caller that already
|
|
317
|
+
// has it can skip `serializeDocument`.
|
|
318
|
+
export async function saveDocumentText(
|
|
319
|
+
text: string,
|
|
320
|
+
path: string,
|
|
321
|
+
): Promise<void> {
|
|
322
|
+
const tmpPath = `${path}.tmp-${process.pid}-${crypto.randomUUID().slice(0, 8)}`;
|
|
323
|
+
try {
|
|
324
|
+
await Bun.write(tmpPath, text);
|
|
325
|
+
await rename(tmpPath, path);
|
|
326
|
+
} catch (err) {
|
|
327
|
+
await rm(tmpPath, { force: true });
|
|
328
|
+
throw err;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Writes a document to `path` atomically: a killed process never leaves a
|
|
334
|
+
* truncated file.
|
|
335
|
+
*/
|
|
336
|
+
export async function saveDocument(
|
|
337
|
+
doc: ProfileDocument,
|
|
338
|
+
path: string,
|
|
339
|
+
): Promise<void> {
|
|
340
|
+
await saveDocumentText(serializeDocument(doc), path);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* What `loadDocument` throws for a file that isn't JSON, isn't a document,
|
|
345
|
+
* or has a `schemaVersion` this ostia doesn't read.
|
|
346
|
+
*/
|
|
347
|
+
export class OstiaDocumentError extends Error {
|
|
348
|
+
readonly code: "invalid-json" | "not-a-document" | "unsupported-schema";
|
|
349
|
+
readonly path?: string;
|
|
350
|
+
readonly schemaVersion?: unknown;
|
|
351
|
+
|
|
352
|
+
constructor(
|
|
353
|
+
code: OstiaDocumentError["code"],
|
|
354
|
+
message: string,
|
|
355
|
+
opts: { path?: string; schemaVersion?: unknown } = {},
|
|
356
|
+
) {
|
|
357
|
+
super(message);
|
|
358
|
+
this.name = "OstiaDocumentError";
|
|
359
|
+
this.code = code;
|
|
360
|
+
if (opts.path !== undefined) this.path = opts.path;
|
|
361
|
+
this.schemaVersion = opts.schemaVersion;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Reads a document `saveDocument` wrote; throws `OstiaDocumentError`
|
|
367
|
+
* unless it's valid JSON with `schemaVersion: 2`.
|
|
368
|
+
*/
|
|
369
|
+
export async function loadDocument(path: string): Promise<ProfileDocument> {
|
|
370
|
+
const text = await Bun.file(path).text();
|
|
371
|
+
let raw: unknown;
|
|
372
|
+
try {
|
|
373
|
+
raw = JSON.parse(text);
|
|
374
|
+
} catch (err) {
|
|
375
|
+
const cause = errorMessage(err);
|
|
376
|
+
throw new OstiaDocumentError(
|
|
377
|
+
"invalid-json",
|
|
378
|
+
`${path}: invalid JSON (${cause})`,
|
|
379
|
+
{ path },
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
const schemaVersion =
|
|
383
|
+
raw !== null && typeof raw === "object" && "schemaVersion" in raw
|
|
384
|
+
? raw.schemaVersion
|
|
385
|
+
: undefined;
|
|
386
|
+
if (typeof schemaVersion !== "number") {
|
|
387
|
+
throw new OstiaDocumentError(
|
|
388
|
+
"not-a-document",
|
|
389
|
+
`${path}: not a ProfileDocument (missing schemaVersion)`,
|
|
390
|
+
{ path },
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
if (schemaVersion !== 2) {
|
|
394
|
+
throw new OstiaDocumentError(
|
|
395
|
+
"unsupported-schema",
|
|
396
|
+
`${path}: unsupported ProfileDocument schemaVersion ${schemaVersion} (this ostia reads 2)`,
|
|
397
|
+
{ path, schemaVersion },
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
assertDocumentShape(raw, path);
|
|
401
|
+
return renamePairedRatioFields(backfillTimingStats(raw));
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const isObject = (v: unknown): v is Record<string, unknown> =>
|
|
405
|
+
typeof v === "object" && v !== null && !Array.isArray(v);
|
|
406
|
+
|
|
407
|
+
// Cheap structural check, so a hand-edited or truncated document fails
|
|
408
|
+
// here with a path and index instead of a TypeError deep in a renderer.
|
|
409
|
+
function assertDocumentShape(
|
|
410
|
+
doc: unknown,
|
|
411
|
+
path: string,
|
|
412
|
+
): asserts doc is ProfileDocument {
|
|
413
|
+
const bad = (what: string) =>
|
|
414
|
+
new OstiaDocumentError(
|
|
415
|
+
"not-a-document",
|
|
416
|
+
`${path}: malformed document: ${what}`,
|
|
417
|
+
{
|
|
418
|
+
path,
|
|
419
|
+
},
|
|
420
|
+
);
|
|
421
|
+
// invariant: loadDocument passes an object with a `schemaVersion`.
|
|
422
|
+
if (!isObject(doc)) throw bad("not an object");
|
|
423
|
+
if (!Array.isArray(doc.workloads)) throw bad(`"workloads" must be an array`);
|
|
424
|
+
if (!Array.isArray(doc.measurements)) {
|
|
425
|
+
throw bad(`"measurements" must be an array`);
|
|
426
|
+
}
|
|
427
|
+
for (const [i, w] of doc.workloads.entries()) {
|
|
428
|
+
if (!isObject(w) || typeof w.id !== "string") {
|
|
429
|
+
throw bad(`workloads[${i}] must be an object with a string "id"`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
for (const [i, m] of doc.measurements.entries()) {
|
|
433
|
+
if (
|
|
434
|
+
!isObject(m) ||
|
|
435
|
+
typeof m.id !== "string" ||
|
|
436
|
+
typeof m.workloadId !== "string" ||
|
|
437
|
+
typeof m.phase !== "string"
|
|
438
|
+
) {
|
|
439
|
+
throw bad(
|
|
440
|
+
`measurements[${i}] must be an object with string "id", "workloadId" and "phase"`,
|
|
441
|
+
);
|
|
442
|
+
}
|
|
443
|
+
for (const key of ["trials", "warnings", "artifacts"]) {
|
|
444
|
+
if (!Array.isArray(m[key])) {
|
|
445
|
+
throw bad(`measurements[${i}].${key} must be an array`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// `ab` documents from ostia 0.2.8-0.2.9 name the ratio quartiles
|
|
452
|
+
// `p25`/`p75`, now `ratioP25`/`ratioP75`; read the old names so saved
|
|
453
|
+
// documents still render. Those from before 0.2.12 lack `ab.metric`.
|
|
454
|
+
interface LegacyRatioFields {
|
|
455
|
+
ratioP25?: unknown;
|
|
456
|
+
ratioP75?: unknown;
|
|
457
|
+
p25?: unknown;
|
|
458
|
+
p75?: unknown;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function renamePairedRatioFields(doc: ProfileDocument): ProfileDocument {
|
|
462
|
+
const rename = (r: LegacyRatioFields) => {
|
|
463
|
+
if (r.ratioP25 !== undefined || r.p25 === undefined) return;
|
|
464
|
+
r.ratioP25 = r.p25;
|
|
465
|
+
r.ratioP75 = r.p75;
|
|
466
|
+
delete r.p25;
|
|
467
|
+
delete r.p75;
|
|
468
|
+
};
|
|
469
|
+
for (const m of doc.measurements) {
|
|
470
|
+
if (!m.paired) continue;
|
|
471
|
+
rename(m.paired);
|
|
472
|
+
for (const r of m.paired.repeats ?? []) rename(r);
|
|
473
|
+
}
|
|
474
|
+
// Before 0.2.12, `ab` judged by time alone.
|
|
475
|
+
if (doc.ab) doc.ab.metric ??= "time";
|
|
476
|
+
return doc;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
// Documents from before ostia 0.2.4 lack `p25`/`p75`/`p99`/`mad`;
|
|
480
|
+
// recompute them so every consumer sees the full `TimingStats`.
|
|
481
|
+
function backfillTimingStats(doc: ProfileDocument): ProfileDocument {
|
|
482
|
+
for (const m of doc.measurements) {
|
|
483
|
+
const t = m.timing;
|
|
484
|
+
if (!t || t.mad !== undefined || t.samples.length === 0) continue;
|
|
485
|
+
m.timing = {
|
|
486
|
+
...computeTimingStats(t.samples),
|
|
487
|
+
...(t.batch !== undefined && { batch: t.batch }),
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
return doc;
|
|
491
|
+
}
|
package/src/ir/fp.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// Key-order-independent JSON: equal values give equal text, so `fp()` ids
|
|
2
|
+
// and saved documents stay stable.
|
|
3
|
+
export function canonicalJSON(value: unknown, indent?: number): string {
|
|
4
|
+
return JSON.stringify(sortKeysDeep(value), null, indent);
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
// Deep copy with plain-object keys sorted. Arrays of only primitives (a
|
|
8
|
+
// 10k-entry `samples`) are returned as is, keeping `JSON.stringify` on its
|
|
9
|
+
// fast path.
|
|
10
|
+
function sortKeysDeep(value: unknown): unknown {
|
|
11
|
+
if (Array.isArray(value)) {
|
|
12
|
+
const hasObjects = value.some((v) => v !== null && typeof v === "object");
|
|
13
|
+
return hasObjects ? value.map(sortKeysDeep) : value;
|
|
14
|
+
}
|
|
15
|
+
if (value !== null && typeof value === "object") {
|
|
16
|
+
const out: Record<string, unknown> = {};
|
|
17
|
+
for (const key of Object.keys(value).sort()) {
|
|
18
|
+
out[key] = sortKeysDeep(Reflect.get(value, key));
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function fp(tag: string, ...parts: unknown[]): string {
|
|
26
|
+
const hex = Bun.CryptoHasher.hash("sha256", canonicalJSON(parts), "hex");
|
|
27
|
+
return `${tag}_${hex.slice(0, 16)}`;
|
|
28
|
+
}
|
package/src/ir/git.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { GitMetadata } from "./types.ts";
|
|
2
|
+
|
|
3
|
+
const GIT_TIMEOUT_MS = 200;
|
|
4
|
+
|
|
5
|
+
// eslint-disable-next-line no-restricted-syntax -- the process-lifetime memo captureGitMetadata keeps
|
|
6
|
+
let memo: { git: GitMetadata | undefined } | undefined;
|
|
7
|
+
|
|
8
|
+
function runGit(args: string[]): string | undefined {
|
|
9
|
+
const proc = Bun.spawnSync(["git", ...args], {
|
|
10
|
+
timeout: GIT_TIMEOUT_MS,
|
|
11
|
+
stdout: "pipe",
|
|
12
|
+
stderr: "ignore",
|
|
13
|
+
});
|
|
14
|
+
return proc.success ? proc.stdout.toString().trim() : undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function readGitMetadata(): GitMetadata | undefined {
|
|
18
|
+
try {
|
|
19
|
+
const sha = runGit(["rev-parse", "--short", "HEAD"]);
|
|
20
|
+
if (sha === undefined) return undefined;
|
|
21
|
+
return {
|
|
22
|
+
sha,
|
|
23
|
+
branch: runGit(["rev-parse", "--abbrev-ref", "HEAD"]) ?? "HEAD",
|
|
24
|
+
dirty: (runGit(["status", "--porcelain"])?.length ?? 0) > 0,
|
|
25
|
+
};
|
|
26
|
+
} catch {
|
|
27
|
+
return undefined;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Repo state of the process's cwd, memoized for the process lifetime.
|
|
32
|
+
// Undefined outside a repo, without `git`, or past the 200ms per-call
|
|
33
|
+
// timeout: metadata is never worth failing a measurement over.
|
|
34
|
+
export function captureGitMetadata(): GitMetadata | undefined {
|
|
35
|
+
memo ??= { git: readGitMetadata() };
|
|
36
|
+
return memo.git;
|
|
37
|
+
}
|