Public: anyone can read this; the crew can change it.

Checks: the terminal app stops with its forge, and a red shard says what happened (#16446) #16449

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

fix/shards-leak → main 0 commits

  • Merged. fix/shards-leak was merged into main as b18ff5f.

Review

Sign in to review this change.
7 files changed +193 −18
scripts/shards.ts +44 −5
@@ -403,12 +403,47 @@ export function lastStarted(output: string): string | undefined {
403403 return [...output.matchAll(FILE_STARTED)].at(-1)?.[1];
404404 }
405405
406 /** The line for a red shard that named no test: where it was and how long it ran, when known. */
406 /** Where bun starts an error that no test owns: a timer or socket a file before left running. */
407 const BETWEEN_TESTS = /^# Unhandled error between tests/m;
408 /** An error's own line: `RangeError: Cannot use a closed database`, or bun's `error: …`. */
409 const ERROR_LINE = /^\s*((?:[A-Z][A-Za-z]*(?:Error|Exception)|error): \S.*)$/;
410 /** How many lines of a red shard's error the ending keeps, so the log's tail always holds them. */
411 export const ERROR_LINES = 24;
412
413 /**
414 * Why a red shard that named no test went red, from its own output: the error bun printed between
415 * tests (or the first error line at all), with the lines around it, or nothing when it printed none
416 * (a process stopped from outside).
417 */
418 export function errorOf(output: string): { what: string; between: boolean; lines: string[] } | undefined {
419 const lines = output.split("\n");
420 const marker = lines.findIndex((l) => BETWEEN_TESTS.test(l));
421 const from = marker === -1 ? 0 : marker;
422 const at = lines.findIndex((l, i) => i >= from && ERROR_LINE.test(l));
423 if (at === -1) return undefined;
424 const what = ERROR_LINE.exec(lines[at]!)![1]!.trim().slice(0, 160);
425 // From bun's heading when the error is near it, else a few lines of what led up to it.
426 const start = marker !== -1 && at - marker < ERROR_LINES / 2 ? marker : Math.max(0, at - 8);
427 return { what, between: marker !== -1, lines: lines.slice(start, start + ERROR_LINES) };
428 }
429
430 const SIGNALS: Readonly<Record<number, string>> = { 1: "SIGHUP", 2: "SIGINT", 6: "SIGABRT", 9: "SIGKILL", 11: "SIGSEGV", 15: "SIGTERM" };
431
432 /**
433 * The line for a red shard that named no test: what happened (the error it printed, or the signal
434 * that stopped it), then where it was, as the last file it started (not as the culprit: an error
435 * between tests is often a timer a file before left behind).
436 */
407437 function unnamedLine(n: number, result: ShardResult): string {
408438 const running = lastStarted(result.output);
409 if (running !== undefined && result.seconds !== undefined)
410 return `shard ${n} killed after ${Math.round(result.seconds)} s, running ${running}`;
411 return `shard ${n} exited ${result.code} without naming a test: ${result.files.join(" ")}`;
439 const error = errorOf(result.output);
440 const after = result.seconds === undefined ? "" : ` after ${Math.round(result.seconds)} s`;
441 const where = running === undefined ? `; its files: ${result.files.join(" ")}` : `; the last file it started was ${running}`;
442 if (error !== undefined) return `shard ${n} exited ${result.code}${after} with an error ${error.between ? "between tests" : "outside any test"}: ${error.what}${where}`;
443 const signal = result.code > 128 ? SIGNALS[result.code - 128] : undefined;
444 if (signal !== undefined) return `shard ${n} was stopped by ${signal} (exit ${result.code})${after}${where}`;
445 if (running === undefined) return `shard ${n} exited ${result.code} without naming a test: ${result.files.join(" ")}`;
446 return `shard ${n} exited ${result.code}${after} without naming a test or an error${where}`;
412447 }
413448
414449 /**
@@ -451,8 +486,12 @@ export function tally(results: readonly ShardResult[], seconds: number): Tally {
451486 }
452487 const named = nameUnnamed(result.output.split("\n")).join("\n").match(FAIL) ?? [];
453488 for (const line of new Set(named)) failing.push(`${line} [shard ${i + 1}]`);
454 if (result.code !== 0 && named.length === 0)
489 if (result.code !== 0 && named.length === 0) {
455490 unnamed.push(unnamedLine(i + 1, result));
491 // Its error, quoted, in the ending: a long log is read by its tail, and the shard's own
492 // section may be far above it.
493 for (const line of errorOf(result.output)?.lines ?? []) unnamed.push(` │ ${line}`);
494 }
456495 });
457496 const took = `${seconds.toFixed(1)}s`;
458497 const shards = `${results.length} shard${results.length === 1 ? "" : "s"}`;
src/checks/summary.ts +1 −1
@@ -25,7 +25,7 @@ export const GATE_SUMMARY_HEADING = "── gate summary";
2525
2626 /** The sharded gate's line for a red shard that named no test (`tally` in scripts/shards.ts). */
2727 const UNNAMED_SHARD =
28 /^shard [0-9]+ (?:exited -?[0-9]+ without naming a test: |killed after [0-9]+ s, running )/;
28 /^shard [0-9]+ (?:exited -?[0-9]+(?: after [0-9]+ s)? (?:without naming a test|with an error )|was stopped by SIG|killed after [0-9]+ s, running )/;
2929
3030 /**
3131 * The lines `scripts/test-shards.ts` prints after the tally about the records
src/tui/app/app.ts +17 −1
@@ -289,6 +289,12 @@ export interface AppOpts extends SessionOpts {
289289 * says whether the screen has a place to tell from, and takes the key.
290290 */
291291 readonly tell?: TellHook;
292 /**
293 * The host's lifetime: when it ends (the forge closing its database), the loop stops as if
294 * the terminal had closed, so no frame, footer or palette search runs against what the host
295 * closed. Unset, only the terminal or a quit stops it.
296 */
297 readonly until?: AbortSignal;
292298 }
293299
294300 /** What the host does for the tell key, given the focused screen. */
@@ -375,6 +381,14 @@ export class App {
375381 return this.frames;
376382 }
377383
384 /** True once stopped (or never started): no timer is armed and nothing more is drawn. */
385 get stopped(): boolean {
386 return !this.running && this.timer === null;
387 }
388
389 /** Stops the loop when the host's lifetime ends (`AppOpts.until`). */
390 private readonly hostEnded = (): void => this.stop();
391
378392 track<T>(work: Promise<T>): Promise<T> {
379393 this.pending++;
380394 return work.finally(() => {
@@ -603,8 +617,9 @@ export class App {
603617 // ---- lifecycle ----
604618
605619 start(): void {
606 if (this.running) return;
620 if (this.running || this.opts.until?.aborted === true) return;
607621 this.running = true;
622 this.opts.until?.addEventListener("abort", this.hostEnded, { once: true });
608623 this.session.enter();
609624 this.opts.terminal.onInput((chunk) => this.onChunk(chunk));
610625 this.opts.terminal.onResize((cols, rows) => this.onResize(cols, rows));
@@ -616,6 +631,7 @@ export class App {
616631 stop(): void {
617632 if (!this.running) return;
618633 this.running = false;
634 this.opts.until?.removeEventListener("abort", this.hostEnded);
619635 if (this.timer !== null) clearTimeout(this.timer);
620636 this.timer = null;
621637 if (this.escTimer !== null) clearTimeout(this.escTimer);
src/tui/forge.ts +2
@@ -1039,6 +1039,8 @@ export function createForgeApp(
10391039 onTheme: (name) => session.saveTheme(name),
10401040 onPrefs: (prefs) => session.savePrefs(prefs),
10411041 tell: tellHook(session),
1042 // Its screens read the forge's database: the forge closing stops the loop first (#16446).
1043 until: forge.closing.signal,
10421044 });
10431045 return { app, session };
10441046 }
test/checks-failure-summary.test.ts +7 −1
@@ -255,10 +255,16 @@ describe("summariseCheckFailure: a red gate is summarised by its red test, never
255255 results[1]!,
256256 ];
257257 expect(summariseCheckFailure(log(crashed), "check exited with code 1").summary).toBe(
258 "shard 1 exited 137 without naming a test: test/standards.test.ts",
258 "shard 1 was stopped by SIGKILL (exit 137) after 1 s; its files: test/standards.test.ts",
259259 );
260260 });
261261
262 test("a shard's error between tests is the summary, before the files it ran", () => {
263 const line =
264 "shard 66 exited 1 after 22 s with an error between tests: RangeError: Cannot use a closed database; the last file it started was test/web-browse.test.ts";
265 expect(summariseCheckFailure(["test/web-browse.test.ts:", line, " │ # Unhandled error between tests"], "check exited with code 1").summary).toBe(line);
266 });
267
262268 test("a killed shard's line is the summary, and the old line is still recognised", () => {
263269 expect(
264270 summariseCheckFailure(["shard 258 killed after 412 s, running test/x.test.ts"], "check exited with code 1").summary,
test/shards.test.ts +65 −10
@@ -39,6 +39,8 @@ import {
3939 splitCapped,
4040 splitFiles,
4141 tally,
42 errorOf,
43 ERROR_LINES,
4244 weigher,
4345 workerCpus,
4446 type ShardResult,
@@ -438,7 +440,7 @@ describe("tally", () => {
438440 ]);
439441 });
440442
441 test("a shard that crashes without naming a test still fails, by its files", () => {
443 test("a shard that crashes without naming a test still fails, saying its error and its files", () => {
442444 const ending = tally(
443445 [
444446 green(["a"], 2),
@@ -448,21 +450,74 @@ describe("tally", () => {
448450 );
449451 expect(ending.code).toBe(1);
450452 expect(ending.lines).toContain(
451 "shard 2 exited 1 without naming a test: b c",
453 "shard 2 exited 1 with an error outside any test: error: boom; its files: b c",
452454 );
453455 });
454456 });
455457
456 describe("tally, a shard killed mid-file", () => {
457 test("names the last file it started and how long it ran", () => {
458 const output = "test/a.test.ts:\n(pass) x [1ms]\n\ntest/x.test.ts:\n(pass) y [1ms]\n";
459 const ending = tally([{ files: ["test/a.test.ts", "test/x.test.ts"], code: 143, output, seconds: 411.6 }], 412);
460 expect(ending.lines).toContain("shard 1 killed after 412 s, running test/x.test.ts");
458 describe("tally, a shard red with an error between tests (#16446)", () => {
459 // What bun printed when a file's frame timer drew against a database the file had closed.
460 const output = [
461 "test/tui-forge-it.test.ts:",
462 "(pass) Forge it confirms [387.80ms]",
463 "",
464 "test/tui-home-pins.test.ts:",
465 "",
466 "# Unhandled error between tests",
467 "-------------------------------",
468 "496 | const row = db",
469 '497 | .query<UserRow, [string]>("SELECT * FROM user WHERE id = ?1")',
470 " ^",
471 "RangeError: Cannot use a closed database",
472 " at getUserById (src/core/users.ts:497:6)",
473 " at drawFooter (src/tui/app/app.ts:1148:37)",
474 "-------------------------------",
475 "",
476 "(pass) tui home pins > the palette offers the door [56.62ms]",
477 "",
478 "test/web-browse.test.ts:",
479 "(pass) browse [1ms]",
480 "",
481 " 40 pass",
482 " 0 fail",
483 " 1 error",
484 ].join("\n");
485
486 test("says what happened, and names the last file started as where it was, not as the culprit", () => {
487 const ending = tally([{ files: ["test/tui-forge-it.test.ts", "test/web-browse.test.ts"], code: 1, output, seconds: 22 }], 22);
488 expect(ending.lines).toContain(
489 "shard 1 exited 1 after 22 s with an error between tests: RangeError: Cannot use a closed database; the last file it started was test/web-browse.test.ts",
490 );
461491 });
462492
463 test("without a started file or a timing, the old line stands", () => {
464 const ending = tally([{ files: ["b"], code: 143, output: "", seconds: 5 }], 5);
465 expect(ending.lines).toContain("shard 1 exited 143 without naming a test: b");
493 test("the ending quotes the error, so a log read by its tail still holds it", () => {
494 const ending = tally([{ files: ["a"], code: 1, output, seconds: 22 }], 22);
495 const at = ending.lines.findIndex((l) => l.startsWith("shard 1 exited 1"));
496 const quoted = ending.lines.slice(at + 1).filter((l) => l.startsWith(" │ "));
497 expect(quoted[0]).toBe(" │ # Unhandled error between tests");
498 expect(quoted).toContain(" │ at drawFooter (src/tui/app/app.ts:1148:37)");
499 expect(quoted.length).toBeLessThanOrEqual(ERROR_LINES);
500 // Quoted, it is never counted as a red of its own.
501 expect(ending.lines.filter((l) => l.startsWith("(fail)"))).toEqual([]);
502 });
503
504 test("errorOf finds nothing in a shard that printed no error", () => {
505 expect(errorOf("test/a.test.ts:\n(pass) x [1ms]\n")).toBeUndefined();
506 });
507 });
508
509 describe("tally, a shard killed mid-file", () => {
510 test("names the signal that stopped it, how long it ran and the last file it started", () => {
511 const output = "test/a.test.ts:\n(pass) x [1ms]\n\ntest/x.test.ts:\n(pass) y [1ms]\n";
512 const ending = tally([{ files: ["test/a.test.ts", "test/x.test.ts"], code: 143, output, seconds: 411.6 }], 412);
513 expect(ending.lines).toContain("shard 1 was stopped by SIGTERM (exit 143) after 412 s; the last file it started was test/x.test.ts");
514 });
515
516 test("without a started file, its files; without a signal or an error, the old line stands", () => {
517 const stopped = tally([{ files: ["b"], code: 143, output: "", seconds: 5 }], 5);
518 expect(stopped.lines).toContain("shard 1 was stopped by SIGTERM (exit 143) after 5 s; its files: b");
519 const plain = tally([{ files: ["b"], code: 1, output: "" }], 5);
520 expect(plain.lines).toContain("shard 1 exited 1 without naming a test: b");
466521 });
467522 });
468523
test/tui-stops-with-forge.test.ts added +57
@@ -0,0 +1,57 @@
1 /**
2 * A terminal session stops when its forge closes (#16446): its frame timer, its footer and its
3 * palette search read the forge's database, so a forge closing with a session still open (a test's
4 * teardown, a process exit) stops the loop first, and nothing draws against a closed database.
5 */
6 import { afterAll, beforeAll, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createUser, type User } from "../src/core/users.ts";
12 import { createForgeApp } from "../src/tui/forge.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { settleApp } from "./helpers/tui.ts";
15
16 let dir: string;
17 let forge: App;
18 let alice: User;
19
20 beforeAll(async () => {
21 dir = await mkdtemp(join(tmpdir(), "forge-tui-stops-"));
22 forge = createApp({ dataDir: dir, url: "https://forge.test", port: 0 });
23 const made = await createUser(forge.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-long-passphrase", isAdmin: true });
24 if (!made.ok) throw new Error(made.error);
25 alice = made.value;
26 });
27 afterAll(async () => {
28 await rm(dir, { recursive: true, force: true });
29 });
30
31 const open = (on: App) =>
32 createForgeApp(on, { sshUsername: "alice", remoteAddress: "127.0.0.1", user: alice }, { terminal: headlessTerminal(120, 40), exitHooks: false }).app;
33
34 test("closing the forge stops an open session: no timer is left, and nothing draws after", async () => {
35 const app = open(forge);
36 app.start();
37 await settleApp(app);
38 // A toast keeps the frame timer armed, as a spinner would.
39 app.ctx.toast("still here");
40 expect(app.stopped).toBe(false);
41 const errors: unknown[] = [];
42 const caught = (e: unknown) => errors.push(e);
43 process.on("uncaughtException", caught);
44 try {
45 forge.close();
46 expect(app.stopped).toBe(true);
47 const frames = app.frameCount;
48 app.dispatch({ type: "key", key: "j", ctrl: false, alt: false, shift: false });
49 // No timer is armed (`stopped`), so no frame can come later; none came now.
50 expect(app.stopped).toBe(true);
51 expect(app.frameCount).toBe(frames);
52 expect(errors).toEqual([]);
53 } finally {
54 process.off("uncaughtException", caught);
55 }
56 });
57

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs