ostia 0.6.1 → 0.7.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/cli/run.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  saveDocument,
32
32
  } from "../ir/document.ts";
33
33
  import type { AbSummary, ProfileDocument } from "../ir/types.ts";
34
+ import { exitCodeOf, handleInterrupt } from "../live.ts";
34
35
  import { sideLabel } from "../measure/paired.ts";
35
36
  import { isHarnessFailure } from "../measure/timing.ts";
36
37
  import { formatGit, workloadLabel } from "../renderers/format.ts";
@@ -43,6 +44,8 @@ import type { MinimalProtocolContext } from "../renderers/minimal.ts";
43
44
  import type { TimeSource, TimeUnit } from "../spawn/index.ts";
44
45
  import {
45
46
  createProgress,
47
+ isAgent,
48
+ isDumb,
46
49
  type Paint,
47
50
  PLAIN,
48
51
  plural,
@@ -51,12 +54,13 @@ import {
51
54
  truncatePath,
52
55
  truncateWords,
53
56
  } from "../terminal.ts";
54
- import { agentVariable, withDefaultFormat } from "./agent.ts";
57
+ import { withDefaultFormat } from "./agent.ts";
55
58
  import {
56
59
  CliUsageError,
57
60
  COLOR_FLAGS,
58
61
  CONFIG_FLAGS,
59
62
  type ConfigArgs,
63
+ didYouMean,
60
64
  flag,
61
65
  FORMAT_ALIASES,
62
66
  HELP_FLAGS,
@@ -86,6 +90,17 @@ import {
86
90
 
87
91
  const isHelpArg = (arg: string | undefined) => arg === "--help" || arg === "-h";
88
92
 
93
+ // A missing argument is a usage error like any other: one line, naming
94
+ // what's missing and where the help is (`ostia time needs a command to
95
+ // time. Run "ostia time --help".`), so a program parses it as one.
96
+ const missingArgument = (command: string, what: string) => {
97
+ const name = command === "" ? "ostia" : `ostia ${command}`;
98
+ return new CliError(
99
+ "invalid-flag",
100
+ `${name} needs ${what}. Run "${name} --help".`,
101
+ );
102
+ };
103
+
89
104
  interface Human {
90
105
  paint: Paint;
91
106
  progress: Progress;
@@ -113,7 +128,7 @@ async function humanFor(args: {
113
128
  }
114
129
  const { isatty } = await import("node:tty");
115
130
  const shown =
116
- !args.quiet && isatty(2) && agentVariable(processEnv()) === undefined;
131
+ !args.quiet && isatty(2) && !isDumb(processEnv()) && !isAgent(processEnv());
117
132
  return {
118
133
  paint: await paintFor(1, args.color),
119
134
  progress: shown
@@ -127,22 +142,33 @@ async function humanFor(args: {
127
142
  };
128
143
  }
129
144
 
130
- // Runs `run` with SIGINT wired to its `AbortSignal`, so Ctrl-C cancels
131
- // cleanly with partial results.
145
+ // Runs `run` with Ctrl-C and SIGTERM wired to its `AbortSignal`, so
146
+ // either stops it cleanly with what finished; `stopped` is then the exit
147
+ // code, 130, or 143 for SIGTERM, which the command returns once it has
148
+ // printed that. A second one exits at once, for a run slow to stop.
132
149
  async function withSigintAbort<T>(
133
150
  failure: string,
134
151
  run: (signal: AbortSignal) => Promise<T>,
135
- ): Promise<{ result: T; aborted: boolean }> {
136
- const controller = new AbortController();
137
- const onSigint = () => controller.abort();
138
- process.on("SIGINT", onSigint);
152
+ ): Promise<{ result: T; stopped?: number }> {
153
+ const { isatty } = await import("node:tty");
154
+ const interrupt = handleInterrupt({
155
+ process,
156
+ write: (text) => writeSync(2, text),
157
+ terminal: isatty(2) && !isDumb(processEnv()),
158
+ // The command prints the partial result and exits itself, once the
159
+ // run resolves.
160
+ exit: false,
161
+ });
139
162
  try {
140
163
  const result = await orFail("spawn-failed", failure, () =>
141
- run(controller.signal),
164
+ run(interrupt.signal),
142
165
  );
143
- return { result, aborted: controller.signal.aborted };
166
+ const signal = await interrupt.settle();
167
+ return signal === undefined
168
+ ? { result }
169
+ : { result, stopped: exitCodeOf(signal) };
144
170
  } finally {
145
- process.off("SIGINT", onSigint);
171
+ interrupt.dispose();
146
172
  }
147
173
  }
148
174
 
@@ -266,8 +292,9 @@ async function timeCommand(argv: string[]): Promise<number> {
266
292
  ...parsed.commands,
267
293
  ...(parsed.argvCommand.length > 0 ? [parsed.argvCommand] : []),
268
294
  ];
269
- if (parsed.help || commandList.length === 0) {
270
- return showHelp("time", parsed.help);
295
+ if (parsed.help) return showHelp("time", true);
296
+ if (commandList.length === 0) {
297
+ throw missingArgument("time", "a command to time");
271
298
  }
272
299
 
273
300
  if (
@@ -317,7 +344,7 @@ async function timeCommand(argv: string[]): Promise<number> {
317
344
  }));
318
345
 
319
346
  const human = await humanFor(parsed);
320
- const { result: doc, aborted } = await withSigintAbort(
347
+ const { result: doc, stopped } = await withSigintAbort(
321
348
  "Run failed",
322
349
  (signal) =>
323
350
  time({
@@ -358,7 +385,7 @@ async function timeCommand(argv: string[]): Promise<number> {
358
385
  {},
359
386
  { paint: human.paint, elapsedMs: elapsedMsSince(human.startNs) },
360
387
  );
361
- if (aborted) return 130;
388
+ if (stopped !== undefined) return stopped;
362
389
 
363
390
  // A failing command is exit 2 (couldn't measure), not 1, because 1 is
364
391
  // reserved for compare/ci's regression verdict.
@@ -381,6 +408,8 @@ async function timeCommand(argv: string[]): Promise<number> {
381
408
  throw new CliError(
382
409
  code,
383
410
  "One or more commands failed to produce a clean measurement; see the report above for details.",
411
+ undefined,
412
+ { reported: true },
384
413
  );
385
414
  }
386
415
  return 0;
@@ -470,10 +499,15 @@ async function benchCommand(argv: string[]): Promise<number> {
470
499
  const config = await loadProjectConfig(parsed.config);
471
500
  const resolved = await resolveBenchOptions(parsed, config?.bench);
472
501
 
473
- if (resolved.suites.length === 0) return showHelp("bench", false);
502
+ if (resolved.suites.length === 0) {
503
+ throw missingArgument(
504
+ "bench",
505
+ 'a suite file, or a config whose "bench" section names them',
506
+ );
507
+ }
474
508
 
475
509
  const human = await humanFor(parsed);
476
- const { result: doc, aborted } = await withSigintAbort(
510
+ const { result: doc, stopped } = await withSigintAbort(
477
511
  "Bench failed",
478
512
  (signal) =>
479
513
  bench({
@@ -503,7 +537,7 @@ async function benchCommand(argv: string[]): Promise<number> {
503
537
  elapsedMs: elapsedMsSince(human.startNs),
504
538
  },
505
539
  );
506
- return aborted ? 130 : 0;
540
+ return stopped ?? 0;
507
541
  }
508
542
 
509
543
  const AB_METRICS: readonly AbSummary["metric"][] = ["time", "instructions"];
@@ -674,7 +708,12 @@ async function abCommand(argv: string[]): Promise<number> {
674
708
  noiseCheck,
675
709
  noiseBudgetMs,
676
710
  } = await resolveBenchOptions(parsed, config?.bench);
677
- if (suites.length === 0) return showHelp("ab", false);
711
+ if (suites.length === 0) {
712
+ throw missingArgument(
713
+ "ab",
714
+ 'a suite file, or a config whose "bench" section names them',
715
+ );
716
+ }
678
717
 
679
718
  const human = await humanFor(parsed);
680
719
  const { isatty } = await import("node:tty");
@@ -689,7 +728,7 @@ async function abCommand(argv: string[]): Promise<number> {
689
728
  ? progressWriter(isatty(2))
690
729
  : undefined;
691
730
 
692
- const { result: doc, aborted } = await withSigintAbort(
731
+ const { result: doc, stopped } = await withSigintAbort(
693
732
  "A/B run failed",
694
733
  async (signal) => {
695
734
  try {
@@ -745,12 +784,12 @@ async function abCommand(argv: string[]): Promise<number> {
745
784
  if (!summary) throw new Error("ostia ab: the document has no ab summary");
746
785
  // Computed before rendering: `minimal`'s trailing `summary` event carries
747
786
  // it. A task that threw ran on both sides, so it counts as paired here.
748
- const exitCode = aborted
749
- ? 130
750
- : gateExitCode({
751
- matched: summary.matched + summary.threw,
752
- verdict: summary.verdict,
753
- });
787
+ const exitCode =
788
+ stopped ??
789
+ gateExitCode({
790
+ matched: summary.matched + summary.threw,
791
+ verdict: summary.verdict,
792
+ });
754
793
  const byId = new Map(doc.workloads.map((w) => [w.id, w]));
755
794
  const workloadsFor = (ids: string[] = []) =>
756
795
  ids.flatMap((id) => byId.get(id) ?? []);
@@ -787,7 +826,12 @@ async function abCommand(argv: string[]): Promise<number> {
787
826
  },
788
827
  );
789
828
  if (unpaired) {
790
- await writeCliError("no-matches", `${unpaired.what}: ${unpaired.next}.`);
829
+ await writeCliError(
830
+ "no-matches",
831
+ `${unpaired.what}: ${unpaired.next}.`,
832
+ undefined,
833
+ { reported: true },
834
+ );
791
835
  }
792
836
  return exitCode;
793
837
  }
@@ -828,7 +872,9 @@ async function compareCommand(argv: string[]): Promise<number> {
828
872
  const [basePath, candPath] = parsed.baseline
829
873
  ? [parsed.baseline, parsed.paths[0]]
830
874
  : parsed.paths;
831
- if (!basePath || !candPath) return showHelp("compare", false);
875
+ if (!basePath || !candPath) {
876
+ throw missingArgument("compare", "two documents, base and candidate");
877
+ }
832
878
 
833
879
  const [base, cand] = await orFail(
834
880
  "document-load-failed",
@@ -893,6 +939,8 @@ async function compareCommand(argv: string[]): Promise<number> {
893
939
  await writeCliError(
894
940
  "no-matches",
895
941
  "No workload matched between base and candidate; nothing was compared.",
942
+ undefined,
943
+ { reported: true },
896
944
  );
897
945
  }
898
946
 
@@ -985,7 +1033,8 @@ async function renderReport(
985
1033
 
986
1034
  async function reportCommand(argv: string[]): Promise<number> {
987
1035
  const parsed = parseReportArgs(argv);
988
- if (parsed.help || !parsed.path) return showHelp("report", parsed.help);
1036
+ if (parsed.help) return showHelp("report", true);
1037
+ if (!parsed.path) throw missingArgument("report", "a document");
989
1038
  return renderReport(parsed.path, parsed);
990
1039
  }
991
1040
 
@@ -1035,7 +1084,7 @@ async function ciCommand(argv: string[]): Promise<number> {
1035
1084
  // A saved baseline must be fresh measurements, never a cached run.
1036
1085
  const full = parsed.full || parsed.saveBaseline;
1037
1086
  const human = await humanFor(parsed);
1038
- const { result: outcome, aborted } = await withSigintAbort(
1087
+ const { result: outcome, stopped } = await withSigintAbort(
1039
1088
  "CI run failed",
1040
1089
  (signal) =>
1041
1090
  runCi({
@@ -1052,10 +1101,10 @@ async function ciCommand(argv: string[]): Promise<number> {
1052
1101
  .finally(() => human.progress.clear()),
1053
1102
  );
1054
1103
  const { document, summary } = outcome;
1055
- if (aborted) {
1104
+ if (stopped !== undefined) {
1056
1105
  // Partial: no comparison, no gate, never a baseline.
1057
1106
  await emitDocument(document, parsed, {}, { paint: human.paint });
1058
- return 130;
1107
+ return stopped;
1059
1108
  }
1060
1109
  const baselineName = parsed.baseline ?? config.baseline;
1061
1110
  const baselineFile = baselinePath(config, baselineName);
@@ -1077,6 +1126,9 @@ async function ciCommand(argv: string[]): Promise<number> {
1077
1126
  await writeCliError(
1078
1127
  "command-failed",
1079
1128
  `${summary.failed} workload(s) failed (harness error, a command exited non-zero or produced no samples): ${failedLabels.join(", ")}`,
1129
+ undefined,
1130
+ // The document follows on stdout, and is the one there.
1131
+ { reported: true },
1080
1132
  );
1081
1133
  }
1082
1134
 
@@ -1228,7 +1280,8 @@ async function baselineListCommand(argv: string[]): Promise<number> {
1228
1280
 
1229
1281
  async function baselineShowCommand(argv: string[]): Promise<number> {
1230
1282
  const [name, ...rest] = argv;
1231
- if (!name || isHelpArg(name)) return showHelp("baseline", !!name);
1283
+ if (isHelpArg(name)) return showHelp("baseline", true);
1284
+ if (!name) throw missingArgument("baseline show", "a baseline name");
1232
1285
  assertBaselineName(name);
1233
1286
 
1234
1287
  const parsed = parseFlags<ReportArgs>(rest, {
@@ -1260,18 +1313,30 @@ async function dispatchSubcommand(
1260
1313
  rest: string[],
1261
1314
  handlers: Record<string, Handler>,
1262
1315
  help: HelpTopic,
1263
- unknownMessage: (sub: string) => string,
1316
+ unknownMessage: (sub: string, known: readonly string[]) => string,
1264
1317
  commandPrefix = "",
1265
1318
  ): Promise<number> {
1266
- if (sub === undefined || isHelpArg(sub))
1267
- return showHelp(help, sub !== undefined);
1268
- const handler = Object.hasOwn(handlers, sub) ? handlers[sub] : undefined;
1319
+ if (isHelpArg(sub)) return showHelp(help, true);
1269
1320
  try {
1270
- if (!handler) throw new CliError("invalid-flag", unknownMessage(sub));
1321
+ if (sub === undefined) {
1322
+ throw missingArgument(
1323
+ commandPrefix.trim(),
1324
+ `a command: ${Object.keys(handlers).join(", ")}`,
1325
+ );
1326
+ }
1327
+ const handler = Object.hasOwn(handlers, sub) ? handlers[sub] : undefined;
1328
+ if (!handler) {
1329
+ throw new CliError(
1330
+ "invalid-flag",
1331
+ unknownMessage(sub, Object.keys(handlers)),
1332
+ );
1333
+ }
1271
1334
  return await handler(rest);
1272
1335
  } catch (err) {
1273
1336
  if (err instanceof CliError) {
1274
- await writeCliError(err.code, err.message, err.data);
1337
+ await writeCliError(err.code, err.message, err.data, {
1338
+ reported: err.reported,
1339
+ });
1275
1340
  } else if (err instanceof ConfigError) {
1276
1341
  await writeCliError("config-invalid", err.message);
1277
1342
  } else if (err instanceof CliUsageError) {
@@ -1300,11 +1365,43 @@ function baselineCommand(argv: string[]): Promise<number> {
1300
1365
  show: baselineShowCommand,
1301
1366
  },
1302
1367
  "baseline",
1303
- (s) => `Unknown "ostia baseline ${s}". Run "ostia baseline --help".`,
1368
+ (s, known) =>
1369
+ `Unknown "ostia baseline ${s}"${didYouMean(s, known)}. Run "ostia baseline --help".`,
1304
1370
  "baseline ",
1305
1371
  );
1306
1372
  }
1307
1373
 
1374
+ // Every flag a command takes, so a typo of one before the command, as
1375
+ // `ostia --jsno`, names the flag it meant.
1376
+ const EVERY_FLAG = Object.keys({
1377
+ ...TIME_FLAGS,
1378
+ ...BENCH_FLAGS,
1379
+ ...AB_FLAGS,
1380
+ ...COMPARE_FLAGS,
1381
+ ...REPORT_FLAGS,
1382
+ ...CI_FLAGS,
1383
+ ...BASELINE_FLAGS,
1384
+ "--version": true,
1385
+ });
1386
+
1387
+ // A flag before the command is the likeliest slip, as `ostia --json`,
1388
+ // so it says where the flag goes.
1389
+ function unknownCommand(given: string, commands: readonly string[]): string {
1390
+ const name = given.split("=")[0] ?? "";
1391
+ if (EVERY_FLAG.includes(name)) {
1392
+ const example = Object.hasOwn(OUTPUT_FLAGS, name)
1393
+ ? `, as "ostia time ${given}"`
1394
+ : "";
1395
+ return `${given} goes after a command${example}: one of ${commands.join(", ")}. Run "ostia --help".`;
1396
+ }
1397
+ if (given.startsWith("-")) {
1398
+ // A long flag, since one letter is an edit from any other.
1399
+ const long = EVERY_FLAG.filter((flag) => flag.startsWith("--"));
1400
+ return `Unknown flag "${given}"${didYouMean(name, long)}. Run "ostia --help".`;
1401
+ }
1402
+ return `Unknown subcommand "${given}"${didYouMean(given, commands)}. Run "ostia --help".`;
1403
+ }
1404
+
1308
1405
  // The commands that take `--format`, so the only ones a default
1309
1406
  // format can be added to.
1310
1407
  const FORMATTED = new Set(["time", "bench", "ab", "compare", "report", "ci"]);
@@ -1330,6 +1427,6 @@ export async function main(): Promise<number> {
1330
1427
  baseline: baselineCommand,
1331
1428
  },
1332
1429
  "main",
1333
- (s) => `Unknown subcommand "${s}". Run "ostia --help".`,
1430
+ unknownCommand,
1334
1431
  );
1335
1432
  }
package/src/ir/git.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import type { GitMetadata } from "./types.ts";
2
2
 
3
- const GIT_TIMEOUT_MS = 200;
3
+ // A cold `git status` in a large repository takes some 300 ms on an
4
+ // idle machine, and more on a busy one; the metadata is read once a
5
+ // process, so a slow git costs at most this, once.
6
+ const GIT_TIMEOUT_MS = 1000;
4
7
 
5
8
  // eslint-disable-next-line no-restricted-syntax -- the process-lifetime memo captureGitMetadata keeps
6
9
  let memo: { git: GitMetadata | undefined } | undefined;
@@ -29,7 +32,7 @@ function readGitMetadata(): GitMetadata | undefined {
29
32
  }
30
33
 
31
34
  // 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
35
+ // Undefined outside a repo, without `git`, or past the 1 s per-call
33
36
  // timeout: metadata is never worth failing a measurement over.
34
37
  export function captureGitMetadata(): GitMetadata | undefined {
35
38
  memo ??= { git: readGitMetadata() };