ostia 0.4.0 → 0.6.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/README.md +31 -30
- package/docs/agent-protocol.md +13 -9
- package/docs/cli.md +174 -126
- package/docs/config.md +2 -2
- package/docs/document-schema.md +15 -12
- package/docs/library.md +32 -21
- package/docs/preload-recipes.md +4 -4
- package/docs/statistics.md +14 -13
- package/index.d.ts +202 -60
- package/package.json +1 -1
- package/src/ab/ab-runner.ts +6 -6
- package/src/ab/index.ts +56 -6
- package/src/ab/unpaired.ts +54 -0
- package/src/bench/index.ts +40 -3
- package/src/bench/registry.ts +6 -4
- package/src/bench/run-tasks.ts +16 -2
- package/src/bench/runner.ts +10 -3
- package/src/bench/support.ts +8 -4
- package/src/bench/sweep.ts +2 -2
- package/src/cache/fingerprint.ts +2 -2
- package/src/capture/bunflags.ts +2 -2
- package/src/capture/cpu.ts +2 -2
- package/src/capture/heap-parse.ts +2 -2
- package/src/ci/index.ts +39 -48
- package/src/cli/agent.ts +54 -0
- package/src/cli/flags.ts +58 -9
- package/src/cli/help.ts +670 -245
- package/src/cli/main.ts +2 -3
- package/src/cli/output.ts +17 -14
- package/src/cli/run.ts +317 -92
- package/src/compare/index.ts +4 -4
- package/src/config/index.ts +14 -10
- package/src/config/validate.ts +4 -4
- package/src/glob.ts +2 -2
- package/src/index.ts +3 -2
- package/src/ir/document.ts +2 -2
- package/src/ir/types.ts +49 -24
- package/src/measure/alloc.ts +2 -2
- package/src/measure/cpu.ts +2 -2
- package/src/measure/environment.ts +11 -6
- package/src/measure/inprocess.ts +14 -10
- package/src/measure/instructions.ts +2 -2
- package/src/measure/noise.ts +51 -13
- package/src/measure/paired.ts +2 -2
- package/src/measure/peak.ts +4 -4
- package/src/measure/timing.ts +27 -6
- package/src/profile.ts +6 -4
- package/src/renderers/collapsed.ts +2 -2
- package/src/renderers/concise.ts +148 -0
- package/src/renderers/format.ts +13 -4
- package/src/renderers/human.ts +402 -0
- package/src/renderers/index.ts +9 -2
- package/src/renderers/markdown.ts +2 -2
- package/src/renderers/mermaid.ts +2 -2
- package/src/renderers/minimal.ts +8 -7
- package/src/renderers/relative.ts +2 -2
- package/src/renderers/select.ts +2 -2
- package/src/renderers/terminal.ts +1178 -383
- package/src/renderers/types.ts +3 -0
- package/src/spawn/index.ts +47 -14
- package/src/stats/bootstrap.ts +2 -2
- package/src/stats/index.ts +2 -2
- package/src/terminal.ts +321 -0
- package/src/time.ts +124 -20
package/src/renderers/types.ts
CHANGED
package/src/spawn/index.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
interface TrialResult {
|
|
2
2
|
wallNs: number;
|
|
3
|
+
/** Where `outputPath` wrote the command's output. */
|
|
4
|
+
outputPath?: string;
|
|
3
5
|
/** `null` when the trial timed out: its exit code carries no information. */
|
|
4
6
|
exitCode: number | null;
|
|
5
7
|
userNs?: number;
|
|
@@ -8,8 +10,8 @@ interface TrialResult {
|
|
|
8
10
|
/** Parsed from the command's output via `timeSource`, in ns. */
|
|
9
11
|
reportedNs?: number;
|
|
10
12
|
/**
|
|
11
|
-
* `timeoutMs` elapsed and the process was SIGKILLed; contributes
|
|
12
|
-
* sample.
|
|
13
|
+
* `timeoutMs` elapsed and the process was SIGKILLed; contributes
|
|
14
|
+
* no sample.
|
|
13
15
|
*/
|
|
14
16
|
timedOut?: true;
|
|
15
17
|
/**
|
|
@@ -96,6 +98,12 @@ export interface SpawnTrialOptions {
|
|
|
96
98
|
* Aborting SIGKILLs the process. Unlike `timeoutMs`, the caller discards
|
|
97
99
|
* the trial rather than recording `timedOut`. */
|
|
98
100
|
signal?: AbortSignal;
|
|
101
|
+
/**
|
|
102
|
+
* Write the command's stdout, then its stderr, to this file once it
|
|
103
|
+
* exits, after the clock stops. */
|
|
104
|
+
outputPath?: string;
|
|
105
|
+
/** Pass the command's output to ostia's stderr, keeping stdout ostia's. */
|
|
106
|
+
showOutput?: boolean;
|
|
99
107
|
}
|
|
100
108
|
|
|
101
109
|
const UNIT_NS: Record<TimeUnit, number> = {
|
|
@@ -127,24 +135,41 @@ export function killSwitch(
|
|
|
127
135
|
}
|
|
128
136
|
|
|
129
137
|
export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
|
|
130
|
-
const capture =
|
|
138
|
+
const capture =
|
|
139
|
+
opts.timeSource !== undefined || opts.outputPath !== undefined;
|
|
131
140
|
const start = Bun.nanoseconds();
|
|
132
141
|
|
|
133
142
|
const kill = killSwitch(opts.timeoutMs, opts.signal);
|
|
134
|
-
const
|
|
143
|
+
const where = {
|
|
135
144
|
...(opts.cwd !== undefined && { cwd: opts.cwd }),
|
|
136
145
|
...(opts.env !== undefined && { env: opts.env }),
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
146
|
+
};
|
|
147
|
+
const piped = capture
|
|
148
|
+
? Bun.spawn(opts.argv, {
|
|
149
|
+
...where,
|
|
150
|
+
stdout: "pipe",
|
|
151
|
+
stderr: "pipe",
|
|
152
|
+
stdin: "ignore",
|
|
153
|
+
...kill.spawn,
|
|
154
|
+
})
|
|
155
|
+
: undefined;
|
|
156
|
+
// fd 2: shown output goes to ostia's stderr, so a machine format on
|
|
157
|
+
// stdout stays parseable.
|
|
158
|
+
const proc =
|
|
159
|
+
piped ??
|
|
160
|
+
Bun.spawn(opts.argv, {
|
|
161
|
+
...where,
|
|
162
|
+
stdout: opts.showOutput ? 2 : "ignore",
|
|
163
|
+
stderr: opts.showOutput ? 2 : "ignore",
|
|
164
|
+
stdin: "ignore",
|
|
165
|
+
...kill.spawn,
|
|
166
|
+
});
|
|
142
167
|
// Drain concurrently with exit: a full pipe would block the command and
|
|
143
168
|
// inflate the wall time.
|
|
144
|
-
const output =
|
|
169
|
+
const output = piped
|
|
145
170
|
? Promise.all([
|
|
146
|
-
new Response(
|
|
147
|
-
new Response(
|
|
171
|
+
new Response(piped.stdout).text(),
|
|
172
|
+
new Response(piped.stderr).text(),
|
|
148
173
|
])
|
|
149
174
|
: undefined;
|
|
150
175
|
const exitCode = await proc.exited;
|
|
@@ -164,6 +189,14 @@ export async function runTrial(opts: SpawnTrialOptions): Promise<TrialResult> {
|
|
|
164
189
|
};
|
|
165
190
|
if (output) {
|
|
166
191
|
const [stdout, stderr] = await output;
|
|
192
|
+
if (opts.outputPath !== undefined) {
|
|
193
|
+
await Bun.write(
|
|
194
|
+
opts.outputPath,
|
|
195
|
+
stderr ? `${stdout}\n--- stderr ---\n${stderr}` : stdout,
|
|
196
|
+
);
|
|
197
|
+
result.outputPath = opts.outputPath;
|
|
198
|
+
}
|
|
199
|
+
if (opts.showOutput) await Bun.write(Bun.stderr, stdout + stderr);
|
|
167
200
|
// A killed process's output is partial: nothing to parse.
|
|
168
201
|
if (opts.timeSource && !timedOut) {
|
|
169
202
|
try {
|
|
@@ -351,8 +384,8 @@ function commandArgv(hook: string | string[]): string[] {
|
|
|
351
384
|
return Array.isArray(hook) ? hook : splitCommand(hook);
|
|
352
385
|
}
|
|
353
386
|
|
|
354
|
-
// The command form's argv, for the document; a function
|
|
355
|
-
// serializable.
|
|
387
|
+
// The command form's argv, for the document; a function
|
|
388
|
+
// isn't serializable.
|
|
356
389
|
export function prepareArgv(
|
|
357
390
|
hook: PrepareHook | undefined,
|
|
358
391
|
): string[] | undefined {
|
package/src/stats/bootstrap.ts
CHANGED
|
@@ -97,8 +97,8 @@ function resampleMedian(s: Side, rng: () => number): number {
|
|
|
97
97
|
return sorted[n - 1] ?? 0;
|
|
98
98
|
}
|
|
99
99
|
|
|
100
|
-
// Hash of both arrays, so identical input always gets the same CI
|
|
101
|
-
// verdict.
|
|
100
|
+
// Hash of both arrays, so identical input always gets the same CI
|
|
101
|
+
// and verdict.
|
|
102
102
|
function seedFromSamples(base: number[], cand: number[]): number {
|
|
103
103
|
const all = new Float64Array(base.length + cand.length + 1);
|
|
104
104
|
all.set(base);
|
package/src/stats/index.ts
CHANGED
|
@@ -110,8 +110,8 @@ export function timingWarnings(
|
|
|
110
110
|
}
|
|
111
111
|
|
|
112
112
|
// In-process samples always have a long right tail (GC, tier-up) that the
|
|
113
|
-
// median is robust to; with a handful of subprocess trials one
|
|
114
|
-
// matters.
|
|
113
|
+
// median is robust to; with a handful of subprocess trials one
|
|
114
|
+
// outlier matters.
|
|
115
115
|
if (mode !== "inprocess" && stats.outliers.mild + stats.outliers.severe > 0) {
|
|
116
116
|
warnings.push({
|
|
117
117
|
code: "outliers-detected",
|
package/src/terminal.ts
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// Terminal output shared by metonym's command-line tools: color, tables,
|
|
2
|
+
// trees, the closing line and the progress line. Each tool carries an
|
|
3
|
+
// identical copy, since a package here has no runtime dependencies; a
|
|
4
|
+
// change is made once and copied to all of them.
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Color for the human format on a terminal only: the agent format and
|
|
8
|
+
* JSON are read by programs. Each color marks a verdict or recedes,
|
|
9
|
+
* never decorates.
|
|
10
|
+
*/
|
|
11
|
+
export type Paint = {
|
|
12
|
+
good: (text: string) => string;
|
|
13
|
+
warn: (text: string) => string;
|
|
14
|
+
bad: (text: string) => string;
|
|
15
|
+
dim: (text: string) => string;
|
|
16
|
+
bold: (text: string) => string;
|
|
17
|
+
faint: (text: string) => string;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
const asIs = (text: string) => text;
|
|
21
|
+
|
|
22
|
+
export const PLAIN: Paint = {
|
|
23
|
+
good: asIs,
|
|
24
|
+
warn: asIs,
|
|
25
|
+
bad: asIs,
|
|
26
|
+
dim: asIs,
|
|
27
|
+
bold: asIs,
|
|
28
|
+
faint: asIs,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// The 16 ANSI colors, never a fixed hex: each terminal theme defines
|
|
32
|
+
// its own green or gray, picked to read on its own background, light,
|
|
33
|
+
// dark or pink. The codes are written out, not asked of Bun.color, so
|
|
34
|
+
// a package that also runs on Node prints the same.
|
|
35
|
+
export function createPaint(): Paint {
|
|
36
|
+
const wrap = (code: number) => (text: string) =>
|
|
37
|
+
text === "" ? text : `\x1b[${code}m${text}\x1b[39m`;
|
|
38
|
+
return {
|
|
39
|
+
good: wrap(32),
|
|
40
|
+
warn: wrap(33),
|
|
41
|
+
bad: wrap(31),
|
|
42
|
+
// Bright black, the gray every theme dims secondary text with.
|
|
43
|
+
dim: wrap(90),
|
|
44
|
+
// Bold is a weight, not a color: names and section heads.
|
|
45
|
+
bold: (text) => (text === "" ? text : `\x1b[1m${text}\x1b[22m`),
|
|
46
|
+
// Faint is the text color at lower intensity, so a table's header
|
|
47
|
+
// recedes in every theme, even one whose gray is odd.
|
|
48
|
+
faint: (text) => (text === "" ? text : `\x1b[2m${text}\x1b[22m`),
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// The person's explicit ask wins, because they know where the output
|
|
53
|
+
// goes: the flag, then NO_COLOR and FORCE_COLOR (no-color.org,
|
|
54
|
+
// force-color.org). Otherwise color only for a terminal no coding agent
|
|
55
|
+
// reads, since escape codes are noise to a program.
|
|
56
|
+
export function wantsColor(
|
|
57
|
+
forced: boolean | undefined,
|
|
58
|
+
terminal: boolean,
|
|
59
|
+
env: Readonly<Record<string, string | undefined>>,
|
|
60
|
+
agent: boolean,
|
|
61
|
+
): boolean {
|
|
62
|
+
if (forced !== undefined) return forced;
|
|
63
|
+
if ((env.NO_COLOR ?? "") !== "") return false;
|
|
64
|
+
const force = env.FORCE_COLOR;
|
|
65
|
+
if (force !== undefined && force !== "") return force !== "0";
|
|
66
|
+
return terminal && !agent;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// "n/a", because an em dash for a missing value reads as punctuation.
|
|
70
|
+
export const MISSING = "n/a";
|
|
71
|
+
|
|
72
|
+
// A zero difference has no sign, so "±" only ever means noise. The
|
|
73
|
+
// minus is ASCII, so a pasted number parses.
|
|
74
|
+
export const signed = (value: number, show: (n: number) => string): string =>
|
|
75
|
+
value === 0 ? show(0) : `${value > 0 ? "+" : "-"}${show(Math.abs(value))}`;
|
|
76
|
+
|
|
77
|
+
// The one separator, so every header and status line splits its parts
|
|
78
|
+
// the same way.
|
|
79
|
+
export const SEPARATOR = " · ";
|
|
80
|
+
|
|
81
|
+
// A sub-row's branch, so a group's last row closes it: ├ then └.
|
|
82
|
+
export const branch = (index: number, count: number): string =>
|
|
83
|
+
index === count - 1 ? "└ " : "├ ";
|
|
84
|
+
|
|
85
|
+
// A note under a row, indented past the label's branch, as a reason or
|
|
86
|
+
// a problem that would push the row past 80 columns.
|
|
87
|
+
export const NOTE_INDENT = " ";
|
|
88
|
+
|
|
89
|
+
// The last line of a run that finished: what it did and what it took,
|
|
90
|
+
// so a person sees it ended and why it took that long.
|
|
91
|
+
export function closingLine(
|
|
92
|
+
paint: Paint,
|
|
93
|
+
what: string,
|
|
94
|
+
detail?: string,
|
|
95
|
+
): string {
|
|
96
|
+
return `${paint.good("✓")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// A run that found problems ends in a cross, so the last line says
|
|
100
|
+
// whether to act, as the check mark does when there's nothing to do.
|
|
101
|
+
export function failLine(paint: Paint, what: string, detail?: string): string {
|
|
102
|
+
return `${paint.bad("✗")} ${what}${detail === undefined ? "" : paint.dim(`${SEPARATOR}${detail}`)}`;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Cut at a word boundary, so a label never ends mid-word; JSON keeps
|
|
106
|
+
// it whole.
|
|
107
|
+
export function truncateWords(text: string, max: number): string {
|
|
108
|
+
if ([...text].length <= max) return text;
|
|
109
|
+
const cut = [...text].slice(0, max - 1).join("");
|
|
110
|
+
const space = cut.lastIndexOf(" ");
|
|
111
|
+
return `${(space > max / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:]+$/, "")}…`;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Since the file name matters more than its folders, and its first and
|
|
115
|
+
// last words more than its middle, folders go from the left first, then
|
|
116
|
+
// the stem's middle words, and the build hash and extension always stay,
|
|
117
|
+
// as in …/carbon-…DataTableSkeleton-Lp9Rk3Ds.js.
|
|
118
|
+
const HASH_TAIL = /[-.][^-./]+\.\w+$/;
|
|
119
|
+
const WORD_END = /(?<=[-_.])/;
|
|
120
|
+
const width = (text: string) => [...text].length;
|
|
121
|
+
|
|
122
|
+
export function truncatePath(path: string, max: number): string {
|
|
123
|
+
if (width(path) <= max) return path;
|
|
124
|
+
const parts = path.split("/");
|
|
125
|
+
const name = parts.pop() ?? path;
|
|
126
|
+
for (let keep = parts.length - 1; keep >= 0; keep--) {
|
|
127
|
+
const candidate = `…/${[...parts.slice(parts.length - keep), name].join("/")}`;
|
|
128
|
+
if (width(candidate) <= max) return candidate;
|
|
129
|
+
}
|
|
130
|
+
const prefix = parts.length > 0 ? "…/" : "";
|
|
131
|
+
const tail = HASH_TAIL.exec(name)?.[0] ?? "";
|
|
132
|
+
const stem = name.slice(0, name.length - tail.length);
|
|
133
|
+
const room = max - width(prefix) - width(tail) - 1;
|
|
134
|
+
if (room < 4)
|
|
135
|
+
return `${prefix}…${[...name].slice(-(max - width(prefix) - 1)).join("")}`;
|
|
136
|
+
const words = stem.split(WORD_END);
|
|
137
|
+
const first = words[0] ?? "";
|
|
138
|
+
let end = "";
|
|
139
|
+
for (let i = words.length - 1; i > 0; i--) {
|
|
140
|
+
const word = words[i] ?? "";
|
|
141
|
+
if (width(first) + 1 + width(word + end) > room) break;
|
|
142
|
+
end = word + end;
|
|
143
|
+
}
|
|
144
|
+
return end === ""
|
|
145
|
+
? `${prefix}${[...stem].slice(0, room).join("")}…${tail}`
|
|
146
|
+
: `${prefix}${first}…${end}${tail}`;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// A mark in the left margin for a row that needs work, in its rating's
|
|
150
|
+
// color, so a scan finds what to fix while the numbers stay plain.
|
|
151
|
+
export function withGutter(
|
|
152
|
+
lines: readonly string[],
|
|
153
|
+
marks: ReadonlyMap<number, (text: string) => string>,
|
|
154
|
+
): string[] {
|
|
155
|
+
return lines.map((line, i) => {
|
|
156
|
+
const mark = marks.get(i);
|
|
157
|
+
return mark === undefined ? line : `${mark("▌")}${line.slice(1)}`;
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// eslint-disable-next-line no-control-regex -- escape codes are what it strips
|
|
162
|
+
const ESCAPE = /\x1b\[[0-9;]*m/g;
|
|
163
|
+
|
|
164
|
+
// Widths come from Bun when it runs, since it counts wide characters;
|
|
165
|
+
// a package that also runs on Node counts one column per code point,
|
|
166
|
+
// because the text these tools print has no wide ones.
|
|
167
|
+
export const textWidth = (text: string): number =>
|
|
168
|
+
typeof Bun === "undefined"
|
|
169
|
+
? [...text.replace(ESCAPE, "")].length
|
|
170
|
+
: Bun.stringWidth(text);
|
|
171
|
+
|
|
172
|
+
// 80 columns, because that's the width a terminal opens at.
|
|
173
|
+
export const MEASURE = 80;
|
|
174
|
+
|
|
175
|
+
// A cell that draws a rule as wide as its column, so totals read apart
|
|
176
|
+
// from the rows above them.
|
|
177
|
+
export const RULE = "\u0000rule";
|
|
178
|
+
|
|
179
|
+
// Numbers right-align, so the columns in `right` pad on the left. A
|
|
180
|
+
// left-aligned last cell is left ragged, since padding it would only add
|
|
181
|
+
// trailing spaces.
|
|
182
|
+
export function aligned(
|
|
183
|
+
table: readonly (readonly string[])[],
|
|
184
|
+
rightColumns: readonly number[] = [],
|
|
185
|
+
paintRule: (text: string) => string = asIs,
|
|
186
|
+
indent = " ",
|
|
187
|
+
): string[] {
|
|
188
|
+
const blank = (cell: string) => cell === "" || cell === RULE;
|
|
189
|
+
// A column empty in every row, such as noise from one run, is left
|
|
190
|
+
// out, or it would print as a double gap.
|
|
191
|
+
const used = new Set(
|
|
192
|
+
table.flatMap((row) => row.flatMap((cell, i) => (blank(cell) ? [] : [i]))),
|
|
193
|
+
);
|
|
194
|
+
const keep = (row: readonly string[]) => row.filter((_, i) => used.has(i));
|
|
195
|
+
const rows = table.map(keep);
|
|
196
|
+
const right = [...used]
|
|
197
|
+
.sort((a, b) => a - b)
|
|
198
|
+
.flatMap((column, i) => (rightColumns.includes(column) ? [i] : []));
|
|
199
|
+
// Escape codes take no columns, so a colored cell pads as wide as
|
|
200
|
+
// it shows.
|
|
201
|
+
const cellWidth = (cell: string) => (cell === RULE ? 0 : textWidth(cell));
|
|
202
|
+
const widths: number[] = [];
|
|
203
|
+
for (const row of rows) {
|
|
204
|
+
for (const [i, cell] of row.entries()) {
|
|
205
|
+
if (i === row.length - 1 && !right.includes(i)) continue;
|
|
206
|
+
widths[i] = Math.max(widths[i] ?? 0, cellWidth(cell));
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
const pad = (cell: string, i: number) =>
|
|
210
|
+
" ".repeat(Math.max(0, (widths[i] ?? 0) - cellWidth(cell)));
|
|
211
|
+
const columnsWidth = (from: number, to: number) =>
|
|
212
|
+
widths.slice(from, to).reduce((sum, w) => sum + w + 2, 0);
|
|
213
|
+
return rows.map((row) => {
|
|
214
|
+
const first = row.indexOf(RULE);
|
|
215
|
+
if (first !== -1) {
|
|
216
|
+
const last = row.lastIndexOf(RULE);
|
|
217
|
+
const line = "─".repeat(columnsWidth(first, last + 1) - 2);
|
|
218
|
+
return `${indent}${" ".repeat(columnsWidth(0, first))}${paintRule(line)}`;
|
|
219
|
+
}
|
|
220
|
+
// An empty row is a blank line, with no indent left trailing.
|
|
221
|
+
return `${indent}${row
|
|
222
|
+
.map((cell, i) =>
|
|
223
|
+
right.includes(i)
|
|
224
|
+
? pad(cell, i) + cell
|
|
225
|
+
: i === row.length - 1
|
|
226
|
+
? cell
|
|
227
|
+
: cell + pad(cell, i),
|
|
228
|
+
)
|
|
229
|
+
.join(" ")}`.trimEnd();
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// aligned, with a row that overflows the measure shortened in its last
|
|
234
|
+
// cell by `shrink`, by just its overflow. Other rows, the header and a
|
|
235
|
+
// colored cell, which a cut would break, stay as they are.
|
|
236
|
+
export function fitted(
|
|
237
|
+
table: readonly (readonly string[])[],
|
|
238
|
+
rightColumns: readonly number[],
|
|
239
|
+
shrink: (text: string, max: number) => string,
|
|
240
|
+
paintRule: (text: string) => string = asIs,
|
|
241
|
+
): string[] {
|
|
242
|
+
const lines = aligned(table, rightColumns, paintRule);
|
|
243
|
+
if (lines.every((line) => textWidth(line) <= MEASURE)) return lines;
|
|
244
|
+
const shrunk = table.map((row, r) => {
|
|
245
|
+
const over = textWidth(lines[r] ?? "") - MEASURE;
|
|
246
|
+
const last = row.length - 1;
|
|
247
|
+
const cell = row[last] ?? "";
|
|
248
|
+
if (r === 0 || over <= 0 || cell === RULE || cell.includes("\x1b")) {
|
|
249
|
+
return row;
|
|
250
|
+
}
|
|
251
|
+
const copy = [...row];
|
|
252
|
+
copy[last] = shrink(cell, textWidth(cell) - over);
|
|
253
|
+
return copy;
|
|
254
|
+
});
|
|
255
|
+
return aligned(shrunk, rightColumns, paintRule);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Lines with notes under some of them, keyed by the line's index, so a
|
|
259
|
+
// note follows its row without widening the table.
|
|
260
|
+
export function withNotes(
|
|
261
|
+
lines: readonly string[],
|
|
262
|
+
notes: ReadonlyMap<number, readonly string[]>,
|
|
263
|
+
): string[] {
|
|
264
|
+
return lines.flatMap((line, i) => [line, ...(notes.get(i) ?? [])]);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// A table's header row is read once, then consulted, so it takes the
|
|
268
|
+
// smallest effective difference: faint, with no rule under it.
|
|
269
|
+
export const headerRow = (paint: Paint, cells: readonly string[]): string[] =>
|
|
270
|
+
cells.map((cell) => paint.faint(cell));
|
|
271
|
+
|
|
272
|
+
export const plural = (count: number, one: string, many = `${one}s`): string =>
|
|
273
|
+
`${count} ${count === 1 ? one : many}`;
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* One stderr line, rewritten in place while a long run works, so it never
|
|
277
|
+
* looks stuck. Made only when stderr is a terminal, and not for a coding
|
|
278
|
+
* agent or JSON; cleared before the result prints.
|
|
279
|
+
*/
|
|
280
|
+
export type Progress = {
|
|
281
|
+
step(text: string, doneRatio: number): void;
|
|
282
|
+
clear(): void;
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
export const SILENT: Progress = { step: () => {}, clear: () => {} };
|
|
286
|
+
|
|
287
|
+
const BAR_WIDTH = 20;
|
|
288
|
+
const CLEAR_LINE = "\r\x1b[2K";
|
|
289
|
+
|
|
290
|
+
export function createProgress(
|
|
291
|
+
write: (text: string) => void,
|
|
292
|
+
paint: Paint,
|
|
293
|
+
nowMs: () => number,
|
|
294
|
+
): Progress {
|
|
295
|
+
const startMs = nowMs();
|
|
296
|
+
let text = "";
|
|
297
|
+
let doneRatio = 0;
|
|
298
|
+
const render = () => {
|
|
299
|
+
const done = Math.round(Math.min(1, Math.max(0, doneRatio)) * BAR_WIDTH);
|
|
300
|
+
// Done and to-do differ in shape as well as color, so the bar reads
|
|
301
|
+
// without color too.
|
|
302
|
+
const bar =
|
|
303
|
+
paint.good("━".repeat(done)) + paint.dim("─".repeat(BAR_WIDTH - done));
|
|
304
|
+
const seconds = Math.floor((nowMs() - startMs) / 1000);
|
|
305
|
+
write(`${CLEAR_LINE}${bar} ${text}${paint.dim(` · ${seconds} s`)}`);
|
|
306
|
+
};
|
|
307
|
+
// A tick each second, so the clock moves while a step is in flight.
|
|
308
|
+
const timer = setInterval(render, 1000);
|
|
309
|
+
timer.unref();
|
|
310
|
+
return {
|
|
311
|
+
step(next, ratio) {
|
|
312
|
+
text = next;
|
|
313
|
+
doneRatio = ratio;
|
|
314
|
+
render();
|
|
315
|
+
},
|
|
316
|
+
clear() {
|
|
317
|
+
clearInterval(timer);
|
|
318
|
+
write(CLEAR_LINE);
|
|
319
|
+
},
|
|
320
|
+
};
|
|
321
|
+
}
|
package/src/time.ts
CHANGED
|
@@ -22,11 +22,7 @@ import {
|
|
|
22
22
|
noisyMachineWarning,
|
|
23
23
|
stampDrift,
|
|
24
24
|
} from "./measure/environment.ts";
|
|
25
|
-
import {
|
|
26
|
-
assertSamplingOptions,
|
|
27
|
-
createTimingPhase,
|
|
28
|
-
drainTimingPhase,
|
|
29
|
-
} from "./measure/timing.ts";
|
|
25
|
+
import { assertSamplingOptions, createTimingPhase } from "./measure/timing.ts";
|
|
30
26
|
import {
|
|
31
27
|
type PrepareHook,
|
|
32
28
|
type PrepareRun,
|
|
@@ -56,6 +52,23 @@ export interface CommandSpec {
|
|
|
56
52
|
|
|
57
53
|
export interface TimeOptions {
|
|
58
54
|
commands: (string | string[] | CommandSpec)[];
|
|
55
|
+
/**
|
|
56
|
+
* Run each string command, and a string `prepare`, as `shell -c COMMAND`
|
|
57
|
+
* (`"sh"`, `"bash"`) instead of splitting it on whitespace, so env
|
|
58
|
+
* prefixes, pipes, `&&` and `$(...)` work. An argv array runs as given.
|
|
59
|
+
* The shell's own startup is measured and recorded as `doc.shell`,
|
|
60
|
+
* not subtracted.
|
|
61
|
+
*/
|
|
62
|
+
shell?: string;
|
|
63
|
+
/**
|
|
64
|
+
* Save each trial's stdout and stderr under this directory, one folder
|
|
65
|
+
* per command (its label, made safe for a path, and its id), as
|
|
66
|
+
* `trial-N.log` and `warmup-N.log`; each trial's `outputPath` names
|
|
67
|
+
* its file.
|
|
68
|
+
*/
|
|
69
|
+
saveOutput?: string;
|
|
70
|
+
/** Pass each trial's output to stderr, for debugging. */
|
|
71
|
+
showOutput?: boolean;
|
|
59
72
|
/**
|
|
60
73
|
* Runs unmeasured before every trial (warmup and instrumented included),
|
|
61
74
|
* in `cwd`/`env`: a command spawned and awaited, or a function. */
|
|
@@ -75,8 +88,9 @@ export interface TimeOptions {
|
|
|
75
88
|
warmup?: number;
|
|
76
89
|
/**
|
|
77
90
|
* Round-robin trials across commands instead of finishing each command
|
|
78
|
-
* first, so drift hits every command equally. Default: true with
|
|
79
|
-
* commands.
|
|
91
|
+
* first, so drift hits every command equally. Default: true with
|
|
92
|
+
* 2+ commands.
|
|
93
|
+
*/
|
|
80
94
|
interleave?: boolean;
|
|
81
95
|
cwd?: string;
|
|
82
96
|
env?: Record<string, string>;
|
|
@@ -85,9 +99,11 @@ export interface TimeOptions {
|
|
|
85
99
|
cpuIntervalUs?: number;
|
|
86
100
|
outDir?: string;
|
|
87
101
|
/**
|
|
88
|
-
* Measure the machine's noise floor first (default true,
|
|
89
|
-
* it on the document as `environment`. */
|
|
102
|
+
* Measure the machine's noise floor first (default true, 25 to 50 ms) and
|
|
103
|
+
* stamp it on the document as `environment`. */
|
|
90
104
|
noiseCheck?: boolean;
|
|
105
|
+
/** Sample the noise floor for exactly this many ms instead. */
|
|
106
|
+
noiseBudgetMs?: number;
|
|
91
107
|
/**
|
|
92
108
|
* SIGKILLs a trial (or prepare hook) still running after this many ms. No
|
|
93
109
|
* default. A timed-out trial contributes no sample. */
|
|
@@ -102,6 +118,19 @@ export interface TimeOptions {
|
|
|
102
118
|
* trial still contributes its sample and gets no `nonzero-exit` warning.
|
|
103
119
|
* */
|
|
104
120
|
ignoreExitCodes?: number[];
|
|
121
|
+
/** Called after each trial, for a progress line. */
|
|
122
|
+
onProgress?: (progress: TimeProgress) => void;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** What `time()` is doing, for `onProgress`. Counts start at 1. */
|
|
126
|
+
export interface TimeProgress {
|
|
127
|
+
command: number;
|
|
128
|
+
commands: number;
|
|
129
|
+
label: string;
|
|
130
|
+
/** Trials run so far for this command, warmup excluded. */
|
|
131
|
+
runs: number;
|
|
132
|
+
/** How far the whole run is, 0 to 1. */
|
|
133
|
+
doneRatio: number;
|
|
105
134
|
}
|
|
106
135
|
|
|
107
136
|
export function abortedWarning(): Warning {
|
|
@@ -127,7 +156,9 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
|
127
156
|
});
|
|
128
157
|
const artifactDir = `${opts.outDir ?? DEFAULT_OUT_DIR}/artifacts`;
|
|
129
158
|
const environment =
|
|
130
|
-
opts.noiseCheck === false
|
|
159
|
+
opts.noiseCheck === false
|
|
160
|
+
? undefined
|
|
161
|
+
: captureEnvironment(opts.noiseBudgetMs);
|
|
131
162
|
const noiseWarning = environment
|
|
132
163
|
? noisyMachineWarning(environment)
|
|
133
164
|
: undefined;
|
|
@@ -143,8 +174,14 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
|
143
174
|
: entry;
|
|
144
175
|
const argv = Array.isArray(spec.command)
|
|
145
176
|
? spec.command
|
|
146
|
-
:
|
|
147
|
-
|
|
177
|
+
: opts.shell
|
|
178
|
+
? [opts.shell, "-c", spec.command]
|
|
179
|
+
: splitCommand(spec.command);
|
|
180
|
+
const givenPrepare = spec.prepare ?? opts.prepare;
|
|
181
|
+
const prepare =
|
|
182
|
+
opts.shell && typeof givenPrepare === "string"
|
|
183
|
+
? [opts.shell, "-c", givenPrepare]
|
|
184
|
+
: givenPrepare;
|
|
148
185
|
const timeSource = spec.timeSource ?? opts.timeSource;
|
|
149
186
|
const workload = makeSubprocessWorkload(
|
|
150
187
|
argv,
|
|
@@ -182,6 +219,10 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
|
182
219
|
ignoreExitCodes: entry.ignoreExitCodes,
|
|
183
220
|
}),
|
|
184
221
|
...(opts.signal !== undefined && { signal: opts.signal }),
|
|
222
|
+
...(opts.saveOutput !== undefined && {
|
|
223
|
+
outputDir: `${opts.saveOutput}/${outputFolder(entry.workload)}`,
|
|
224
|
+
}),
|
|
225
|
+
...(opts.showOutput && { showOutput: true }),
|
|
185
226
|
}),
|
|
186
227
|
}));
|
|
187
228
|
|
|
@@ -201,8 +242,8 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
|
201
242
|
...(interleave && { interleaved: true }),
|
|
202
243
|
});
|
|
203
244
|
measurements.push(timingMeasurement);
|
|
204
|
-
// An instrumented capture is one more spawned run, so don't start it
|
|
205
|
-
// cancelled.
|
|
245
|
+
// An instrumented capture is one more spawned run, so don't start it
|
|
246
|
+
// once cancelled.
|
|
206
247
|
if (!opts.signal?.aborted) {
|
|
207
248
|
measurements.push(
|
|
208
249
|
...(await captureInstrumentedPhases({
|
|
@@ -218,19 +259,53 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
|
218
259
|
}
|
|
219
260
|
};
|
|
220
261
|
|
|
262
|
+
const shell = opts.shell
|
|
263
|
+
? { command: opts.shell, startupNs: await shellStartupNs(opts.shell) }
|
|
264
|
+
: undefined;
|
|
265
|
+
|
|
266
|
+
const runsDone = runs.map(() => 0);
|
|
267
|
+
const report = (index: number) => {
|
|
268
|
+
const entry = runs[index]?.entry;
|
|
269
|
+
if (!opts.onProgress || !entry) return;
|
|
270
|
+
opts.onProgress({
|
|
271
|
+
command: index + 1,
|
|
272
|
+
commands: runs.length,
|
|
273
|
+
label: entry.workload.label ?? entry.argv.join(" "),
|
|
274
|
+
runs: runsDone[index] ?? 0,
|
|
275
|
+
doneRatio:
|
|
276
|
+
runs.reduce((sum, { phase }) => sum + phase.doneRatio(), 0) /
|
|
277
|
+
runs.length,
|
|
278
|
+
});
|
|
279
|
+
};
|
|
280
|
+
const step = async (index: number): Promise<boolean> => {
|
|
281
|
+
const stepped = (await runs[index]?.phase.step()) ?? false;
|
|
282
|
+
if (stepped) {
|
|
283
|
+
runsDone[index] = (runsDone[index] ?? 0) + 1;
|
|
284
|
+
report(index);
|
|
285
|
+
}
|
|
286
|
+
return stepped;
|
|
287
|
+
};
|
|
288
|
+
|
|
221
289
|
if (interleave) {
|
|
222
|
-
for (const { phase } of runs
|
|
290
|
+
for (const [index, { phase }] of runs.entries()) {
|
|
291
|
+
report(index);
|
|
292
|
+
await phase.warmup();
|
|
293
|
+
}
|
|
223
294
|
let stepped = true;
|
|
224
295
|
while (stepped) {
|
|
225
296
|
stepped = false;
|
|
226
|
-
for (const
|
|
227
|
-
if (await
|
|
297
|
+
for (const index of runs.keys()) {
|
|
298
|
+
if (await step(index)) stepped = true;
|
|
228
299
|
}
|
|
229
300
|
}
|
|
230
301
|
for (const run of runs) await record(run);
|
|
231
302
|
} else {
|
|
232
|
-
for (const run of runs) {
|
|
233
|
-
|
|
303
|
+
for (const [index, run] of runs.entries()) {
|
|
304
|
+
report(index);
|
|
305
|
+
await run.phase.warmup();
|
|
306
|
+
while (await step(index)) {
|
|
307
|
+
// Each step runs one trial.
|
|
308
|
+
}
|
|
234
309
|
await record(run);
|
|
235
310
|
}
|
|
236
311
|
}
|
|
@@ -241,7 +316,36 @@ export async function time(opts: TimeOptions): Promise<ProfileDocument> {
|
|
|
241
316
|
}
|
|
242
317
|
|
|
243
318
|
stampDrift(environment);
|
|
244
|
-
|
|
319
|
+
const doc = createDocument(workloads, measurements, environment);
|
|
320
|
+
if (shell) doc.shell = shell;
|
|
321
|
+
return doc;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
// A command's folder under `--save-output`: its label, safe for a path,
|
|
325
|
+
// then its id, since two commands can share a label.
|
|
326
|
+
function outputFolder(workload: Workload): string {
|
|
327
|
+
const name = (workload.label ?? workload.command?.join(" ") ?? "command")
|
|
328
|
+
.replace(/[^\w.-]+/g, "-")
|
|
329
|
+
.replace(/^-+|-+$/g, "")
|
|
330
|
+
.slice(0, 60);
|
|
331
|
+
return `${name || "command"}-${workload.id.slice(3, 11)}`;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const SHELL_STARTUP_RUNS = 5;
|
|
335
|
+
|
|
336
|
+
// The median wall time of `shell -c :`, the startup every command run
|
|
337
|
+
// through the shell pays, so a reader can tell it from the command's own.
|
|
338
|
+
async function shellStartupNs(shell: string): Promise<number> {
|
|
339
|
+
const samples: number[] = [];
|
|
340
|
+
for (let i = 0; i < SHELL_STARTUP_RUNS; i++) {
|
|
341
|
+
const start = Bun.nanoseconds();
|
|
342
|
+
// eslint-disable-next-line no-await-in-loop -- one at a time, so the runs don't share the machine
|
|
343
|
+
await Bun.spawn([shell, "-c", ":"], { stdout: "ignore", stderr: "ignore" })
|
|
344
|
+
.exited;
|
|
345
|
+
samples.push(Bun.nanoseconds() - start);
|
|
346
|
+
}
|
|
347
|
+
samples.sort((a, b) => a - b);
|
|
348
|
+
return samples[samples.length >> 1] ?? 0;
|
|
245
349
|
}
|
|
246
350
|
|
|
247
351
|
async function captureInstrumentedPhases({
|