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

One rule for a check's details, wherever they are read #17767

opened this

Its check is red, 16h 44m ago

check failed: 3 of 24420 tests — "on production's size > a cold /map answers within a few passes over the runs", "surfaces adversarial: web > N+1: a pull's crew activity does not cost more as its agent runs grow" …

sold/check-details → main 6 commits

Review

Sign in to review this change.
34 files changed +719 −173
docs/features/run-logs.md +8
@@ -18,6 +18,14 @@ Every one of these asks first whether the run is in this repository and the view
1818
1919 When a run fails, the forge keeps the one line that says why (`findingsOf` in `src/logs/findings.ts`): the failing test its check named, at that test's own `(fail)` line; else the line the run's verdict quotes; else, for a deploy or an agent's run, the last line that states an error. The feed's post says it and links to it. `GET …/check.txt` says up to five failing tests with the end of each one's output, above the last 80 lines. A word in passing (`0 failed`, a passing test named for an error) is never taken for it.
2020
21 ## A check's kept details
22
23 A failed check keeps its failing tests with their assertions and the end of their output (`checkDetail`). They are read and masked as its log is: each line is masked as it enters (`src/checks/step_lines.ts`), before any cut, and the runs API gives `checkDetail` only to who may read the run's log (null for anyone else). The summary, which names the first failing tests, is public with the run and masked too. A failed test is re-run by the name it printed, held in memory only. The merge queue's gate lines are masked as they enter too (`src/checks/gate_run.ts`).
24
25 An issue or a comment about a failed check names the failing tests and links the run (`src/checks/failure_names.ts`); it carries no assertion and no output. So the full-suite report, the note after three reds, the builder's second "no change" and the sentinel's shared red lead to the run's page, and the batch doctor's hold to the gate's log. Both open for who may read the repository's logs. A crew builder sent back for a red gets the assertion and the output in its brief, read from the run (`src/crew/failure_brief.ts`).
26
27 Kept details get one pass of the same mask (`src/checks/detail_pass.ts`). It starts five minutes after boot. A slice is at most 25 runs, 256 KiB of text or 20 ms, and the wait after it is at least 250 ms, longer while the event loop is late (twenty times its worst lateness of the last ten seconds, at most 30 s). `check-details-pass.json` under the data directory says how far it is, so a restart goes on and a finished pass is not run again.
28
2129 ## When the store is down
2230
2331 A log that fails to archive stays local and the next sweep tries again. The seven-day prune never removes the log of a finished run the store does not hold, and one sweep runs at a time.
src/actions/runs.ts +12 −6
@@ -200,16 +200,22 @@ export function mayReadLogOfRun(
200200 * facts (`canSeeOwnerFacts`), and so is the machinery under it: the agent
201201 * session a follow-up resumes and the node it ran on (#2917). A reader who
202202 * cannot write here gets what ran, why and how it ended, never those — on
203 * every door, since every door reads runs through here.
203 * every door, since every door reads runs through here. A check's kept details
204 * quote its log, so they are for the log's readers (`mayReadRunLog`).
204205 */
205206 export function runForReader(
206207 app: App,
207208 actor: User | undefined,
208209 repo: Repo,
209210 ): (run: Run) => Run {
210 return canSeeOwnerFacts(app.db, repo, actor)
211 ? (run) => run
212 : (run) => ({ ...run, costUsd: 0, turns: 0, sessionId: "", node: "" });
211 const facts = canSeeOwnerFacts(app.db, repo, actor);
212 const details = mayReadRunLog(app, actor, repo);
213 if (facts && details) return (run) => run;
214 return (run) => ({
215 ...run,
216 ...(facts ? {} : { costUsd: 0, turns: 0, sessionId: "", node: "" }),
217 ...(details ? {} : { checkDetail: null }),
218 });
213219 }
214220
215221 export function listRepoRuns(
@@ -244,12 +250,12 @@ export function workingNowCount(app: App, actor: User | undefined, repo: Repo):
244250
245251 /**
246252 * What the runs list shows this reader, before the list is built: whether
247 * they see cost and turns. Call it only for someone who may read runs. The
253 * they see cost and turns, and a check's details. Call it only for someone who may read runs. The
248254 * owner and a stranger never share it.
249255 */
250256 export function runsViewKey(app: App, actor: User | undefined, repo: Repo, options: ListRunsOptions): string {
251257 const facts = canSeeOwnerFacts(app.db, repo, actor);
252 return `${facts ? "f" : "-"}\n${runsMarker(app.db, repo.id, options)}`;
258 return `${facts ? "f" : "-"}${mayReadRunLog(app, actor, repo) ? "l" : "-"}\n${runsMarker(app.db, repo.id, options)}`;
253259 }
254260
255261 /**
src/apps/push_gate.ts +2 −1
@@ -7,6 +7,7 @@
77
88 import { background } from "../perf/jobs.ts";
99 import { parseBunTestFailure } from "../checks/bun-test.ts";
10 import { redactHeld } from "../kernel/log.ts";
1011 import { err, type Result } from "../kernel/result.ts";
1112
1213 /** Whether this deploy waits for its tests before it switches in. */
@@ -19,7 +20,7 @@ export function gatesPush(env: string, reason: string, hasLive: boolean, declare
1920 * `bun test`'s.
2021 */
2122 export function nameFailingTests(error: string, lines: readonly string[]): string {
22 const names = parseBunTestFailure(lines)?.names.slice(0, 3) ?? [];
23 const names = parseBunTestFailure(lines.map((l) => redactHeld(l)))?.names.slice(0, 3) ?? [];
2324 if (names.length === 0) return error;
2425 const head = error.split("\n")[0] ?? error;
2526 return `${head} — failing: ${names.map((n) => `"${n.slice(0, 80)}"`).join(", ")}`;
src/checks/detail_pass.ts added +157
@@ -0,0 +1,157 @@
1 /**
2 * One pass of the log's mask (`redactHeld`) over the check details, summaries and error lines runs
3 * keep. It walks the runs there are when it starts, and `check-details-pass.json` under the data
4 * directory holds how far it is, so a restart goes on and a later boot reads that one file.
5 *
6 * It yields to everything: it starts `FIRST_MS` after boot, a slice ends at `ROWS` runs, `BYTES` of
7 * text or `SLICE_MS` of the thread, whichever is first, and the wait before the next is at least
8 * `PAUSE_MS` and longer while the event loop is late. A slice that fails (a write lock held
9 * elsewhere) is logged and tried again after `FAILED_MS`.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { rename } from "node:fs/promises";
14 import { join } from "node:path";
15 import type { App } from "../app.ts";
16 import { SLICE_MS } from "../kernel/breathe.ts";
17 import { withoutWaiting } from "../kernel/db.ts";
18 import { redactHeld } from "../kernel/log.ts";
19 import { background } from "../perf/jobs.ts";
20 import { currentLoopLag } from "../perf/loop_worst.ts";
21
22 export interface Progress {
23 /** The last run read, and the newest there was when the pass began. */
24 readonly at: string;
25 readonly until: string;
26 readonly done: boolean;
27 readonly read: number;
28 readonly masked: number;
29 /** Details that are not JSON: left as they are. */
30 readonly unread: number;
31 }
32
33 export const FIRST_MS = 5 * 60_000;
34 export const ROWS = 25;
35 export const BYTES = 256 * 1024;
36 export const PAUSE_MS = 250;
37 const PAUSE_MAX_MS = 30_000;
38 const FAILED_MS = 60_000;
39 /** The wait is this many times the loop's worst lateness of the last ten seconds. */
40 const LATE_X = 20;
41
42 /** The wait before the next slice, while the loop is `lagMs` late. */
43 export const pauseFor = (lagMs: number): number => Math.min(PAUSE_MAX_MS, Math.max(PAUSE_MS, Math.ceil(lagMs * LATE_X)));
44
45 /** Every string in a value masked; its keys and shape stay. */
46 function maskDeep(value: unknown): unknown {
47 if (typeof value === "string") return redactHeld(value);
48 if (Array.isArray(value)) return value.map(maskDeep);
49 if (value === null || typeof value !== "object") return value;
50 return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, maskDeep(v)]));
51 }
52
53 interface Row {
54 id: string;
55 check_detail: string;
56 summary: string;
57 error_line: string;
58 }
59
60 export const passFrom = (db: Database): Progress => ({
61 at: "",
62 until: db.query<{ id: string | null }, []>("SELECT MAX(id) AS id FROM run").get()?.id ?? "",
63 done: false,
64 read: 0,
65 masked: 0,
66 unread: 0,
67 });
68
69 /** The next slice, its changes in one transaction; `done` once no run is left. */
70 export function maskSlice(db: Database, p: Progress, now: () => number = () => performance.now()): Progress {
71 // One run a read: a slice never holds more text than it masks.
72 const next = db.query<Row, [string, string]>(
73 "SELECT id, check_detail, summary, error_line FROM run WHERE id > ?1 AND id <= ?2 ORDER BY id LIMIT 1",
74 );
75 const from = now();
76 const changed: { was: Row; now: Row }[] = [];
77 let { at, read, unread } = p;
78 let done = false;
79 for (let rows = 0, bytes = 0; rows < ROWS && bytes < BYTES && (rows === 0 || now() - from < SLICE_MS); rows++) {
80 const r = next.get(at, p.until);
81 if (r === null) {
82 done = true;
83 break;
84 }
85 at = r.id;
86 read++;
87 bytes += r.check_detail.length + r.summary.length + r.error_line.length;
88 let detail = r.check_detail;
89 if (detail !== "")
90 try {
91 const was = JSON.parse(detail) as unknown;
92 const masks = JSON.stringify(maskDeep(was));
93 if (masks !== JSON.stringify(was)) detail = masks;
94 } catch {
95 unread++;
96 }
97 const summary = redactHeld(r.summary);
98 const line = redactHeld(r.error_line);
99 if (detail !== r.check_detail || summary !== r.summary || line !== r.error_line)
100 changed.push({ was: r, now: { id: r.id, check_detail: detail, summary, error_line: line } });
101 }
102 // The write lock is asked for only when there is something to write, once, and never waited for
103 // (`.immediate`: no retry that spins). The engine's thread may have written a run since it was
104 // read: that run is left as it wrote it, which is masked.
105 let masked = p.masked;
106 if (changed.length > 0) {
107 const write = db.query(
108 `UPDATE run SET check_detail = ?2, summary = ?3, error_line = ?4
109 WHERE id = ?1 AND check_detail = ?5 AND summary = ?6 AND error_line = ?7`,
110 );
111 withoutWaiting(db, () =>
112 db.transaction(() => {
113 for (const { was, now: n } of changed)
114 masked += write.run(n.id, n.check_detail, n.summary, n.error_line, was.check_detail, was.summary, was.error_line).changes;
115 }).immediate(),
116 );
117 }
118 return { at, until: p.until, done, read, masked, unread };
119 }
120
121 /** Start the pass on its own timer; the returned function stops it. */
122 export function startDetailPass(app: App, firstMs = FIRST_MS, pause = pauseFor): () => void {
123 const path = join(app.config.dataDir, "check-details-pass.json");
124 let stopped = false;
125 let timer: ReturnType<typeof setTimeout> | undefined;
126 let p: Progress | undefined;
127 const step = async (): Promise<void> => {
128 let wait: number | undefined = FAILED_MS;
129 try {
130 p ??= ((await Bun.file(path).json().catch(() => undefined)) as Progress | undefined) ?? passFrom(app.db);
131 if (stopped || p.done) {
132 wait = undefined;
133 return;
134 }
135 p = maskSlice(app.db, p);
136 await Bun.write(`${path}.tmp`, JSON.stringify(p));
137 await rename(`${path}.tmp`, path);
138 wait = p.done ? undefined : pause(currentLoopLag());
139 if (p.done) app.log.info("kept check details masked", { read: p.read, masked: p.masked, unread: p.unread });
140 } finally {
141 if (wait !== undefined) arm(wait);
142 }
143 };
144 const arm = (ms: number): void => {
145 if (stopped) return;
146 timer = setTimeout(() => {
147 if (stopped) return;
148 void background("kept-details", step, undefined, app);
149 }, ms);
150 timer.unref?.();
151 };
152 arm(firstMs);
153 return () => {
154 stopped = true;
155 clearTimeout(timer);
156 };
157 }
src/checks/doctor.ts +5 −5
@@ -2,7 +2,7 @@
22 * The batch doctor (#7555): a merge-queue gate found one pull red. It classes
33 * the red (`doctor_classify.ts`), and only a functional red of a pull alone
44 * on its merge is held — out of the line, with a comment naming the exact
5 * test, its file, the error line and the command to reproduce, and the pull
5 * test, its file, the gate's log and the command to reproduce, and the pull
66 * handed back to its builder. The hold is "until green": the first check
77 * that passes on a new head lets it go (`actions/holds.ts` `releaseOnGreen`).
88 * A hold already on the pull — a person's above all — is never overwritten.
@@ -70,14 +70,14 @@ function whyLine(d: Diagnosis): string {
7070 return `${HOLD_PREFIX} ${name} fails alone`;
7171 }
7272
73 /** The comment a held pull gets: test, file, error line, command, what lifts it. */
74 export function holdComment(d: Diagnosis, builder: User | undefined): string {
73 /** The comment a held pull gets: test, file, the gate's log, command, what lifts it. */
74 export function holdComment(d: Diagnosis, builder: User | undefined, log?: string): string {
7575 const lines = ["The batch doctor held this pull: it is red on its own merge with main, in a functional test."];
7676 if (d.test !== undefined) {
7777 lines.push("", `- test: \`${d.test.name}\``);
7878 if (d.test.file !== undefined) lines.push(`- file: \`${d.test.file}\``);
7979 }
80 lines.push(`- error: \`${d.probe}\``);
80 if (log !== undefined) lines.push(`- error: in [the gate's log](${log}), for who may read it`);
8181 const cmd = reproduce(d.test);
8282 if (cmd !== undefined) lines.push(`- reproduce: \`${cmd}\``);
8383 lines.push(
@@ -155,7 +155,7 @@ export function treatRed(app: App, repo: Repo, by: User, pull: Pull, red: Red, b
155155 });
156156 if (issue !== undefined) {
157157 const builder = builderOf(app.db, repo, issue);
158 addComment(app, by, repo, issue, holdComment(d, builder));
158 addComment(app, by, repo, issue, holdComment(d, builder, red.log));
159159 if (builder && setAssignee(app.db, issue.id, builder.id))
160160 app.bus.append({
161161 kind: "pull.assigned",
src/checks/failure_names.ts added +20
@@ -0,0 +1,20 @@
1 /**
2 * What an issue or a comment says of a failed check: the failing tests by name and the way to the
3 * run. The assertion and the output stay with the run, for who may read its log.
4 */
5
6 import type { Run } from "../core/runs.ts";
7
8 /** The most names one comment says. */
9 const NAMES = 5;
10
11 /** The failing tests by name; the summary's first line when the run named none. */
12 export function failureNames(run: Pick<Run, "checkDetail" | "summary">): string[] {
13 const names = (run.checkDetail?.names ?? []).filter((n) => n !== "");
14 const said = names.length > 0 ? names : [run.summary.trim().split("\n")[0] || "the check failed"];
15 return [...said.slice(0, NAMES).map((n) => n.slice(0, 200)), ...(said.length > NAMES ? [`and ${said.length - NAMES} more`] : [])];
16 }
17
18 /** The sentence that leads to a run's details. */
19 export const runDetails = (slug: string, runId: string): string =>
20 `The assertion and the output are with [the check run](/${slug}/runs/${runId}), for who may read its log.`;
src/checks/gate_run.ts +2 −1
@@ -8,6 +8,7 @@ import { JOB_VANISHED } from "./job_step.ts";
88 import { gateRunId } from "./queue.ts";
99 import type { LaneState } from "./lane_state.ts";
1010 import { runTier } from "./run_tier.ts";
11 import { redactHeld } from "../kernel/log.ts";
1112
1213 /** A gate this forge would not start, for it is stopping. */
1314 const INTERRUPTED = "this forge is stopping";
@@ -35,7 +36,7 @@ async function gateOnce(
3536 commitOid,
3637 pull,
3738 tier: "full",
38 write: (line) => lines.push(line),
39 write: (line) => lines.push(redactHeld(line)),
3940 signal: controller.signal,
4041 });
4142 if (done.ok) return { ok: true, error: "", lines };
src/checks/job_step.ts +2 −1
@@ -6,6 +6,7 @@
66 */
77 import { JobVanished, runJob, type JobOptions, type JobSpec } from "../cluster/jobs.ts";
88 import { err, ok, type Result } from "../kernel/result.ts";
9 import type { StepLines } from "./step_lines.ts";
910 import type { Placement } from "./placement.ts";
1011
1112 /** What a NetworkPolicy selects a check's pod by (docs/APPS.md, Placement). */
@@ -26,7 +27,7 @@ export async function runJobStep(
2627 timeoutMs: number;
2728 limits: { memoryMiB: number; cpus: number; diskMiB: number };
2829 /** The Job's own output, apart from the echoed commands. */
29 output: string[];
30 output: Pick<StepLines, "push">;
3031 onNode: (node: string) => void;
3132 /** The proxy variables of this run's egress gate (`checks/job_gate.ts`). */
3233 proxy?: Record<string, string>;
src/checks/queue_store.ts +2 −1
@@ -140,7 +140,7 @@ function stepsOf(text: string): RecordedStep[] | undefined {
140140 function verdictOf(text: string): Judged | undefined {
141141 const v = parsed(text);
142142 if (typeof v !== "object" || v === null) return undefined;
143 const { lands, reopen, comment, learn, reason } = v as Record<string, unknown>;
143 const { lands, reopen, comment, learn, reason, log } = v as Record<string, unknown>;
144144 if (lands === true) return { lands: true };
145145 if (lands !== false || reopen !== true || typeof comment !== "string") return undefined;
146146 if (!Array.isArray(learn) || !learn.every((f) => typeof f === "string")) return undefined;
@@ -154,6 +154,7 @@ function verdictOf(text: string): Judged | undefined {
154154 learn: learn as string[],
155155 ...(why === undefined ? {} : { reason: why }),
156156 ...(named === undefined ? {} : { tests: named }),
157 ...(typeof log === "string" ? { log } : {}),
157158 };
158159 }
159160
src/checks/report.ts +10 −26
@@ -15,6 +15,7 @@ import { addComment, createLabel, getLabel, labelsFor, listIssues, setIssueLabel
1515 import { getRepo, type Repo } from "../core/repos.ts";
1616 import { ownRepoPath } from "../kernel/own_repo.ts";
1717 import type { CheckDetail, Run } from "../core/runs.ts";
18 import { runDetails } from "./failure_names.ts";
1819 import { failedTests, fileIssueOnce } from "./flake.ts";
1920 import { isSummaryLine } from "./bun-test.ts";
2021 import { safeFile } from "./verify.ts";
@@ -195,26 +196,9 @@ export function failuresDetail(
195196 }
196197
197198 /**
198 * `text` as a code span or block that nothing in it can close: the fence is longer than any run of
199 * backticks inside.
200 */
201 function fence(text: string): string {
202 const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
203 return "`".repeat(Math.max(3, longest + 1));
204 }
205
206 /**
207 * What a report says of one failing file: each quoted failure, then how to reproduce it (#12295).
199 * How to reproduce one failing file (#12295).
208200 */
209201 export function redBody(detail: CheckDetail | null | undefined, file: string): string {
210 const quotes = (detail?.failures ?? []).filter((f) => f.file === file && f.excerpt !== undefined);
211 const parts: string[] = [];
212 for (const q of quotes) {
213 const output = q.excerpt!.join("\n");
214 const f = fence(output);
215 const head = q.assertion === undefined ? "" : `: ${inline(q.assertion)}`;
216 parts.push(`${inline(q.name)} failed${head}\n\n${f}text\n${output}\n${f}`);
217 }
218202 const shard = detail?.shards?.find((s) => s.file === file);
219203 const repro = [`bun test ./${file}`, `bun test ./${file} ${RERUN}`];
220204 if (shard !== undefined && shard.slice.length > 1 && shard.slice.length <= SLICE_MAX)
@@ -224,13 +208,12 @@ export function redBody(detail: CheckDetail | null | undefined, file: string): s
224208 shard !== undefined && shard.slice.length > 1 ? `beside ${shard.slice.length - 1} other file${shard.slice.length === 2 ? "" : "s"}` : undefined,
225209 detail?.concurrency,
226210 ].filter((s) => s !== undefined);
227 parts.push(
211 return (
228212 `To reproduce:\n\n\`\`\`sh\n${repro.join("\n")}\n\`\`\`\n\n` +
229213 (ran.length === 0
230214 ? "The run's log did not say which shard it ran in."
231 : `The full suite ran it ${ran.join(", ")}${repro.length > 2 ? " (the last command runs that shard as one `bun test`)" : ""}.`),
215 : `The full suite ran it ${ran.join(", ")}${repro.length > 2 ? " (the last command runs that shard as one `bun test`)" : ""}.`)
232216 );
233 return parts.join("\n\n");
234217 }
235218
236219 /** `text` as one inline code span, whatever backticks it holds. */
@@ -284,8 +267,8 @@ function openReports(app: App, repo: Repo): { id: string; number: number; title:
284267 }
285268
286269 /**
287 * What a report says of one red file: its failing tests by name, then the quoted failures and how
288 * to reproduce it.
270 * What a report says of one red file: its failing tests by name and how to reproduce it. What each
271 * said stays with the run (`failure_names.ts`).
289272 */
290273 function fileSection(run: Run, file: string): string {
291274 const names = (run.checkDetail?.failures ?? []).filter((f) => f.file === file).map((f) => f.name);
@@ -329,9 +312,10 @@ export function reportRed(app: App, repo: Repo, run: Run, alone: ReadonlyMap<str
329312 ? `Still red in the full suite (${where}).${fileSection(run, issue.files[0]!)}`
330313 : `Still red in the full suite (${where}): ${issue.files.map((f) => `\`${f}\``).join(", ")}.\n\n` +
331314 issue.files.map((f) => `### \`${f}\`${fileSection(run, f)}`).join("\n\n");
315 const told = `${said}\n\n${runDetails(`${repo.ownerName}/${repo.name}`, run.id)}`;
332316 const body = lifted
333 ? `A second full-suite run is red for it, so it is no longer held as \`${ALONE_GREEN_LABEL}\`: a builder may start it.\n\n${said}`
334 : said;
317 ? `A second full-suite run is red for it, so it is no longer held as \`${ALONE_GREEN_LABEL}\`: a builder may start it.\n\n${told}`
318 : told;
335319 const noted = addComment(app.db, { issueId: issue.id, authorId: repo.ownerId, body });
336320 if (noted.ok)
337321 app.bus.append({
@@ -421,7 +405,7 @@ function fileFresh(
421405 const labelIds = [label?.id, hold?.id].filter((id): id is string => id !== undefined);
422406 const filed = fileIssueOnce(app.db, app.bus, repo, {
423407 title: fresh.length === 1 ? reportTitle(fresh[0]!) : runReportTitle(run.id, fresh.length),
424 body: `${body}\n\nFiles: ${fresh.join(", ")}`,
408 body: `${body}\n\n${runDetails(`${repo.ownerName}/${repo.name}`, run.id)}\n\nFiles: ${fresh.join(", ")}`,
425409 labelIds,
426410 });
427411 const named = fresh.join(", ");
src/checks/run_tier.ts +7 −5
@@ -47,6 +47,7 @@ import { tryRunner } from "./tier_runner.ts";
4747 import { judgeLentGreen, type LentGreen } from "../actions/runners.ts";
4848 import { runInstall } from "./tier_install.ts";
4949 import { settleFlakes } from "./tier_flake.ts";
50 import { StepLines } from "./step_lines.ts";
5051 import { deepsecStep } from "./deepsec_step.ts";
5152 import { pickSubscription } from "../core/subscriptions.ts";
5253 import { checksRoot, reclaimIfFull, removeRunDir } from "./sweep.ts";
@@ -292,7 +293,8 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
292293 ...stepFloorEnv({ alone: floor !== undefined, inCell: cell !== undefined, cellsFloored: cell?.floor !== undefined || cellsFloored() }),
293294 });
294295 let ran: Result<void, string>;
295 const checkLines: string[] = [];
296 const said = new StepLines();
297 const checkLines = said.masked;
296298 // A bisection step runs only some files: what it shows green says nothing of the rest.
297299 const wholeVerify = x.tier === "verify" && x.only === undefined;
298300 // The gate is held to what a cell holds: the forge, the registry and
@@ -321,7 +323,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
321323 commands: manifest.install === null ? [step] : [manifest.install, step],
322324 env,
323325 log: write,
324 output: checkLines,
326 output: said,
325327 signal,
326328 timeoutMs: manifest.timeout * 1000,
327329 limits: resolveLimits("step", manifest.limits),
@@ -341,7 +343,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
341343 if (installed !== undefined) return lostCheckout(dir, installed);
342344 if (runnerRed !== undefined) {
343345 // The runner's check is this check's: its lines and its red, for the failed tests alone.
344 checkLines.push(...runnerRed.lines);
346 for (const line of runnerRed.lines) said.push(line);
345347 ran = err(runnerRed.error);
346348 } else {
347349 // The check step's own lines are kept beside what `write` already
@@ -354,7 +356,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
354356 cwd: dir,
355357 env,
356358 log: (line) => {
357 if (sawEcho) checkLines.push(line);
359 if (sawEcho) said.push(line);
358360 sawEcho = true;
359361 write(line);
360362 },
@@ -369,7 +371,7 @@ async function runTierOnce(lane: LaneState, x: Execution, sample: (green: LentGr
369371 ran = await settleFlakes(
370372 lane,
371373 x,
372 { run, repo, bare, dir, env, cell, manifest, tip, inJob: job !== undefined, checkLines, write, signal },
374 { run, repo, bare, dir, env, cell, manifest, tip, inJob: job !== undefined, checkLines, rawLines: said.raw, write, signal },
373375 ran,
374376 );
375377 if (!ran.ok && !existsSync(dir)) return { ok: false, error: LOST_CHECKOUT, infrastructure: true };
src/checks/runner_step.ts +4 −3
@@ -36,6 +36,7 @@ import {
3636 type RunnerStepResult,
3737 type RunnerStepSpec,
3838 } from "./runner_jobs.ts";
39 import type { StepLines } from "./step_lines.ts";
3940 import { summariseCheckFailure } from "./summary.ts";
4041
4142 /** How long a job waits for a runner to take it before the forge runs the check itself. */
@@ -87,7 +88,7 @@ export interface RunnerStepInput {
8788 readonly job: Omit<RunnerJob, "id">;
8889 readonly log: (line: string) => void;
8990 /** The check step's own output, apart from the echoed command. */
90 readonly output: string[];
91 readonly output: Pick<StepLines, "push" | "clear">;
9192 readonly signal: AbortSignal;
9293 /** The pull's author, as a lent runner's authors scope reads it. */
9394 readonly author?: string | undefined;
@@ -222,8 +223,7 @@ export async function runRunnerStep(
222223 ? `runner ${holder} stopped the job (${view.result.slice(13)}): queued again, and that is not a try, nor a result`
223224 : `runner ${holder} went silent: the job is queued again, and that is not a try`,
224225 );
225 // What a half-run printed is not the check's output.
226 input.output.length = 0;
226 input.output.clear();
227227 sawEcho = false;
228228 holder = "";
229229 offeredAt = now();
@@ -297,6 +297,7 @@ export interface RunnerRed {
297297 readonly alone: true;
298298 /** The runner that ran it, as its log names it. */
299299 readonly runner: string;
300 /** As printed, in memory alone: `run_tier.ts` masks each as it takes it. */
300301 readonly lines: readonly string[];
301302 readonly error: string;
302303 }
src/checks/shared_red.ts −29
@@ -351,32 +351,3 @@ function lanes(db: Database, rows: readonly Row[], now: number): Row[] {
351351 return !pullsOwnBy(mains.get(r.repo_id), db, r.repo_id, r.test, now - SHARED_WINDOW_MS);
352352 });
353353 }
354
355 /** The most lines of a failing test's output a finding quotes. */
356 export const ASSERTION_LINES = 20;
357
358 const RESULT = /^\((?:pass|fail|skip|todo)\) /;
359 const FILE_HEADER = /^\S+\.test\.[cm]?[jt]sx?:$/;
360 /** bun's closing tally: a `(fail)` line under it is the recap, not the report. */
361 const TALLY = /^\s*\d+ (?:pass|fail|skip|todo)$|^\d+ tests? failed:$|^Ran \d+ tests? /;
362
363 /**
364 * What bun printed for one failing test: the lines above its `(fail)` line,
365 * back to the result or file header before them, at most
366 * {@link ASSERTION_LINES}. The newest report wins; bun's recap of `(fail)`
367 * lines under its tally quotes nothing. Empty when no report is in `lines`.
368 */
369 export function assertionLines(lines: readonly string[], test: string): string[] {
370 for (let at = lines.length - 1; at >= 0; at--) {
371 const line = lines[at]!;
372 if (line !== `(fail) ${test}` && !line.startsWith(`(fail) ${test} [`)) continue;
373 let from = at;
374 while (from > 0 && at - from < ASSERTION_LINES && !RESULT.test(lines[from - 1]!) && !FILE_HEADER.test(lines[from - 1]!))
375 from--;
376 const block = lines.slice(from, at);
377 if (block.some((l) => TALLY.test(l))) continue;
378 const quoted = block.filter((l) => l.trim() !== "");
379 if (quoted.length > 0) return quoted;
380 }
381 return [];
382 }
src/checks/step_lines.ts added +25
@@ -0,0 +1,25 @@
1 /**
2 * A check step's own output, kept while the check runs. Every line is masked as it enters, as the
3 * run's log masks it, before anything cuts or stores it: what a check keeps is made from `masked`.
4 */
5
6 import { redactHeld } from "../kernel/log.ts";
7
8 export class StepLines {
9 readonly masked: string[] = [];
10 /** As printed, in memory alone: a failed test is re-run by the name it has (`tier_flake.ts`). */
11 readonly raw: string[] = [];
12
13 push(...lines: readonly string[]): void {
14 for (const line of lines) {
15 this.masked.push(redactHeld(line));
16 this.raw.push(line);
17 }
18 }
19
20 /** What a half-run printed is not the check's output. */
21 clear(): void {
22 this.masked.length = 0;
23 this.raw.length = 0;
24 }
25 }
src/checks/summary.ts +5 −3
@@ -9,6 +9,7 @@
99
1010 import { STEP_TOOK_LINE, TOOK_LINE } from "./took_line.ts";
1111 import type { CheckDetail, Run } from "../core/runs.ts";
12 import { redactHeld } from "../kernel/log.ts";
1213 import { parseBunTestFailure } from "./bun-test.ts";
1314 import { fullShard, OUT_OF_ROOM, TEMP_FULL } from "./disk_full.ts";
1415 import { oneLine } from "./words.ts";
@@ -83,8 +84,8 @@ export interface CheckFailure {
8384 }
8485
8586 /**
86 * `lines` is the check step's own output, nothing from `install` mixed in
87 * (`checks/service.ts` keeps them apart already). `fallback` is what
87 * `lines` is the check step's own output, masked (`step_lines.ts`), nothing from `install` mixed in
88 * (`checks/service.ts` keeps them apart already). `error` is what
8889 * `runStep` says when a step exits non-zero — "check exited with code 1",
8990 * sometimes with a reason it found on its own — used only when this
9091 * output named nothing better, so a truthful "no output at all" is never
@@ -97,8 +98,9 @@ export interface CheckFailure {
9798 */
9899 export function summariseCheckFailure(
99100 lines: readonly string[],
100 fallback: string,
101 error: string,
101102 ): CheckFailure {
103 const fallback = redactHeld(error);
102104 const parsed = parseBunTestFailure(lines);
103105 // A shard that ran out of temp space is marked on the detail, not worded
104106 // into the summary: the crew reads the mark, the summary keeps the failures.
src/checks/tier_flake.ts +6 −3
@@ -8,6 +8,7 @@ import { parseBunTestFailure } from "./bun-test.ts";
88 import { recordCrashFlakes, passedAlone, recordFlakes, rerunCommand, rerunnable, pullOwnsRed } from "./flake.ts";
99 import { childEnv, runStep } from "../apps/process.ts";
1010 import type { CellSpec } from "../apps/contain.ts";
11 import { redactHeld } from "../kernel/log.ts";
1112 import type { Result } from "../kernel/result.ts";
1213 import type { LaneState } from "./lane_state.ts";
1314 import type { Execution } from "./local_runner.ts";
@@ -29,7 +30,9 @@ export interface FlakeCheck {
2930 readonly tip: string | undefined;
3031 /** Whether the check ran in a cluster Job, where it is not re-run here. */
3132 readonly inJob: boolean;
33 /** The step's output, masked, and as printed: the second only finds the test to re-run. */
3234 readonly checkLines: readonly string[];
35 readonly rawLines: readonly string[];
3336 readonly write: (line: string) => void;
3437 readonly signal: AbortSignal;
3538 }
@@ -46,7 +49,7 @@ export async function settleFlakes(
4649 result: Result<void, string>,
4750 ): Promise<Result<void, string>> {
4851 const { app } = lane;
49 const { run, repo, bare, dir, env, cell, manifest, tip, inJob, checkLines, write, signal } = c;
52 const { run, repo, bare, dir, env, cell, manifest, tip, inJob, checkLines, rawLines, write, signal } = c;
5053 let ran = result;
5154 // A file the gate cleared because it passed alone is still a failure
5255 // to track: the cell cannot reach the forge, so it is filed from here.
@@ -76,7 +79,7 @@ export async function settleFlakes(
7679 // A pull's red is the same unless the pull touched the test (#7426).
7780 if (!ran.ok && !inJob && (x.isMain === true || tip !== undefined)) {
7881 try {
79 let tests = rerunnable(checkLines, parseBunTestFailure(checkLines));
82 let tests = rerunnable(rawLines, parseBunTestFailure(rawLines));
8083 if (tests !== undefined && x.isMain !== true) {
8184 const diff = await runGit(
8285 ["diff", "--name-only", "-z", `${tip}...${x.commitOid}`],
@@ -118,7 +121,7 @@ export async function settleFlakes(
118121 }
119122 }
120123 if (alone) {
121 recordFlakes(app.db, app.bus, repo, tests, { runId: run.id, commit: run.commitOid, pull: x.isMain !== true });
124 recordFlakes(app.db, app.bus, repo, tests.map((t) => ({ ...t, name: redactHeld(t.name) })), { runId: run.id, commit: run.commitOid, pull: x.isMain !== true });
122125 for (const t of tests) write(`flake: ${t.file} > ${t.name} passed alone`);
123126 write(`flaky: ${tests.map((t) => `"${t.name}"`).join(", ")} failed in the full run and passed alone; recorded, ${x.isMain === true ? "main" : "the check"} stays green`);
124127 ran = { ok: true, value: undefined };
src/checks/tier_runner.ts +5 −3
@@ -10,6 +10,7 @@ import { recordCrashFlakes, recordFlakes, rerunnable } from "./flake.ts";
1010 import { handoverEnv, handsTimesBack } from "./handover.ts";
1111 import { capacityEnv, checkShardCpus, egressSetting, shardsInForce, shardsLine } from "../core/capacity.ts";
1212 import { resolveLimits, STEP_HOSTS } from "../apps/contain.ts";
13 import { StepLines } from "./step_lines.ts";
1314 import { HANDED_OVER, runRunnerStep, runnerTakes, runnerVerdict, type RunnerRed } from "./runner_step.ts";
1415 import type { CheckOutcome } from "./runner.ts";
1516 import type { LaneState } from "./lane_state.ts";
@@ -99,7 +100,8 @@ export async function tryRunner(
99100 write("placement: runner; the install command cannot be run without its scripts; running here");
100101 return undefined;
101102 }
102 const lines: string[] = [];
103 const said = new StepLines();
104 const lines = said.masked;
103105 // The shard count an admin set reaches a runner's check as it does one run here (#14844); the
104106 // default is sized as one run here is (`checkShardCpus`), never from the runner machine's CPUs.
105107 const effective = resolveLimits("step", manifest.limits);
@@ -161,7 +163,7 @@ export async function tryRunner(
161163 ...(handsTimesBack(x) ? { hands: HAND_FILES } : {}),
162164 },
163165 log: write,
164 output: lines,
166 output: said,
165167 signal,
166168 waitMs: lane.placement.waitMs,
167169 // A release stopping this forge leaves the job with its runner (`adoptRunnerJobs`).
@@ -189,7 +191,7 @@ export async function tryRunner(
189191 if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`);
190192 else if ("alone" in verdict) {
191193 write(`placement: runner; one or two tests failed on runner ${verdict.runner}: only they are re-run here, alone, never the whole check`);
192 return verdict;
194 return { ...verdict, lines: said.raw };
193195 } else if (verdict.ok && sent.taken && sampleLentGreen(app, sent.runnerId, sent.jobId)) {
194196 // A share of a lent runner's greens is run here as well (`lent_scope.ts`): this forge's
195197 // own verdict is the one that stands, and a red pauses the runner (`judgeLentGreen`).
src/checks/tiers.ts +3
@@ -565,6 +565,8 @@ export type Judged =
565565 readonly reason?: GateReason;
566566 /** What its tests said: the counts and the failing tests by name (#6739). */
567567 readonly tests?: GateTests;
568 /** Where the gate's log is read, by who may read it. */
569 readonly log?: string;
568570 };
569571
570572 /**
@@ -602,5 +604,6 @@ export function landVerdict(
602604 learn: [...new Set(failedFiles)],
603605 ...(reason === undefined ? {} : { reason }),
604606 ...(tests === undefined ? {} : { tests }),
607 ...(logLink === undefined ? {} : { log: logLink }),
605608 };
606609 }
src/core/runs.ts +3 −1
@@ -12,6 +12,7 @@ import type { Database } from "bun:sqlite";
1212 import { hostname } from "node:os";
1313 import { BUDGET_PREFIX } from "../kernel/budgets.ts";
1414 import { id } from "../kernel/id.ts";
15 import { redactHeld } from "../kernel/log.ts";
1516 import { appendRun } from "./ledger.ts";
1617 import { meterOf } from "./run_compute.ts";
1718
@@ -416,7 +417,8 @@ export function finishRun(
416417 .run(
417418 runId,
418419 outcome.state,
419 outcome.summary.slice(0, 500),
420 // Read with the run by anyone who may read the repository: masked as its log is, before the cut.
421 redactHeld(outcome.summary).slice(0, 500),
420422 outcome.sessionId ?? null,
421423 outcome.costUsd ?? null,
422424 outcome.turns ?? null,
src/crew/failure_quote.ts +2 −1
@@ -1,5 +1,6 @@
11 /**
2 * What a failed check says, quoted for a person or a builder (#12968): the failing test, its
2 * What a failed check says, quoted in a builder's brief (#12968); an issue or a comment names the
3 * tests instead (`checks/failure_names.ts`): the failing test, its
34 * assertion and the end of its own output. Plain data in, one string out; a run that named no
45 * test is quoted by its summary.
56 */
src/crew/no_change.ts +4 −5
@@ -4,8 +4,8 @@
44 *
55 * - First "no change": a re-check of that head is queued (reason `no_change`). Green, the pull
66 * moves on; red on a named test, the red goes back to the builder with that test's assertion.
7 * - Second "no change" on a head whose re-check was red: the failure is quoted once, in a
8 * comment that names the head, and the pull waits for a person (the asks carry it). A later
7 * - Second "no change" on a head whose re-check was red: the failing tests are named once, in
8 * a comment that names the head and links the run, and the pull waits for a person (the asks carry it). A later
99 * "no change" on that head finds the comment and says nothing again. It is never closed.
1010 * - A re-check the forge cut short proved nothing: it is queued again and is no try.
1111 */
@@ -20,8 +20,7 @@ import type { Repo } from "../core/repos.ts";
2020 import { checkSummary, getRun, isCut, type Run } from "../core/runs.ts";
2121 import { getUserById } from "../core/users.ts";
2222 import { createLog } from "../kernel/log.ts";
23 import { failingLines, failureQuote } from "./failure_quote.ts";
24 import { readRunLog } from "../runs/log.ts";
23 import { failureNames, runDetails } from "../checks/failure_names.ts";
2524
2625 const log = createLog("no-change");
2726
@@ -81,7 +80,7 @@ export function afterNoChange(app: App, repo: Repo, issueId: string): NoChangeMo
8180 by,
8281 repo,
8382 issue,
84 `${quotedMark(pull.headOid)} is red again after a re-check:\n\n${failureQuote(prior, failingLines(readRunLog(app.config.dataDir, prior.id, 32 * 1024).lines))}\n\nIt stays open for a person or a new head.`,
83 `${quotedMark(pull.headOid)} is red again after a re-check:\n\n${failureNames(prior).join("\n")}\n\n${runDetails(`${repo.ownerName}/${repo.name}`, prior.id)}\n\nIt stays open for a person or a new head.`,
8584 );
8685 log.info("no change twice on a red", { pull: pull.number });
8786 return "quoted";
src/crew/red_thrice.ts +12 −14
@@ -1,6 +1,6 @@
11 /**
22 * A crew pull red on three checks in a row is not built a fourth time (#15819). Its issue is held
3 * as `red_thrice`, gets one note quoting the last failure, and is owed to the planner to split or
3 * as `red_thrice`, gets one note naming the last failure, and is owed to the planner to split or
44 * rewrite. Counts red checks only: the reviewer's changes-requested path is `guard.ts`'s.
55 *
66 * The streak is the pull's failed checks since its last green one. A check the forge cut short,
@@ -13,7 +13,7 @@ import { getIssue } from "../core/issues.ts";
1313 import type { Pull } from "../core/pulls.ts";
1414 import type { Repo } from "../core/repos.ts";
1515 import { getRun, isCut } from "../core/runs.ts";
16 import { failureQuote } from "./failure_quote.ts";
16 import { failureNames, runDetails } from "../checks/failure_names.ts";
1717 import { proposedWork } from "./direct.ts";
1818
1919 /** Failed checks in a row at which a pull goes back to the planner. */
@@ -22,17 +22,15 @@ export const RED_STRIKES = 3;
2222 /** What the note starts with, before the pull it names. */
2323 export const RED_THRICE_NOTE = "Red on three checks:";
2424
25 /** How many lines of the last failure the note quotes. */
26 const QUOTE_LINES = 6;
27
2825 export interface RedThrice {
2926 readonly pull: Pull;
3027 /** The failed checks in the streak. */
3128 readonly failures: number;
3229 /** When the oldest of them was queued. */
3330 readonly since: string;
34 /** The first lines of the newest failure. */
35 readonly quote: string;
31 /** The newest failure: its run, and its failing tests by name. */
32 readonly runId: string;
33 readonly failing: readonly string[];
3634 }
3735
3836 /** The streak on one pull, or undefined when it is under the strikes. */
@@ -55,8 +53,7 @@ export function redStreak(db: Database, pull: Pull): Omit<RedThrice, "pull"> | u
5553 }
5654 if (failures < RED_STRIKES || newest === undefined) return undefined;
5755 const run = getRun(db, newest);
58 const lines = (run === undefined ? "the check failed" : failureQuote(run)).split("\n");
59 return { failures, since, quote: lines.slice(0, QUOTE_LINES).join("\n") };
56 return { failures, since, runId: newest, failing: run === undefined ? ["the check failed"] : failureNames(run) };
6057 }
6158
6259 /** The issues whose open crew pull is red on three checks, by issue number. */
@@ -70,13 +67,14 @@ export function redThrice(db: Database, repo: Repo): Map<number, RedThrice> {
7067 return out;
7168 }
7269
73 /** The note on the issue: which pull, how often, and what the last failure said. */
74 export function redThriceNote(r: RedThrice): string {
75 const quoted = r.quote.split("\n").map((l) => (l.trim() === "" ? ">" : `> ${l.replace(/\s+$/, "")}`));
70 /** The note on the issue: which pull, how often, and what the last failure was. */
71 export function redThriceNote(slug: string, r: RedThrice): string {
7672 return [
7773 `${RED_THRICE_NOTE} pull #${r.pull.number} failed its check ${r.failures} times in a row, so no builder starts on it again. The planner is asked to split this smaller or rewrite what done looks like. The last failure:`,
7874 "",
79 ...quoted,
75 ...r.failing.map((l) => `> ${l.trim()}`),
76 "",
77 runDetails(slug, r.runId),
8078 ].join("\n");
8179 }
8280
@@ -106,7 +104,7 @@ export function redThricePulls(db: Database, repo: Repo) {
106104 repoId: repo.id,
107105 number,
108106 title: issue.title,
109 reasons: [r.quote.split("\n")[0] ?? ""],
107 reasons: [r.failing[0] ?? ""],
110108 byAgent: true,
111109 at,
112110 });
src/crew/sentinel.ts +17 −18
@@ -37,7 +37,6 @@ import { QUEUE_AGENT_FULL, QUEUE_CHECK_FULL, QUEUE_WAIT_MAX_MS } from "../kernel
3737 import { STALE_AFTER_MS } from "../runs/lease.ts";
3838 import { isOutageSummary } from "./network.ts";
3939 import {
40 assertionLines,
4140 mainVerdict,
4241 pullsFailedSince,
4342 pullsOwn,
@@ -45,7 +44,6 @@ import {
4544 SHARED_WINDOW_MS,
4645 sharedRuns,
4746 } from "../checks/shared_red.ts";
48 import { readRunLogTail } from "../runs/log.ts";
4947 import { clip } from "../text/clip.ts";
5048 import { forgeCeiling } from "../flow/ceiling.ts";
5149 import { personSpoke } from "./person_spoke.ts";
@@ -586,7 +584,7 @@ export function degradedCauses(
586584 `first open: ${new Date(d.first).toISOString()}`,
587585 `total: ${minutes} minutes in the day`,
588586 `href: ${d.href}`,
589 ...sharedLines(db, cause, now, forgeRepoId, dataDir),
587 ...sharedLines(db, cause, now, forgeRepoId),
590588 // /system is admin people only: the finding carries what grew, so a builder can name it
591589 // (#14362).
592590 ...(cause === "memory-growth" ? memoryEvidence(watch, dataDir, from) : []),
@@ -666,7 +664,7 @@ export function budgetBreaches(db: Database, now: number, forgeRepoId?: string,
666664 `since: ${new Date(s.openedAt).toISOString()}`,
667665 `href: ${s.href}`,
668666 ...runLogLines(db, s.cause, veiled),
669 ...sharedLines(db, s.cause, now, forgeRepoId, dataDir),
667 ...sharedLines(db, s.cause, now, forgeRepoId),
670668 ],
671669 pillar: "P0 Trust: the forge says when it is not well, and is well again",
672670 kind: "defect",
@@ -702,22 +700,18 @@ function runLogLines(db: Database, cause: string, veiled: boolean): string[] {
702700 return [`run ${id}: ${run.state}${run.summary && !veiled ? `, ${oneLine(run.summary)}` : ""}`];
703701 }
704702
705 /** How many log lines a shared finding reads from the end of its newest run's log: never the whole file. */
706 const SHARED_LOG_TAIL = 400;
707
708703 /**
709704 * What a builder needs to reproduce a `shared:` cause (#8286): the pulls
710705 * and runs that failed its test, newest first, the base the newest merged,
711 * the newest one's assertion lines from the tail of its log, and whether
712 * main's newest check passes the test. A private repository's pulls and log
713 * lines stay out of a finding filed anywhere but in that repository.
706 * and whether main's newest check passes the test. A private repository's
707 * pulls stay out of a finding filed anywhere but in that repository. What the
708 * test said stays with the run: `runPathOf` leads there.
714709 */
715710 function sharedLines(
716711 db: Database,
717712 cause: string,
718713 now: number,
719714 forgeRepoId: string | undefined,
720 dataDir: string | undefined,
721715 ): string[] {
722716 if (!cause.startsWith("shared:")) return [];
723717 const repoId = cause.split(":")[1] ?? "";
@@ -732,12 +726,7 @@ function sharedLines(
732726 `test: ${oneLine(found.test)}`,
733727 ...found.runs.map((r) => `failed: pull #${r.pull}, check run ${r.runId}`),
734728 ];
735 if (newest !== undefined) {
736 out.push(`base: ${newest.baseOid || "none recorded"} (run ${newest.runId})`);
737 const quoted =
738 dataDir === undefined ? [] : assertionLines(readRunLogTail(dataDir, newest.runId, SHARED_LOG_TAIL).lines, found.test);
739 out.push(...quoted.map((l) => `log: ${clip(oneLine(l), QUOTE_MAX)}`));
740 }
729 if (newest !== undefined) out.push(`base: ${newest.baseOid || "none recorded"} (run ${newest.runId})`);
741730 const main = mainVerdict(db, repoId, found.test);
742731 out.push(
743732 main === undefined
@@ -749,6 +738,16 @@ function sharedLines(
749738 return out;
750739 }
751740
741 /**
742 * The way to the newest run a shared finding names. Built of the forge's own names and added after
743 * `scrub`, which takes a path this long for a token.
744 */
745 function runPathOf(db: Database, f: Finding): string[] {
746 const run = f.evidence.map((e) => /^failed: pull #\d+, check run (\w+)$/.exec(e)?.[1]).find((id) => id !== undefined);
747 const repoId = /^shared:([^:]+):/.exec(f.cause ?? "")?.[1];
748 return run === undefined || repoId === undefined ? [] : [`log: /${repoSlug(db, repoId)}/runs/${run}`];
749 }
750
752751 /** Everything the sentinel reads, in one pass. */
753752 export function findFaults(
754753 db: Database,
@@ -777,7 +776,7 @@ export function findFaults(
777776 .map((f) => ({
778777 ...f,
779778 title: scrub(f.title),
780 evidence: f.evidence.map(scrub),
779 evidence: [...f.evidence.map(scrub), ...runPathOf(db, f)],
781780 }));
782781 }
783782
src/crew/unstick.ts +2 −2
@@ -21,7 +21,7 @@ import { landedUnder, stallReason } from "./stalls.ts";
2121 const log = createLog("autonomy");
2222
2323 /**
24 * One note on each issue whose pull is red on three checks (`red_thrice.ts`), quoting the last
24 * One note on each issue whose pull is red on three checks (`red_thrice.ts`), naming the last
2525 * failure; a streak already noted is not noted again. Returns how many notes it wrote.
2626 */
2727 export function noteRedThrice(app: App, repo: Repo, by: User): number {
@@ -29,7 +29,7 @@ export function noteRedThrice(app: App, repo: Repo, by: User): number {
2929 for (const [number, r] of redThrice(app.db, repo)) {
3030 const issue = getIssue(app.db, repo.id, number);
3131 if (issue === undefined || issue.state !== "open" || notedAt(app.db, issue.id, r) !== undefined) continue;
32 if (!addComment(app, by, repo, issue, redThriceNote(r)).ok) continue;
32 if (!addComment(app, by, repo, issue, redThriceNote(`${repo.ownerName}/${repo.name}`, r)).ok) continue;
3333 log.info("red on three checks; handed to the planner", { repo: `${repo.ownerName}/${repo.name}`, issue: number, pull: r.pull.number });
3434 wrote++;
3535 }
src/http/api.ts +4 −2
@@ -3675,6 +3675,8 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
36753675 // hidden by a deploy that ended after it (#17705). `runs` keeps every run.
36763676 const summary = checkSummaryOf(runs);
36773677 const latest = summary.run ?? undefined;
3678 // Each run as this reader may see it, as the runs doors give it.
3679 const forReader = runForReader(ctx.app, ctx.auth.user, found.repo);
36783680 // With no run, the reason: a bare "none" does not say whether to wait, approve or add a
36793681 // check.
36803682 const why = latest === undefined ? await whyNoCheck(ctx.app, found.repo, found.pull, head) : undefined;
@@ -3689,11 +3691,11 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
36893691 state: summary.state,
36903692 required: found.repo.requireChecks,
36913693 ...(why === undefined ? {} : { why }),
3692 run: latest ?? null,
3694 run: latest === undefined ? null : forReader(latest),
36933695 looks: latest
36943696 ? looksOfCheck(ctx.app, ctx.auth.user, found.repo, { id: latest.id, commitOid: latest.commitOid })
36953697 : [],
3696 runs,
3698 runs: runs.map(forReader),
36973699 }),
36983700 );
36993701 },
src/main.ts +4
@@ -55,6 +55,7 @@ import { startAdvisoryFeed } from "./core/advisory_feed.ts";
5555 import { followTick, watchLandings } from "./spawn/app_follow.ts";
5656 import { startReachWatch } from "./spawn/reach.ts";
5757 import { isHookName, runHookClient } from "./git/hooks.ts";
58 import { startDetailPass } from "./checks/detail_pass.ts";
5859 import { drainBudgets } from "./drain.ts";
5960 import { drainStreams } from "./http/sse.ts";
6061 import { serve } from "./http/server.ts";
@@ -802,6 +803,8 @@ const [mirrorOut, mirrorPulls, looks, talkLive, errorFixes, maintain, probes, ni
802803 // /metrics kept as a series every 30 s for /explore/series (series/sampler.ts).
803804 startService(app.log, "seriesSampler", async () => (await import("./series/sampler.ts")).startSeriesSampler(app)),
804805 ]);
806 // Runs' kept check details get one pass of the log's mask, from five minutes after boot (`checks/detail_pass.ts`).
807 const stopDetailPass = startDetailPass(app);
805808 // Off unless FORGE_HEAP_CAPTURE_DIR is set, for a copy of production (perf/heap_capture.ts).
806809 const stopHeapCapture = startHeapCapture(process.env, (m) => app.log.info(m));
807810 // The starting boards, once each (actions/boards.ts).
@@ -1385,6 +1388,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
13851388 memorySampler?.stop(),
13861389 seriesSampler?.stop(),
13871390 stopHeapCapture(),
1391 stopDetailPass(),
13881392 engineStopped,
13891393 ])
13901394 .catch(() => {})
test/check-details-pass.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * The pass over kept check details yields to everything (`src/checks/detail_pass.ts`): it starts
3 * minutes after boot, a slice is bounded by runs, by text and by the clock, and the wait between
4 * two grows while the event loop is late. At 50,000 runs no slice holds the thread for 50 ms.
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 { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { BYTES, FIRST_MS, maskSlice, passFrom, PAUSE_MS, pauseFor, ROWS } from "../src/checks/detail_pass.ts";
13 import { createRun } from "../src/core/runs.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18
19 const SHAPE = `forge_${"a1B2".repeat(10)}`;
20 let dir = "";
21 let app: App;
22 beforeAll(async () => {
23 dir = await mkdtemp(join(tmpdir(), "check-details-pass-"));
24 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
25 const alice = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
26 if (!alice.ok) throw new Error(alice.error);
27 const made = await createRepo(app, alice.value, { name: "many", visibility: "public" });
28 if (!made.ok) throw new Error("repo");
29 createRun(app.db, { repoId: made.value.id, kind: "check", env: "main", commitOid: "a".repeat(40), summary: "" });
30 });
31 afterAll(async () => {
32 app.close();
33 await rm(dir, { recursive: true, force: true });
34 });
35
36 /** Exactly `n` runs, ids in order; `detail(i)` is SQL over `i`. */
37 function fill(n: number, detail: string): void {
38 const cols = app.db.query<{ name: string }, []>("SELECT name FROM pragma_table_info('run')").all().map((c) => c.name);
39 const put = cols.map((c) => (c === "id" ? "'r' || printf('%08d', i)" : c === "check_detail" ? detail : c === "summary" ? "'check failed: 1 of 2 tests'" : `t.${c}`));
40 app.db.run("CREATE TEMP TABLE IF NOT EXISTS seed AS SELECT * FROM run LIMIT 1");
41 app.db.run("DELETE FROM run");
42 app.db.run(`WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < ${n}) INSERT INTO run (${cols.join(", ")}) SELECT ${put.join(", ")} FROM n, temp.seed t`);
43 }
44
45 const still = (): number => 0;
46 const detailOf = (failures: number, lines: number, width: number, secret: string): string =>
47 JSON.stringify({
48 passed: 1,
49 failed: failures,
50 names: ["adds"],
51 failures: Array.from({ length: failures }, (_, i) => ({ file: "t/a.test.ts", name: `adds ${i}`, assertion: "error: no", excerpt: [`got ${secret}`, ...Array.from({ length: lines }, () => "word ".repeat(width / 5))] })),
52 });
53
54 test("it starts five minutes after boot at the soonest, and waits longer while the loop is late", () => {
55 expect(FIRST_MS).toBeGreaterThanOrEqual(5 * 60_000);
56 expect(PAUSE_MS).toBeGreaterThanOrEqual(250);
57 expect(pauseFor(0)).toBe(PAUSE_MS);
58 expect(pauseFor(100)).toBeGreaterThan(pauseFor(20));
59 expect(pauseFor(1_000)).toBeGreaterThanOrEqual(10_000);
60 });
61
62 test("a slice ends at 25 runs, at 256 KiB of text or with its time, whichever is first", () => {
63 expect([ROWS, BYTES]).toEqual([25, 256 * 1024]);
64 fill(60, "''");
65 const first = maskSlice(app.db, passFrom(app.db), still);
66 expect(first).toMatchObject({ read: 25, at: "r00000025", done: false });
67 const last = maskSlice(app.db, maskSlice(app.db, first, still), still);
68 expect(last).toMatchObject({ read: 60, masked: 0, done: true });
69 // 100 KiB a run: the third passes the bound and is the last.
70 fill(10, `'"' || printf('%.102400c', 'x') || '"'`);
71 expect(maskSlice(app.db, passFrom(app.db), still).read).toBe(3);
72 // A clock that says each run took 30 ms: one run a slice, never none.
73 fill(10, "''");
74 let t = 0;
75 expect(maskSlice(app.db, passFrom(app.db), () => (t += 30)).read).toBe(1);
76 });
77
78 test("50,000 runs: every one is masked and no slice holds the thread for 50 ms", () => {
79 const red = detailOf(1, 30, 80, SHAPE);
80 const worst = detailOf(40, 30, 160, SHAPE);
81 // One run in ten is red; a stretch of fifty carries the most a check keeps.
82 fill(50_000, `CASE WHEN i BETWEEN 20000 AND 20049 THEN '${worst}' WHEN i % 10 = 0 THEN '${red}' ELSE '' END`);
83 app.db.run("CREATE TEMP TABLE was AS SELECT id, check_detail FROM run WHERE check_detail <> ''");
84 app.db.run("CREATE INDEX temp.was_id ON was (id)");
85 const took: number[] = [];
86 let p = passFrom(app.db);
87 while (!p.done) {
88 const at = p.at;
89 let best = Infinity;
90 let next = p;
91 // A slice over the bound is put back and timed again: the machine's own pause is not its work.
92 for (let tries = 0; tries < 4 && best >= 50; tries++) {
93 if (tries > 0) app.db.query("UPDATE run SET check_detail = (SELECT check_detail FROM temp.was WHERE was.id = run.id) WHERE id > ?1 AND id <= ?2 AND check_detail <> ''").run(at, next.at);
94 const from = performance.now();
95 next = maskSlice(app.db, p);
96 best = Math.min(best, performance.now() - from);
97 }
98 took.push(best);
99 p = next;
100 }
101 const sorted = [...took].sort((a, b) => a - b);
102 console.log(`kept details: ${p.read} runs, ${p.masked} masked, ${took.length} slices, ${(took.reduce((a, b) => a + b, 0) / 1000).toFixed(2)} s of work, median ${sorted[took.length >> 1]!.toFixed(2)} ms, worst ${sorted.at(-1)!.toFixed(1)} ms`);
103 expect(p).toMatchObject({ read: 50_000, masked: 5_045, unread: 0 });
104 expect(app.db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM run WHERE instr(check_detail, ?1) > 0").get(SHAPE)!.n).toBe(0);
105 expect(sorted.at(-1)!).toBeLessThan(50);
106 }, 120_000);
test/check-details.test.ts added +245
@@ -0,0 +1,245 @@
1 /**
2 * A check's kept details are read and masked as its log is (`checks/step_lines.ts`): each line is
3 * masked as it enters, before any cut; the API gives the details to who may read the log; what is
4 * kept already gets one pass (`checks/detail_pass.ts`). A failed test is still re-run by its own name.
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 { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { startDetailPass } from "../src/checks/detail_pass.ts";
14 import { failuresDetail } from "../src/checks/report.ts";
15 import type { runRunnerStep } from "../src/checks/runner_step.ts";
16 import { startChecks } from "../src/checks/service.ts";
17 import { StepLines } from "../src/checks/step_lines.ts";
18 import { createRun, finishRun, claimRun, getRun, getRunErrorLine, listRuns, setRunErrorLine, type Run } from "../src/core/runs.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { forgeHttp } from "../src/http/server.ts";
22 import { err, ok } from "../src/kernel/result.ts";
23 import { holdValues, releaseValues } from "../src/kernel/log.ts";
24 import { jobWatchOf, runningOf } from "../src/perf/jobs.ts";
25 import { readRunLog } from "../src/runs/log.ts";
26 import { quietLogs } from "./helpers/globals.ts";
27 import { waitFor } from "./helpers/poll.ts";
28
29 quietLogs();
30
31 const VALUE = "s3cr3t-Value-91x";
32 const SHAPE = `forge_${"a1B2".repeat(10)}`;
33 const priorCells = process.env["FORGE_CELLS"]; // env-restored: afterAll
34 let dir = "";
35 let app: App;
36 let alice: User;
37 let bob: User;
38 beforeAll(async () => {
39 process.env["FORGE_CELLS"] = "off"; // env-restored: afterAll
40 dir = await mkdtemp(join(tmpdir(), "check-details-"));
41 app = createApp({ dataDir: dir, port: 0, host: "forge.test" });
42 const make = async (username: string, adminIfFirst: boolean): Promise<User> => {
43 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst });
44 if (!u.ok) throw new Error(u.error);
45 return u.value;
46 };
47 alice = await make("alice", true);
48 bob = await make("bob", false);
49 holdValues("check-details", [VALUE]);
50 });
51 afterAll(async () => {
52 releaseValues("check-details");
53 if (priorCells === undefined) delete process.env["FORGE_CELLS"];
54 else process.env["FORGE_CELLS"] = priorCells;
55 app.close();
56 await rm(dir, { recursive: true, force: true });
57 });
58
59 /** A test named with a secret, whose assertion puts one across the cut at 200. */
60 const said = (name: string, secret: string): string[] => [
61 "t/a.test.ts:",
62 `error: ${"x".repeat(185)} ${secret} end`,
63 `got ${secret}`,
64 `(fail) ${name}`,
65 " 41 pass",
66 " 1 fail",
67 "Ran 42 tests across 9 files.",
68 ];
69
70 test("a line is masked as it enters, before the cut at 200", () => {
71 for (const secret of [VALUE, SHAPE]) {
72 const lines = new StepLines();
73 for (const l of said(`signs in with ${secret}`, secret)) lines.push(l);
74 const detail = JSON.stringify(failuresDetail(undefined, ["t/a.test.ts"], lines.masked));
75 expect(detail).toContain("got [redacted]");
76 expect(detail).toContain("signs in with [redacted]");
77 expect(detail).not.toContain(secret.slice(0, 8));
78 expect(lines.raw[3]).toBe(`(fail) signs in with ${secret}`);
79 // A runner that went silent: what its half-run printed goes, in both.
80 lines.clear();
81 expect([lines.masked, lines.raw]).toEqual([[], []]);
82 }
83 });
84
85 /** The checks on a pull give the same details to the same people. */
86 async function pullDoor(slug: string, number: number): Promise<void> {
87 const http = forgeHttp(app);
88 const get = async (who?: User): Promise<string> =>
89 (
90 await http.handle(
91 new Request(`http://forge.test/api/v1/repos/alice/${slug}/pulls/${String(number)}/checks`, who === undefined ? {} : { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } }),
92 )
93 ).text();
94 expect(await get(alice)).toContain('"excerpt"');
95 for (const who of [undefined, bob]) {
96 const body = await get(who);
97 expect(body).toContain('"state":"failed"');
98 expect(body).toContain('"checkDetail":null');
99 expect(body).not.toContain('"excerpt"');
100 }
101 }
102
103 /** A pull's check whose step says `lines` here or on a runner; the test's file passes alone or not. */
104 async function checked(slug: string, where: "here" | "runner", name: string, secret: string, passes: boolean): Promise<{ run: Run; log: string; gate: string }> {
105 const made = await createRepo(app, alice, { name: slug, visibility: "public" });
106 if (!made.ok) throw new Error("repo");
107 const repo = made.value;
108 const spec = `import { test, expect } from "bun:test";\ntest(${JSON.stringify(name)}, () => { expect(1).toBe(${passes ? "1" : "2"}); });\n`;
109 const base = await commitToBranch(app, alice, repo, {
110 message: "base",
111 files: [
112 { path: "forge.json", content: JSON.stringify({ check: { run: "true", install: "" } }) },
113 { path: "t/a.test.ts", content: spec },
114 ],
115 });
116 if (!base.ok) throw new Error(JSON.stringify(base.error));
117 const topic = await commitToBranch(app, alice, repo, { branch: "topic", message: "topic", files: [{ path: "notes.txt", content: "x" }] });
118 if (!topic.ok) throw new Error(JSON.stringify(topic.error));
119 const runnerStep: typeof runRunnerStep = async (_app, input) => {
120 for (const line of said(name, secret)) {
121 input.output.push(line);
122 input.log(line);
123 }
124 return { taken: true, ran: err("check exited with code 1"), failed: "check", runner: "local-1", contained: true, note: "" };
125 };
126 const checks = startChecks(app, {
127 forgeUrl: "http://forge.test",
128 concurrency: 1,
129 ...(where === "runner" ? { placement: { mode: "runner" as const, waitMs: 300 }, runnerStep } : {}),
130 checkStep: async (_step, command, options) => {
131 if (where === "runner") return ok();
132 for (const line of [`$ ${command}`, ...said(name, secret)]) options.log(line);
133 return err("check exited with code 1");
134 },
135 });
136 try {
137 const pull = await openPull(app, alice, repo, { title: "t", body: "", baseBranch: "main", headBranch: "topic" });
138 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
139 const finished = () => listRuns(app.db, repo.id, { kind: "check", limit: 50 }).find((r) => r.issueId !== null && (r.state === "ok" || r.state === "failed"));
140 expect(await waitFor(() => finished() !== undefined, { within: 40_000 })).toBe(true);
141 const run = finished()!;
142 // The merge queue's gate of the same commit, whose lines are kept and read too.
143 const gate = run.state === "failed" && where === "here" ? (await checks.gate(repo, pull.value, topic.value.commitOid)).lines.join("\n") : "";
144 return { run, log: readRunLog(app.config.dataDir, run.id).lines.join("\n"), gate };
145 } finally {
146 await checks.stop();
147 }
148 }
149
150 for (const where of ["here", "runner"] as const) {
151 test(`a check that ran ${where}: its details and summary are masked, and its failed test is re-run by its own name`, async () => {
152 for (const [i, secret] of [VALUE, SHAPE].entries()) {
153 const { run, log, gate } = await checked(`red-${where}-${String(i)}`, where, `signs in with ${secret}`, secret, false);
154 expect(run.state).toBe("failed");
155 expect(log).toContain(`"signs in with [redacted]" fails alone too`);
156 expect(run.summary).toContain("signs in with [redacted]");
157 expect(run.checkDetail?.names).toEqual(["signs in with [redacted]"]);
158 expect(JSON.stringify(run.checkDetail)).toContain("got [redacted]");
159 if (where === "here") expect(gate).toContain("signs in with [redacted]");
160 for (const kept of [run.summary, JSON.stringify(run.checkDetail), log, gate]) expect(kept).not.toContain(secret.slice(0, 8));
161 }
162 }, 120_000);
163
164 test(`a check that ran ${where}: a test whose name is masked passes alone, so the check is green and the flake is kept masked`, async () => {
165 const { run } = await checked(`flake-${where}`, where, `signs in with ${SHAPE}`, SHAPE, true);
166 expect(run.state).toBe("ok");
167 const kept = app.db.query<{ test: string }, [string]>("SELECT test FROM check_flake WHERE run_id = ?1").all(run.id);
168 expect(kept).toEqual([{ test: "signs in with [redacted]" }]);
169 }, 60_000);
170 }
171
172 test("the API gives a run's details to who may read its log, and to nobody else", async () => {
173 const made = await createRepo(app, alice, { name: "doors", visibility: "public" });
174 if (!made.ok) throw new Error("repo");
175 const detail = { passed: 1, failed: 1, names: ["adds"], failures: [{ file: "t/a.test.ts", name: "adds", excerpt: ["got 3"] }] };
176 const run = createRun(app.db, { repoId: made.value.id, kind: "check", env: "main", commitOid: "a".repeat(40), summary: "" });
177 claimRun(app.db, run.id);
178 finishRun(app.db, run.id, { state: "failed", summary: "check failed: 1 of 2 tests", checkDetail: detail });
179 const http = forgeHttp(app);
180 const get = async (path: string, who?: User) =>
181 http.handle(new Request(`http://forge.test/api/v1/repos/alice/doors${path}`, who === undefined ? {} : { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } }));
182 for (const path of ["/runs", `/runs/${run.id}`]) {
183 expect(await (await get(path, alice)).text()).toContain("got 3");
184 for (const who of [undefined, bob]) {
185 const res = await get(path, who);
186 const body = await res.text();
187 expect(res.status).toBe(200);
188 expect(body).toContain("1 of 2 tests");
189 expect(body).toContain('"checkDetail":null');
190 expect(body).not.toContain("got 3");
191 }
192 }
193 expect((await get(`/runs/${run.id}/log`, bob)).status).toBe(404);
194 // The checks on a pull give the same details to the same people.
195 for (const branch of [undefined, "topic"]) {
196 const put = await commitToBranch(app, alice, made.value, { ...(branch === undefined ? {} : { branch }), message: "m", files: [{ path: `${branch ?? "base"}.txt`, content: "x" }] });
197 if (!put.ok) throw new Error(JSON.stringify(put.error));
198 }
199 const pull = await openPull(app, alice, made.value, { title: "t", body: "", baseBranch: "main", headBranch: "topic" });
200 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
201 const its = createRun(app.db, { repoId: made.value.id, kind: "check", env: "pull-1", issueId: pull.value.id, commitOid: pull.value.headOid, summary: "" });
202 claimRun(app.db, its.id);
203 finishRun(app.db, its.id, { state: "failed", summary: "check failed: 1 of 2 tests", checkDetail: detail });
204 await pullDoor("doors", pull.value.number);
205 });
206
207 test("what is kept already is masked once, and counted", async () => {
208 const made = await createRepo(app, alice, { name: "kept", visibility: "public" });
209 if (!made.ok) throw new Error("repo");
210 const keep = (secret: string): string => {
211 const run = createRun(app.db, { repoId: made.value.id, kind: "check", env: "main", commitOid: "b".repeat(40), summary: "" });
212 claimRun(app.db, run.id);
213 finishRun(app.db, run.id, { state: "failed", summary: "x" });
214 const detail = { passed: 1, failed: 1, names: [`a "${secret}" name`], failures: [{ file: "t/a.test.ts", name: "adds", assertion: `error: ${secret}`, excerpt: [`got ${secret}`] }], diskFree: 0.5 };
215 app.db.query("UPDATE run SET check_detail = ?2, summary = ?3 WHERE id = ?1").run(run.id, JSON.stringify(detail), `check failed: ${secret}`);
216 setRunErrorLine(app.db, run.id, `error: ${secret}`, 4);
217 return run.id;
218 };
219 const ids = [keep(VALUE), keep(SHAPE), keep("plain")];
220 app.db.query("UPDATE run SET check_detail = ?2 WHERE id = ?1").run(ids[2]!, "{not json");
221 const before = app.db.query("SELECT COUNT(*) AS n FROM run").get() as { n: number };
222 // A new handle each time: a BunFile keeps the size it first saw.
223 const record = () => Bun.file(join(dir, "check-details-pass.json")).text().catch(() => "{}");
224 const kept = async () => JSON.parse(await record()) as { done?: boolean };
225 const stop = startDetailPass(app, 0, () => 0);
226 expect(await waitFor(async () => (await kept()).done === true, { within: 20_000 })).toBe(true);
227 stop();
228 expect(await kept()).toMatchObject({ read: before.n, masked: 2, unread: 1 });
229 for (const id of ids.slice(0, 2)) {
230 const run = getRun(app.db, id)!;
231 expect(run.checkDetail).toEqual({ passed: 1, failed: 1, names: ['a "[redacted]" name'], failures: [{ file: "t/a.test.ts", name: "adds", assertion: "error: [redacted]", excerpt: ["got [redacted]"] }], diskFree: 0.5 });
232 expect(run.summary).toBe("check failed: [redacted]");
233 expect(getRunErrorLine(app.db, id)).toEqual({ text: "error: [redacted]", at: 4 });
234 }
235 // Once: a run kept after it is another path's to mask, and a later boot leaves it and the record.
236 const was = await record();
237 const later = keep(SHAPE);
238 const from = performance.now();
239 const again = startDetailPass(app, 0, () => 0);
240 const looked = () => jobWatchOf(app).across(from, performance.now()).includes("kept-details") && !runningOf(app).some((j) => j.name === "kept-details");
241 expect(await waitFor(looked, { within: 20_000 })).toBe(true);
242 again();
243 expect(await record()).toBe(was);
244 expect(getRun(app.db, later)!.summary).toContain(SHAPE);
245 }, 30_000);
test/crew-red-thrice.test.ts +3 −1
@@ -61,7 +61,7 @@ describe("a pull red on three checks goes back to the planner", () => {
6161 finishRun(app.db, run.id, {
6262 state,
6363 summary: state === "ok" ? "ok" : "check failed: 1 test failed",
64 ...(state === "failed" ? { checkDetail: { passed: 1, failed: 1, names: [`widget renders ${n}`] } } : {}),
64 ...(state === "failed" ? { checkDetail: { passed: 1, failed: 1, names: [`widget renders ${n}`], failures: [{ file: "t/w.test.ts", name: `widget renders ${n}`, assertion: "error: no widget", excerpt: ["got none"] }] } } : {}),
6565 });
6666 }
6767
@@ -112,6 +112,8 @@ describe("a pull red on three checks goes back to the planner", () => {
112112 expect(noteRedThrice(app, repo, me)).toBe(0); // once, not on every tick
113113 expect(notes(three)).toHaveLength(1);
114114 expect(notes(three)[0]!.body).toContain("> widget renders 3");
115 expect(notes(three)[0]!.body).toContain("(/alice/engine/runs/");
116 for (const said of ["no widget", "got none"]) expect(notes(three)[0]!.body).not.toContain(said);
115117 expect(notes(two)).toHaveLength(0);
116118
117119 // The planner is owed it, once the note is said.
test/doctor-culprit.test.ts +5 −3
@@ -12,9 +12,10 @@ describe("the batch doctor and a red culprit", () => {
1212 });
1313 afterAll(() => w.close());
1414
15 test("a functional red alone is held with a comment naming test, file, error and command; the batch is recorded", async () => {
15 test("a functional red alone is held with a comment naming test, file, the gate's log and command; the batch is recorded", async () => {
1616 const pull = await w.pull("bad.ts");
17 const red = redFor("adds two numbers", "test/add.test.ts", "error: expect(received).toBe(expected)");
17 const log = "/api/v1/repos/alice/app/gates/g1/log";
18 const red = { ...redFor("adds two numbers", "test/add.test.ts", "error: expect(received).toBe(expected)"), log };
1819 expect(treatRed(w.app, w.repo, w.alice, pull, red, "b".repeat(40))).toBe("held");
1920 const hold = getHold(w.app.db, pull.id)!;
2021 expect(hold.until).toBe("green");
@@ -25,7 +26,8 @@ describe("the batch doctor and a red culprit", () => {
2526 const said = listComments(w.app.db, pull.id).map((c) => c.body).join("\n");
2627 expect(said).toContain("adds two numbers");
2728 expect(said).toContain("test/add.test.ts");
28 expect(said).toContain("expect(received).toBe(expected)");
29 expect(said).toContain(`(${log})`);
30 expect(said).not.toContain("expect(received)");
2931 expect(said).toContain("bun test ./test/add.test.ts");
3032 const [run] = doctorRuns(w.app.db, w.repo.id);
3133 expect(run).toMatchObject({ culprit: pull.number, class: "functional", action: "held" });
test/full-suite-report.test.ts +15 −13
@@ -476,15 +476,15 @@ describe("the report", () => {
476476 return getRun(app.db, run.id)!;
477477 };
478478
479 test("the issue quotes the failing assertion and its output, fenced so nothing in it closes the block (#12295)", () => {
480 reportRed(app, repo, redFrom(SHARD_LOG, "a".repeat(40)));
479 test("the issue names the failing test and links the run; what it said stays with the run", () => {
480 const run = redFrom(SHARD_LOG, "a".repeat(40));
481 reportRed(app, repo, run);
481482 const body = reports()[0]!.body;
482 expect(body).toContain("error: expect(received).toBe(expected)");
483 expect(body).toContain("noise before the error\n4 | test(");
484 expect(body).toContain("Received: \"<b>`x`</b>```\"");
485 expect(body).toContain("````text\n");
486 expect(body).not.toContain("(pass) a > ok");
487 expect(body.indexOf("error:")).toBeLessThan(body.indexOf("Files: test/a.test.ts"));
483 expect(body).toContain("a > one");
484 expect(body).toContain(`(/${repo.ownerName}/${repo.name}/runs/${run.id})`);
485 for (const said of ["error: expect", "noise before the error", "Received:", "```text"]) expect(body).not.toContain(said);
486 expect(body.trimEnd()).toEndWith("Files: test/a.test.ts");
487 expect(run.checkDetail!.failures![0]!.excerpt!.join("\n")).toContain("noise before the error");
488488 });
489489
490490 test("the issue says how to reproduce it: the file, ten reruns, and the shard and concurrency it ran under (#12295)", () => {
@@ -496,12 +496,15 @@ describe("the report", () => {
496496 expect(body).toContain("in shard 7/120, beside 1 other file, 4 files at a time");
497497 });
498498
499 test("each Still red comment carries the excerpt and the commands too (#12295)", () => {
499 test("each Still red comment carries the name, the run and the commands too (#12295)", () => {
500500 reportRed(app, repo, redFrom(SHARD_LOG, "a".repeat(40)));
501 reportRed(app, repo, redFrom(SHARD_LOG, "b".repeat(40)));
501 const second = redFrom(SHARD_LOG, "b".repeat(40));
502 reportRed(app, repo, second);
502503 const [comment] = listComments(app.db, reports()[0]!.id);
503504 expect(comment!.body).toStartWith("Still red in the full suite");
504 expect(comment!.body).toContain("error: expect(received).toBe(expected)");
505 expect(comment!.body).toContain("a > one");
506 expect(comment!.body).toContain(`/runs/${second.id})`);
507 expect(comment!.body).not.toContain("error: expect");
505508 expect(comment!.body).toContain(`bun test ./test/a.test.ts ${RERUN}`);
506509 });
507510
@@ -518,10 +521,9 @@ describe("the report", () => {
518521 expect(body).toContain(`bun test ./test/a.test.ts ${RERUN}`);
519522 });
520523
521 test("a failure that printed nothing is named, not quoted with its bare (fail) line", () => {
524 test("a failure that printed nothing keeps its name alone", () => {
522525 const detail = redDetail(undefined, ["test/a.test.ts"], ["test/a.test.ts:", "(fail) a > one", "1 tests failed:"])!;
523526 expect(detail.failures).toEqual([{ file: "test/a.test.ts", name: "a > one" }]);
524 expect(redBody(detail, "test/a.test.ts")).not.toContain("```text");
525527 });
526528
527529 test("a log with no shard banner still says how to reproduce, and that the shard is unknown", () => {
test/job-slices.test.ts +3
@@ -67,6 +67,7 @@ import { nightlyDue } from "../src/checks/scan_store.ts";
6767 import { startNotifier } from "../src/crew/notify.ts";
6868 import { pullDue } from "../src/apps/pull_schedule.ts";
6969 import { startMaintain } from "../src/maintain/runner.ts";
70 import { maskSlice, passFrom } from "../src/checks/detail_pass.ts";
7071 import { retentionJobs } from "../src/system/retention.ts";
7172 import { returnSnoozed } from "../src/actions/gate_snooze.ts";
7273 import { synced } from "../src/games/notify.ts";
@@ -290,6 +291,8 @@ function jobs(): Record<string, () => unknown> {
290291 "retention-deploys": () => retention.deploys.slice(Date.now()),
291292 "retention-telemetry": () => retention.telemetry.slice(Date.now() + 40 * 86_400_000),
292293 "retention-vacuum": () => retention.vacuum.slice(Date.now()),
294 // One slice; check-details-pass.test.ts times 50,000 runs.
295 "kept-details": () => maskSlice(app.db, passFrom(app.db)),
293296 };
294297 }
295298
test/no_change_recheck.test.ts +4 −3
@@ -87,7 +87,7 @@ test("a deploy that came up is never offered as the failure", () => {
8787 expect(taskPrompt({ ...base, noFailure: true } as unknown as TaskInput)).toContain("no check of its head is recorded as failed");
8888 });
8989
90 test("a cut check is no failure; a builder's no change re-checks the head, and a second quotes the failure", () => {
90 test("a cut check is no failure; a builder's no change re-checks the head, and a second names the failure and links the run", () => {
9191 app.db.query("DELETE FROM run WHERE issue_id = ?1").run(pull.id);
9292 const cut = run("check");
9393 mark(cut.id, "failed", "interrupted by a restart; queued again");
@@ -100,14 +100,15 @@ test("a cut check is no failure; a builder's no change re-checks the head, and a
100100 expect(noChange()).toBe(false);
101101 expect(rechecks()).toHaveLength(1);
102102
103 // It ends red on a named test: the stall is counted, and a second no change quotes it.
103 // It ends red on a named test: the stall is counted, and a second no change names it.
104104 mark(rechecks()[0]!.id, "failed", "failed: engine > adds up", JSON.stringify({ names: ["engine > adds up"], failures: [{ file: "a.test.ts", name: "engine > adds up", assertion: "expected 2, got 3" }] }));
105105 expect(redUnattended(app, repo, [])).toBe(1);
106106 expect(noChange()).toBe(true);
107107 expect(rechecks()).toHaveLength(1);
108108 const said = listComments(app.db, pull.id).map((c) => c.body).join("\n");
109109 expect(said).toContain("engine > adds up");
110 expect(said).toContain("expected 2, got 3");
110 expect(said).toContain(`/runs/${rechecks()[0]!.id})`);
111 expect(said).not.toContain("expected 2, got 3");
111112
112113 // A third no change on the same head finds the quote and says nothing again.
113114 const before = listComments(app.db, pull.id).length;
test/sentinel-shared-evidence.test.ts +15 −23
@@ -1,9 +1,8 @@
11 /**
22 * A shared-red finding a builder can reproduce (#8286): it names the pulls
3 * and check runs that failed the test, quotes the newest run's assertion
4 * lines from the tail of its log, carries the base that run merged, and says
5 * whether main's newest check passes. A private repository's pulls and log
6 * lines never reach a finding filed elsewhere.
3 * and check runs that failed the test, carries the base the newest merged, leads to that run, and
4 * says whether main's newest check passes. What the test said stays with the run. A private
5 * repository's pulls never reach a finding filed elsewhere.
76 */
87 import { beforeEach, describe, expect, test } from "bun:test";
98 import type { Database } from "bun:sqlite";
@@ -13,8 +12,8 @@ import { join } from "node:path";
1312 import { migrations } from "../src/core/schema.ts";
1413 import { openDb } from "../src/kernel/db.ts";
1514 import { claimRun, createRun, finishRun, setRunBase, type Run } from "../src/core/runs.ts";
16 import { assertionLines, sharedCause } from "../src/checks/shared_red.ts";
17 import { budgetBreaches, degradedCauses } from "../src/crew/sentinel.ts";
15 import { sharedCause } from "../src/checks/shared_red.ts";
16 import { budgetBreaches, degradedCauses, findFaults } from "../src/crew/sentinel.ts";
1817 import { runLogPath } from "../src/runs/log.ts";
1918
2019 const TEST = "board > a card keeps its place";
@@ -70,8 +69,8 @@ const open = (now: number) =>
7069 now - 20 * 60_000,
7170 ]);
7271
73 describe("a shared-red finding names its pulls and quotes the failure (#8286)", () => {
74 test("three failed checks: the pulls, their runs newest first, the newest's lines and base", () => {
72 describe("a shared-red finding names its pulls and the run (#8286)", () => {
73 test("three failed checks: the pulls, their runs newest first, the newest's base, and no line of its log", () => {
7574 const runs = recordThree();
7675 const now = Date.now();
7776 open(now);
@@ -85,12 +84,13 @@ describe("a shared-red finding names its pulls and quotes the failure (#8286)",
8584 `failed: pull #41, check run ${runs[0]!.id}`,
8685 ]);
8786 expect(ev).toContain(`base: ${"d".repeat(40)} (run ${runs[2]!.id})`);
88 expect(ev.filter((l) => l.startsWith("log: "))).toEqual([
89 "log: error: expect(received).toBe(expected)",
90 'log: Expected: "third"',
91 'log: Received: "moved"',
92 "log: at <anonymous> (test/board.test.ts:12:5)",
93 ]);
87 const filed = findFaults(db, now, "r1", dataDir).filter((f) => f.evidence.includes(`test: ${TEST}`));
88 expect(filed.length).toBeGreaterThan(0);
89 for (const f of filed) {
90 expect(f.evidence.filter((l) => l.startsWith("log: "))).toEqual([`log: /trevato/forge/runs/${runs[2]!.id}`]);
91 expect(f.evidence.join("\n")).not.toContain("expect(received)");
92 expect(f.evidence.join("\n")).not.toContain("third");
93 }
9494 expect(ev).toContain("main: no check of main recorded");
9595 // The day's degraded finding for the same cause carries the same evidence.
9696 expect(degradedCauses(db, now, "r1", dataDir)[0]!.evidence.filter((l) => l.startsWith("failed: "))).toEqual(failed);
@@ -154,7 +154,7 @@ describe("a shared-red finding names its pulls and quotes the failure (#8286)",
154154 expect(budgetBreaches(db, now, "r1", dataDir)[0]!.evidence).toContain(`base: none recorded (run ${last.id})`);
155155 });
156156
157 test("a private repository's pulls and log lines stay out of a finding filed elsewhere", () => {
157 test("a private repository's pulls and runs stay out of a finding filed elsewhere", () => {
158158 db.run("UPDATE repo SET visibility = 'private' WHERE id = 'r1'");
159159 recordThree();
160160 const now = Date.now();
@@ -164,12 +164,4 @@ describe("a shared-red finding names its pulls and quotes the failure (#8286)",
164164 // Filed in that same repository, its own readers see it.
165165 expect(budgetBreaches(db, now, "r1", dataDir)[0]!.evidence.some((l) => l.startsWith("failed: "))).toBe(true);
166166 });
167
168 test("the quote stops at twenty lines and skips bun's recap", () => {
169 const long = ["x.test.ts:", ...Array.from({ length: 30 }, (_, i) => `line ${i}`), `(fail) ${TEST}`, " 0 pass", " 1 fail", "1 tests failed:", `(fail) ${TEST}`];
170 const quoted = assertionLines(long, TEST);
171 expect(quoted).toHaveLength(20);
172 expect(quoted.at(-1)).toBe("line 29");
173 expect(assertionLines(["1 tests failed:", `(fail) ${TEST}`], TEST)).toEqual([]);
174 });
175167 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs