ostia 0.5.0 → 0.6.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/src/index.ts CHANGED
@@ -2,7 +2,7 @@ import type { OstiaConfigInput } from "./config/index.ts";
2
2
 
3
3
  export type { AbOptions, AbProgress } from "./ab/index.ts";
4
4
  export { ab, AbBaseError, AbSetupError, AbSuiteError } from "./ab/index.ts";
5
- export type { BenchOptions } from "./bench/index.ts";
5
+ export type { BenchOptions, BenchProgress } from "./bench/index.ts";
6
6
  export { bench } from "./bench/index.ts";
7
7
  export { range } from "./bench/range.ts";
8
8
  export type { GroupOptions, TaskOptions } from "./bench/registry.ts";
@@ -60,6 +60,7 @@ export type {
60
60
  MinimalUnmatchedLine,
61
61
  } from "./renderers/minimal.ts";
62
62
  export { MINIMAL_PROTOCOL_VERSION } from "./renderers/minimal.ts";
63
+ export type { TableOptions } from "./renderers/terminal.ts";
63
64
  export type { FormatName, Renderer, VizOptions } from "./renderers/types.ts";
64
65
  export type {
65
66
  PrepareFn,
@@ -68,7 +69,7 @@ export type {
68
69
  TimeSource,
69
70
  TimeUnit,
70
71
  } from "./spawn/index.ts";
71
- export type { CommandSpec, TimeOptions } from "./time.ts";
72
+ export type { CommandSpec, TimeOptions, TimeProgress } from "./time.ts";
72
73
  export { time } from "./time.ts";
73
74
 
74
75
  /** Identity function that types an `ostia.config.ts` default export. */
package/src/ir/types.ts CHANGED
@@ -467,6 +467,7 @@ export const WARNING_CODES: readonly [
467
467
  "environment-mismatch",
468
468
  "peak-hidden",
469
469
  "suite-changed",
470
+ "repeats-disagree",
470
471
  ] = [
471
472
  "slow-first-run",
472
473
  "outliers-detected",
@@ -485,6 +486,7 @@ export const WARNING_CODES: readonly [
485
486
  "environment-mismatch",
486
487
  "peak-hidden",
487
488
  "suite-changed",
489
+ "repeats-disagree",
488
490
  ];
489
491
 
490
492
  export type WarningCode = (typeof WARNING_CODES)[number];
@@ -53,6 +53,8 @@ interface TimingPhaseIterator {
53
53
  */
54
54
  step(): Promise<boolean>;
55
55
  done(): boolean;
56
+ /** How far toward its stopping criterion, 0 to 1, for a progress line. */
57
+ doneRatio(): number;
56
58
  result(): TimingPhaseResult;
57
59
  }
58
60
 
@@ -157,6 +159,12 @@ export function createTimingPhase(
157
159
  return true;
158
160
  },
159
161
  done,
162
+ doneRatio() {
163
+ if (done()) return 1;
164
+ if (samples !== undefined) return i / samples;
165
+ // Both must be met, so the one further from it is how far along.
166
+ return Math.min(i / Math.max(minSamples, 1), totalNs / budgetNs);
167
+ },
160
168
  result(): TimingPhaseResult {
161
169
  // Excluded, never a `wallNs` fallback: that would mix wall time into a
162
170
  // reported-time series.
@@ -207,9 +215,7 @@ export function createTimingPhase(
207
215
  };
208
216
  }
209
217
 
210
- export async function drainTimingPhase(
211
- phase: TimingPhaseIterator,
212
- ): Promise<void> {
218
+ async function drainTimingPhase(phase: TimingPhaseIterator): Promise<void> {
213
219
  await phase.warmup();
214
220
  while (await phase.step()) {
215
221
  // Each step runs one trial.
@@ -0,0 +1,402 @@
1
+ // The pieces of the human (table) format that every command shares:
2
+ // numbers to three significant figures, the context line, a warning in
3
+ // words, and a table whose names shrink to fit 80 columns.
4
+
5
+ import type { Environment, TimingStats, Warning } from "../ir/types.ts";
6
+ import { percentile, sortedCopy } from "../stats/index.ts";
7
+ import {
8
+ aligned,
9
+ MEASURE,
10
+ MISSING,
11
+ NOTE_INDENT,
12
+ type Paint,
13
+ plural,
14
+ SEPARATOR,
15
+ signed,
16
+ textWidth,
17
+ truncateWords,
18
+ withNotes,
19
+ } from "../terminal.ts";
20
+
21
+ // Three significant figures, so a column of numbers reads at one
22
+ // precision: 22.2, 248, 8.80.
23
+ function toSig3(value: number): string {
24
+ if (value === 0) return "0";
25
+ const abs = Math.abs(value);
26
+ return abs >= 100
27
+ ? value.toFixed(0)
28
+ : abs >= 10
29
+ ? value.toFixed(1)
30
+ : value.toFixed(2);
31
+ }
32
+
33
+ // Up a unit when rounding reaches 1000, since 999.7 µs should print
34
+ // 1.00 ms, not 1000 µs.
35
+ function scaled(
36
+ value: number,
37
+ units: readonly (readonly [string, number])[],
38
+ ): string {
39
+ if (!Number.isFinite(value)) return MISSING;
40
+ const abs = Math.abs(value);
41
+ let i = 0;
42
+ while (i < units.length - 1 && abs >= (units[i + 1]?.[1] ?? Infinity)) i++;
43
+ let [unit, size] = units[i] ?? ["", 1];
44
+ let text = toSig3(value / size);
45
+ const next = units[i + 1];
46
+ if (next && Math.abs(Number(text)) >= 1000) {
47
+ [unit, size] = next;
48
+ text = toSig3(value / size);
49
+ }
50
+ return unit === "" ? text : `${text}${unit}`;
51
+ }
52
+
53
+ const DURATION_UNITS = [
54
+ [" ns", 1],
55
+ [" µs", 1e3],
56
+ [" ms", 1e6],
57
+ [" s", 1e9],
58
+ ] as const;
59
+
60
+ const COUNT_UNITS = [
61
+ ["", 1],
62
+ ["K", 1e3],
63
+ ["M", 1e6],
64
+ ["G", 1e9],
65
+ ] as const;
66
+
67
+ // invariant: every byte count ostia prints is 1024-based.
68
+ const BYTE_UNITS = [
69
+ [" B", 1],
70
+ [" KiB", 1024],
71
+ [" MiB", 1024 ** 2],
72
+ [" GiB", 1024 ** 3],
73
+ ] as const;
74
+
75
+ export function toDuration(ns: number): string {
76
+ return scaled(ns, DURATION_UNITS);
77
+ }
78
+
79
+ export function toCount(count: number): string {
80
+ return count < 1000 ? String(Math.round(count)) : scaled(count, COUNT_UNITS);
81
+ }
82
+
83
+ export function toBytes(bytes: number): string {
84
+ return Math.abs(bytes) < 1024
85
+ ? `${Math.round(bytes)} B`
86
+ : scaled(bytes, BYTE_UNITS);
87
+ }
88
+
89
+ export function toElapsed(ms: number): string {
90
+ return toDuration(ms * 1e6);
91
+ }
92
+
93
+ export function toShare(pct: number): string {
94
+ return `${toSig3(pct)}%`;
95
+ }
96
+
97
+ export function toTimes(ratio: number): string {
98
+ return `${ratio < 1000 ? toSig3(ratio) : toCount(ratio)}×`;
99
+ }
100
+
101
+ const toPercent = (pct: number) =>
102
+ `${Math.abs(pct) < 100 ? pct.toFixed(1) : pct.toFixed(0)}%`;
103
+
104
+ // The minus is ASCII, so a pasted change parses; zero has no sign.
105
+ export function toChange(pct: number): string {
106
+ if (!Number.isFinite(pct)) return MISSING;
107
+ // Past 10×, a multiple reads at a glance where +64237% doesn't.
108
+ if (pct >= 900) return toTimes(1 + pct / 100);
109
+ return Number(toPercent(pct).slice(0, -1)) === 0
110
+ ? "0.0%"
111
+ : signed(pct, toPercent);
112
+ }
113
+
114
+ // The median absolute deviation, since a long right tail would skew a
115
+ // standard deviation.
116
+ export function toNoise(mad: number, median: number): string {
117
+ return median > 0 ? `±${toPercent((mad / median) * 100)}` : "";
118
+ }
119
+
120
+ export function medianAbsoluteDeviation(values: readonly number[]): number {
121
+ if (values.length === 0) return Number.NaN;
122
+ const median = percentile(sortedCopy([...values]), 0.5);
123
+ return percentile(sortedCopy(values.map((v) => Math.abs(v - median))), 0.5);
124
+ }
125
+
126
+ // The parts of a verdict that fit 80 columns: every required part, then
127
+ // the optional ones in order while they fit, so a long verdict drops its
128
+ // least telling counts rather than wrap.
129
+ export function fittedParts(
130
+ parts: readonly { text: string; required?: boolean }[],
131
+ ): string {
132
+ let width = parts
133
+ .filter((p) => p.required)
134
+ .reduce((sum, p, i) => sum + textWidth(p.text) + (i > 0 ? 3 : 0), 0);
135
+ return parts
136
+ .filter((p) => {
137
+ if (p.required) return true;
138
+ const more = textWidth(p.text) + 3;
139
+ if (width + more > MEASURE) return false;
140
+ width += more;
141
+ return true;
142
+ })
143
+ .map((p) => p.text)
144
+ .join(SEPARATOR);
145
+ }
146
+
147
+ // The machine, since a number means little without where it ran.
148
+ export function environmentParts(env: Environment | undefined): string[] {
149
+ if (!env) return [];
150
+ return [
151
+ env.cpuModel,
152
+ `${env.cores} cores`,
153
+ `load ${env.loadAvg1.toFixed(1)}`,
154
+ `noise floor ${env.noise.floorPct.toFixed(1)}%`,
155
+ ];
156
+ }
157
+
158
+ // The context, packed into as few dim lines as fit 80 columns, a part
159
+ // never split, so a long environment wraps between parts.
160
+ export function contextLines(parts: readonly string[], paint: Paint): string[] {
161
+ const lines: string[] = [];
162
+ let line = "";
163
+ for (const part of parts.filter((p) => p !== "")) {
164
+ const next = line === "" ? part : `${line}${SEPARATOR}${part}`;
165
+ if (line !== "" && textWidth(next) > MEASURE) {
166
+ lines.push(line);
167
+ line = truncateWords(part, MEASURE);
168
+ } else
169
+ line = textWidth(next) > MEASURE ? truncateWords(next, MEASURE) : next;
170
+ }
171
+ if (line !== "") lines.push(line);
172
+ return lines.map((l) => paint.dim(l));
173
+ }
174
+
175
+ type Tone = "good" | "warn" | "bad" | "dim";
176
+
177
+ export interface Note {
178
+ text: string;
179
+ tone: Tone;
180
+ }
181
+
182
+ // Tukey's fences, as `computeTimingStats` uses, so a note agrees with
183
+ // the count.
184
+ const OUTLIER_FENCE = 1.5;
185
+
186
+ // Whether the outliers move the median by more than the noise: the median
187
+ // with them dropped, against the median, past one MAD. The median shrugs
188
+ // off a few outliers, so a count alone says nothing; a shift past the
189
+ // noise is what makes the number wrong.
190
+ function isOutlierShifted(timing: TimingStats): boolean {
191
+ const iqr = timing.p75 - timing.p25;
192
+ const low = timing.p25 - OUTLIER_FENCE * iqr;
193
+ const high = timing.p75 + OUTLIER_FENCE * iqr;
194
+ const kept = timing.samples.filter((s) => s >= low && s <= high);
195
+ if (kept.length === 0 || kept.length === timing.samples.length) return false;
196
+ const median = percentile(sortedCopy(kept), 0.5);
197
+ return Math.abs(median - timing.median) > Math.max(timing.mad, 0);
198
+ }
199
+
200
+ export const numberIn = (
201
+ data: Warning["data"],
202
+ key: string,
203
+ ): number | undefined => {
204
+ const value = data?.[key];
205
+ return typeof value === "number" ? value : undefined;
206
+ };
207
+
208
+ // A message as written for the JSON, without its full stop, so it reads
209
+ // as a note.
210
+ const asNote = (message: string) => message.replace(/\.$/, "");
211
+
212
+ // A warning in words, with its fix where there is one; `timing` decides
213
+ // whether outliers are a problem or an aside, since that turns on
214
+ // the samples.
215
+ export function toWarningNote(w: Warning, timing?: TimingStats): Note {
216
+ const data = w.data;
217
+ switch (w.code) {
218
+ case "slow-first-run": {
219
+ const firstNs = numberIn(data, "firstNs");
220
+ const medianNs = numberIn(data, "medianNs");
221
+ if (firstNs === undefined || medianNs === undefined || medianNs <= 0) {
222
+ return { text: asNote(w.message), tone: "warn" };
223
+ }
224
+ return {
225
+ text: `first run ${toDuration(firstNs)}, ${toTimes(firstNs / medianNs)} the median: add warmup`,
226
+ tone: "warn",
227
+ };
228
+ }
229
+ case "outliers-detected": {
230
+ const mild = numberIn(data, "mild") ?? 0;
231
+ const severe = numberIn(data, "severe") ?? 0;
232
+ const shifted = timing !== undefined && isOutlierShifted(timing);
233
+ return {
234
+ text: `${plural(mild + severe, "outlier")}, ${severe} severe${shifted ? ", enough to move the median: a busy machine, or GC" : ": the median holds"}`,
235
+ tone: shifted ? "warn" : "dim",
236
+ };
237
+ }
238
+ case "fast-command":
239
+ return { text: "under 5 ms: spawn overhead may dominate", tone: "dim" };
240
+ case "nonzero-exit":
241
+ return {
242
+ text: `${asNote(w.message)}: --ignore-failure times them anyway`,
243
+ tone: "bad",
244
+ };
245
+ case "timeout":
246
+ case "time-source-no-match":
247
+ return { text: asNote(w.message), tone: "bad" };
248
+ case "noisy-machine": {
249
+ const load = numberIn(data, "loadAvg1");
250
+ const cores = numberIn(data, "cores");
251
+ return load === undefined || cores === undefined
252
+ ? { text: asNote(w.message), tone: "warn" }
253
+ : {
254
+ text: `load ${load.toFixed(1)} on ${cores} cores: timings may be noisy`,
255
+ tone: "warn",
256
+ };
257
+ }
258
+ case "jit-cold": {
259
+ const slow =
260
+ (numberIn(data, "llintPct") ?? 0) +
261
+ (numberIn(data, "baselinePct") ?? 0);
262
+ return {
263
+ text: `${slow.toFixed(0)}% of samples in the slow tiers: the JIT never warmed it up`,
264
+ tone: "warn",
265
+ };
266
+ }
267
+ case "thin-comparison": {
268
+ const base = numberIn(data, "baseSamples");
269
+ const cand = numberIn(data, "candSamples");
270
+ return {
271
+ text: `only ${base ?? "?"} and ${cand ?? "?"} samples: judged by a threshold, not a CI`,
272
+ tone: "warn",
273
+ };
274
+ }
275
+ case "low-sample-count": {
276
+ const samples = numberIn(data, "samples");
277
+ const target = numberIn(data, "target");
278
+ return samples === undefined || target === undefined
279
+ ? { text: asNote(w.message), tone: "warn" }
280
+ : {
281
+ text: `only ${samples} samples, under the ${target} this cost needs: raise the budget`,
282
+ tone: "warn",
283
+ };
284
+ }
285
+ case "peak-hidden": {
286
+ const slack = numberIn(data, "slackBytes");
287
+ return slack === undefined
288
+ ? { text: asNote(w.message), tone: "warn" }
289
+ : {
290
+ text: `may read up to ${toBytes(slack)} low: setup freed memory the call reused; skip it when OSTIA_PEAK_MEM is set`,
291
+ tone: "warn",
292
+ };
293
+ }
294
+ case "suite-changed":
295
+ return {
296
+ text: "the suite and its output both changed, so it isn't judged",
297
+ tone: "dim",
298
+ };
299
+ case "repeats-disagree": {
300
+ const factor = numberIn(data, "factor");
301
+ return {
302
+ text:
303
+ factor === undefined
304
+ ? asNote(w.message)
305
+ : `fresh-process repeats ${toTimes(factor)} apart from the paired run: --filter to measure it alone`,
306
+ tone: "warn",
307
+ };
308
+ }
309
+ case "skipped":
310
+ return { text: asNote(w.message), tone: "dim" };
311
+ case "aborted":
312
+ case "artifact-missing":
313
+ case "empty-profile":
314
+ case "environment-mismatch":
315
+ return { text: asNote(w.message), tone: "warn" };
316
+ }
317
+ }
318
+
319
+ // Shown once, under the table, since they're about the run, not a row.
320
+ export const RUN_WARNINGS: ReadonlySet<string> = new Set([
321
+ "noisy-machine",
322
+ "aborted",
323
+ "environment-mismatch",
324
+ ]);
325
+
326
+ const paintTone = (paint: Paint, tone: Tone): ((s: string) => string) =>
327
+ tone === "good"
328
+ ? paint.good
329
+ : tone === "warn"
330
+ ? paint.warn
331
+ : tone === "bad"
332
+ ? paint.bad
333
+ : paint.dim;
334
+
335
+ // A note wrapped at a word to fit 80 columns, each line at its indent:
336
+ // a note is read whole, so it isn't cut.
337
+ export function noteLines(note: Note, indent: string, paint: Paint): string[] {
338
+ const room = MEASURE - indent.length;
339
+ const lines: string[] = [];
340
+ let line = "";
341
+ for (const word of note.text.split(" ")) {
342
+ if (line !== "" && textWidth(`${line} ${word}`) > room) {
343
+ lines.push(line);
344
+ line = word;
345
+ } else line = line === "" ? word : `${line} ${word}`;
346
+ }
347
+ if (line !== "") lines.push(line);
348
+ return lines.map((l) => `${indent}${paintTone(paint, note.tone)(l)}`);
349
+ }
350
+
351
+ /** One row of a named table: its label, then its cells. */
352
+ export interface NamedRow {
353
+ /** `├ ` or `└ ` under a group, else empty. */
354
+ branch: string;
355
+ name: string;
356
+ /** Bold for a group's label row; plain for a task. */
357
+ bold?: boolean;
358
+ cells: readonly string[];
359
+ notes?: readonly Note[];
360
+ }
361
+
362
+ const MIN_NAME_WIDTH = 12;
363
+
364
+ // The table's names cut at a word to fit 80 columns, since the numbers
365
+ // can't shrink; notes under a row indent past its branch.
366
+ export function namedTable(
367
+ header: readonly string[],
368
+ rows: readonly NamedRow[],
369
+ rightColumns: readonly number[],
370
+ paint: Paint,
371
+ ): string[] {
372
+ const widths = header
373
+ .slice(1)
374
+ .map((cell, i) =>
375
+ Math.max(
376
+ textWidth(cell),
377
+ ...rows.map((row) => textWidth(row.cells[i] ?? "")),
378
+ ),
379
+ );
380
+ const used = widths.filter((w) => w > 0);
381
+ const room = Math.max(
382
+ MIN_NAME_WIDTH,
383
+ MEASURE - 2 - used.reduce((sum, w) => sum + w + 2, 0),
384
+ );
385
+ const table: string[][] = [[...header]];
386
+ const notes = new Map<number, string[]>();
387
+ for (const row of rows) {
388
+ const name = truncateWords(row.name, room - textWidth(row.branch));
389
+ table.push([
390
+ `${row.branch}${row.bold ? paint.bold(name) : name}`,
391
+ ...row.cells,
392
+ ]);
393
+ if (row.notes?.length) {
394
+ const indent = row.branch === "" ? NOTE_INDENT : ` ${NOTE_INDENT}`;
395
+ notes.set(
396
+ table.length - 1,
397
+ row.notes.flatMap((note) => noteLines(note, indent, paint)),
398
+ );
399
+ }
400
+ }
401
+ return withNotes(aligned(table, rightColumns, paint.dim), notes);
402
+ }
@@ -7,14 +7,14 @@ import { markdownRenderer } from "./markdown.ts";
7
7
  import { type MermaidOptions, mermaidRenderer } from "./mermaid.ts";
8
8
  import { minimalRenderer, type MinimalRenderOptions } from "./minimal.ts";
9
9
  import { speedscopeRenderer } from "./speedscope.ts";
10
- import { terminalRenderer } from "./terminal.ts";
10
+ import { type TableOptions, terminalRenderer } from "./terminal.ts";
11
11
  import type { FormatName, Renderer, VizOptions } from "./types.ts";
12
12
 
13
13
  /** Each format's renderer, typed with its own options. `Renderer<never>` is
14
14
  * the top type, so `satisfies` checks every format is present without
15
15
  * widening the options. */
16
16
  export const renderers: {
17
- table: Renderer;
17
+ table: Renderer<TableOptions>;
18
18
  json: Renderer;
19
19
  markdown: Renderer;
20
20
  jsonl: Renderer;
@@ -40,4 +40,5 @@ export const renderers: {
40
40
  cpuprofile: cpuprofileRenderer,
41
41
  } satisfies Record<FormatName, Renderer<never>>;
42
42
 
43
+ export type { TableOptions } from "./terminal.ts";
43
44
  export type { FormatName, Renderer, RenderResult } from "./types.ts";