ostia 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +4 -4
  2. package/docs/agent-protocol.md +13 -9
  3. package/docs/cli.md +90 -73
  4. package/docs/config.md +2 -2
  5. package/docs/document-schema.md +14 -12
  6. package/docs/library.md +17 -15
  7. package/docs/preload-recipes.md +4 -4
  8. package/docs/statistics.md +10 -10
  9. package/index.d.ts +197 -126
  10. package/package.json +1 -1
  11. package/src/ab/ab-runner.ts +6 -6
  12. package/src/ab/index.ts +15 -6
  13. package/src/bench/index.ts +12 -3
  14. package/src/bench/registry.ts +9 -7
  15. package/src/bench/run-tasks.ts +2 -2
  16. package/src/bench/runner.ts +2 -2
  17. package/src/bench/support.ts +8 -4
  18. package/src/bench/sweep.ts +3 -3
  19. package/src/cache/fingerprint.ts +2 -2
  20. package/src/capture/bunflags.ts +2 -2
  21. package/src/capture/cpu.ts +2 -2
  22. package/src/capture/heap-parse.ts +2 -2
  23. package/src/ci/index.ts +7 -6
  24. package/src/cli/agent.ts +54 -0
  25. package/src/cli/flags.ts +50 -9
  26. package/src/cli/help.ts +29 -11
  27. package/src/cli/output.ts +6 -3
  28. package/src/cli/run.ts +29 -5
  29. package/src/compare/index.ts +4 -4
  30. package/src/config/index.ts +14 -10
  31. package/src/config/validate.ts +4 -4
  32. package/src/glob.ts +2 -2
  33. package/src/index.ts +18 -1
  34. package/src/ir/document.ts +2 -2
  35. package/src/ir/types.ts +50 -27
  36. package/src/measure/alloc.ts +2 -2
  37. package/src/measure/cpu.ts +2 -2
  38. package/src/measure/environment.ts +11 -6
  39. package/src/measure/inprocess.ts +14 -10
  40. package/src/measure/instructions.ts +2 -2
  41. package/src/measure/noise.ts +51 -13
  42. package/src/measure/paired.ts +2 -2
  43. package/src/measure/peak.ts +4 -4
  44. package/src/measure/timing.ts +18 -3
  45. package/src/profile.ts +6 -4
  46. package/src/renderers/collapsed.ts +2 -2
  47. package/src/renderers/concise.ts +148 -0
  48. package/src/renderers/format.ts +13 -4
  49. package/src/renderers/index.ts +6 -0
  50. package/src/renderers/markdown.ts +2 -2
  51. package/src/renderers/mermaid.ts +2 -2
  52. package/src/renderers/minimal.ts +11 -10
  53. package/src/renderers/relative.ts +2 -2
  54. package/src/renderers/select.ts +2 -2
  55. package/src/renderers/terminal.ts +6 -3
  56. package/src/renderers/types.ts +3 -0
  57. package/src/spawn/index.ts +47 -14
  58. package/src/stats/bootstrap.ts +2 -2
  59. package/src/stats/index.ts +2 -2
  60. package/src/time.ts +75 -10
@@ -10,8 +10,8 @@ export interface MemorySnapshot {
10
10
  }
11
11
 
12
12
  // Taken before the suite loads so `measurePeakMem` can split the starting
13
- // RSS into live data and memory setup freed that the allocator still
14
- // holds.
13
+ // RSS into live data and memory setup freed that the allocator
14
+ // still holds.
15
15
  export function memorySnapshot(): MemorySnapshot {
16
16
  const { heapSize, extraMemorySize } = heapStats();
17
17
  const rssBytes = process.memoryUsage.rss();
@@ -23,8 +23,8 @@ export function memorySnapshot(): MemorySnapshot {
23
23
  }
24
24
 
25
25
  // Bun 1.4.3+ reports the physical footprint as RSS on macOS, which misses
26
- // reused freed pages for a while (oven-sh/bun#44951). Resident size
27
- // doesn't.
26
+ // reused freed pages for a while (oven-sh/bun#44951). Resident
27
+ // size doesn't.
28
28
  function residentBytes(): number | undefined {
29
29
  if (process.platform !== "darwin") return undefined;
30
30
  readResident ??= residentReader();
@@ -19,6 +19,11 @@ interface TimingPhaseOptions extends SpawnTrialOptions {
19
19
  budgetMs?: number;
20
20
  /** Runs unmeasured before every trial, warmup included. */
21
21
  prepare?: PrepareHook;
22
+ /**
23
+ * Save each trial's output here, as `trial-N.log`, and each warmup's
24
+ * as `warmup-N.log`.
25
+ */
26
+ outputDir?: string;
22
27
  /**
23
28
  * Exit codes treated as success (hyperfine's `--ignore-failure`): such a
24
29
  * trial still contributes its sample and never triggers `nonzero-exit`. */
@@ -51,8 +56,8 @@ interface TimingPhaseIterator {
51
56
  result(): TimingPhaseResult;
52
57
  }
53
58
 
54
- // `undefined` is a timed-out trial: killed, so it has no exit code to fail
55
- // on.
59
+ // `undefined` is a timed-out trial: killed, so it has no exit code to
60
+ // fail on.
56
61
  function isFailedExit(code: number | undefined, ignored: Set<number>): boolean {
57
62
  return code !== undefined && code !== 0 && !ignored.has(code);
58
63
  }
@@ -99,7 +104,14 @@ export function createTimingPhase(
99
104
  },
100
105
  );
101
106
  }
102
- return runTrial(opts);
107
+ return runTrial(
108
+ opts.outputDir === undefined
109
+ ? opts
110
+ : {
111
+ ...opts,
112
+ outputPath: `${opts.outputDir}/${phase === "warmup" ? "warmup" : "trial"}-${index}.log`,
113
+ },
114
+ );
103
115
  }
104
116
 
105
117
  return {
@@ -132,6 +144,9 @@ export function createTimingPhase(
132
144
  }),
133
145
  ...(result.timedOut && { timedOut: true as const }),
134
146
  ...(result.timeSourceNoMatch && { timeSourceNoMatch: true as const }),
147
+ ...(result.outputPath !== undefined && {
148
+ outputPath: result.outputPath,
149
+ }),
135
150
  });
136
151
  // The budget bounds the loop's wall time even for reported-time samples.
137
152
  totalNs += result.wallNs;
package/src/profile.ts CHANGED
@@ -17,8 +17,9 @@ export interface ProfileOptions {
17
17
  /**
18
18
  * Names the workload: it becomes the label and, instead of the function's
19
19
  * name and source, what the id hashes, so closures that differ only in
20
- * captured values get distinct ids and the id survives editing the
21
- * function. */
20
+ * captured values get distinct ids and the id survives editing
21
+ * the function.
22
+ */
22
23
  name?: string;
23
24
  /**
24
25
  * `"inspector"` (default) captures through CDP and writes a portable
@@ -28,8 +29,9 @@ export interface ProfileOptions {
28
29
  /**
29
30
  * There's no child to kill, so an already-aborted signal skips the
30
31
  * profiler, calls `fn` plain (still returning its `result`) and records an
31
- * `aborted` warning instead of CPU evidence. It can't interrupt a running
32
- * `fn`. */
32
+ * `aborted` warning instead of CPU evidence. It can't interrupt a
33
+ * running `fn`.
34
+ */
33
35
  signal?: AbortSignal;
34
36
  }
35
37
 
@@ -23,8 +23,8 @@ export const collapsedRenderer: Renderer<VizOptions> = {
23
23
  pathOf[i] = p === -1 ? name : `${pathOf[p]};${name}`;
24
24
  }
25
25
 
26
- // Typed counts plus a first-seen list, because this runs over every
27
- // sample.
26
+ // Typed counts plus a first-seen list, because this runs over
27
+ // every sample.
28
28
  const counts = new Float64Array(tree.count);
29
29
  const seen: number[] = [];
30
30
  for (const id of cpu.samples?.nodeIds ?? []) {
@@ -0,0 +1,148 @@
1
+ import { formatDuration, pickDurationUnit } from "../format.ts";
2
+ import type { ProfileDocument, Warning, Workload } from "../ir/types.ts";
3
+ import {
4
+ formatRelative,
5
+ formatShellLine,
6
+ formatSignedPct,
7
+ workloadLabel,
8
+ } from "./format.ts";
9
+ import { abRows, formatAbSummary, formatThrew, pairedCells } from "./paired.ts";
10
+ import { relativeRatios, type TimingRow } from "./relative.ts";
11
+ import {
12
+ comparedRows,
13
+ memoryReadings,
14
+ noSampleRuns,
15
+ oneSidedNote,
16
+ runWarnings,
17
+ timingRuns,
18
+ workloadsById,
19
+ } from "./select.ts";
20
+ import type { Renderer, RenderResult } from "./types.ts";
21
+
22
+ // One line per command or task, and each warning on a short line after
23
+ // them: the fewest tokens that still read as text, for an agent or a
24
+ // person (metonym/ostia#54). `events` is the format a script parses.
25
+
26
+ // Each line's columns, padded so they line up.
27
+ function aligned(rows: string[][]): string[] {
28
+ const widths: number[] = [];
29
+ for (const row of rows) {
30
+ for (const [i, cell] of row.entries()) {
31
+ widths[i] = Math.max(widths[i] ?? 0, cell.length);
32
+ }
33
+ }
34
+ return rows.map((row) =>
35
+ row
36
+ .map((cell, i) =>
37
+ i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0),
38
+ )
39
+ .join(" ")
40
+ .trimEnd(),
41
+ );
42
+ }
43
+
44
+ function warningLines(label: string, warnings: readonly Warning[]): string[] {
45
+ return warnings.map((w) => `! ${label}: ${w.message}`);
46
+ }
47
+
48
+ function timingLines(doc: ProfileDocument): string[] {
49
+ const memory = memoryReadings(doc);
50
+ const byId = new Map(timingRuns(doc).map((run) => [run.workloadId, run]));
51
+ const empty = new Map(noSampleRuns(doc).map((run) => [run.workloadId, run]));
52
+ const measured: TimingRow[] = [];
53
+ for (const workload of doc.workloads) {
54
+ const run = byId.get(workload.id);
55
+ if (run) measured.push({ run, workload });
56
+ }
57
+ const ratios = relativeRatios(measured);
58
+ const rows: string[][] = [];
59
+ const warnings: string[] = [];
60
+ for (const workload of doc.workloads) {
61
+ const label = workloadLabel(workload);
62
+ const run = byId.get(workload.id);
63
+ const noSamples = empty.get(workload.id);
64
+ if (run) {
65
+ const { median, mad } = run.timing;
66
+ const unit = pickDurationUnit(median);
67
+ const row = measured.find((r) => r.run === run);
68
+ const ratio = row && ratios?.get(row);
69
+ rows.push([
70
+ label,
71
+ formatDuration(median, unit),
72
+ `±${(median === 0 ? 0 : (mad / median) * 100).toFixed(1)}%`,
73
+ ratio === undefined ? "" : formatRelative(ratio, !!workload.baseline),
74
+ ]);
75
+ warnings.push(...warningLines(label, runWarnings(run, memory)));
76
+ } else if (noSamples) {
77
+ rows.push([label, "no samples"]);
78
+ warnings.push(...warningLines(label, runWarnings(noSamples, memory)));
79
+ } else if (workload.skipped) {
80
+ rows.push([label, "skipped"]);
81
+ }
82
+ }
83
+ return [...aligned(rows), ...warnings];
84
+ }
85
+
86
+ function comparisonLines(doc: ProfileDocument): string[] {
87
+ const rows: string[][] = [];
88
+ const notCompared: string[] = [];
89
+ for (const { row } of comparedRows(doc)) {
90
+ if (row.verdict === "missing-base" || row.verdict === "missing-cand") {
91
+ notCompared.push(`- ${row.task}: ${oneSidedNote(row.verdict)}`);
92
+ continue;
93
+ }
94
+ const mark = row.pass === false ? "✗" : "✓";
95
+ if (!row.timing) {
96
+ rows.push([`${mark} ${row.task}`, `(${row.verdict})`]);
97
+ continue;
98
+ }
99
+ const { baseMedian, candMedian, medianDeltaPct } = row.timing;
100
+ const unit = pickDurationUnit(Math.max(baseMedian, candMedian));
101
+ rows.push([
102
+ `${mark} ${row.task}`,
103
+ `${formatDuration(baseMedian, unit)} -> ${formatDuration(candMedian, unit)}`,
104
+ formatSignedPct(medianDeltaPct),
105
+ `(${row.verdict})`,
106
+ ]);
107
+ }
108
+ return [...aligned(rows), ...notCompared];
109
+ }
110
+
111
+ function abLines(
112
+ doc: ProfileDocument,
113
+ ab: NonNullable<ProfileDocument["ab"]>,
114
+ ): string[] {
115
+ const workloads = workloadsById(doc);
116
+ const label = (id: string) => {
117
+ const workload: Workload | undefined = workloads.get(id);
118
+ return workload ? workloadLabel(workload) : id;
119
+ };
120
+ const rows: string[][] = [];
121
+ for (const row of abRows(doc)) {
122
+ if (row.kind === "threw") {
123
+ rows.push([label(row.run.workloadId), formatThrew(row.run.threw)]);
124
+ continue;
125
+ }
126
+ const cells = pairedCells(row.run, ab.metric);
127
+ rows.push([
128
+ label(row.run.workloadId),
129
+ `${cells.base} -> ${cells.candidate}`,
130
+ cells.change,
131
+ cells.verdict,
132
+ ]);
133
+ }
134
+ return [formatAbSummary(ab), ...aligned(rows)];
135
+ }
136
+
137
+ export const conciseRenderer: Renderer = {
138
+ name: "concise",
139
+ render(doc: ProfileDocument): Promise<RenderResult> {
140
+ return Promise.try(() => {
141
+ const lines = doc.ab
142
+ ? abLines(doc, doc.ab)
143
+ : [...timingLines(doc), ...comparisonLines(doc)];
144
+ if (doc.shell) lines.push(formatShellLine(doc.shell));
145
+ return { text: lines.length > 0 ? `${lines.join("\n")}\n` : "" };
146
+ });
147
+ },
148
+ };
@@ -6,6 +6,7 @@ import type {
6
6
  GitMetadata,
7
7
  HeapEvidence,
8
8
  Measurement,
9
+ ProfileDocument,
9
10
  Workload,
10
11
  } from "../ir/types.ts";
11
12
  import { percentile, sortedCopy } from "../stats/index.ts";
@@ -41,8 +42,8 @@ export function frameName(frame: Frame | undefined): string {
41
42
  return frame?.name || "(anonymous)";
42
43
  }
43
44
 
44
- // `cpu.totals` is pre-sorted by self time, so the first `limit` are the
45
- // heaviest.
45
+ // `cpu.totals` is pre-sorted by self time, so the first `limit` are
46
+ // the heaviest.
46
47
  export function topSelfFrames(
47
48
  cpu: CpuEvidence,
48
49
  limit: number,
@@ -81,6 +82,14 @@ export function labelOrId(w: Workload | undefined, id: string): string {
81
82
  return w ? workloadLabel(w) : id;
82
83
  }
83
84
 
85
+ // The shell a run went through and its startup, which every time it
86
+ // prints includes, so a fast command's time isn't read as its own.
87
+ export function formatShellLine(
88
+ shell: NonNullable<ProfileDocument["shell"]>,
89
+ ): string {
90
+ return `Shell: ${shell.command} -c, ${formatDuration(shell.startupNs)} to start, included in each time`;
91
+ }
92
+
84
93
  export function formatRelative(relative: number, baseline: boolean): string {
85
94
  if (relative === 1) return baseline ? "1.00× (baseline)" : "1.00×";
86
95
  if (relative > 1) return `${relative.toFixed(2)}× slower`;
@@ -97,8 +106,8 @@ export function escapeMdCell(s: string): string {
97
106
  .replace(/\r\n|\r|\n/g, "<br>");
98
107
  }
99
108
 
100
- // Median per trial; in-process measurements have no CPU times, so
101
- // undefined.
109
+ // Median per trial; in-process measurements have no CPU times,
110
+ // so undefined.
102
111
  export function cpuTimes(
103
112
  run: Pick<Measurement, "trials">,
104
113
  ): { userNs: number; systemNs: number } | undefined {
@@ -1,4 +1,5 @@
1
1
  import { collapsedRenderer } from "./collapsed.ts";
2
+ import { conciseRenderer } from "./concise.ts";
2
3
  import { cpuprofileRenderer } from "./cpuprofile.ts";
3
4
  import { jsonRenderer } from "./json.ts";
4
5
  import { jsonlRenderer } from "./jsonl.ts";
@@ -17,7 +18,10 @@ export const renderers: {
17
18
  json: Renderer;
18
19
  markdown: Renderer;
19
20
  jsonl: Renderer;
21
+ events: Renderer<MinimalRenderOptions>;
22
+ /** `events`, by the name it had until 0.5.0. */
20
23
  minimal: Renderer<MinimalRenderOptions>;
24
+ concise: Renderer;
21
25
  collapsed: Renderer<VizOptions>;
22
26
  mermaid: Renderer<MermaidOptions>;
23
27
  speedscope: Renderer<VizOptions>;
@@ -27,7 +31,9 @@ export const renderers: {
27
31
  json: jsonRenderer,
28
32
  markdown: markdownRenderer,
29
33
  jsonl: jsonlRenderer,
34
+ events: minimalRenderer,
30
35
  minimal: minimalRenderer,
36
+ concise: conciseRenderer,
31
37
  collapsed: collapsedRenderer,
32
38
  mermaid: mermaidRenderer,
33
39
  speedscope: speedscopeRenderer,
@@ -373,8 +373,8 @@ function timingSection(
373
373
  for (const { run, workload } of groupRows) {
374
374
  const v1 = workload?.params?.[key1];
375
375
  const v2 = workload?.params?.[key2];
376
- // invariant: `pivotKeysFor` pivots only rows whose params hold both
377
- // keys.
376
+ // invariant: `pivotKeysFor` pivots only rows whose params hold
377
+ // both keys.
378
378
  if (v1 === undefined || v2 === undefined) continue;
379
379
  if (!rowValues.includes(v1)) rowValues.push(v1);
380
380
  if (!colValues.includes(v2)) colValues.push(v2);
@@ -57,8 +57,8 @@ export const mermaidRenderer: Renderer<MermaidOptions> = {
57
57
  const { parentIx } = tree;
58
58
  const rootIx = tree.roots[0] ?? -1;
59
59
 
60
- // The top-N self-time nodes plus every ancestor, so each has a path to the
61
- // root.
60
+ // The top-N self-time nodes plus every ancestor, so each has a path to
61
+ // the root.
62
62
  const included = new Set<number>(rootIx !== -1 ? [rootIx] : []);
63
63
  for (const ix of topNBySelf(selfUs, tree.count, rootIx, topN)) {
64
64
  const path: number[] = [];
@@ -98,7 +98,7 @@ interface MinimalMemoryChange {
98
98
  /**
99
99
  * One per timing run, for piping into an agent's context in place of the
100
100
  * full `ProfileDocument`. Numbers stay in the IR's units (ns). */
101
- interface MinimalRunLine {
101
+ export interface MinimalRunLine {
102
102
  event: "run";
103
103
  protocolVersion: typeof MINIMAL_PROTOCOL_VERSION;
104
104
  schemaVersion: ProfileDocument["schemaVersion"];
@@ -112,8 +112,8 @@ interface MinimalRunLine {
112
112
  groupDescription?: string;
113
113
  params?: Record<string, string | number | boolean>;
114
114
  /**
115
- * `task.skip()` / `group.skip()`: no measurement, so every stats field is
116
- * absent.
115
+ * `task.skip()` / `group.skip()`: no measurement, so every stats field
116
+ * is absent.
117
117
  */
118
118
  skipped?: true;
119
119
  unit?: "ns";
@@ -166,7 +166,7 @@ interface MinimalRunLine {
166
166
  }
167
167
 
168
168
  /** A workload present on only one side of a `compare`/`ci` run. */
169
- interface MinimalUnmatchedLine {
169
+ export interface MinimalUnmatchedLine {
170
170
  event: "unmatched";
171
171
  protocolVersion: typeof MINIMAL_PROTOCOL_VERSION;
172
172
  workloadId: string;
@@ -177,7 +177,7 @@ interface MinimalUnmatchedLine {
177
177
  /**
178
178
  * The last line of a `compare`/`ci`/`ab` run; never emitted for a bare
179
179
  * `time`/`bench` document. */
180
- interface MinimalSummaryLine {
180
+ export interface MinimalSummaryLine {
181
181
  event: "summary";
182
182
  protocolVersion: typeof MINIMAL_PROTOCOL_VERSION;
183
183
  command: "compare" | "ci" | "ab";
@@ -207,8 +207,8 @@ interface MinimalSummaryLine {
207
207
  /** `ab` only: the gate on `geomeanPct`. */
208
208
  geomeanThresholdPct?: number;
209
209
  /**
210
- * `ab` only: flagged in the first process but not reproduced; counted in
211
- * `unchanged`.
210
+ * `ab` only: flagged in the first process but not reproduced; counted
211
+ * in `unchanged`.
212
212
  */
213
213
  unconfirmed?: number;
214
214
  /**
@@ -239,8 +239,9 @@ export type MinimalEvent =
239
239
  /**
240
240
  * What the `unmatched`/`summary` events need beyond one `ProfileDocument`.
241
241
  * The CLI builds it for `compare`/`ci`/`ab`; without it `minimal` emits
242
- * only `run` lines. `exitCode` is inline because the CLI decides it after
243
- * rendering. */
242
+ * only `run` lines. `exitCode` is inline because the CLI decides it
243
+ * after rendering.
244
+ */
244
245
  export interface MinimalProtocolContext {
245
246
  command: "compare" | "ci" | "ab";
246
247
  exitCode: number;
@@ -584,7 +585,7 @@ function summaryLine(
584
585
  }
585
586
 
586
587
  export const minimalRenderer: Renderer<MinimalRenderOptions> = {
587
- name: "minimal",
588
+ name: "events",
588
589
  render(
589
590
  doc: ProfileDocument,
590
591
  options: MinimalRenderOptions = {},
@@ -7,8 +7,8 @@ export interface TimingRow {
7
7
  }
8
8
 
9
9
  // The explicit `entry.group` the bench runner records, else the
10
- // "group/name" id split on its last "/" (documents from before that field
11
- // existed).
10
+ // "group/name" id split on its last "/" (documents from before that
11
+ // field existed).
12
12
  export function groupOf(workload: Workload | undefined): string | undefined {
13
13
  if (!workload?.entry) return undefined;
14
14
  if (workload.entry.group !== undefined) return workload.entry.group;
@@ -224,8 +224,8 @@ function rebuildCompared(doc: ProfileDocument): ComparedTask[] {
224
224
  ];
225
225
  }
226
226
 
227
- // Heap readings move with GC timing, so a small change is noise, not a
228
- // line.
227
+ // Heap readings move with GC timing, so a small change is noise, not
228
+ // a line.
229
229
  const MIN_MEMORY_DISPLAY_PCT = 10;
230
230
 
231
231
  const MEMORY_READING_LABELS: Record<MemoryDelta["reading"], string> = {
@@ -14,6 +14,7 @@ import {
14
14
  formatInstructions,
15
15
  formatNsAsMs,
16
16
  formatRelative,
17
+ formatShellLine,
17
18
  formatSignedPct,
18
19
  formatSpan,
19
20
  formatUsAsMs,
@@ -123,9 +124,11 @@ export const terminalRenderer: Renderer = {
123
124
  name: "table",
124
125
  render(doc: ProfileDocument): Promise<RenderResult> {
125
126
  return Promise.try(() => {
126
- const env = doc.environment
127
- ? [formatEnvironmentLine(doc.environment), ""]
128
- : [];
127
+ const env = [
128
+ ...(doc.environment ? [formatEnvironmentLine(doc.environment)] : []),
129
+ ...(doc.shell ? [formatShellLine(doc.shell)] : []),
130
+ ];
131
+ if (env.length > 0) env.push("");
129
132
 
130
133
  // Only `ab()` writes paired measurements, and it always stamps `ab`.
131
134
  if (doc.ab) return finish(renderPaired(doc, doc.ab, env));
@@ -5,7 +5,10 @@ export type FormatName =
5
5
  | "json"
6
6
  | "markdown"
7
7
  | "jsonl"
8
+ | "events"
9
+ /** `events`, by the name it had until 0.5.0. */
8
10
  | "minimal"
11
+ | "concise"
9
12
  | "collapsed"
10
13
  | "mermaid"
11
14
  | "speedscope"
@@ -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 no
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 = opts.timeSource !== undefined;
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 proc = Bun.spawn(opts.argv, {
143
+ const where = {
135
144
  ...(opts.cwd !== undefined && { cwd: opts.cwd }),
136
145
  ...(opts.env !== undefined && { env: opts.env }),
137
- stdout: capture ? "pipe" : "ignore",
138
- stderr: capture ? "pipe" : "ignore",
139
- stdin: "ignore",
140
- ...kill.spawn,
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 = capture
169
+ const output = piped
145
170
  ? Promise.all([
146
- new Response(proc.stdout).text(),
147
- new Response(proc.stderr).text(),
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 isn't
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 {
@@ -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 and
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);
@@ -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 outlier
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",