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

A pull that lands while its check runs keeps the check, and a red it ends with is main's, said on the home's first line #17632

opened this

Merged 18h 24m ago, live in production

fix/landed-check-runs-on → main 0 commits 1 thread · 1 unresolved

  • Merged. fix/landed-check-runs-on was merged into main as f270a47.

Review

Sign in to review this change.
8 files changed +317 −31
docs/features/first-wrong.md +9 −2
@@ -4,8 +4,15 @@ row: The first thing wrong, in one line on home
44 ---
55 # The first thing wrong
66
7 When something needs you, home says so in one calm line under the title, with the one link that fixes it. At most one line shows, the most urgent first: production behind main (admins), a pull whose check is stuck (anyone who can write to its repository), the crew past its share of the week (admins). When all is well there is no line, and a guest never sees one.
7 When something needs you, home says so in one calm line under the title, with the one link that fixes it. At most one line shows, the most urgent first:
8
9 1. **A red that landed on main** (anyone who can read its repository). On a repository that lets a pull land before its check answers, the landing does not cut that check: it runs on at the pull's head, and across a forge restart it is queued again there. If it then fails, main carries the red, and the next release would hold on it: "alice/lib #12 landed and its check then failed: main carries the red until it is fixed. See the red", linked to the pull. It clears when main passes a check after it, and it is read at most every 10 s, so it shows or clears that much late. Code: `src/checks/landed_red.ts`.
10 2. **Production behind main** (admins).
11 3. **A pull whose check is stuck** (anyone who can write to its repository).
12 4. **The crew past its share of the week** (admins).
13
14 When all is well there is no line, and a guest never sees one.
815
916 The terminal home shows the same line, read by the same function, with the web path to fix it at the end. The allowance line waits until the week has a share above zero.
1017
11 Code: `src/web/first_wrong.ts` (`firstWrong`, `readFacts`), `src/web/pages/home_flow.ts` (the page), `src/tui/screens/dashboard.ts` (the terminal). Test: `test/home-first-wrong.test.ts`, `test/tui-dashboard-alarms.test.ts`.
18 Code: `src/web/first_wrong.ts` (`firstWrong`, `readFacts`), `src/web/pages/home_flow.ts` (the page), `src/tui/screens/dashboard.ts` (the terminal). Test: `test/home-first-wrong.test.ts`, `test/tui-dashboard-alarms.test.ts`, `test/landed-check-runs-on.test.ts`.
src/checks/event_handler.ts +5 −1
@@ -142,17 +142,21 @@ export async function onEvent(lane: LaneState, event: ForgeEvent): Promise<void>
142142 await lane.request(repo, env, head, "approved", pull.id, actor);
143143 return;
144144 }
145 // Landed or closed: nothing left to check, so nothing waits in the lane.
145 // Landed or closed: its previews wait no more, and a closed pull's check stops.
146146 case "pull.merged":
147147 case "pull.closed": {
148148 const number = event.payload["number"];
149149 if (typeof number !== "number") return;
150150 const pull = getPull(app.db, repo.id, number);
151151 if (!pull) return;
152 // A landing does not cut the pull's check: on a repository that lets a pull land before its
153 // check answers, that check is the only one of what landed, and its red is main's to fix
154 // (`landed_red.ts`, #17542). A closed pull's check proves nothing and stops.
152155 const cancelled = cancelRunsForPull(
153156 app.db,
154157 pull.id,
155158 event.kind === "pull.merged" ? "pull landed" : "pull closed",
159 event.kind === "pull.merged",
156160 );
157161 for (const run of cancelled) {
158162 lane.inFlight.get(run.id)?.abort.abort();
src/checks/landed_red.ts added +87
@@ -0,0 +1,87 @@
1 /**
2 * A pull that landed before its check answered (a repository that does not require checks) keeps
3 * that check running (`event_handler.ts`), and a red it ends with is a red of what landed: main's to
4 * fix, said where main's reds are said (the home's first-wrong line), naming the pull, before the
5 * next release tick runs into it (#17542 landed 35 s after approval; its check would have caught
6 * the red that held the 17:24 tick). It stands until main has a passing check finished after it.
7 * Read from the runs; nothing is stored.
8 */
9
10 import type { Database } from "bun:sqlite";
11 import { canRead, getRepoById } from "../core/repos.ts";
12 import type { User } from "../core/users.ts";
13 import { isCut } from "../core/runs.ts";
14
15 /** One landed pull whose own check ended red after it landed. */
16 export interface LandedRed {
17 readonly repoId: string;
18 readonly ownerName: string;
19 readonly repoName: string;
20 readonly number: number;
21 readonly title: string;
22 readonly summary: string;
23 readonly finishedAt: string;
24 }
25
26 /** How far back a landed red is looked for: a release ticks every 30 minutes, and main's checks clear it sooner. */
27 export const LANDED_RED_DAYS = 2;
28
29 /** The landed pulls, newest red first, whose own check failed after they landed and that main has not passed since. */
30 export function landedReds(db: Database, now: Date = new Date()): LandedRed[] {
31 const since = new Date(now.getTime() - LANDED_RED_DAYS * 86_400_000).toISOString();
32 const rows = db
33 .query<
34 { repo_id: string; owner: string; repo: string; number: number; title: string; summary: string; state: string; finished_at: string },
35 [string]
36 >(
37 `SELECT run.repo_id, u.username AS owner, r.name AS repo, i.number, i.title, run.summary, run.state, run.finished_at
38 FROM run
39 JOIN issue i ON i.id = run.issue_id AND i.kind = 'pull'
40 JOIN pull p ON p.issue_id = i.id AND p.merged_at IS NOT NULL
41 JOIN repo r ON r.id = run.repo_id AND p.base_branch = r.default_branch
42 JOIN user u ON u.id = r.owner_id
43 WHERE run.kind = 'check' AND run.state = 'failed' AND run.finished_at >= ?1
44 AND run.finished_at > p.merged_at AND run.commit_oid = p.head_oid
45 AND NOT EXISTS (
46 SELECT 1 FROM run m
47 WHERE m.repo_id = run.repo_id AND m.kind = 'check' AND m.issue_id IS NULL
48 AND m.env = r.default_branch AND m.state = 'ok' AND m.finished_at > run.finished_at)
49 ORDER BY run.finished_at DESC LIMIT 20`,
50 )
51 .all(since);
52 return rows
53 .filter((row) => !isCut({ state: "failed", summary: row.summary }))
54 .map((row) => ({
55 repoId: row.repo_id,
56 ownerName: row.owner,
57 repoName: row.repo,
58 number: row.number,
59 title: row.title,
60 summary: row.summary,
61 finishedAt: row.finished_at,
62 }));
63 }
64
65 /**
66 * How long one read of the landed reds serves every home: a red that lands, or one main clears, is
67 * said within this, and a home looked at again costs no statement for it (home-200's budget).
68 */
69 export const LANDED_RED_KEPT_MS = 10_000;
70 const kept = new WeakMap<Database, { at: number; reds: LandedRed[] }>();
71
72 /** `landedReds`, read at most once per `LANDED_RED_KEPT_MS` per database; a read kept from a later moment is read again. */
73 function keptReds(db: Database, now: Date): LandedRed[] {
74 const had = kept.get(db);
75 if (had !== undefined && now.getTime() - had.at >= 0 && now.getTime() - had.at < LANDED_RED_KEPT_MS) return had.reds;
76 const reds = landedReds(db, now);
77 kept.set(db, { at: now.getTime(), reds });
78 return reds;
79 }
80
81 /** The newest landed red `viewer` may read; undefined when none. */
82 export function landedRedFor(db: Database, viewer: User, now: Date = new Date()): LandedRed | undefined {
83 return keptReds(db, now).find((red) => {
84 const repo = getRepoById(db, red.repoId);
85 return repo !== undefined && canRead(db, repo, viewer);
86 });
87 }
src/core/runs.ts +14 −10
@@ -498,14 +498,16 @@ export function cancelRunsForPull(
498498 db: Database,
499499 issueId: string,
500500 summary: string,
501 /** A landing keeps the pull's check: it runs on to say whether what landed is red (`checks/landed_red.ts`). */
502 keepChecks = false,
501503 ): Run[] {
502504 const ids = db
503 .query<{ id: string }, [string]>(
505 .query<{ id: string }, [string, number]>(
504506 `SELECT id FROM run WHERE issue_id = ?1 AND
505 ((kind = 'check' AND state IN ('queued','running'))
507 ((kind = 'check' AND state IN ('queued','running') AND ?2 = 0)
506508 OR (kind = 'deploy' AND state = 'queued')) ORDER BY id`,
507509 )
508 .all(issueId);
510 .all(issueId, keepChecks ? 1 : 0);
509511 const out: Run[] = [];
510512 for (const { id } of ids) {
511513 const cancelled = cancelRun(db, id, summary);
@@ -981,16 +983,18 @@ export interface AbandonedChecks {
981983 readonly requeued: readonly { cancelled: Run; again: Run }[];
982984 /** Past `CHECK_RESTART_LIMIT`: failed once, saying the forge kept dying. */
983985 readonly failed: readonly Run[];
984 /** No longer any open pull's head: cancelled, not retried. */
986 /** No longer the head of an open pull or of a landed one: cancelled, not retried. */
985987 readonly cancelled: readonly Run[];
986988 }
987989
988990 /**
989991 * Checks whose lease lapsed — their forge died under them, which is never
990 * the commit's fault. One whose commit is still the head of an open pull is
991 * queued again (`requeueCheck`) until `CHECK_RESTART_LIMIT`, then failed
992 * once with a summary that says why; one whose commit no longer heads any
993 * open pull is cancelled and says so. Every move is a compare-and-swap on
992 * the commit's fault. One whose commit is still the head of an open pull, or
993 * is the head a pull landed at (its check runs on after the landing and its
994 * red is main's, `checks/landed_red.ts`), is queued again (`requeueCheck`)
995 * until `CHECK_RESTART_LIMIT`, then failed once with a summary that says why;
996 * one whose commit no longer heads any open or landed pull is cancelled and
997 * says so. Every move is a compare-and-swap on
994998 * the lapsed lease, so two forges sweeping at once move each run once.
995999 */
9961000 export function sweepAbandonedChecks(
@@ -1002,8 +1006,8 @@ export function sweepAbandonedChecks(
10021006 .query<RunRow & { live: number }, [string, number]>(
10031007 `SELECT run.*, EXISTS (
10041008 SELECT 1 FROM pull JOIN issue ON issue.id = pull.issue_id
1005 WHERE pull.issue_id = run.issue_id AND issue.state = 'open'
1006 AND pull.merged_at IS NULL AND pull.head_oid = run.commit_oid
1009 WHERE pull.issue_id = run.issue_id AND pull.head_oid = run.commit_oid
1010 AND ((issue.state = 'open' AND pull.merged_at IS NULL) OR pull.merged_at IS NOT NULL)
10071011 ) AS live
10081012 FROM run
10091013 WHERE kind = 'check' AND state = 'running'
src/web/first_wrong.ts +13 −4
@@ -10,8 +10,9 @@ import { behindStanding } from "../release/behind.ts";
1010 import type { User } from "../core/users.ts";
1111 import type { Database } from "bun:sqlite";
1212 import { html, type Html } from "./html.ts";
13 import { landedRedFor } from "../checks/landed_red.ts";
1314
14 export type WrongKey = "behind" | "stuck" | "allowance";
15 export type WrongKey = "landed" | "behind" | "stuck" | "allowance";
1516
1617 /** What is wrong and the one link that fixes it. `href` is a same-origin path. */
1718 export interface Wrong {
@@ -21,10 +22,10 @@ export interface Wrong {
2122 }
2223
2324 /**
24 * Most urgent first: production not following main, then work that cannot move, then the crew's own
25 * limit.
25 * Most urgent first: a red that landed on main (the next release holds on it), production not
26 * following main, then work that cannot move, then the crew's own limit.
2627 */
27 export const PRIORITY: readonly WrongKey[] = ["behind", "stuck", "allowance"];
28 export const PRIORITY: readonly WrongKey[] = ["landed", "behind", "stuck", "allowance"];
2829
2930 export type Facts = Partial<Record<WrongKey, Wrong>>;
3031
@@ -47,6 +48,14 @@ export function readFacts(
4748 o: { readonly admin: boolean; readonly week: { readonly usedPct: number; readonly mayUsePct: number } | null | undefined; readonly now: number; readonly stalled?: readonly StalledStep[] },
4849 ): Facts {
4950 const facts: { -readonly [K in WrongKey]?: Wrong } = {};
51 // A pull that landed while its check ran, and the check then failed: main carries that red.
52 const landed = landedRedFor(db, user, new Date(o.now));
53 if (landed !== undefined)
54 facts.landed = {
55 says: `${landed.ownerName}/${landed.repoName} #${String(landed.number)} landed and its check then failed: main carries the red until it is fixed.`,
56 href: `/${landed.ownerName}/${landed.repoName}/pulls/${String(landed.number)}`,
57 action: "See the red",
58 };

Add this fact to docs/features/first-wrong.md in the same pull (the list there names three facts; this is a fourth and the first in priority).

5059 const behind = o.admin ? behindStanding(o.now) : undefined;
5160 if (behind !== undefined) facts.behind = { says: `${behind.sentence}.`, href: "/releases", action: "See the release" };
5261 // A caller that has read the stalled steps passes them, so nothing is read twice.
test/checks-queue.test.ts +14 −10
@@ -193,8 +193,9 @@ describe("checks", () => {
193193 });
194194
195195 for (const ending of ["merge", "close"] as const)
196 test(`${ending === "merge" ? "merging" : "closing"} a pull leaves no queued or running run for it`, async () => {
197 // Invariant: a pull merged or closed has its queued checks cancelled with that reason.
196 test(`${ending === "merge" ? "merging a pull keeps its queued check, which then runs and answers" : "closing a pull leaves no queued or running run for it"}`, async () => {
197 // Invariant: a closed pull's queued check is cancelled with that reason; a landed pull's is
198 // kept and runs, since it is the only check of what landed (#17542, `checks/landed_red.ts`).
198199 const blocker = await commitToBranch(f.app, f.alice, f.repo, {
199200 message: "Hold the lane",
200201 files: [{ path: "forge.json", content: checkJson(f.held(`lane-${ending}`)) }],
@@ -227,20 +228,23 @@ describe("checks", () => {
227228 const closed = setIssueState(f.app, f.alice, f.repo, pull, "closed");
228229 if (!closed.ok) throw new Error(String(closed.error));
229230 }
230 await f.until(() => mine().every((r) => r.state !== "queued"), "the pull's check gone");
231 expect(mine().filter((r) => r.state === "queued")).toEqual([]);
232 expect(
233 mine().some(
234 (r) =>
235 r.summary === (ending === "merge" ? "pull landed" : "pull closed"),
236 ),
237 ).toBe(true);
231 if (ending === "close") {
232 await f.until(() => mine().every((r) => r.state !== "queued"), "the pull's check gone");
233 expect(mine().filter((r) => r.state === "queued")).toEqual([]);
234 expect(mine().some((r) => r.summary === "pull closed")).toBe(true);
235 } else {
236 // Still in the line behind the holder, not cut.
237 expect(mine().some((r) => r.state === "queued")).toBe(true);
238 expect(mine().some((r) => r.summary === "pull landed")).toBe(false);
239 }
238240 // The lane is let go, and left empty for the next test.
239241 f.release(`lane-${ending}`);
240242 await f.until(
241243 () => f.checksOf(blocker.value.commitOid).every((r) => r.state !== "queued" && r.state !== "running"),
242244 "the lane's holder done",
243245 );
246 if (ending === "merge")
247 await f.until(() => mine().every((r) => r.state === "ok" || r.state === "failed"), "the landed pull's check answered");
244248 });
245249
246250 test("a check asked for a closed pull is refused and queues nothing (#16662)", async () => {
test/home-first-wrong.test.ts +5 −4
@@ -19,11 +19,12 @@ import { headerSays } from "../src/web/pages/home_flow.ts";
1919 import { seedAdmin } from "./helpers/admin.ts";
2020
2121 const w = (says: string) => ({ says, href: "/x", action: "Fix" });
22 const ALL: Facts = { allowance: w("c"), stuck: w("b"), behind: w("a") };
22 const ALL: Facts = { allowance: w("c"), stuck: w("b"), behind: w("a"), landed: w("0") };
2323
24 test("the priority is behind, stuck, allowance, and the first held fact wins", () => {
25 expect(PRIORITY).toEqual(["behind", "stuck", "allowance"]);
26 expect(firstWrong(ALL)?.key).toBe("behind");
24 test("the priority is landed, behind, stuck, allowance, and the first held fact wins", () => {
25 expect(PRIORITY).toEqual(["landed", "behind", "stuck", "allowance"]);
26 expect(firstWrong(ALL)?.key).toBe("landed");
27 expect(firstWrong({ allowance: w("c"), stuck: w("b"), behind: w("a") })?.key).toBe("behind");
2728 expect(firstWrong({ allowance: w("c"), stuck: w("b") })?.key).toBe("stuck");
2829 expect(firstWrong({ allowance: w("c") })?.key).toBe("allowance");
2930 expect(firstWrong({})).toBeNull();
test/landed-check-runs-on.test.ts added +170
@@ -0,0 +1,170 @@
1 /**
2 * A pull that lands while its check runs keeps that check (#17542): on a repository that does not
3 * require checks, the landing used to cut it ("pull landed"), and the release gate was the first
4 * to run what landed. Now the check runs on at the pull's head, and a red it ends with is main's:
5 * said on the home's first-wrong line, naming the pull, until main passes a check after it.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { mergePull, openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { LANDED_RED_KEPT_MS, landedRedFor } from "../src/checks/landed_red.ts";
15 import { requeueAbandonedChecks, startChecks, type ChecksHandle } from "../src/checks/service.ts";
16 import { STALE_AFTER_MS } from "../src/runs/lease.ts";
17 import { getPull } from "../src/core/pulls.ts";
18 import type { Repo } from "../src/core/repos.ts";
19 import { listRuns, type Run } from "../src/core/runs.ts";
20 import { createSession } from "../src/core/sessions.ts";
21 import { createUser, type User } from "../src/core/users.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { firstWrong, readFacts } from "../src/web/first_wrong.ts";
24 import { waitFor } from "./helpers/poll.ts";
25
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29 let checks: ChecksHandle;
30 let alice: User;
31 let repo: Repo;
32
33 const checkJson = (run: string): string => `{"check": {"run": ${JSON.stringify(run)}, "install": ""}}\n`;
34 /** The landed red alice reads now, past the 10 s a home keeps one read: each ask is a later moment, so it reads afresh. */
35 let later = 0;
36 const redNow = () => landedRedFor(app.db, alice, new Date(Date.now() + ++later * LANDED_RED_KEPT_MS));
37 const checksOf = (where: (r: Run) => boolean): Run[] => listRuns(app.db, repo.id, { kind: "check", limit: 50 }).filter(where);
38
39 beforeAll(async () => {
40 dataDir = await mkdtemp(join(tmpdir(), "forge-landed-check-"));
41 app = createApp({ dataDir, port: 0 });
42 servers = await serve(app);
43 checks = startChecks(app, { forgeUrl: servers.url, concurrency: 1 });
44 const a = await createUser(app.db, {
45 origin: "seed",
46 trusted: true,
47 username: "alice",
48 email: "[email protected]",
49 password: "a-good-passphrase",
50 adminIfFirst: true,
51 });
52 if (!a.ok) throw new Error(a.error);
53 alice = a.value;
54 const made = await createRepo(app, alice, { name: "lib", visibility: "public" });
55 if (!made.ok) throw new Error(String(made.error));
56 repo = made.value;
57 // Checks are not required here, as on the forge's own repository: a person may land at once.
58 expect(repo.requireChecks).toBe(false);
59 // The check is read from the base, and takes a moment, so a landing can come while it runs.
60 const base = await commitToBranch(app, alice, repo, {
61 message: "A passing check",
62 files: [{ path: "forge.json", content: checkJson("sleep 2 && test ! -f BROKEN") }],
63 });
64 if (!base.ok) throw new Error(JSON.stringify(base.error));
65 await waitFor(() => checksOf((r) => r.commitOid === base.value.commitOid && r.state === "ok").length > 0, { every: 50, within: 30_000 });
66 });
67
68 afterAll(async () => {
69 await checks.stop();
70 servers.stop();
71 app.close();
72 await rm(dataDir, { recursive: true, force: true });
73 });
74
75 test("a pull landed while its check runs keeps the check, and its red is main's, on the home's first-wrong line", async () => {
76 const branched = await commitToBranch(app, alice, repo, {
77 branch: "slow",
78 base: "main",
79 message: "Break it slowly",
80 files: [{ path: "BROKEN", content: "x\n" }],
81 });
82 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
83 const opened = await openPull(app, alice, repo, { title: "Break it", baseBranch: "main", headBranch: "slow" });
84 if (!opened.ok) throw new Error(String(opened.error));
85 const pull = getPull(app.db, repo.id, opened.value.number)!;
86 const own = () => checksOf((r) => r.issueId === pull.id && r.commitOid === pull.headOid)[0];
87 await waitFor(() => own()?.state === "running", { every: 20, within: 30_000 });
88
89 const landed = await mergePull(app, alice, repo, pull, "merge");
90 expect(landed.ok).toBe(true);
91 // Not cut by the landing: it runs on and answers.
92 await waitFor(() => own()?.state === "failed", { every: 50, within: 30_000 });
93 expect(own()?.summary).not.toContain("pull landed");
94
95 const red = redNow();
96 expect(red).toMatchObject({ ownerName: "alice", repoName: "lib", number: pull.number });
97 const wrong = firstWrong(readFacts(app.db, alice, { admin: true, week: null, now: Date.now() }));
98 expect(wrong).toMatchObject({ key: "landed", href: `/alice/lib/pulls/${pull.number}` });
99 expect(wrong?.says).toContain(`alice/lib #${pull.number} landed and its check then failed`);
100 const home = await (
101 await fetch(`${servers.url}/`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } })
102 ).text();
103 expect(home).toContain(`data-first-wrong="landed"`);
104
105 // Main passing a check after it clears it.
106 const fixed = await commitToBranch(app, alice, repo, { message: "Fix it", files: [{ path: "forge.json", content: checkJson("true") }] });
107 if (!fixed.ok) throw new Error(JSON.stringify(fixed.error));
108 await waitFor(() => checksOf((r) => r.commitOid === fixed.value.commitOid && r.issueId === null && r.state === "ok").length > 0, {
109 every: 50,
110 within: 30_000,
111 });
112 expect(redNow()).toBeUndefined();
113 }, 90_000);
114
115 test("a closed pull's check still stops: it proves nothing about main", async () => {
116 const branched = await commitToBranch(app, alice, repo, {
117 branch: "dropped",
118 base: "main",
119 message: "Never lands",
120 files: [{ path: "forge.json", content: checkJson("sleep 5") }],
121 });
122 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
123 const opened = await openPull(app, alice, repo, { title: "Dropped", baseBranch: "main", headBranch: "dropped" });
124 if (!opened.ok) throw new Error(String(opened.error));
125 const pull = getPull(app.db, repo.id, opened.value.number)!;
126 const own = () => checksOf((r) => r.issueId === pull.id)[0];
127 await waitFor(() => own() !== undefined, { every: 20, within: 30_000 });
128 const { setIssueState } = await import("../src/actions/issues.ts");
129 const { getIssueById } = await import("../src/core/issues.ts");
130 expect(setIssueState(app, alice, repo, getIssueById(app.db, pull.id)!, "closed").ok).toBe(true);
131 await waitFor(() => own()?.state === "cancelled", { every: 50, within: 30_000 });
132 expect(own()?.summary).toContain("pull closed");
133 }, 60_000);
134
135 test("a landed pull's check cut by a forge restart is queued again at that head, runs, and its red still reaches main's line", async () => {
136 // Main checks for a marker of its own again, and passes.
137 const ready = await commitToBranch(app, alice, repo, { message: "Check for SNAPPED", files: [{ path: "forge.json", content: checkJson("sleep 2 && test ! -f SNAPPED") }] });
138 if (!ready.ok) throw new Error(JSON.stringify(ready.error));
139 await waitFor(() => checksOf((r) => r.commitOid === ready.value.commitOid && r.issueId === null && r.state === "ok").length > 0, { every: 50, within: 30_000 });
140 const branched = await commitToBranch(app, alice, repo, {
141 branch: "restarted",
142 base: "main",
143 message: "Break it across a restart",
144 files: [{ path: "SNAPPED", content: "x\n" }],
145 });
146 if (!branched.ok) throw new Error(JSON.stringify(branched.error));
147 const opened = await openPull(app, alice, repo, { title: "Across a restart", baseBranch: "main", headBranch: "restarted" });
148 if (!opened.ok) throw new Error(String(opened.error));
149 const pull = getPull(app.db, repo.id, opened.value.number)!;
150 const own = () => checksOf((r) => r.issueId === pull.id && r.commitOid === pull.headOid);
151 await waitFor(() => own()[0]?.state === "running", { every: 20, within: 30_000 });
152 // The forge dies under the check (its lease lapses with nothing to renew it), and the pull lands meanwhile.
153 const dying = own()[0]!;
154 await checks.stop();
155 const left = own().find((r) => r.id === dying.id)!;
156 if (left.state !== "running") {
157 // A clean stop already queued it again; make it the dead forge's lapsed run instead.
158 app.db.query("UPDATE run SET state = 'running', summary = '' WHERE id = ?1").run(dying.id);
159 for (const r of own()) if (r.id !== dying.id) app.db.query("DELETE FROM run WHERE id = ?1").run(r.id);
160 }
161 app.db.query("UPDATE run SET heartbeat_at = ?2 WHERE id = ?1").run(dying.id, new Date(Date.now() - STALE_AFTER_MS - 1_000).toISOString());
162 expect((await mergePull(app, alice, repo, getPull(app.db, repo.id, pull.number)!, "merge")).ok).toBe(true);
163 // The next forge boots: what the dead one left is swept, and its checks service runs it.
164 expect(requeueAbandonedChecks(app, STALE_AFTER_MS)).toBe(1);
165 expect(own().some((r) => r.summary.includes("no longer heads"))).toBe(false);
166 checks = startChecks(app, { forgeUrl: servers.url, concurrency: 1 });
167 await waitFor(() => own()[0]?.state === "failed", { every: 50, within: 30_000 });
168 expect(own()[0]!.attempt).toBe(1);
169 expect(redNow()).toMatchObject({ number: pull.number });
170 }, 90_000);

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

Keyboard shortcuts

Docs