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

#16201 (Hetzner Cloud provider) churned 8 agent runs in an hour and deployed… #16228

Merged opened this in answer to

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

Merged

scout/forge:scout/16215-16201-hetzner-cloud-provider-churned-8-a → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/16215-16201-hetzner-cloud-provider-churned-8-a was merged into main as e1ec690.

Review

Sign in to review this change.
6 files changed +329 −5
docs/features/release-waits-for-check.md added +15
@@ -0,0 +1,15 @@
1 ---
2 topic: Ship and undo
3 row: A release waits for its check
4 ---
5 # A release waits for its check (#16228)
6
7 A landed tree of the forge's own repository is swapped in (`FORGE_SELF_SWAP=1`) only once the full check of that commit has finished green (`src/release/check_wait.ts`). Running or queued holds it, polled every 5 seconds for up to 45 minutes. Failed, superseded (main moved on) or never started within the budget refuses it: a log line and a comment on the landed pull say why; the running process keeps serving. A forge with `FORGE_CHECKS=0` has no verdict to wait for and swaps as before.
8
9 The wait runs off the landing chain, so the next landing is not held behind a check still running.
10
11 ## A restart during the wait
12
13 The poll is in memory, so at boot `rearmRelease` (`src/checks/landing.ts`) reads the newest recorded release of the forge's repository and waits again, for what is left of the 45 minutes, when it passed preflight, is not the running commit, has its tree on disk and no open high scan finding holds it. A refusal after a restart is a log line, not a second comment. A release older than 45 minutes is not re-armed: land again or swap by hand.
14
15 Tests: `test/release-check-wait.test.ts` (the wait), `test/release-deploy-wiring.test.ts` (swap on green, none on red or with selfSwap off, re-arm).
src/checks/landing.ts +98 −5
@@ -9,11 +9,15 @@ import type { App } from "../app.ts";
99 import { parseCheck } from "../apps/manifest.ts";
1010 import { readFileAt } from "../apps/checkout.ts";
1111 import { addComment } from "../actions/issues.ts";
12 import type { User } from "../core/users.ts";
13 import { getIssueById } from "../core/issues.ts";
12 import { getUserById, type User } from "../core/users.ts";
13 import { getRepo } from "../core/repos.ts";
14 import { getIssue, getIssueById } from "../core/issues.ts";
15 import { existsSync } from "node:fs";

Non-blocking: move existsSync up with the other node: imports and drop the blank line.

16
1417 import { repoDir } from "../git/repos.ts";
1518 import {
1619 checkoutRelease,
20 releaseDir,
1721 DEFAULT_KEEP,
1822 preflightRelease,
1923 type Verdict,
@@ -22,7 +26,7 @@ import {
2226 import { beginSwap, endSwap, handover, startRelease } from "../release/swap.ts";
2327 import { running } from "../kernel/version.ts";
2428 import { noteReleased } from "../crew/note_closed.ts";
25 import { recordRelease, type Release } from "../release/record.ts";
29 import { latestReleaseOf, recordRelease, type Release } from "../release/record.ts";
2630 import { announceRelease } from "../release/announce.ts";
2731 import { scanHold } from "../release/scan_hold.ts";
2832 import type { Pull } from "../core/pulls.ts";
@@ -37,6 +41,7 @@ import { GATE_DEADLINE_MS, type GateRecord } from "./queue.ts";
3741 import { gateRecorded, gateRunning, recordedVerdict } from "./queue_store.ts";
3842 import { checksFor, type GateDone } from "./service.ts";
3943 import { landVerdict, type LandVerdict } from "./tiers.ts";
44 import { CHECK_WAIT_MS, waitForCheck } from "../release/check_wait.ts";
4045 import { ownProbeHeaders } from "../kernel/probe.ts";
4146 import { listKeeperReleases } from "../keeper/record.ts";
4247 import { treeOf } from "../keeper/swapper.ts";
@@ -137,7 +142,10 @@ export function releaseOnLand(
137142 () => undefined,
138143 () => undefined,
139144 );
140 return run;
145 return run.then(async (cutRelease) => {
146 await cutRelease.deploy?.();
147 return cutRelease.release;
148 });
141149 }
142150
143151 /**
@@ -170,6 +178,19 @@ async function cut(
170178 repo: Repo,
171179 pull: Pull,
172180 sha: string,
181 ): Promise<{ release: Release | undefined; deploy?: () => Promise<void> }> {
182 let deploy: (() => Promise<void>) | undefined;
183 const release = await cutTree(app, by, repo, pull, sha, (d) => (deploy = d));
184 return deploy === undefined ? { release } : { release, deploy };
185 }
186
187 async function cutTree(
188 app: App,
189 by: User,
190 repo: Repo,
191 pull: Pull,
192 sha: string,
193 later: (deploy: () => Promise<void>) => void,
173194 ): Promise<Release | undefined> {
174195 if (app.config.forgeRepo !== `${repo.ownerName}/${repo.name}`) return undefined;
175196 const dataDir = app.config.dataDir;
@@ -223,10 +244,82 @@ async function cut(
223244 warn: (m, f) => app.log.warn(m, f),
224245 ...(app.config.releaseSend === undefined ? {} : { send: app.config.releaseSend }),
225246 }).catch((error) => app.log.warn("release notice failed", { error: String(error) }));
226 if (verdict.ok && out.ok && !hold.held) await swapIn(app, by, repo, pull, sha, out.value);
247 // The deploy waits for the commit's own check to finish green, off the landing chain
248 // (`releaseOnLand`), so the next landing is not held behind a check still running.
249 if (verdict.ok && out.ok && !hold.held) later(() => deployWhenChecked(app, by, repo, pull, sha, out.value));
outdated

Untested wiring: add a test that a red or superseded check yields no swapIn and a comment, and that a green check swaps. Also handle a restart during the 45 minute wait, since the in-memory poll is lost.

227250 return release;
228251 }
229252
253 /** What the deploy leans on, so a test can stand in for the wait and the swap. */
254 export interface DeployDeps {
255 readonly wait: typeof waitForCheck;
256 readonly swap: (app: App, by: User, repo: Repo, pull: Pull, sha: string, dir: string) => Promise<void>;
257 }
258 const realDeps: DeployDeps = { wait: waitForCheck, swap: (...a) => swapIn(...a) };
259
260 /**
261 * Swap in only on a green check of the commit; red, superseded or late is a log line and, when
262 * `tell`, a comment on the landed pull. Nothing swaps while `FORGE_SELF_SWAP` is off.
263 */
264 export async function deployWhenChecked(
265 app: App,
266 by: User,
267 repo: Repo,
268 pull: Pull,
269 sha: string,
270 dir: string,
271 deps: DeployDeps = realDeps,
272 tell = true,
273 budgetMs?: number,
274 ): Promise<void> {
275 if (app.config.selfSwap !== true) return;
276 const waited = await deps.wait({
277 db: app.db,
278 repoId: repo.id,
279 branch: repo.defaultBranch,
280 sha,
281 checks: checksFor(app) !== undefined,
282 ...(budgetMs === undefined ? {} : { budgetMs }),
283 });
284 if (waited.ok) return deps.swap(app, by, repo, pull, sha, dir);
285 app.log.warn("release not swapped in: check not green", { sha: sha.slice(0, 12), line: waited.line });
286 if (tell)
287 addComment(
288 app,
289 by,
290 repo,
291 getIssueById(app.db, pull.id) ?? pull,
292 `The landed tree ${sha.slice(0, 12)} was not deployed: ${waited.line}. The running process keeps serving; a green check of the commit lets it ship.`,
293 );
294 }
295
296 /**
297 * A restart during the wait drops the in-memory poll, so boot asks again: the newest release of
298 * the forge's own repository, if it passed preflight, is younger than the wait, is not what runs
299 * and its tree is still on disk, waits for its check again (for what is left of the budget). It is
300 * a log line, not a second comment, when the check is not green. Scan holds are asked again.
301 */
302 export async function rearmRelease(app: App, deps: DeployDeps = realDeps): Promise<boolean> {
303 const slug = app.config.forgeRepo;
304 if (app.config.selfSwap !== true || slug === undefined) return false;
305 const [owner = "", name = ""] = slug.split("/");
306 const repo = getRepo(app.db, owner, name);
307 const release = repo && latestReleaseOf(app.db, repo.id);
308 if (!repo || !release || !release.ok || release.pullNumber === null) return false;
309 const left = CHECK_WAIT_MS - (Date.now() - Date.parse(release.createdAt));
310 if (!(left > 0) || release.sha === running().commit) return false;
311 const dir = releaseDir(app.config.dataDir, release.sha);
312 const pull = getIssue(app.db, repo.id, release.pullNumber) as Pull | undefined; // only id and number are read
313 const by = getUserById(app.db, repo.ownerId);
314 if (!pull || !by || !existsSync(dir)) return false;

Non-blocking: the as Pull cast hides that only id and number are read. Narrow the parameter type instead.

315 if ((await scanHold(app, repo, release.sha)).held) return false;
316 app.log.info("release re-armed after restart", { sha: release.sha.slice(0, 12) });
317 void deployWhenChecked(app, by, repo, pull, release.sha, dir, deps, false, left).catch((error) =>
318 app.log.warn("release deploy failed", { error: String(error) }),
319 );
320 return true;
321 }
322
230323 /**
231324 * Hand the port to a green release and drain this process, once the new one
232325 * has read healthy. Off unless `FORGE_SELF_SWAP=1`. A release that does not
src/main.ts +3
@@ -64,6 +64,7 @@ import { listApps } from "./core/apps.ts";
6464 import { holdAppHosts, releaseAppHosts } from "./apps/holding.ts";
6565 import { resolveAppDomain } from "./apps/host.ts";
6666 import { LAND_SETTLE_MS, requeueAbandonedChecks, startChecks } from "./checks/service.ts";
67 import { rearmRelease } from "./checks/landing.ts";
6768 import { VERIFY_EVERY_MS } from "./checks/verify.ts";
6869 import { RED_HOLD_MS } from "./checks/red_main.ts";
6970 import { stopQueue } from "./checks/queue.ts";
@@ -647,6 +648,8 @@ const checks =
647648 // Main is verified after landing at most this often (#7786).
648649 verifyEveryMs: VERIFY_EVERY_MS,
649650 });
651 // A release that was waiting for its check when this process started waits again (#16228).
652 if (checks !== undefined) void rearmRelease(app).catch((error) => app.log.warn("release re-arm failed", { error: String(error) }));
650653 // Under the runner placement the forge is its own first runner pool: N runner processes sized
651654 // to this machine beside serving, children of this process so a release replaces them (#14201).
652655 const localRunners = (() => {
src/release/check_wait.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * A release waits for its commit's check: the forge's own deploy is swapped in
3 * only once the full check of that commit (`checks/commit_check.ts`) has
4 * finished green. Running or queued holds it; failed, superseded (main moved
5 * on) or never started within the budget refuses it, with a line that says so.
6 * A forge that runs no checks (`FORGE_CHECKS=0`) has no verdict to wait for.
7 *
8 * Plain data in, plain data out; the clock and the sleep are arguments.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import { commitCheck } from "../checks/commit_check.ts";
13
14 /** How long a release waits for its check, and how often it looks. */

A 45 minute in-process poll does not survive a restart. Persist the pending deploy or re-arm it on boot.

15 export const CHECK_WAIT_MS = 45 * 60_000;
16 export const CHECK_POLL_MS = 5_000;
17
18 export type CheckWait = { readonly ok: true } | { readonly ok: false; readonly line: string };
19
20 export interface CheckWaitInput {
21 readonly db: Database;
22 readonly repoId: string;
23 readonly branch: string;
24 readonly sha: string;
25 /** False when this forge runs no checks: there is nothing to wait for. */
26 readonly checks: boolean;
27 readonly budgetMs?: number;
28 readonly pollMs?: number;
29 readonly sleep?: (ms: number) => Promise<void>;
30 readonly now?: () => number;
31 }
32
33 export async function waitForCheck(i: CheckWaitInput): Promise<CheckWait> {
34 if (!i.checks) return { ok: true };
35 const now = i.now ?? Date.now;
36 const sleep = i.sleep ?? ((ms: number) => Bun.sleep(ms));
37 const deadline = now() + (i.budgetMs ?? CHECK_WAIT_MS);
38 const short = i.sha.slice(0, 12);
39 for (;;) {
40 const c = commitCheck(i.db, i.repoId, i.branch, i.sha);
41 if (c.state === "ok") return { ok: true };
42 if (c.state === "failed") return { ok: false, line: `its check failed${c.summary === "" ? "" : `: ${c.summary}`}` };
43 if (c.state === "superseded") return { ok: false, line: `its check was cancelled (main moved past ${short})` };
44 if (now() >= deadline)
45 return { ok: false, line: c.state === "none" ? "its check never started" : "its check did not finish in time" };
46 await sleep(i.pollMs ?? CHECK_POLL_MS);
47 }
48 }
test/release-check-wait.test.ts added +77
@@ -0,0 +1,77 @@
1 /** A release is deployed only after its commit's check finished green (`release/check_wait.ts`). */
2
3 import { expect, test } from "bun:test";
4 import { createRepo } from "../src/actions/repos.ts";
5 import { createUser } from "../src/core/users.ts";
6 import { createApp } from "../src/app.ts";
7 import { createRun, claimRun, finishRun, cancelRun } from "../src/core/runs.ts";
8 import { waitForCheck } from "../src/release/check_wait.ts";
9 import { mkdtempSync } from "node:fs";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12
13 const SHA = "a".repeat(40);
14
15 async function fixture() {
16 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "forge-check-wait-")), port: 0 });
17 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
18 if (!u.ok) throw new Error("user");
19 const r = await createRepo(app, u.value, { name: "forge-code", visibility: "public" });
20 if (!r.ok) throw new Error("repo");
21 const repoId = r.value.id;
22 const check = createRun(app.db, { repoId, kind: "check", env: "main", commitOid: SHA });
23 let t = 0;
24 const base = { db: app.db, repoId, branch: "main", sha: SHA, checks: true, budgetMs: 100, pollMs: 10, now: () => t };
25 return { app, check, base, tick: (ms: number) => (t += ms), at: () => t };
26 }
27
28 test("a failed check blocks the deploy", async () => {
29 const f = await fixture();
30 claimRun(f.app.db, f.check.id);
31 finishRun(f.app.db, f.check.id, { state: "failed", summary: "2 tests failed" });
32 const r = await waitForCheck({ ...f.base, sleep: async () => { throw new Error("must not wait on a verdict"); } });
33 expect(r).toEqual({ ok: false, line: "its check failed: 2 tests failed" });
34 });
35
36 test("a running check holds the deploy until it is green, and never lets it through early", async () => {
37 const f = await fixture();
38 claimRun(f.app.db, f.check.id);
39 let polls = 0;
40 const r = await waitForCheck({
41 ...f.base,
42 budgetMs: 1000,
43 sleep: async (ms) => {
44 polls++;
45 f.tick(ms);
46 if (polls === 3) finishRun(f.app.db, f.check.id, { state: "ok", summary: "" });
47 },
48 });
49 expect(r).toEqual({ ok: true });
50 expect(polls).toBe(3);
51 });
52
53 test("a check still running at the budget is refused, not deployed", async () => {
54 const f = await fixture();
55 claimRun(f.app.db, f.check.id);
56 const r = await waitForCheck({ ...f.base, sleep: async (ms) => void f.tick(ms) });
57 expect(r).toEqual({ ok: false, line: "its check did not finish in time" });
58 });
59
60 test("a check that never started is refused at the budget", async () => {
61 const f = await fixture();
62 cancelRun(f.app.db, f.check.id, "x");
63 const none = await waitForCheck({ ...f.base, sha: "b".repeat(40), sleep: async (ms) => void f.tick(ms) });
64 expect(none).toEqual({ ok: false, line: "its check never started" });
65 });
66
67 test("a cancelled check (main moved on) is refused", async () => {
68 const f = await fixture();
69 cancelRun(f.app.db, f.check.id, "superseded");
70 const r = await waitForCheck({ ...f.base, sleep: async () => {} });
71 expect(r.ok).toBe(false);
72 });
73
74 test("a forge that runs no checks has nothing to wait for", async () => {
75 const f = await fixture();
76 expect(await waitForCheck({ ...f.base, checks: false })).toEqual({ ok: true });
77 });
test/release-deploy-wiring.test.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * The wiring of a release's deploy: only a green check swaps; red says so; a restart re-arms the
3 * wait.
4 */
5
6 import { expect, test } from "bun:test";
7 import { mkdirSync, mkdtempSync } from "node:fs";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { createApp } from "../src/app.ts";
13 import { createIssue, listComments } from "../src/core/issues.ts";
14 import { deployWhenChecked, rearmRelease, type DeployDeps } from "../src/checks/landing.ts";
15 import { recordRelease } from "../src/release/record.ts";
16 import { releaseDir } from "../src/release/checkout.ts";
17 import type { Pull } from "../src/core/pulls.ts";
18
19 const SHA = "b".repeat(40);
20
21 async function fixture(selfSwap: boolean) {
22 const app = createApp({ dataDir: mkdtempSync(join(tmpdir(), "forge-deploy-wiring-")), port: 0, selfSwap, forgeRepo: "alice/forge-code" });
23 const u = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
24 if (!u.ok) throw new Error("user");
25 const r = await createRepo(app, u.value, { name: "forge-code", visibility: "public" });
26 if (!r.ok) throw new Error("repo");
27 const issue = createIssue(app.db, { repoId: r.value.id, authorId: u.value.id, title: "landed" });
28 if (!issue.ok) throw new Error("issue");
29 const pull = issue.value as unknown as Pull;
30 const swaps: string[] = [];
31 const waits: (number | undefined)[] = [];
32 const deps = (verdict: { ok: true } | { ok: false; line: string }): DeployDeps => ({
33 wait: async (i) => (waits.push(i.budgetMs), verdict),
34 swap: async (_a, _b, _c, _d, sha) => void swaps.push(sha),
35 });
36 const comments = () => listComments(app.db, issue.value.id).map((c) => c.body);
37 return { app, user: u.value, repo: r.value, pull, swaps, waits, deps, comments };
38 }
39
40 test("a green check swaps the release in", async () => {
41 const f = await fixture(true);
42 await deployWhenChecked(f.app, f.user, f.repo, f.pull, SHA, "/x", f.deps({ ok: true }));
43 expect(f.swaps).toEqual([SHA]);
44 });
45
46 test("a red or superseded check does not swap, and the pull is told", async () => {
47 const f = await fixture(true);
48 await deployWhenChecked(f.app, f.user, f.repo, f.pull, SHA, "/x", f.deps({ ok: false, line: "its check failed: 2 tests failed" }));
49 expect(f.swaps).toEqual([]);
50 expect(f.comments().join("\n")).toContain("was not deployed: its check failed: 2 tests failed");
51 });
52
53 test("with selfSwap off nothing waits and nothing swaps", async () => {
54 const f = await fixture(false);
55 await deployWhenChecked(f.app, f.user, f.repo, f.pull, SHA, "/x", f.deps({ ok: true }));
56 expect(f.swaps).toEqual([]);
57 expect(f.waits).toEqual([]);
58 });
59
60 test("a restart re-arms the wait for the recorded release, for what is left of the budget", async () => {
61 const f = await fixture(true);
62 recordRelease(f.app.db, { sha: SHA, repoId: f.repo.id, pullNumber: f.pull.number, ok: true, line: "ok" });
63 mkdirSync(releaseDir(f.app.config.dataDir, SHA), { recursive: true });
64 let done!: () => void;
65 const swapped = new Promise<void>((r) => (done = r));
66 const d = f.deps({ ok: true });
67 expect(await rearmRelease(f.app, { wait: d.wait, swap: async (...a) => (await d.swap(...a), done()) })).toBe(true);
68 await swapped;
69 expect(f.swaps).toEqual([SHA]);
70 expect(f.waits[0]!).toBeGreaterThan(0);
71 expect(f.waits[0]!).toBeLessThanOrEqual(45 * 60_000);
72 });
73
74 test("a restart re-arms nothing for a failed preflight, a stale release, a missing tree or selfSwap off", async () => {
75 const f = await fixture(true);
76 expect(await rearmRelease(f.app, f.deps({ ok: true }))).toBe(false);
77 recordRelease(f.app.db, { sha: SHA, repoId: f.repo.id, pullNumber: f.pull.number, ok: true, line: "ok" });
78 expect(await rearmRelease(f.app, f.deps({ ok: true }))).toBe(false); // tree gone
79 const off = await fixture(false);
80 recordRelease(off.app.db, { sha: SHA, repoId: off.repo.id, pullNumber: off.pull.number, ok: true, line: "ok" });
81 mkdirSync(releaseDir(off.app.config.dataDir, SHA), { recursive: true });
82 expect(await rearmRelease(off.app, off.deps({ ok: true }))).toBe(false);
83 const bad = await fixture(true);
84 recordRelease(bad.app.db, { sha: SHA, repoId: bad.repo.id, pullNumber: bad.pull.number, ok: false, line: "red" });
85 mkdirSync(releaseDir(bad.app.config.dataDir, SHA), { recursive: true });
86 expect(await rearmRelease(bad.app, bad.deps({ ok: true }))).toBe(false);
87 expect(f.swaps.length + off.swaps.length + bad.swaps.length).toBe(0);
88 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs