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

A failure deferred while a builder run is at work is forgotten by a restart; re-derive it #16961

Merged opened this

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

Merged

mason/forge:mason/6594-a-failure-deferred-while-a-builder-run-i → main 0 commits fork 3 threads · 3 unresolved

  • Merged. mason/6594-a-failure-deferred-while-a-builder-run-i was merged into main as 2162e6b.

Review

Sign in to review this change.
3 files changed +223 −3
src/crew/dispatch.ts +57 −3
@@ -50,7 +50,7 @@ import {
5050 type Issue,
5151 } from "../core/issues.ts";
5252 import { authorsInRepoPull } from "./authors_pull.ts";
53 import { closesFromBody, getPull, pullDir, type Pull } from "../core/pulls.ts";
53 import { closesFromBody, getPull, listOpenPulls, pullDir, type Pull } from "../core/pulls.ts";
5454 import { claimedClones, sweepIdleDependencies, sweepOrphanClones, sweepStaleClones } from "./orphans.ts";
5555 import { pruneRunFiles } from "../runs/prune.ts";
5656 import { sweepRunLogs } from "../runs/archive.ts";
@@ -82,6 +82,9 @@ import {
8282 automaticRunsSince,
8383 cancelRun,
8484 sameRedTwice,
85 newestAgentRun,
86 RUN_STATES,
87 verdictForHead,
8588 createRun,
8689 finishRun,
8790 getRun,
@@ -154,6 +157,7 @@ import { during } from "../perf/jobs.ts";
154157 import { BoundedSet } from "../perf/bounded.ts";
155158 import { threadHeld } from "../perf/held.ts";
156159 import { recheckUsage } from "./usage_check.ts";
160 import { markRedRouted, redRouted } from "./red_routed.ts";
157161
158162 const log = createLog("crew");
159163
@@ -396,6 +400,7 @@ export async function startCrew(
396400 during("crew", () => {
397401 requeueInterrupted(app);
398402 sweepAssigned(app);
403 decideStrandedAtBoot(app);
399404 pump(app, ready, inFlight);
400405 }, undefined, app);
401406
@@ -940,6 +945,7 @@ export function route(app: App, event: ForgeEvent): void {
940945 actorId: finished?.actorId ?? null,
941946 });
942947 decideDeferred(app, repo);
outdated

No test fails without this call. Cover the run-ends path. See the body, point 1.

948 decideStranded(app, repo);
943949 return;
944950 }
945951 if (
@@ -999,6 +1005,8 @@ export function route(app: App, event: ForgeEvent): void {
9991005 });
10001006 return;
10011007 }
1008 if (typeof event.payload["runId"] === "string")
1009 markRedRouted(app.db, repo.id, issue.id, event.payload["runId"]);
10021010 // A pull that does not merge is no failed try: the forge settles a
10031011 // list-doc clash itself, else a bring-up-to-date run is queued. It
10041012 // counts towards no limit and parks nothing (#7909).
@@ -1176,8 +1184,8 @@ async function recheckOutsideDiff(
11761184
11771185 /**
11781186 * Failures that arrived while the builder's run was still at work on the
1179 * pull, by pull. Memory only: a restart forgets them, and the pull's next
1180 * push or a person's ask checks it again.
1187 * pull, by pull. Memory only: a restart forgets them, and `decideStranded`
1188 * finds them again from the run table.
11811189 */
11821190 const deferredFailures = new Map<string, ForgeEvent>();
11831191
@@ -1213,6 +1221,52 @@ function decideDeferred(app: App, repo: Repo): void {
12131221 }
12141222 }
12151223
1224 /**
1225 * A failure the memory above forgot (a restart) or never had: an open pull whose newest check or
1226 * deploy at its head failed, with no builder at work, no agent run made since that red and no
1227 * decision on it in the ledger (`markRedRouted`), is routed as the failed check it is. Read from
1228 * the run table alone, so what was deferred is found again (#6594).
outdated

Every open pull is re-routed on each agent run end and each boot. Reds already decided without an agent run get decided again. Track what was decided so each red is routed once. See the body, point 2.

1229 */
1230 function decideStranded(app: App, repo: Repo): void {
1231 for (const pull of listOpenPulls(app.db, repo.id)) {
1232 const issue = getIssueById(app.db, pull.id);
1233 if (!issue || builderAtWork(app, repo, issue)) continue;
1234 // The verdict is the newest run of each kind and environment at the head, so a red deploy
1235 // stands beside an ok check, as it does when the event arrives live.
1236 const red = verdictForHead(app.db, pull.id, pull.headOid).find((run) => run.state === "failed");
1237 if (!red || redRouted(app.db, pull.id, red.id)) continue;
1238 // A rework (or a review) queued since the red is the decision.
1239 const since = newestAgentRun(app.db, pull.id, RUN_STATES);
1240 if (since !== undefined && since.id > red.id) continue;
1241 route(app, {
1242 id: red.id,
1243 kind: "run.finished",
1244 repoId: repo.id,
1245 actorId: red.actorId,
1246 payload: {
1247 kind: red.kind,
1248 issueId: pull.id,
1249 runId: red.id,
1250 state: "failed",
1251 commitOid: red.commitOid,
1252 env: red.env,
1253 },
1254 createdAt: red.finishedAt ?? red.createdAt,
1255 });
1256 }
1257 }
1258
1259 /** At boot: every repository with an open pull is read for failures a restart forgot. */
1260 export function decideStrandedAtBoot(app: App): void {
1261 const rows = app.db
1262 .query<{ repo_id: string }, []>("SELECT DISTINCT repo_id FROM issue WHERE kind = 'pull' AND state = 'open'")
1263 .all();
1264 for (const row of rows) {
1265 const repo = getRepoById(app.db, row.repo_id);
1266 if (repo) decideStranded(app, repo);
1267 }
1268 }
1269
12161270 /**
12171271 * Pulls whose check failed only on what main fails, or on what the lane
12181272 * fails across pulls (`checks/shared_red.ts`), per repository, with
src/crew/red_routed.ts added +36
@@ -0,0 +1,36 @@
1 /**
2 * Which failed runs the crew has already decided on, kept in the decision ledger (kind `guard`,
3 * answer `routed`, the run's id in its state) so a restart does not decide a red twice (#6594).
4 * A red deferred while the builder was at work is not marked: it is still undecided.
5 */
6
7 import type { Database } from "bun:sqlite";
8 import { recordDecision } from "../core/decisions.ts";
9
10 const REASON = "red";
11
12 /** The crew decided on this failed run: a rework, a park, a wait on main, or a no. */
13 export function markRedRouted(db: Database, repoId: string, issueId: string, runId: string): void {
14 if (redRouted(db, issueId, runId)) return;
15 recordDecision(db, {
16 kind: "guard",
17 repoId,
18 issueId,
19 state: { reason: REASON, runId },
20 answer: "routed",
21 p: 1,
22 by: "rule",
23 ms: 0,
24 });
25 }
26
27 /** Whether the crew already decided on this failed run. */
28 export function redRouted(db: Database, issueId: string, runId: string): boolean {
29 const row = db
30 .query<{ n: number }, [string, string]>(
31 `SELECT COUNT(*) AS n FROM decision
32 WHERE issue_id = ?1 AND kind = 'guard' AND answer = 'routed' AND state = ?2`,
33 )
34 .get(issueId, JSON.stringify({ reason: REASON, runId }));
35 return (row?.n ?? 0) > 0;
36 }
test/crew-stranded-failure.test.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * A failed check the crew had not decided when the forge restarted is decided again (#6594):
3 * the run table is read, not the memory that held it while the builder was at work.
4 */
5
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import type { App } from "../src/app.ts";
8 import type { Pull } from "../src/core/pulls.ts";
9 import { assignIssue, openIssue } from "../src/actions/issues.ts";
10 import { announceRun } from "../src/actions/runs.ts";
11 import { decideStrandedAtBoot } from "../src/crew/dispatch.ts";
12 import { redRouted } from "../src/crew/red_routed.ts";
13 import { getPull, listOpenPulls } from "../src/core/pulls.ts";
14 import { claimRun, createRun, finishRun, listRuns } from "../src/core/runs.ts";
15 import { pollUntil } from "./helpers/poll.ts";
16 import { startStandInCrew, stopStandInCrew, type StandInCrew } from "./helpers/crew-standin.ts";
17
18 describe("a failure nothing decided", () => {
19 let standIn: StandInCrew;
20 let app: App;
21
22 beforeAll(async () => {
23 standIn = await startStandInCrew({
24 tickMs: 50,
25 files: [{ path: "forge.json", content: '{"check": {"run": "true", "install": ""}}\n' }],
26 });
27 app = standIn.app;
28 }, 30_000);
29
30 afterAll(() => stopStandInCrew(standIn));
31
32 const agentRuns = () => listRuns(app.db, standIn.repo.id, { kind: "agent", limit: 50 });
33 const settled = () => agentRuns().every((r) => r.state === "ok" || r.state === "failed" || r.state === "cancelled");
34 let titles = 0;
35
36 /** A pull the builder opened for a new issue, once every agent run is over. */
37 async function builtPull(): Promise<Pull> {
38 const { alice, bot, repo } = standIn;
39 const before = new Set(listOpenPulls(app.db, repo.id).map((p) => p.id));
40 const issue = openIssue(app, alice, repo, { title: `Plant bulbs ${++titles}`, body: "Along the wall." });
41 if (!issue.ok) throw new Error(String(issue.error));
42 expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true);
43 await pollUntil(
44 () => listOpenPulls(app.db, repo.id).some((p) => !before.has(p.id)) && settled(),
45 "the builder opened a pull and settled",
46 );
47 const pull = listOpenPulls(app.db, repo.id).find((p) => !before.has(p.id));
48 if (!pull) throw new Error("no pull was opened");
49 return getPull(app.db, repo.id, pull.number)!;
50 }
51
52 /** A run at the pull's head that already ended, as the run table holds it. */
53 function ended(pull: Pull, kind: "check" | "deploy", state: "ok" | "failed") {
54 const run = createRun(app.db, {
55 repoId: standIn.repo.id,
56 kind,
57 issueId: pull.id,
58 env: kind === "check" ? `pull-${pull.number}` : `preview-${pull.number}`,
59 commitOid: getPull(app.db, standIn.repo.id, pull.number)!.headOid,
60 });
61 claimRun(app.db, run.id);
62 finishRun(app.db, run.id, { state, summary: `${kind} ${state}` });
63 return run;
64 }
65
66 test("is routed to the builder at boot, once", async () => {
67 const pull = await builtPull();
68 const before = agentRuns().length;
69 // The red the restart forgot: newest at the head, nothing queued since.
70 ended(pull, "check", "failed");
71 decideStrandedAtBoot(app);
72 // The answer may wait on a read of the failing log; it is queued within a moment.
73 await pollUntil(() => agentRuns().length > before, "the rework was queued");
74 expect(agentRuns().length).toBe(before + 1);
75 expect(agentRuns().filter((r) => r.reason === "check_failed").length).toBe(1);
76 await pollUntil(settled, "the rework settled");
77 // Decided: a second boot queues nothing more.
78 const after = agentRuns().length;
79 decideStrandedAtBoot(app);
80 expect(agentRuns().length).toBe(after);
81 }, 30_000);
82
83 test("a red that landed while the builder was at work is answered when its run ends", async () => {
84 const { repo } = standIn;
85 const pull = await builtPull();
86 const before = agentRuns().length;
87 // The builder is at work on the pull: a running agent run, no process behind it.
88 const work = createRun(app.db, { repoId: repo.id, kind: "agent", issueId: pull.id, env: "agent" });
89 claimRun(app.db, work.id);
90 // The red lands unannounced: the memory of deferred failures holds nothing, as after a restart.
91 ended(pull, "check", "failed");
92 finishRun(app.db, work.id, { state: "ok", summary: "pushed" });
93 announceRun(app, { ...work, state: "ok" });
94 await pollUntil(() => agentRuns().some((r) => r.reason === "check_failed" && r.id !== work.id), "the run's end queued the rework");
95 expect(agentRuns().filter((r) => r.reason === "check_failed").length).toBeGreaterThan(0);
96 expect(agentRuns().length).toBe(before + 2);
97 }, 30_000);
98
99 test("a red the crew decided without a rework is not decided again at the next boot", async () => {
100 const { repo } = standIn;
101 const pull = await builtPull();
102 // The same red twice after a rework: the pull is parked for a person, no run is queued.
103 const first = ended(pull, "check", "failed");
104 decideStrandedAtBoot(app);
105 await pollUntil(() => agentRuns().some((r) => r.reason === "check_failed" && r.createdAt >= first.createdAt), "the first rework");
106 await pollUntil(settled, "the rework settled");
107 const second = ended(pull, "check", "failed");
108 const decide = () => listRuns(app.db, repo.id, { kind: "agent", limit: 50 }).length;
109 decideStrandedAtBoot(app);
110 const parked = decide();
111 // Nothing since the decision: every later boot leaves it be.
112 decideStrandedAtBoot(app);
113 decideStrandedAtBoot(app);
114 expect(decide()).toBe(parked);
115 expect(redRouted(app.db, pull.id, second.id)).toBe(true);
116 }, 30_000);
117
118 test("a red deploy beside an ok check is the verdict still, and is routed once", async () => {
119 const pull = await builtPull();
120 const before = agentRuns().length;
121 ended(pull, "deploy", "failed");
122 ended(pull, "check", "ok");
123 decideStrandedAtBoot(app);
124 await pollUntil(() => agentRuns().length > before, "the red deploy was answered");
125 await pollUntil(settled, "the rework settled");
126 const after = agentRuns().length;
127 decideStrandedAtBoot(app);
128 expect(agentRuns().length).toBe(after);
129 }, 30_000);
130 });

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

Keyboard shortcuts

Docs