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

A test file that fails in its shard is run once more alone; one that passes alone is named as 'fails only beside others' and does not fail the pull #2433

Parked opened this
Closed without merging

scout/forge:scout/2416-a-test-file-that-fails-in-its-shard-is-r → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
5 files changed +156 −6
scripts/shards.ts +50
@@ -7,6 +7,8 @@
77 * is disjoint and covering, and that one red shard makes the run red.
88 */
99
10 import { resolve } from "node:path";
11
1012 /**
1113 * No more than this many `bun test` processes at once, whatever the host:
1214 * a ceiling for a big shared machine, not the check cell's number. The cell
@@ -332,6 +334,8 @@ export interface ShardResult {
332334 readonly files: readonly string[];
333335 readonly code: number;
334336 readonly output: string;
337 /** Files that failed beside their shard-mates and passed run alone. */
338 readonly beside?: readonly string[];
335339 }
336340
337341 /** What the log ends with, and the exit code of the whole run. */
@@ -343,6 +347,43 @@ export interface Tally {
343347 const RAN = /^Ran (\d+) tests? across (\d+) files?\./m;
344348 const FAIL = /^\(fail\) .*$/gm;
345349
350 /** The most files of one shard that are run again alone. */
351 export const RETRY_MAX = 3;
352
353 const FILE_HEADER = /^(\S+\.test\.[cm]?[jt]sx?):$/;
354 const SUMMARY = /^\s*\d+ pass$/;
355
356 /**
357 * Which of a shard's files failed, read from its `bun test` output: a
358 * `(fail)` line, or an unhandled error between tests, under that file's
359 * header. `sure` is false when some failure could not be given to one of
360 * `files`, or when none was named: then nothing is run again and the
361 * shard stays red.
362 */
363 export function failedFiles(
364 output: string,
365 files: readonly string[],
366 ): { failed: string[]; sure: boolean } {
367 // bun prints each header relative to its cwd, which may climb with `..`.
368 const norm = (path: string): string => resolve(path);
369 const known = new Map(files.map((file) => [norm(file), file]));
370 const failed = new Set<string>();
371 let sure = true;
372 let current: string | undefined;
373 for (const line of output.split("\n")) {
374 if (SUMMARY.test(line)) break;
375 const header = FILE_HEADER.exec(line);
376 if (header) {
377 current = known.get(norm(header[1]!));
378 continue;
379 }
380 if (!line.startsWith("(fail) ") && !line.startsWith("# Unhandled error")) continue;
381 if (current !== undefined) failed.add(current);
382 else sure = false;
383 }
384 return { failed: [...failed], sure: sure && failed.size > 0 };
385 }
386
346387 /**
347388 * Reads every shard's `bun test` output into one ending. Green: one line,
348389 * how many tests across how many files and how long. Red: every failing
@@ -354,12 +395,19 @@ export function tally(results: readonly ShardResult[], seconds: number): Tally {
354395 let files = 0;
355396 const failing: string[] = [];
356397 const unnamed: string[] = [];
398 const besides: string[] = [];
357399 results.forEach((result, i) => {
400 for (const file of result.beside ?? [])
401 besides.push(
402 `fails only beside others: ${file} (shard-mates: ${result.files.filter((f) => f !== file).join(" ")})`,
403 );
358404 const ran = RAN.exec(result.output);
359405 if (ran) {
360406 tests += Number(ran[1]);
361407 files += Number(ran[2]);
362408 }
409 // A shard whose every failing file passed alone is green.
410 if (result.code === 0) return;
363411 const named = result.output.match(FAIL) ?? [];
364412 for (const line of new Set(named)) failing.push(`${line} [shard ${i + 1}]`);
365413 if (result.code !== 0 && named.length === 0)
@@ -374,6 +422,7 @@ export function tally(results: readonly ShardResult[], seconds: number): Tally {
374422 return {
375423 code: 0,
376424 lines: [
425 ...besides,
377426 `Ran ${tests} tests across ${files} files in ${took} (${shards}).`,
378427 ],
379428 };
@@ -383,6 +432,7 @@ export function tally(results: readonly ShardResult[], seconds: number): Tally {
383432 `${red} of ${shards} failed:`,
384433 ...failing,
385434 ...unnamed,
435 ...besides,
386436 `Ran ${tests} tests across ${files} files in ${took}; ${failing.length} failed.`,
387437 ],
388438 };
scripts/test-shards.ts +33 −3
@@ -23,7 +23,10 @@
2323 * finishes, so the log reads one shard at a time. Either way the tail
2424 * names every failing test from every shard. The first red shard stops
2525 * the rest (fail-fast) so a known fail does not burn the remaining wall
26 * clock. Exits non-zero if any shard does.
26 * clock. A red shard of several files first runs each failing file
27 * (at most 3, once) alone: if all pass alone the shard is green and the
28 * tail says `fails only beside others: <file> (shard-mates: …)` (#2416).
29 * Exits non-zero if any shard does.
2730 *
2831 * The whole gate, unsliced (`--gate` on the full tier, as `check.run`),
2932 * runs one file per `bun test`, heaviest first into whichever worker is
@@ -58,6 +61,8 @@ import {
5861 splitFiles,
5962 tally,
6063 weigher,
64 failedFiles,
65 RETRY_MAX,
6166 type ShardResult,
6267 } from "./shards.ts";
6368 import { gateFiles, gateRefusal, presentTests } from "./gate.ts";
@@ -437,9 +442,11 @@ async function runShard(
437442 slice: string[],
438443 index: number,
439444 live: boolean,
445 /** Names a run that is not one of the slices: a file run again alone. */
446 label?: string,
440447 ): Promise<Timed> {
441448 const started = performance.now();
442 const where = `${index + 1}/${slices.length}`;
449 const where = label ?? `${index + 1}/${slices.length}`;
443450 // Print before spawn so a mid-suite cgroup SIGKILL still leaves a breadcrumb.
444451 // stderr: Actions often block-buffers stdout until exit; an OOM never flushes.
445452 process.stderr.write(`test-shards: start ${where} ${slice.join(" ")}\n`);
@@ -509,6 +516,26 @@ async function runShard(
509516 };
510517 }
511518
519 /**
520 * A red shard of several files: each file that failed is run once more as
521 * its own `bun test`. When every one of them (at most {@link RETRY_MAX})
522 * passes alone, the shard is green and names them as failing only beside
523 * others; otherwise it stays as it was. Never for a shard of one file, the
524 * perFile modes, or a failure no file can be given.
525 */
526 async function retryAlone(result: Timed, index: number): Promise<Timed> {
527 if (result.code === 0 || result.files.length < 2 || perFile) return result;
528 const { failed, sure } = failedFiles(result.output, result.files);
529 if (!sure || failed.length > RETRY_MAX) return result;
530 const passed: string[] = [];
531 for (const file of failed) {
532 const alone = await runShard([file], index, false, `${index + 1}/${slices.length} again alone`);
533 if (alone.code !== 0) return result;
534 passed.push(file);
535 }
536 return { ...result, code: 0, beside: passed };
537 }
538
512539 /** Runs every slice, at most `width` at once, in the slices' order.
513540 * Stops starting new slices after the first non-zero exit and signals
514541 * in-flight children so a red shard does not burn the rest of the wall. */
@@ -521,7 +548,10 @@ async function pool(width: number): Promise<Timed[]> {
521548 if (stop) break;
522549 const index = next++;
523550 if (stop) break;
524 results[index] = await runShard(slices[index]!, index, width === 1);
551 results[index] = await retryAlone(
552 await runShard(slices[index]!, index, width === 1),
553 index,
554 );
525555 if (results[index]!.code !== 0) {
526556 stop = true;
527557 for (const child of children) child.kill("SIGTERM");
test/test-shards-retry.test.ts added +70
@@ -0,0 +1,70 @@
1 import { afterAll, describe, expect, test } from "bun:test";
2 import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { failedFiles, tally } from "../scripts/shards.ts";
6
7 const dir = mkdtempSync(join(tmpdir(), "retry-"));
8 afterAll(() => rmSync(dir, { recursive: true, force: true }));
9
10 const write = (name: string, body: string): string => {
11 const path = join(dir, name);
12 writeFileSync(path, `import { test, expect } from "bun:test";\n${body}\n`);
13 return path;
14 };
15
16 /** A heavy file keeps itself in a shard alone; the two small ones share the other. */
17 const big = write("big.test.ts", `test("big", () => {});\n${"// padding\n".repeat(4000)}`);
18 const leaker = write("a-leaker.test.ts", `test("sets a global", () => { (globalThis as any).__leak = 1; });`);
19 const victim = write(
20 "b-victim.test.ts",
21 `test("sees the global", () => { expect((globalThis as any).__leak).toBeUndefined(); });`,
22 );
23 const broken = write("c-broken.test.ts", `test("always red", () => { expect(1).toBe(2); });`);
24
25 async function run(files: string[]): Promise<{ code: number; out: string }> {
26 const child = Bun.spawn(["bun", "scripts/test-shards.ts", ...files], {
27 stdout: "pipe",
28 stderr: "pipe",
29 env: { ...process.env, FORGE_CHECK_SHARDS: "2", FORGE_CHECK_IMPACT: "" },
30 });
31 const [out, err] = await Promise.all([new Response(child.stdout).text(), new Response(child.stderr).text()]);
32 return { code: await child.exited, out: out + err };
33 }
34
35 describe("a file that fails only beside others", () => {
36 test("passes alone: the run is green and the file is named", async () => {
37 const { code, out } = await run([big, leaker, victim]);
38 expect(out).toContain(`fails only beside others: ${victim} (shard-mates: ${leaker})`);
39 expect(code).toBe(0);
40 }, 60_000);
41
42 test("fails alone too: the run stays red", async () => {
43 const { code, out } = await run([big, leaker, broken]);
44 expect(out).not.toContain("fails only beside others");
45 expect(code).toBe(1);
46 }, 60_000);
47 });
48
49 describe("failedFiles", () => {
50 const out = (body: string): string => `${body}\n\n 1 pass\n 1 fail\nRan 2 tests across 2 files.\n`;
51 test("attributes a (fail) to the file header above it", () => {
52 const got = failedFiles(out("test/a.test.ts:\n(pass) ok\n\ntest/b.test.ts:\n(fail) x [1ms]"), ["test/a.test.ts", "test/b.test.ts"]);
53 expect(got).toEqual({ failed: ["test/b.test.ts"], sure: true });
54 });
55 test("a failure under no known file, or none named, is not sure", () => {
56 expect(failedFiles(out("(fail) x [1ms]"), ["test/a.test.ts"]).sure).toBe(false);
57 expect(failedFiles(out("test/a.test.ts:\n(pass) ok"), ["test/a.test.ts"]).sure).toBe(false);
58 });
59 });
60
61 describe("tally with a file that passed alone", () => {
62 test("names it and stays green", () => {
63 const ending = tally(
64 [{ files: ["a", "b"], code: 0, beside: ["b"], output: "(fail) t [1ms]\nRan 2 tests across 2 files.\n" }],
65 1,
66 );
67 expect(ending.code).toBe(0);
68 expect(ending.lines[0]).toBe("fails only beside others: b (shard-mates: a)");
69 });
70 });
test/toolbar-actions.test.ts +1 −1
@@ -80,7 +80,7 @@ describe("toolbar actions", () => {
8080 servers.stop();
8181 app.close();
8282 await rm(dataDir, { recursive: true, force: true });
83 });
83 }, 30_000);
8484
8585 const url = (env: string) =>
8686 `/alice/notes/toolbar?env=${env}&page=${encodeURIComponent(PAGE)}`;
test/tui-flags.test.ts +2 −2
@@ -67,12 +67,12 @@ describe("flags in the terminal", () => {
6767 }
6868 forge.db.query("UPDATE user SET is_admin = 1, is_agent = 1 WHERE username = 'carol'").run();
6969 useFlagRegistry(reg);
70 });
70 }, 30_000);
7171 afterAll(async () => {
7272 useFlagRegistry(undefined);
7373 forge.close();
7474 await rm(dataDir, { recursive: true, force: true });
75 });
75 }, 30_000);
7676
7777 const open = async (h: ReturnType<typeof boot>) => {
7878 await h.ctrl("k");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs