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

A pull red on three checks is not built a fourth time: it goes back to the planner with its failures quoted #15829

Merged opened this

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

Merged

scout/forge:scout/15819-a-pull-red-on-three-checks-is-not-built → main 0 commits fork

  • Merged. scout/15819-a-pull-red-on-three-checks-is-not-built was merged into main as e96e144.

Review

Sign in to review this change.
5 files changed +277 −1
src/crew/autonomy.ts +20 −1
@@ -150,6 +150,7 @@ import { sweepStaleReds } from "./stale_reds.ts";
150150 import { sweepStranded } from "./stranded.ts";
151151 import { afterNoChange } from "./no_change.ts";
152152 import { redUnattended } from "./red_unattended.ts";
153 import { notedAt, redThrice, redThriceNote, redThricePulls } from "./red_thrice.ts";
153154 import { parkPull, strikeNote } from "./park_pull.ts";
154155 import { keepVerdict } from "../flow/culprits.ts";
155156 import { sweepRepeats } from "./repeat_checks.ts";
@@ -509,6 +510,8 @@ async function driveOnce(
509510 const sorted = () => heldBy(app, repo, readyNow(repoGraph(app.db, repo.id, { sealed: true })), crew, active);
510511 let held = sorted();
511512 if (freeParked(app, repo, by, held) > 0) held = sorted();
513 // A pull red on three checks is said once on its issue and owed to the planner.
514 noteRedThrice(app, repo, by);
512515 // An issue a landing left open with boxes is given the reviewer's pass once (#8682).
513516 await passLanded(app, repo, held.by.landed);
514517 holdHot(
@@ -585,6 +588,22 @@ async function driveOnce(
585588 return redUnattended(app, repo, active) > 0 ? "stalled" : "idle";
586589 }
587590
591 /**
592 * One note on each issue whose pull is red on three checks (`red_thrice.ts`), quoting the last
593 * failure; a streak already noted is not noted again. Returns how many notes it wrote.
594 */
595 export function noteRedThrice(app: App, repo: Repo, by: User): number {
596 let wrote = 0;
597 for (const [number, r] of redThrice(app.db, repo)) {
598 const issue = getIssue(app.db, repo.id, number);
599 if (issue === undefined || issue.state !== "open" || notedAt(app.db, issue.id, r) !== undefined) continue;
600 if (!addComment(app, by, repo, issue, redThriceNote(r)).ok) continue;
601 log.info("red on three checks; handed to the planner", { repo: `${repo.ownerName}/${repo.name}`, issue: number, pull: r.pull.number });
602 wrote++;
603 }
604 return wrote;
605 }
606
588607 /**
589608 * A ready issue assigned to a planner or a reviewer with no run on it is
590609 * parked on a crew member that never builds it — a sentinel's finding, a
@@ -783,7 +802,7 @@ async function planIfThin(
783802 // The direction is the planner's own issue: a park on it (the breaker's, for runs that repeat)
784803 // hands the planner nothing it has not read, so it owes no pass. Counted, each park bought
785804 // another empty pass, which bought another park.
786 const handed = [...parkedTwice(app.db, [repo]), ...handedOverPulls(app.db, repo)].filter(
805 const handed = [...parkedTwice(app.db, [repo]), ...handedOverPulls(app.db, repo), ...redThricePulls(app.db, repo)].filter(
787806 (h) => h.issueId !== repo.directionIssueId,
788807 );
789808 const limbs = pendingReplans(app.db, repo);
src/crew/dispatch.ts +7
@@ -16,6 +16,7 @@ import { freshPullFor } from "./fresh_pull.ts";
1616 import { betCapHold } from "./bet_cap_hold.ts";
1717 import { weekHold } from "./week_hold.ts";
1818 import { weekFor, weekSpent } from "./week_read.ts";
19 import { redStreak } from "./red_thrice.ts";
1920 import { twinNote, twinOf, type Twin } from "./twin.ts";
2021 import { NO_MERGE } from "../checks/merged.ts";
2122 import { resolveListConflicts } from "../actions/list-conflicts.ts";
@@ -1006,6 +1007,12 @@ function answerRed(
10061007 ): void {
10071008 const since = lastHumanWord(app, issue, agent);
10081009 const runId = payload["runId"];
1010 // Red on three checks in a row: no fourth rework; the tick notes the issue for the planner.
1011 const pull = getPull(app.db, repo.id, issue.number);
1012 if (pull?.authorIsAgent && redStreak(app.db, pull) !== undefined) {
1013 log.info("check failed a third time; the pull goes back to the planner", { issue: issue.number });
1014 return;
1015 }
10091016 if (sameRedTwice(app.db, issue.id, since)) {
10101017 const run = typeof runId === "string" ? getRun(app.db, runId) : undefined;
10111018 log.info("check failed the same way after a rework; the pull stays open and waits for a person", {
src/crew/held.ts +8
@@ -7,6 +7,8 @@
77 *
88 * The filters, in the order they are asked:
99 * - `running`: a run is in flight on it.
10 * - `red_thrice`: its open crew pull failed its check three times in a row: it is
11 * the planner's to split or rewrite, not a builder's fourth try (`red_thrice.ts`).
1012 * - `open_pull`: an open pull already proposes it (`direct.ts`), or one a
1113 * builder opened in the last 10 minutes (`fresh_pull.ts`).
1214 * - `planner`: the planner or a reviewer holds it, not a builder. The tick
@@ -66,6 +68,7 @@ import { landedUnanswered, landingDoneAnswered } from "./landed.ts";
6668 import { NO_KEY_HELD, repoHasNoKey } from "./no_key.ts";
6769 import { CREW_OFF_HELD, CREW_OFF_WORDS, crewBuildsHere } from "../core/crew_switch.ts";
6870 import { PARK_STRIKES, parkedCount } from "./parks.ts";
71 import { redThrice } from "./red_thrice.ts";
6972 import { retryReason } from "./retry.ts";
7073 import { heldFiles, type FileHold } from "./file_holds.ts";
7174 import { expectedFiles, hotFiles, hotOverlap, pullsTouching, relievedFiles } from "./hot_files.ts";
@@ -76,6 +79,7 @@ import { variantGroupOf } from "../core/runs.ts";
7679
7780 export const HOLDS = [
7881 "running",
82 "red_thrice",
7983 "open_pull",
8084 "planner",
8185 "with_planner",
@@ -213,6 +217,8 @@ export function heldBy(
213217 // Read once for the whole pass, matched per issue in memory (#10445).
214218 const fresh = builders.length === 0 ? [] : freshPulls(app.db, repo.id);
215219 const handed = withPlanner(app.db, repo);
220 // Crew pulls red on three checks in a row, read once for the pass.
221 const reds = proposed.size === 0 ? new Map() : redThrice(app.db, repo);
216222 // Asked once for the pass, and only when a builder could otherwise start something.
217223 const noKey = ready.length > 0 && repoHasNoKey(app.db, repo, crew.filter((c) => c.role === "builder").map((c) => c.agent.user.id));
218224 // `crew builds here` off (#13644): every ready issue waits, asked once for the pass.
@@ -274,6 +280,7 @@ export function heldBy(
274280 );
275281 const holdOf = (issue: Issue): HoldName | null => {
276282 if (busyIssues.has(issue.id)) return "running";
283 if (reds.has(issue.number)) return "red_thrice";
277284 if (proposed.has(issue.number)) return "open_pull";
278285 if (issue.assigneeId !== null && planners.has(issue.assigneeId)) return "planner";
279286 if (handed.has(issue.id)) return "with_planner";
@@ -385,6 +392,7 @@ export interface MapHold {
385392
386393 const HOLD_WORDS: Readonly<Record<HoldName, string>> = {
387394 running: "a run is in flight on it",
395 red_thrice: "its pull failed its check three times; the planner splits or rewrites it",
388396 open_pull: "an open pull already proposes it",
389397 planner: "the planner or a reviewer holds it",
390398 with_planner: "its limb waits on the planner",
src/crew/red_thrice.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * 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
4 * rewrite. Counts red checks only: the reviewer's changes-requested path is `guard.ts`'s.
5 *
6 * The streak is the pull's failed checks since its last green one. A check the forge cut short,
7 * one still to come and a same-head recheck count for nothing.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { OUTSIDE_DIFF } from "../checks/outside_diff.ts";
12 import { getIssue } from "../core/issues.ts";
13 import type { Pull } from "../core/pulls.ts";
14 import type { Repo } from "../core/repos.ts";
15 import { getRun, isCut } from "../core/runs.ts";
16 import { failureQuote } from "./failure_quote.ts";
17 import { proposedWork } from "./direct.ts";
18
19 /** Failed checks in a row at which a pull goes back to the planner. */
20 export const RED_STRIKES = 3;
21
22 /** What the note starts with, before the pull it names. */
23 export const RED_THRICE_NOTE = "Red on three checks:";
24
25 /** How many lines of the last failure the note quotes. */
26 const QUOTE_LINES = 6;
27
28 export interface RedThrice {
29 readonly pull: Pull;
30 /** The failed checks in the streak. */
31 readonly failures: number;
32 /** When the oldest of them was queued. */
33 readonly since: string;
34 /** The first lines of the newest failure. */
35 readonly quote: string;
36 }
37
38 /** The streak on one pull, or undefined when it is under the strikes. */
39 export function redStreak(db: Database, pull: Pull): Omit<RedThrice, "pull"> | undefined {
40 const rows = db
41 .query<{ id: string; state: string; summary: string; created_at: string; reason: string | null }, [string]>(
42 `SELECT id, state, summary, created_at, reason FROM run
43 WHERE kind = 'check' AND issue_id = ?1 ORDER BY id DESC LIMIT 50`,
44 )
45 .all(pull.id);
46 let failures = 0;
47 let since = "";
48 let newest: string | undefined;
49 for (const r of rows) {
50 if (r.state === "ok") break;
51 if (r.state !== "failed" || isCut({ state: r.state as "failed", summary: r.summary }) || r.reason === OUTSIDE_DIFF) continue;
52 failures++;
53 since = r.created_at;
54 newest ??= r.id;
55 }
56 if (failures < RED_STRIKES || newest === undefined) return undefined;
57 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") };
60 }
61
62 /** The issues whose open crew pull is red on three checks, by issue number. */
63 export function redThrice(db: Database, repo: Repo): Map<number, RedThrice> {
64 const out = new Map<number, RedThrice>();
65 for (const [number, pull] of proposedWork(db, repo)) {
66 if (!pull.authorIsAgent) continue;
67 const streak = redStreak(db, pull);
68 if (streak !== undefined) out.set(number, { pull, ...streak });
69 }
70 return out;
71 }
72
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+$/, "")}`));
76 return [
77 `${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:`,
78 "",
79 ...quoted,
80 ].join("\n");
81 }
82
83 /** When the note for this streak was written on the issue, if it was. */
84 export function notedAt(db: Database, issueId: string, r: RedThrice): string | undefined {
85 return db
86 .query<{ at: string }, [string, string, string]>(
87 `SELECT created_at AS at FROM comment
88 WHERE issue_id = ?1 AND body LIKE ?2 ESCAPE '\\' AND created_at >= ?3
89 ORDER BY created_at DESC LIMIT 1`,
90 )
91 .get(issueId, `${RED_THRICE_NOTE} pull #${r.pull.number} %`, r.since)?.at;
92 }
93
94 /**
95 * What the planner is owed, shaped like a parked issue (`parkedTwice`): noted, and not answered.
96 */
97 export function redThricePulls(db: Database, repo: Repo) {
98 const out = [];
99 for (const [number, r] of redThrice(db, repo)) {
100 const issue = getIssue(db, repo.id, number);
101 if (issue === undefined || issue.state !== "open") continue;
102 const at = notedAt(db, issue.id, r);
103 if (at === undefined) continue;
104 out.push({
105 issueId: issue.id,
106 repoId: repo.id,
107 number,
108 title: issue.title,
109 reasons: [r.quote.split("\n")[0] ?? ""],
110 byAgent: true,
111 at,
112 });
113 }
114 return out;
115 }
test/crew-red-thrice.test.ts added +127
@@ -0,0 +1,127 @@
1 /**
2 * A crew pull red on three checks is not built a fourth time (#15819): its issue is held as
3 * `red_thrice`, gets one note quoting the last failure, and is owed to the planner. Two reds
4 * hold nothing.
5 */
6 import { quietWeek } from "./helpers/week-quiet.ts";
7 import { seatAs } from "./helpers/seat.ts";
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { addToCrew, createAgent } from "../src/actions/crew.ts";
14 import { openIssue } from "../src/actions/issues.ts";
15 import { openPull } from "../src/actions/pulls.ts";
16 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
17
18 import { listComments, type Issue } from "../src/core/issues.ts";
19 import { getRepoById, type Repo } from "../src/core/repos.ts";
20 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
21 import { createUser, getUserByName, type User } from "../src/core/users.ts";
22 import { noteRedThrice } from "../src/crew/autonomy.ts";
23 import { heldNow } from "../src/crew/held.ts";
24 import { redThricePulls, RED_THRICE_NOTE } from "../src/crew/red_thrice.ts";
25
26 describe("a pull red on three checks goes back to the planner", () => {
27 let dataDir: string;
28 let app: App;
29 let alice: User;
30 let mason: User;
31 let repo: Repo;
32
33 const issue = (title: string): Issue => {
34 const opened = openIssue(app, alice, getRepoById(app.db, repo.id)!, { title, body: "" });
35 if (!opened.ok) throw new Error(String(opened.error));
36 return opened.value;
37 };
38
39 async function pullFor(work: Issue, branch: string): Promise<string> {
40 const made = await commitToBranch(app, alice, repo, {
41 branch,
42 base: "main",
43 message: branch,
44 files: [{ path: `${branch.replace("/", "-")}.ts`, content: "export const n = 1;\n" }],
45 });
46 if (!made.ok) throw new Error(JSON.stringify(made.error));
47 const pull = await openPull(app, mason, repo, {
48 title: work.title,
49 body: `Closes #${work.number}`,
50 baseBranch: "main",
51 headBranch: branch,
52 });
53 if (!pull.ok) throw new Error(String(pull.error));
54 return pull.value.id;
55 }
56
57 /** A finished check on the pull: red with a named failure, or green. */
58 function check(pullId: string, state: "ok" | "failed", n: number): void {
59 const run = createRun(app.db, { repoId: repo.id, kind: "check", issueId: pullId, env: "pull", commitOid: `${n}`.repeat(40).slice(0, 40), reason: "push" });
60 claimRun(app.db, run.id);
61 finishRun(app.db, run.id, {
62 state,
63 summary: state === "ok" ? "ok" : "check failed: 1 test failed",
64 ...(state === "failed" ? { checkDetail: { passed: 1, failed: 1, names: [`widget renders ${n}`] } } : {}),
65 });
66 }
67
68 const notes = (work: Issue) => listComments(app.db, work.id).filter((c) => c.body.startsWith(RED_THRICE_NOTE));
69
70 beforeAll(async () => {
71 dataDir = await mkdtemp(join(tmpdir(), "forge-red-thrice-"));
72 app = createApp({ dataDir, port: 0 });
73 quietWeek(app.db);
74 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
75 if (!a.ok) throw new Error(a.error);
76 alice = a.value;
77 const made = await createRepo(app, alice, { name: "engine", visibility: "private" });
78 if (!made.ok) throw new Error(String(made.error));
79 for (const agent of ["atlas", "mason"]) {
80 const created = await createAgent(app, alice, { username: agent });
81 if (!created.ok) throw new Error(String(created.error));
82 expect(addToCrew(app, alice, made.value, agent).ok).toBe(true);
83 }
84 seatAs(app.db, made.value.id, getUserByName(app.db, "atlas")!.id, "planner");
85 mason = getUserByName(app.db, "mason")!;
86 const set = await updateRepoSettings(app, alice, made.value, { autonomy: "autonomous", autonomyDirection: "Keep it small.", autonomySlots: 1, autonomyBy: alice.id });
87 if (!set.ok) throw new Error(JSON.stringify(set.error));
88 repo = getRepoById(app.db, made.value.id)!;
89 const seeded = await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "# engine\n" }] });
90 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
91 });
92
93 afterAll(async () => {
94 app.close();
95 await rm(dataDir, { recursive: true, force: true });
96 });
97
98 test("three failed checks hold the issue under red_thrice and leave one note; two do not", async () => {
99 const three = issue("Red three times");
100 const two = issue("Red twice");
101 const threePull = await pullFor(three, "mason/three");
102 const twoPull = await pullFor(two, "mason/two");
103 for (const n of [1, 2, 3]) check(threePull, "failed", n);
104 for (const n of [1, 2]) check(twoPull, "failed", n);
105
106 const held = heldNow(app, repo);
107 expect(held.by.red_thrice.map((i) => i.number)).toEqual([three.number]);
108 expect(held.by.open_pull.map((i) => i.number)).toEqual([two.number]);
109
110 const me = getUserByName(app.db, "alice")!;
111 expect(noteRedThrice(app, repo, me)).toBe(1);
112 expect(noteRedThrice(app, repo, me)).toBe(0); // once, not on every tick
113 expect(notes(three)).toHaveLength(1);
114 expect(notes(three)[0]!.body).toContain("> widget renders 3");
115 expect(notes(two)).toHaveLength(0);
116
117 // The planner is owed it, once the note is said.
118 expect(redThricePulls(app.db, repo).map((h) => h.number)).toEqual([three.number]);
119 });
120
121 test("a green check between the reds starts the count again", async () => {
122 const work = issue("Red, green, red");
123 const pull = await pullFor(work, "mason/mixed");
124 for (const [state, n] of [["failed", 1], ["failed", 2], ["ok", 3], ["failed", 4]] as const) check(pull, state, n);
125 expect(heldNow(app, repo).by.red_thrice.map((i) => i.number)).not.toContain(work.number);
126 });
127 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs