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

The tests outside the gate run once a night, and one issue says what is red #959

Closed opened this in answer to
Closed without merging

steward/812-outside-gate-daily → main 2 commits

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +729 −11
docs/APPS.md +15
@@ -344,6 +344,21 @@ earlier. The one exception is starvation: a check that has waited ten
344344 minutes to start outranks a newer one regardless, so nothing waits forever.
345345 A pull's status names how long its queued check has been waiting.
346346
347 A suite too slow for every push can run once a day instead, as
348 `check.nightly`:
349
350 ```json
351 "nightly": { "run": "bun scripts/test-outside-gate.ts", "under": 586 }
352 ```
353
354 The forge runs it at the default branch's head, in the same cell and the
355 same slots as the check, and only when no other check waits or runs. The
356 command prints one line per suite — `nightly: pass <file>` or
357 `nightly: fail <file> — <the first failing test>` — and the forge keeps one
358 issue from them: opened when anything fails, linked under the issue `under`
359 names, said again only when what fails changes, closed when everything
360 passes. It pages nobody. `timeout` defaults to two hours.
361
347362 ### Environment
348363
349364 What an app needs that the repository must not carry — an admin password,
forge.json +5 −1
@@ -10,6 +10,10 @@
1010 "check": {
1111 "run": "bun x tsc --noEmit && FORGE_CHECK_SHARDS=2 bun scripts/test-shards.ts --timeout 60000 --gate",
1212 "timeout": 1800,
13 "limits": { "memory": 4096, "cpus": 4, "disk": 8192 }
13 "limits": { "memory": 4096, "cpus": 4, "disk": 8192 },
14 "nightly": {
15 "run": "bun scripts/test-outside-gate.ts --timeout 60000",
16 "under": 586
17 }
1418 }
1519 }
scripts/gate.ts +1
@@ -171,6 +171,7 @@ export const GATE: readonly string[] = [
171171 "test/milestones.test.ts",
172172 "test/mcp.test.ts",
173173 "test/new-forge.test.ts",
174 "test/nightly.test.ts",
174175 "test/notify.test.ts",
175176 "test/onboarding.test.ts",
176177 "test/org-owners.test.ts",
scripts/shards.ts +11
@@ -266,3 +266,14 @@ export function tally(results: readonly ShardResult[], seconds: number): Tally {
266266 ],
267267 };
268268 }
269
270 /**
271 * The line a suite outside the gate reports once a night, which the forge
272 * reads back (`src/checks/nightly.ts`): `nightly: pass <file>`, or
273 * `nightly: fail <file> — <the first failing test>`.
274 */
275 export function nightlyLine(file: string, code: number, output: string): string {
276 if (code === 0) return `nightly: pass ${file}`;
277 const first = /^\(fail\) (.*?)(?: \[[\d.]+m?s\])?$/m.exec(output)?.[1];
278 return `nightly: fail ${file} — ${first ?? `exited ${code} without naming a test`}`;
279 }
scripts/test-outside-gate.ts added +52
@@ -0,0 +1,52 @@
1 /**
2 * The test files the gate does not run, one at a time — the forge's
3 * nightly for its own repository (`forge.json`'s `check.nightly`).
4 *
5 * bun scripts/test-outside-gate.ts [bun test flags…]
6 *
7 * The files are `EXCLUDED` in `scripts/gate.ts` and nothing else, so a file
8 * moved into the gate stops being run here. Each is its own `bun test`; a
9 * red one's output is written through so the log shows why, and the end
10 * names every file with its verdict (`nightlyLine`), which is what the
11 * forge reads back into one issue. Exits non-zero if any file is red.
12 */
13
14 import { EXCLUDED } from "./gate.ts";
15 import { nightlyLine } from "./shards.ts";
16
17 /** A file still running after this long is stopped and counted red. */
18 const FILE_LIMIT_MS = 10 * 60_000;
19
20 const flags = process.argv.slice(2);
21 const verdicts: string[] = [];
22 let red = 0;
23 for (const { file } of EXCLUDED) {
24 const started = performance.now();
25 const child = Bun.spawn(["bun", "test", ...flags, `./${file}`], {
26 stdin: "ignore",
27 stdout: "pipe",
28 stderr: "pipe",
29 });
30 const limit = setTimeout(() => child.kill("SIGKILL"), FILE_LIMIT_MS);
31 const [out, err] = await Promise.all([
32 new Response(child.stdout).text(),
33 new Response(child.stderr).text(),
34 ]);
35 const code = await child.exited;
36 clearTimeout(limit);
37 const seconds = ((performance.now() - started) / 1000).toFixed(1);
38 const output = `${out}${err}`;
39 const line =
40 child.signalCode === "SIGKILL"
41 ? `nightly: fail ${file} — still running after ${FILE_LIMIT_MS / 60_000} minutes`
42 : nightlyLine(file, code, output);
43 console.log(`── ${file} (exit ${code}, ${seconds}s)`);
44 if (code !== 0) {
45 red++;
46 process.stdout.write(output.endsWith("\n") ? output : `${output}\n`);
47 }
48 verdicts.push(line);
49 }
50 console.log(`\n${EXCLUDED.length - red} of ${EXCLUDED.length} files outside the gate pass.`);
51 for (const line of verdicts) console.log(line);
52 process.exit(red === 0 ? 0 : 1);
src/apps/manifest.ts +52
@@ -289,6 +289,21 @@ export interface CheckManifest {
289289 readonly egress: readonly string[];
290290 /** `check.limits`: memory, CPU and disk, within the machine's maximum. */
291291 readonly limits: DeclaredLimits;
292 /**
293 * `check.nightly`: what the forge runs once a day at the default branch,
294 * besides the check every push gets — the slower suites that check does
295 * not hold (`checks/nightly.ts`). Undefined when none is declared.
296 */
297 readonly nightly?: NightlyManifest | undefined;
298 }
299
300 export interface NightlyManifest {
301 /** The command, through `sh -c`; it reports each suite as `nightly: pass|fail …`. */
302 readonly run: string;
303 /** Seconds it may take. */
304 readonly timeout: number;
305 /** The umbrella issue a red report is linked under, when named. */
306 readonly under: number | null;
292307 }
293308
294309 const CHECK_TIMEOUT_DEFAULT = 20 * 60;
@@ -332,7 +347,10 @@ export function parseCheck(
332347 if (!egress.ok) return egress;
333348 const limits = limitsField(check, "check");
334349 if (!limits.ok) return limits;
350 const nightly = nightlyField(check["nightly"]);
351 if (!nightly.ok) return nightly;
335352 return ok({
353 ...(nightly.value === undefined ? {} : { nightly: nightly.value }),
336354 run: run.value,
337355 egress: egress.value,
338356 limits: limits.value,
@@ -346,6 +364,40 @@ export function parseCheck(
346364 });
347365 }
348366
367 /** `check.nightly`, validated: `{ run, timeout?, under? }`. */
368 function nightlyField(
369 value: unknown,
370 ): Result<NightlyManifest | undefined, ManifestError> {
371 if (value === undefined) return ok(undefined);
372 if (!isObject(value))
373 return invalid("forge.json: check.nightly must be an object");
374 const run = value["run"];
375 if (typeof run !== "string" || run.trim() === "")
376 return invalid("forge.json: check.nightly.run is required");
377 const timeout = value["timeout"];
378 if (
379 timeout !== undefined &&
380 (typeof timeout !== "number" ||
381 !Number.isInteger(timeout) ||
382 timeout < 1 ||
383 timeout > CHECK_TIMEOUT_MAX)
384 )
385 return invalid(
386 `forge.json: check.nightly.timeout must be a whole number of seconds, 1–${CHECK_TIMEOUT_MAX}`,
387 );
388 const under = value["under"];
389 if (
390 under !== undefined &&
391 (typeof under !== "number" || !Number.isInteger(under) || under < 1)
392 )
393 return invalid("forge.json: check.nightly.under must be an issue number");
394 return ok({
395 run,
396 timeout: timeout ?? CHECK_TIMEOUT_MAX,
397 under: under ?? null,
398 });
399 }
400
349401 /** Whether `forge.json` declares an app at all, without validating it. */
350402 export function declaresApp(forgeJson: string | undefined): boolean {
351403 if (forgeJson === undefined) return false;
src/checks/nightly.ts added +170
@@ -0,0 +1,170 @@
1 /**
2 * The suites the check on every push does not hold, run once a day (#812).
3 * A repository names them in `forge.json` (`check.nightly`); the forge runs
4 * that command at its default branch, as an ordinary check run in the
5 * environment `nightly` — the same runner, the same cell, the same capacity
6 * (`core/capacity.ts`), and only when no other check waits or runs. The
7 * command says how each suite went, one line each:
8 *
9 * nightly: pass test/a.test.ts
10 * nightly: fail test/b.test.ts — the first failing test's name
11 *
12 * and the forge keeps one issue about it: opened the first time anything
13 * fails, said again when what fails changes, closed when everything passes.
14 * It is linked under the umbrella `check.nightly.under` names, so the map
15 * and the crew see it. Nothing here pages anyone.
16 */
17
18 import type { App } from "../app.ts";
19 import { linkIssue } from "../actions/dependencies.ts";
20 import {
21 addComment,
22 editIssue,
23 openIssue,
24 setIssueState,
25 } from "../actions/issues.ts";
26 import { getIssue, type Issue } from "../core/issues.ts";
27 import type { Repo } from "../core/repos.ts";
28 import { getUserById } from "../core/users.ts";
29 import { readRunLog } from "../runs/log.ts";
30
31 /** The environment a nightly run is in. */
32 export const NIGHTLY_ENV = "nightly";
33
34 /** How often the forge looks for a repository whose nightly is due. */
35 export const NIGHTLY_TICK_MS = 60 * 60_000;
36
37 /** How long after one nightly run the next is due. */
38 export const NIGHTLY_EVERY_MS = 24 * 60 * 60_000;
39
40 /** The title of the one issue a repository's nightly keeps. */
41 export const NIGHTLY_TITLE = "Nightly: suites outside the check are failing";
42
43 export interface NightlyResult {
44 readonly failing: readonly {
45 readonly file: string;
46 readonly first: string;
47 }[];
48 readonly passing: readonly string[];
49 }
50
51 const LINE = /^nightly: (pass|fail) (\S+)(?: — (.*))?$/;
52
53 /** What a nightly run said, from its lines. */
54 export function parseNightly(lines: readonly string[]): NightlyResult {
55 const failing: { file: string; first: string }[] = [];
56 const passing: string[] = [];
57 for (const line of lines) {
58 const m = LINE.exec(line.trim());
59 if (m === null) continue;
60 if (m[1] === "pass") passing.push(m[2]!);
61 else failing.push({ file: m[2]!, first: (m[3] ?? "").trim() });
62 }
63 return { failing, passing };
64 }
65
66 /** Whether `repo`'s nightly is due: none created in the last day. */
67 export function nightlyDue(app: App, repo: Repo, now = Date.now()): boolean {
68 const last = app.db
69 .query<{ at: string | null }, [string, string]>(
70 `SELECT MAX(created_at) AS at FROM run
71 WHERE repo_id = ?1 AND kind = 'check' AND env = ?2`,
72 )
73 .get(repo.id, NIGHTLY_ENV)?.at;
74 return (
75 last === null ||
76 last === undefined ||
77 now - Date.parse(last) >= NIGHTLY_EVERY_MS
78 );
79 }
80
81 /** The repositories whose own check has run here: the ones a nightly may be declared for. */
82 export function checkedRepoIds(app: App): string[] {
83 return app.db
84 .query<{ id: string }, []>(
85 "SELECT DISTINCT repo_id AS id FROM run WHERE kind = 'check'",
86 )
87 .all()
88 .map((r) => r.id);
89 }
90
91 /** The words of the report: which suites fail, and the first failing test of each. */
92 function words(result: NightlyResult): string {
93 return [
94 result.failing.length === 1
95 ? "1 suite outside the check fails on the default branch:"
96 : `${result.failing.length} suites outside the check fail on the default branch:`,
97 "",
98 ...result.failing.map(
99 (f) => `- \`${f.file}\`${f.first === "" ? "" : ` — ${f.first}`}`,
100 ),
101 "",
102 "Each moves into the gate once it is green (`scripts/gate.ts`).",
103 ].join("\n");
104 }
105
106 /** The open issue a repository's nightly keeps, if there is one. */
107 function openReport(app: App, repo: Repo): Issue | undefined {
108 const row = app.db
109 .query<{ number: number }, [string, string]>(
110 `SELECT number FROM issue WHERE repo_id = ?1 AND kind = 'issue'
111 AND state = 'open' AND title = ?2 ORDER BY number DESC LIMIT 1`,
112 )
113 .get(repo.id, NIGHTLY_TITLE);
114 return row ? getIssue(app.db, repo.id, row.number) : undefined;
115 }
116
117 /**
118 * Keep the one issue in step with a finished nightly run: open it when
119 * something fails, say so again only when what fails changed, close it
120 * when it ran through and all pass. Written as the person the forge acts as on this
121 * repository, else its owner, through the same actions a person's own
122 * writes take; a repository with neither is reported in the log only.
123 */
124 export function reportNightly(
125 app: App,
126 repo: Repo,
127 runId: string,
128 under: number | null,
129 outcome: { readonly ok: true } | { readonly ok: false; readonly error: string },
130 ): "opened" | "said" | "unchanged" | "closed" | "quiet" {
131 const said = parseNightly(readRunLog(app.config.dataDir, runId).lines);
132 // A run that failed without naming a suite did not get as far as the
133 // suites (its install, its time limit): that is what fails, never a pass.
134 const result: NightlyResult =
135 !outcome.ok && said.failing.length === 0
136 ? { ...said, failing: [{ file: "the nightly itself", first: outcome.error }] }
137 : said;
138 const author = [repo.autonomyBy, repo.ownerId]
139 .map((id) => (id === null ? undefined : getUserById(app.db, id)))
140 .find((user) => user !== undefined && user.kind === "user");
141 if (author === undefined) return "quiet";
142 const open = openReport(app, repo);
143 if (result.failing.length === 0) {
144 if (open === undefined) return "quiet";
145 addComment(
146 app,
147 author,
148 repo,
149 open,
150 `Every suite outside the check passes again (${result.passing.length}).`,
151 );
152 setIssueState(app, author, repo, open, "closed");
153 return "closed";
154 }
155 const body = words(result);
156 if (open === undefined) {
157 const made = openIssue(app, author, repo, { title: NIGHTLY_TITLE, body });
158 if (!made.ok) return "quiet";
159 const umbrella =
160 under === null ? undefined : getIssue(app.db, repo.id, under);
161 if (umbrella !== undefined && umbrella.state === "open")
162 linkIssue(app, author, repo, umbrella, made.value);
163 return "opened";
164 }
165 if (open.body === body) return "unchanged";
166 // What fails changed: the body says it now, and one comment says so.
167 editIssue(app, author, repo, open, { body });
168 addComment(app, author, repo, open, body);
169 return "said";
170 }
src/checks/service.ts +75 −8
@@ -42,7 +42,7 @@ import { createLog } from "../kernel/log.ts";
4242 import { holdLease } from "../runs/lease.ts";
4343 import { appendRunLog } from "../runs/log.ts";
4444 import { exportTree, readFileAt } from "../apps/checkout.ts";
45 import { parseCheck } from "../apps/manifest.ts";
45 import { parseCheck, type NightlyManifest } from "../apps/manifest.ts";
4646 import { accountActive } from "../core/accounts.ts";
4747 import { childEnv, runStep } from "../apps/process.ts";
4848 import { noteReached } from "../apps/egress_report.ts";
@@ -59,6 +59,13 @@ import {
5959 type CellSpec,
6060 } from "../apps/contain.ts";
6161 import { summariseCheckFailure } from "./summary.ts";
62 import {
63 checkedRepoIds,
64 NIGHTLY_ENV,
65 NIGHTLY_TICK_MS,
66 nightlyDue,
67 reportNightly,
68 } from "./nightly.ts";
6269 import type { CheckDetail } from "../core/runs.ts";
6370
6471 const log = createLog("checks");
@@ -68,6 +75,8 @@ export interface ChecksOptions {
6875 readonly concurrency?: number | undefined;
6976 /** The forge's public URL, told to the check as `FORGE_URL`. */
7077 readonly forgeUrl: string;
78 /** How often a repository whose nightly is due is looked for; 0 never. @default NIGHTLY_TICK_MS */
79 readonly nightlyTickMs?: number | undefined;
7180 }
7281
7382 export interface ChecksHandle {
@@ -80,6 +89,11 @@ export interface ChecksHandle {
8089 issueId?: string,
8190 actorId?: string,
8291 ): Promise<Run | undefined>;
92 /**
93 * Queue the nightly (`checks/nightly.ts`) of every repository whose one
94 * is due, when no other check waits or runs; the runs queued.
95 */
96 nightly(): Promise<Run[]>;
8397 stop(): Promise<void>;
8498 }
8599
@@ -357,6 +371,8 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
357371 });
358372 write(outcome.ok ? `passed in ${seconds}s` : `failed: ${outcome.error}`);
359373 if (done) announceRun(app, done);
374 if (done && claimed.env === NIGHTLY_ENV && outcome.nightly !== undefined)
375 reportNightly(app, repo, run.id, outcome.nightly.under, outcome);
360376 } finally {
361377 release();
362378 }
@@ -368,8 +384,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
368384 write: (line: string) => void,
369385 signal: AbortSignal,
370386 ): Promise<
371 | { ok: true }
372 | { ok: false; error: string; detail?: CheckDetail | undefined }
387 (
388 | { ok: true }
389 | { ok: false; error: string; detail?: CheckDetail | undefined }
390 ) & { nightly?: NightlyManifest | undefined }
373391 > {
374392 const bare = await runDir(app.db, app.reposRoot, repo, run.issueId);
375393 const [forgeJson, packageJson] = await Promise.all([
@@ -387,12 +405,22 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
387405 };
388406 if (declared.value === undefined)
389407 return { ok: false, error: "this commit declares no check" };
390 const manifest = declared.value;
408 // A nightly run is the same check with the command `check.nightly`
409 // names, and its own time limit (`checks/nightly.ts`).
410 const nightly =
411 run.env === NIGHTLY_ENV ? declared.value.nightly : undefined;
412 if (run.env === NIGHTLY_ENV && nightly === undefined)
413 return { ok: false, error: "this commit declares no nightly" };
414 const manifest =
415 nightly === undefined
416 ? declared.value
417 : { ...declared.value, run: nightly.run, timeout: nightly.timeout };
418 const said = nightly === undefined ? {} : { nightly };
391419 const dir = join(checksRoot(app.config.dataDir), run.id);
392420 mkdirSync(dir, { recursive: true });
393421 write(`checking out ${run.commitOid.slice(0, 7)}`);
394422 const exported = await exportTree(bare, run.commitOid, dir);
395 if (!exported.ok) return { ok: false, error: exported.error };
423 if (!exported.ok) return { ok: false, error: exported.error, ...said };
396424 // The check is repository code: it runs in a cell of its own
397425 // (`apps/contain.ts`), its checkout and a home its only places to write,
398426 // the forge, the registry and what it declared its only way out.
@@ -435,7 +463,8 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
435463 timeoutMs: manifest.timeout * 1000,
436464 cell,
437465 });
438 if (!installed.ok) return { ok: false, error: installed.error };
466 if (!installed.ok)
467 return { ok: false, error: installed.error, ...said };
439468 }
440469 // The check step's own lines are kept beside what `write` already
441470 // logs, so a failure can be summarised once here — never by reading
@@ -461,9 +490,9 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
461490 checkLines,
462491 ran.error,
463492 );
464 return { ok: false, error: summary, detail };
493 return { ok: false, error: summary, detail, ...said };
465494 }
466 return { ok: true };
495 return { ok: true, ...said };
467496 } finally {
468497 if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
469498 rmSync(home, { recursive: true, force: true });
@@ -604,17 +633,55 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
604633 return (await resolveOid(dir, ref)) ?? (pull.headOid || undefined);
605634 }
606635
636 /**
637 * The nightly of every repository whose one is due, queued only while no
638 * other check waits or runs — so it takes a slot nobody wanted, and one
639 * repository's at a time. A push's own check queued after it still goes
640 * first (`pickNext`).
641 */
642 async function nightly(): Promise<Run[]> {
643 const queued: Run[] = [];
644 for (const id of checkedRepoIds(app)) {
645 if (stopped || listActive(app.db, "check").length > 0) break;
646 const repo = getRepoById(app.db, id);
647 if (!repo || !nightlyDue(app, repo)) continue;
648 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
649 const head = await resolveOid(bare, `refs/heads/${repo.defaultBranch}`);
650 if (head === undefined) continue;
651 const [forgeJson, packageJson] = await Promise.all([
652 readFileAt(bare, head, "forge.json"),
653 readFileAt(bare, head, "package.json"),
654 ]);
655 const declared = parseCheck(forgeJson, packageJson);
656 if (!declared.ok || declared.value?.nightly === undefined) continue;
657 const run = await request(repo, NIGHTLY_ENV, head, "nightly");
658 if (run !== undefined) queued.push(run);
659 }
660 return queued;
661 }
662
607663 const timer = setInterval(() => {
608664 if (!stopped) schedule();
609665 }, TICK_MS);
666 const nightlyTickMs = options.nightlyTickMs ?? NIGHTLY_TICK_MS;
667 const nightlyTimer =
668 nightlyTickMs > 0
669 ? setInterval(() => {
670 nightly().catch((error) =>
671 log.error("nightly sweep failed", { error: String(error) }),
672 );
673 }, nightlyTickMs)
674 : undefined;
610675 schedule();
611676 void catchUp();
612677
613678 const handle: ChecksHandle = {
614679 request,
680 nightly,
615681 stop: async () => {
616682 stopped = true;
617683 clearInterval(timer);
684 if (nightlyTimer !== undefined) clearInterval(nightlyTimer);
618685 unsubscribe();
619686 for (const { abort } of inFlight.values()) abort.abort();
620687 await Promise.all([...inFlight.values()].map((f) => f.promise));
src/feed/items.ts +4 −1
@@ -21,6 +21,7 @@ import {
2121 import { getUserById, type User } from "../core/users.ts";
2222 import { watchedBy } from "../core/watches.ts";
2323 import { askLinesFor } from "../web/studio/asks.ts";
24 import { NIGHTLY_ENV } from "../checks/nightly.ts";
2425
2526 export type FeedKind =
2627 | "run"
@@ -246,7 +247,9 @@ function fromEvent(
246247 ...common,
247248 kind: "run",
248249 link,
249 urgency: state === "failed" ? 4 : 0,
250 // A nightly's red is the one issue it keeps (`checks/nightly.ts`),
251 // not a fresh alarm each night.
252 urgency: state === "failed" && p["env"] !== NIGHTLY_ENV ? 4 : 0,
250253 what: `${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind} run ${state === "failed" ? "failed" : "finished"}${summary ? `: ${summary}` : ""}`,
251254 };
252255 }
test/crew-brief-gate.test.ts +4 −1
@@ -26,7 +26,10 @@ describe("a crew run does not run the gate the check runs", () => {
2626
2727 test("the repository's own instructions name the files, and forbid the sharded gate", () => {
2828 const guide = readFileSync(join(import.meta.dir, "..", "CLAUDE.md"), "utf8");
29 expect(guide).toContain("Never\n `bun scripts/test-shards.ts --gate` inside a run");
29 // The rule, however the paragraph happens to wrap.
30 expect(guide.replace(/\s+/g, " ")).toContain(
31 "Never `bun scripts/test-shards.ts --gate` inside a run",
32 );
3033 for (const file of [
3134 "test/reserved-names.test.ts",
3235 "test/studio.test.ts",
test/nightly.test.ts added +340
@@ -0,0 +1,340 @@
1 /**
2 * The suites the check on every push does not hold, once a day (#812):
3 * `check.nightly` in forge.json, run at the default branch only while the
4 * runner is idle, and one issue kept from what it says.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { parseCheck } from "../src/apps/manifest.ts";
15 import {
16 NIGHTLY_ENV,
17 NIGHTLY_TITLE,
18 parseNightly,
19 } from "../src/checks/nightly.ts";
20 import { startChecks, type ChecksHandle } from "../src/checks/service.ts";
21 import { blockerNumbersFor } from "../src/core/dependencies.ts";
22 import { getIssue, listComments, type Issue } from "../src/core/issues.ts";
23 import type { Repo } from "../src/core/repos.ts";
24 import { listActive, listRuns, type Run } from "../src/core/runs.ts";
25 import { createUser, type User } from "../src/core/users.ts";
26 import { serve, type Servers } from "../src/http/server.ts";
27 import { nightlyLine } from "../scripts/shards.ts";
28
29 const root = new URL("..", import.meta.url).pathname;
30
31 describe("check.nightly in forge.json", () => {
32 const parse = (nightly: unknown) =>
33 parseCheck(JSON.stringify({ check: { run: "true", nightly } }), undefined);
34
35 test("a command, a time limit two hours by default, and the umbrella it reports under", () => {
36 const parsed = parse({ run: "bun slow.ts", under: 586 });
37 expect(parsed.ok && parsed.value?.nightly).toEqual({
38 run: "bun slow.ts",
39 timeout: 7200,
40 under: 586,
41 });
42 const none = parse(undefined);
43 expect(none.ok && none.value?.nightly).toBeUndefined();
44 });
45
46 test("present and wrong fails the check with the reason, never goes unrun", () => {
47 for (const wrong of [
48 "bun slow.ts",
49 {},
50 { run: "" },
51 { run: "x", timeout: 0 },
52 { run: "x", timeout: 1.5 },
53 { run: "x", under: "586" },
54 { run: "x", under: 0 },
55 ]) {
56 const parsed = parse(wrong);
57 expect(parsed.ok).toBe(false);
58 }
59 });
60 });
61
62 describe("what a nightly says", () => {
63 test("bun test's first failing name, without its time, is the one named", () => {
64 const output = [
65 "(pass) fine [1.00ms]",
66 "(fail) search > finds a private repo's issue [12.34ms]",
67 "(fail) second [1.00ms]",
68 ].join("\n");
69 expect(nightlyLine("test/a.test.ts", 1, output)).toBe(
70 "nightly: fail test/a.test.ts — search > finds a private repo's issue",
71 );
72 expect(nightlyLine("test/a.test.ts", 0, output)).toBe(
73 "nightly: pass test/a.test.ts",
74 );
75 expect(nightlyLine("test/a.test.ts", 1, "SyntaxError")).toBe(
76 "nightly: fail test/a.test.ts — exited 1 without naming a test",
77 );
78 });
79
80 test("the forge reads back exactly those lines, and nothing that only looks like them", () => {
81 expect(
82 parseNightly([
83 "nightly: pass test/a.test.ts",
84 "nightly: fail test/b.test.ts — the first",
85 " nightly: fail test/c.test.ts — indented is still a line of its own",
86 "(fail) nightly: fail test/d.test.ts — inside another line",
87 ]),
88 ).toEqual({
89 passing: ["test/a.test.ts"],
90 failing: [
91 { file: "test/b.test.ts", first: "the first" },
92 {
93 file: "test/c.test.ts",
94 first: "indented is still a line of its own",
95 },
96 ],
97 });
98 });
99
100 test("the forge's own nightly runs the files outside the gate and no list of its own", async () => {
101 const manifest = (await Bun.file(`${root}forge.json`).json()) as {
102 check: { nightly: { run: string; under: number } };
103 };
104 expect(manifest.check.nightly.run).toStartWith(
105 "bun scripts/test-outside-gate.ts",
106 );
107 expect(manifest.check.nightly.under).toBe(586);
108 const script = await Bun.file(`${root}scripts/test-outside-gate.ts`).text();
109 // `EXCLUDED` is the whole list: a file moved into `GATE` leaves it.
110 expect(script).toContain('import { EXCLUDED } from "./gate.ts"');
111 expect(script).not.toMatch(/\.test\.[cm]?[jt]sx?["'`]/);
112 });
113 });
114
115 describe("the nightly run and its one issue", () => {
116 let dataDir: string;
117 let app: App;
118 let servers: Servers;
119 let checks: ChecksHandle;
120 let alice: User;
121 let repo: Repo;
122 let umbrella: Issue;
123
124 const forgeJson = (check: string, nightly: string): string =>
125 JSON.stringify({
126 check: { run: check, install: "", nightly: { run: nightly, under: 1 } },
127 });
128
129 /** What the nightly prints this time: the suites' lines, red when any fails. */
130 async function says(lines: string[], check = "true"): Promise<string> {
131 const nightly = `cat SAYS; ! grep -q '^nightly: fail' SAYS`;
132 const made = await commitToBranch(app, alice, repo, {
133 message: "Say",
134 files: [
135 { path: "forge.json", content: forgeJson(check, nightly) },
136 { path: "SAYS", content: lines.join("\n") + "\n" },
137 ],
138 });
139 if (!made.ok) throw new Error(JSON.stringify(made.error));
140 await settled(
141 (r) => r.env === "main" && r.commitOid === made.value.commitOid,
142 );
143 return made.value.commitOid;
144 }
145
146 async function settled(where: (run: Run) => boolean): Promise<Run> {
147 const deadline = Date.now() + 30_000;
148 while (Date.now() < deadline) {
149 const run = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).find(
150 where,
151 );
152 if (run && (run.state === "ok" || run.state === "failed")) return run;
153 await Bun.sleep(50);
154 }
155 throw new Error("check did not settle");
156 }
157
158 /** A night passes: the last nightly is a day old. */
159 function nightPasses(): void {
160 app.db
161 .query("UPDATE run SET created_at = ?1 WHERE repo_id = ?2 AND env = ?3")
162 .run(
163 new Date(Date.now() - 25 * 3_600_000).toISOString(),
164 repo.id,
165 NIGHTLY_ENV,
166 );
167 }
168
169 async function nightly(): Promise<Run> {
170 const queued = await checks.nightly();
171 expect(queued).toHaveLength(1);
172 const run = await settled((r) => r.id === queued[0]!.id);
173 expect(run.env).toBe(NIGHTLY_ENV);
174 expect(run.reason).toBe("nightly");
175 return run;
176 }
177
178 function report(): Issue | undefined {
179 const row = app.db
180 .query<
181 { number: number },
182 [string, string]
183 >("SELECT number FROM issue WHERE repo_id = ?1 AND title = ?2 ORDER BY number DESC")
184 .get(repo.id, NIGHTLY_TITLE);
185 return row ? getIssue(app.db, repo.id, row.number) : undefined;
186 }
187
188 beforeAll(async () => {
189 dataDir = await mkdtemp(join(tmpdir(), "forge-nightly-"));
190 app = createApp({ dataDir, port: 0 });
191 servers = await serve(app);
192 checks = startChecks(app, {
193 forgeUrl: servers.url,
194 concurrency: 1,
195 nightlyTickMs: 0,
196 });
197 const a = await createUser(app.db, {
198 trusted: true,
199 username: "alice",
200 email: "[email protected]",
201 password: "a-good-passphrase",
202 adminIfFirst: true,
203 });
204 if (!a.ok) throw new Error(a.error);
205 alice = a.value;
206 const made = await createRepo(app, alice, {
207 name: "lib",
208 visibility: "public",
209 });
210 if (!made.ok) throw new Error(String(made.error));
211 repo = made.value;
212 const opened = openIssue(app, alice, repo, {
213 title: "Tests outside the gate",
214 });
215 if (!opened.ok) throw new Error(opened.error);
216 umbrella = opened.value;
217 });
218
219 afterAll(async () => {
220 await checks.stop();
221 servers.stop();
222 app.close();
223 await rm(dataDir, { recursive: true, force: true });
224 });
225
226 test("a repository that declares no nightly is never run at night", async () => {
227 const made = await commitToBranch(app, alice, repo, {
228 message: "Check only",
229 files: [
230 {
231 path: "forge.json",
232 content: JSON.stringify({ check: { run: "true", install: "" } }),
233 },
234 ],
235 });
236 if (!made.ok) throw new Error(JSON.stringify(made.error));
237 await settled((r) => r.commitOid === made.value.commitOid);
238 expect(await checks.nightly()).toEqual([]);
239 });
240
241 test("nothing is queued while another check waits or runs", async () => {
242 const made = await commitToBranch(app, alice, repo, {
243 message: "Slow check",
244 files: [{ path: "forge.json", content: forgeJson("sleep 1", "true") }],
245 });
246 if (!made.ok) throw new Error(JSON.stringify(made.error));
247 const deadline = Date.now() + 10_000;
248 while (listActive(app.db, "check").length === 0 && Date.now() < deadline)
249 await Bun.sleep(10);
250 expect(listActive(app.db, "check").length).toBeGreaterThan(0);
251 expect(await checks.nightly()).toEqual([]);
252 await settled((r) => r.commitOid === made.value.commitOid);
253 });
254
255 test("a red night opens one issue, under the umbrella, naming each file and its first failing test", async () => {
256 await says([
257 "nightly: pass test/a.test.ts",
258 "nightly: fail test/b.test.ts — b > breaks",
259 "nightly: fail test/c.test.ts — c > breaks too",
260 ]);
261 const run = await nightly();
262 expect(run.state).toBe("failed");
263 const issue = report()!;
264 expect(issue.state).toBe("open");
265 expect(issue.authorId).toBe(alice.id);
266 expect(issue.body).toContain("2 suites outside the check fail");
267 expect(issue.body).toContain("`test/b.test.ts` — b > breaks");
268 expect(issue.body).toContain("`test/c.test.ts` — c > breaks too");
269 expect(issue.body).not.toContain("test/a.test.ts");
270 expect(blockerNumbersFor(app.db, [umbrella.id]).get(umbrella.id)).toEqual([
271 issue.number,
272 ]);
273 // Once a day: asked again the same day, nothing runs.
274 expect(await checks.nightly()).toEqual([]);
275 });
276
277 test("the same red the next night says nothing new", async () => {
278 nightPasses();
279 await nightly();
280 const issue = report()!;
281 expect(issue.state).toBe("open");
282 expect(listComments(app.db, issue.id)).toHaveLength(0);
283 const all = app.db
284 .query<
285 { n: number },
286 [string, string]
287 >("SELECT COUNT(*) AS n FROM issue WHERE repo_id = ?1 AND title = ?2")
288 .get(repo.id, NIGHTLY_TITLE)!;
289 expect(all.n).toBe(1);
290 });
291
292 test("a different red is said once, on the same issue", async () => {
293 await says([
294 "nightly: pass test/b.test.ts",
295 "nightly: fail test/c.test.ts — c > breaks another way",
296 ]);
297 nightPasses();
298 await nightly();
299 const issue = report()!;
300 expect(issue.body).toContain("1 suite outside the check fails");
301 expect(issue.body).toContain("c > breaks another way");
302 expect(issue.body).not.toContain("test/b.test.ts");
303 const comments = listComments(app.db, issue.id);
304 expect(comments).toHaveLength(1);
305 expect(comments[0]!.body).toContain("c > breaks another way");
306 });
307
308 test("a nightly that dies before naming any suite is red, never a pass", async () => {
309 await says([]);
310 // The command now exits non-zero without naming a suite.
311 const made = await commitToBranch(app, alice, repo, {
312 message: "Break the nightly",
313 files: [{ path: "forge.json", content: forgeJson("true", "exit 3") }],
314 });
315 if (!made.ok) throw new Error(JSON.stringify(made.error));
316 await settled(
317 (r) => r.env === "main" && r.commitOid === made.value.commitOid,
318 );
319 nightPasses();
320 const run = await nightly();
321 expect(run.state).toBe("failed");
322 const issue = report()!;
323 expect(issue.state).toBe("open");
324 expect(issue.body).toContain("the nightly itself");
325 });
326
327 test("an all-green night closes it, and says so", async () => {
328 await says([
329 "nightly: pass test/b.test.ts",
330 "nightly: pass test/c.test.ts",
331 ]);
332 nightPasses();
333 const run = await nightly();
334 expect(run.state).toBe("ok");
335 const issue = report()!;
336 expect(issue.state).toBe("closed");
337 const comments = listComments(app.db, issue.id);
338 expect(comments.at(-1)!.body).toContain("passes again (2)");
339 });
340 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs