ostia 0.7.0 → 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,7 @@ 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,
46
48
  isDumb,
47
49
  type Paint,
48
50
  PLAIN,
@@ -52,12 +54,13 @@ import {
52
54
  truncatePath,
53
55
  truncateWords,
54
56
  } from "../terminal.ts";
55
- import { agentVariable, withDefaultFormat } from "./agent.ts";
57
+ import { withDefaultFormat } from "./agent.ts";
56
58
  import {
57
59
  CliUsageError,
58
60
  COLOR_FLAGS,
59
61
  CONFIG_FLAGS,
60
62
  type ConfigArgs,
63
+ didYouMean,
61
64
  flag,
62
65
  FORMAT_ALIASES,
63
66
  HELP_FLAGS,
@@ -87,6 +90,17 @@ import {
87
90
 
88
91
  const isHelpArg = (arg: string | undefined) => arg === "--help" || arg === "-h";
89
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
+
90
104
  interface Human {
91
105
  paint: Paint;
92
106
  progress: Progress;
@@ -114,10 +128,7 @@ async function humanFor(args: {
114
128
  }
115
129
  const { isatty } = await import("node:tty");
116
130
  const shown =
117
- !args.quiet &&
118
- isatty(2) &&
119
- !isDumb(processEnv()) &&
120
- agentVariable(processEnv()) === undefined;
131
+ !args.quiet && isatty(2) && !isDumb(processEnv()) && !isAgent(processEnv());
121
132
  return {
122
133
  paint: await paintFor(1, args.color),
123
134
  progress: shown
@@ -131,22 +142,33 @@ async function humanFor(args: {
131
142
  };
132
143
  }
133
144
 
134
- // Runs `run` with SIGINT wired to its `AbortSignal`, so Ctrl-C cancels
135
- // 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.
136
149
  async function withSigintAbort<T>(
137
150
  failure: string,
138
151
  run: (signal: AbortSignal) => Promise<T>,
139
- ): Promise<{ result: T; aborted: boolean }> {
140
- const controller = new AbortController();
141
- const onSigint = () => controller.abort();
142
- 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
+ });
143
162
  try {
144
163
  const result = await orFail("spawn-failed", failure, () =>
145
- run(controller.signal),
164
+ run(interrupt.signal),
146
165
  );
147
- return { result, aborted: controller.signal.aborted };
166
+ const signal = await interrupt.settle();
167
+ return signal === undefined
168
+ ? { result }
169
+ : { result, stopped: exitCodeOf(signal) };
148
170
  } finally {
149
- process.off("SIGINT", onSigint);
171
+ interrupt.dispose();
150
172
  }
151
173
  }
152
174
 
@@ -270,8 +292,9 @@ async function timeCommand(argv: string[]): Promise<number> {
270
292
  ...parsed.commands,
271
293
  ...(parsed.argvCommand.length > 0 ? [parsed.argvCommand] : []),
272
294
  ];
273
- if (parsed.help || commandList.length === 0) {
274
- 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");
275
298
  }
276
299
 
277
300
  if (
@@ -321,7 +344,7 @@ async function timeCommand(argv: string[]): Promise<number> {
321
344
  }));
322
345
 
323
346
  const human = await humanFor(parsed);
324
- const { result: doc, aborted } = await withSigintAbort(
347
+ const { result: doc, stopped } = await withSigintAbort(
325
348
  "Run failed",
326
349
  (signal) =>
327
350
  time({
@@ -362,7 +385,7 @@ async function timeCommand(argv: string[]): Promise<number> {
362
385
  {},
363
386
  { paint: human.paint, elapsedMs: elapsedMsSince(human.startNs) },
364
387
  );
365
- if (aborted) return 130;
388
+ if (stopped !== undefined) return stopped;
366
389
 
367
390
  // A failing command is exit 2 (couldn't measure), not 1, because 1 is
368
391
  // reserved for compare/ci's regression verdict.
@@ -385,6 +408,8 @@ async function timeCommand(argv: string[]): Promise<number> {
385
408
  throw new CliError(
386
409
  code,
387
410
  "One or more commands failed to produce a clean measurement; see the report above for details.",
411
+ undefined,
412
+ { reported: true },
388
413
  );
389
414
  }
390
415
  return 0;
@@ -474,10 +499,15 @@ async function benchCommand(argv: string[]): Promise<number> {
474
499
  const config = await loadProjectConfig(parsed.config);
475
500
  const resolved = await resolveBenchOptions(parsed, config?.bench);
476
501
 
477
- 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
+ }
478
508
 
479
509
  const human = await humanFor(parsed);
480
- const { result: doc, aborted } = await withSigintAbort(
510
+ const { result: doc, stopped } = await withSigintAbort(
481
511
  "Bench failed",
482
512
  (signal) =>
483
513
  bench({
@@ -507,7 +537,7 @@ async function benchCommand(argv: string[]): Promise<number> {
507
537
  elapsedMs: elapsedMsSince(human.startNs),
508
538
  },
509
539
  );
510
- return aborted ? 130 : 0;
540
+ return stopped ?? 0;
511
541
  }
512
542
 
513
543
  const AB_METRICS: readonly AbSummary["metric"][] = ["time", "instructions"];
@@ -678,7 +708,12 @@ async function abCommand(argv: string[]): Promise<number> {
678
708
  noiseCheck,
679
709
  noiseBudgetMs,
680
710
  } = await resolveBenchOptions(parsed, config?.bench);
681
- 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
+ }
682
717
 
683
718
  const human = await humanFor(parsed);
684
719
  const { isatty } = await import("node:tty");
@@ -693,7 +728,7 @@ async function abCommand(argv: string[]): Promise<number> {
693
728
  ? progressWriter(isatty(2))
694
729
  : undefined;
695
730
 
696
- const { result: doc, aborted } = await withSigintAbort(
731
+ const { result: doc, stopped } = await withSigintAbort(
697
732
  "A/B run failed",
698
733
  async (signal) => {
699
734
  try {
@@ -749,12 +784,12 @@ async function abCommand(argv: string[]): Promise<number> {
749
784
  if (!summary) throw new Error("ostia ab: the document has no ab summary");
750
785
  // Computed before rendering: `minimal`'s trailing `summary` event carries
751
786
  // it. A task that threw ran on both sides, so it counts as paired here.
752
- const exitCode = aborted
753
- ? 130
754
- : gateExitCode({
755
- matched: summary.matched + summary.threw,
756
- verdict: summary.verdict,
757
- });
787
+ const exitCode =
788
+ stopped ??
789
+ gateExitCode({
790
+ matched: summary.matched + summary.threw,
791
+ verdict: summary.verdict,
792
+ });
758
793
  const byId = new Map(doc.workloads.map((w) => [w.id, w]));
759
794
  const workloadsFor = (ids: string[] = []) =>
760
795
  ids.flatMap((id) => byId.get(id) ?? []);
@@ -791,7 +826,12 @@ async function abCommand(argv: string[]): Promise<number> {
791
826
  },
792
827
  );
793
828
  if (unpaired) {
794
- 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
+ );
795
835
  }
796
836
  return exitCode;
797
837
  }
@@ -832,7 +872,9 @@ async function compareCommand(argv: string[]): Promise<number> {
832
872
  const [basePath, candPath] = parsed.baseline
833
873
  ? [parsed.baseline, parsed.paths[0]]
834
874
  : parsed.paths;
835
- if (!basePath || !candPath) return showHelp("compare", false);
875
+ if (!basePath || !candPath) {
876
+ throw missingArgument("compare", "two documents, base and candidate");
877
+ }
836
878
 
837
879
  const [base, cand] = await orFail(
838
880
  "document-load-failed",
@@ -897,6 +939,8 @@ async function compareCommand(argv: string[]): Promise<number> {
897
939
  await writeCliError(
898
940
  "no-matches",
899
941
  "No workload matched between base and candidate; nothing was compared.",
942
+ undefined,
943
+ { reported: true },
900
944
  );
901
945
  }
902
946
 
@@ -989,7 +1033,8 @@ async function renderReport(
989
1033
 
990
1034
  async function reportCommand(argv: string[]): Promise<number> {
991
1035
  const parsed = parseReportArgs(argv);
992
- 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");
993
1038
  return renderReport(parsed.path, parsed);
994
1039
  }
995
1040
 
@@ -1039,7 +1084,7 @@ async function ciCommand(argv: string[]): Promise<number> {
1039
1084
  // A saved baseline must be fresh measurements, never a cached run.
1040
1085
  const full = parsed.full || parsed.saveBaseline;
1041
1086
  const human = await humanFor(parsed);
1042
- const { result: outcome, aborted } = await withSigintAbort(
1087
+ const { result: outcome, stopped } = await withSigintAbort(
1043
1088
  "CI run failed",
1044
1089
  (signal) =>
1045
1090
  runCi({
@@ -1056,10 +1101,10 @@ async function ciCommand(argv: string[]): Promise<number> {
1056
1101
  .finally(() => human.progress.clear()),
1057
1102
  );
1058
1103
  const { document, summary } = outcome;
1059
- if (aborted) {
1104
+ if (stopped !== undefined) {
1060
1105
  // Partial: no comparison, no gate, never a baseline.
1061
1106
  await emitDocument(document, parsed, {}, { paint: human.paint });
1062
- return 130;
1107
+ return stopped;
1063
1108
  }
1064
1109
  const baselineName = parsed.baseline ?? config.baseline;
1065
1110
  const baselineFile = baselinePath(config, baselineName);
@@ -1081,6 +1126,9 @@ async function ciCommand(argv: string[]): Promise<number> {
1081
1126
  await writeCliError(
1082
1127
  "command-failed",
1083
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 },
1084
1132
  );
1085
1133
  }
1086
1134
 
@@ -1232,7 +1280,8 @@ async function baselineListCommand(argv: string[]): Promise<number> {
1232
1280
 
1233
1281
  async function baselineShowCommand(argv: string[]): Promise<number> {
1234
1282
  const [name, ...rest] = argv;
1235
- 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");
1236
1285
  assertBaselineName(name);
1237
1286
 
1238
1287
  const parsed = parseFlags<ReportArgs>(rest, {
@@ -1264,18 +1313,30 @@ async function dispatchSubcommand(
1264
1313
  rest: string[],
1265
1314
  handlers: Record<string, Handler>,
1266
1315
  help: HelpTopic,
1267
- unknownMessage: (sub: string) => string,
1316
+ unknownMessage: (sub: string, known: readonly string[]) => string,
1268
1317
  commandPrefix = "",
1269
1318
  ): Promise<number> {
1270
- if (sub === undefined || isHelpArg(sub))
1271
- return showHelp(help, sub !== undefined);
1272
- const handler = Object.hasOwn(handlers, sub) ? handlers[sub] : undefined;
1319
+ if (isHelpArg(sub)) return showHelp(help, true);
1273
1320
  try {
1274
- 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
+ }
1275
1334
  return await handler(rest);
1276
1335
  } catch (err) {
1277
1336
  if (err instanceof CliError) {
1278
- await writeCliError(err.code, err.message, err.data);
1337
+ await writeCliError(err.code, err.message, err.data, {
1338
+ reported: err.reported,
1339
+ });
1279
1340
  } else if (err instanceof ConfigError) {
1280
1341
  await writeCliError("config-invalid", err.message);
1281
1342
  } else if (err instanceof CliUsageError) {
@@ -1304,11 +1365,43 @@ function baselineCommand(argv: string[]): Promise<number> {
1304
1365
  show: baselineShowCommand,
1305
1366
  },
1306
1367
  "baseline",
1307
- (s) => `Unknown "ostia baseline ${s}". Run "ostia baseline --help".`,
1368
+ (s, known) =>
1369
+ `Unknown "ostia baseline ${s}"${didYouMean(s, known)}. Run "ostia baseline --help".`,
1308
1370
  "baseline ",
1309
1371
  );
1310
1372
  }
1311
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
+
1312
1405
  // The commands that take `--format`, so the only ones a default
1313
1406
  // format can be added to.
1314
1407
  const FORMATTED = new Set(["time", "bench", "ab", "compare", "report", "ci"]);
@@ -1334,6 +1427,6 @@ export async function main(): Promise<number> {
1334
1427
  baseline: baselineCommand,
1335
1428
  },
1336
1429
  "main",
1337
- (s) => `Unknown subcommand "${s}". Run "ostia --help".`,
1430
+ unknownCommand,
1338
1431
  );
1339
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() };