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

An outside runner picks up a new forge build between jobs, never mid-job #17099

opened this

Merged 45h 37m ago, live in production

runner-upgrade → main 0 commits

  • Merged. runner-upgrade was merged into main as 492abf7.

Review

Sign in to review this change.
8 files changed +296 −12
docs/features/runners.md +36 −1
@@ -29,7 +29,8 @@ machine with room and never more than 64. They are enrolled as `local-1`…`loca
2929 at each start (a token from before is removed) and listed by
3030 `GET /api/v1/admin/runners` like any other; one that exits is started again
3131 after a pause that doubles up to a minute. Their environment holds only
32 `FORGE_URL`, their token, their directory and `PATH`, `HOME`, `LANG`. Runners
32 `FORGE_URL`, their token, their directory, `FORGE_RUNNER_EXIT_ON_UPGRADE=0`
33 and `PATH`, `HOME`, `LANG`. Runners
3334 started by hand are in addition: an admin removes them with
3435 `DELETE /api/v1/admin/runners/<id>`. Every `local-*` row created by `forge` is
3536 deleted at each boot, so never name a hand-made runner `local-N`.
@@ -71,6 +72,40 @@ and `socat` for cells.
7172 `forge-runner` directory under the temp directory), `FORGE_RUNNER_JOBS` how
7273 many jobs it runs at once (default 1).
7374
75 ## New code between jobs, never mid-job
76
77 A runner outside the forge's container outlives a release, so it must pick up
78 the new code itself. Every claim answer, a job or the empty `204`, names the
79 forge's build in the `x-forge-build` header (`0.7.684+a1b2c3d`, or the version
80 alone). The runner keeps the first build it heard. When a later answer names
81 another, it takes no new job: a runner holding none exits 0 at once, and a busy
82 one finishes its job, reports it, and then exits 0. Its log names both builds:
83 `the forge moved from 0.7.683+… to 0.7.684+…`. A job it claimed on the new
84 build is still run and reported first.
85
86 `FORGE_RUNNER_EXIT_ON_UPGRADE` is on unless set to `0`. The forge's own children
87 run with it off, because they are started again with the forge.
88
89 On the host, run such a runner as a container with `--restart=no`, and a timer
90 (a systemd timer or cron, every minute) that recreates it from the current
91 image when it has exited:
92
93 ```sh
94 docker inspect -f '{{.State.Running}}' forge-runner-1 2>/dev/null | grep -q true || {
95 docker rm -f forge-runner-1 >/dev/null 2>&1
96 docker run -d --name forge-runner-1 --restart=no \
97 --env-file /etc/forge/runner-1.env forge:current bun src/runner/main.ts
98 }
99 ```
100
101 The env file holds `FORGE_URL` and `FORGE_RUNNER_TOKEN`, so the token never
102 appears on a command line.
103
104 `--restart=no` matters: Docker's own restart would bring back the old image.
105 The timer pulls in the image the release just tagged. A release no longer cuts
106 the checks these runners hold: the forge hands their jobs over and the next one
107 takes them back (`checks/adopt.ts`).
108
74109 ## What a job is
75110
76111 Plain data, made by the forge from the repository's `forge.json` as it would
src/checks/runner_pool.ts +2
@@ -191,6 +191,8 @@ export function startLocalPool(app: App, options: PoolOptions): Pool {
191191 FORGE_URL: options.forgeUrl,
192192 FORGE_RUNNER_TOKEN: token,
193193 FORGE_RUNNER_DIR: dir,
194 // A child is started again from the forge's own image with it; it never restarts itself.
195 FORGE_RUNNER_EXIT_ON_UPGRADE: "0",
194196 ...(options.snapshots === undefined ? {} : { FORGE_RUNNER_SNAPSHOTS: options.snapshots }),
195197 });
196198 live.add(child);
src/http/api/runners.ts +5 −2
@@ -29,7 +29,9 @@ import {
2929 } from "../../checks/runner_jobs.ts";
3030 import { readSeed } from "../../checks/runner_seeds.ts";
3131 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
32 import { buildOf } from "../../kernel/version.ts";
3233 import { inFlight } from "../../perf/live.ts";
34 import { RUNNER_VERSION_HEADER } from "../../runner/upgrade.ts";
3335 import { advertiseRefs, serviceRpc } from "../../git/smart-http.ts";
3436 import type { Ctx, Handler } from "../context.ts";
3537 import { STRANGER_MAX } from "../limits.ts";
@@ -165,10 +167,11 @@ export function runnerRoutes(router: Router<Handler>): void {
165167 if (claim !== undefined) {
166168 if (claim.canary === true) hearCanary(ctx.app, claim.job.id);
167169 deskOf(ctx.app).ears.get(claim.job.id)?.wake();
168 return json({ job: claim.job, token: claim.token, lease });
170 return json({ job: claim.job, token: claim.token, lease }, 200, { [RUNNER_VERSION_HEADER]: buildOf() });
169171 }
170172 const left = until - Date.now();
171 if (left <= 0 || stop.aborted) return new Response(null, { status: 204 });
173 if (left <= 0 || stop.aborted)
174 return new Response(null, { status: 204, headers: { [RUNNER_VERSION_HEADER]: buildOf() } });
172175 // Resting, the claim holds nothing: a stall while it waits is not its own
173176 // (`perf/in_flight.ts`).
174177 await inFlight.rest(ctx.request, () => nextOffer(ctx.app, left, stop));
src/kernel/version.ts +9
@@ -54,6 +54,15 @@ export function running(
5454 };
5555 }
5656
57 /**
58 * The build in one header-safe token: `0.7.51+a1b2c3d`, or the version alone. Two forges that
59 * answer the same one run the same code; an outside runner restarts between jobs when it changes
60 * (`runner/main.ts`, `RUNNER_VERSION_HEADER`).
61 */
62 export function buildOf(r: Running = running()): string {
63 return r.commit === null ? r.version : `${r.version}+${shortOf(r.commit)}`;
64 }
65
5766 /** The stamp in a line: `0.7.51 · a1b2c3d`, or the version alone. */
5867 export function runningLine(r: Running = running()): string {
5968 return r.commit === null
src/runner/main.ts +39 −9
@@ -19,6 +19,9 @@
1919 * writes it after a green check of the default branch. Unset: every job is cold.
2020 * FORGE_RUNNER_ONCE `1`: one claim, then exit (a test, a cron line)
2121 * FORGE_CELLS `off`: never use cells here; jobs that require one go back to the forge
22 * FORGE_RUNNER_EXIT_ON_UPGRADE `0`: keep running when the forge's build changes. @default on:
23 * it exits 0 between jobs for its host to start it from the new image
24 * (`upgrade.ts`)
2225 */
2326
2427 import { stepFloorEnv } from "../sandbox/landlock.ts";
@@ -46,6 +49,7 @@ import type {
4649 import { runGit } from "../git/env.ts";
4750 import { isSafeOid } from "../git/guard.ts";
4851 import { during } from "../perf/jobs.ts";
52 import { BuildWatch, exitOnUpgrade, RUNNER_VERSION_HEADER } from "./upgrade.ts";
4953
5054 /** How often a job's lines go to the forge; each report renews the lease. */
5155 const REPORT_MS = 1_000;
@@ -70,6 +74,8 @@ export interface RunnerOptions {
7074 readonly once?: boolean | undefined;
7175 /** Stops it: no new claim, and a job in flight is handed back. */
7276 readonly signal?: AbortSignal | undefined;
77 /** Exit (resolve) when the forge's build changes, after the jobs in hand (`upgrade.ts`). */
78 readonly exitOnUpgrade?: boolean | undefined;
7379 readonly say?: ((line: string) => void) | undefined;
7480 }
7581
@@ -104,7 +110,12 @@ function checkVars(
104110 const dirName = (raw: string): string =>
105111 raw.replace(/[^A-Za-z0-9_-]/g, "").slice(0, 80) || "none";
106112
107 export async function runRunner(options: RunnerOptions): Promise<void> {
113 /** How a runner ended: `upgraded` when it left for a new forge build (`upgrade.ts`). */
114 export interface RunnerEnd {
115 readonly upgraded: boolean;
116 }
117
118 export async function runRunner(options: RunnerOptions): Promise<RunnerEnd> {
108119 const say = options.say ?? ((line: string) => console.log(line));
109120 const forge = options.forgeUrl.replace(/\/+$/, "");
110121 const stopping = options.signal ?? new AbortController().signal;
@@ -429,36 +440,52 @@ export async function runRunner(options: RunnerOptions): Promise<void> {
429440 }
430441 }
431442
443 // A new forge build: no claim loop asks again, and a claim waiting at the forge is let go. A
444 // job in hand is not: `stopping` alone hands one back.
445 const builds = new BuildWatch();
446 const upgrade = new AbortController();
447 const asking = AbortSignal.any([stopping, upgrade.signal]);
448 const hear = (res: Response): void => {
449 if (options.exitOnUpgrade !== true || !builds.hear(res.headers.get(RUNNER_VERSION_HEADER))) return;
450 say(builds.leaving!);
451 upgrade.abort();
452 };
453
432454 async function loop(): Promise<void> {
433 while (!stopping.aborted) {
455 while (!asking.aborted) {
434456 let res: Response;
435457 try {
436458 res = await post(
437459 "/api/v1/runner/claim",
438460 options.token,
439461 { wait: options.once === true ? 0 : CLAIM_WAIT_S, cells: cells.ok, jobs: slots },
440 stopping,
462 asking,
441463 );
442464 } catch {
443 if (stopping.aborted || options.once === true) return;
444 await pause(RETRY_MS, stopping);
465 if (asking.aborted || options.once === true) return;
466 await pause(RETRY_MS, asking);
445467 continue;
446468 }
469 // A job claimed on the new build is still this runner's: its body is read before a new build
470 // is heard, since hearing one aborts this claim's own signal and would cut the read, then it
471 // runs and is reported first.
472 const claim = res.status === 200 ? ((await res.json()) as Pick<Claim, "job" | "token">) : undefined;
473 hear(res);
447474 if (res.status === 401)
448475 throw new Error(
449476 "the forge does not know this runner token (removed, or mistyped)",
450477 );
451 if (res.status === 200)
452 await work((await res.json()) as Pick<Claim, "job" | "token">);
478 if (claim !== undefined) await work(claim);
453479 else {
454480 await res.body?.cancel().catch(() => {});
455 if (res.status !== 204) await pause(RETRY_MS, stopping);
481 if (res.status !== 204) await pause(RETRY_MS, asking);
456482 }
457483 if (options.once === true) return;
458484 }
459485 }
460486
461487 await Promise.all(Array.from({ length: slots }, () => loop()));
488 return { upgraded: upgrade.signal.aborted && !stopping.aborted };
462489 }
463490
464491 // An async function, not a top-level await: a module with one cannot be `require`d from a bundle
@@ -479,7 +506,7 @@ if (import.meta.main)
479506 for (const sig of ["SIGINT", "SIGTERM"] as const)
480507 process.on(sig, () => stopping.abort());
481508 try {
482 await runRunner({
509 const end = await runRunner({
483510 forgeUrl,
484511 token,
485512 root: process.env["FORGE_RUNNER_DIR"] ?? join(tmpdir(), "forge-runner"),
@@ -487,7 +514,10 @@ if (import.meta.main)
487514 snapshots: process.env["FORGE_RUNNER_SNAPSHOTS"] || undefined,
488515 once: process.env["FORGE_RUNNER_ONCE"] === "1",
489516 signal: stopping.signal,
517 exitOnUpgrade: exitOnUpgrade(process.env),
490518 });
519 // Its host starts it again from the current image (docs/features/runners.md).
520 if (end.upgraded) process.exit(0);
491521 } catch (error) {
492522 console.error(error instanceof Error ? error.message : String(error));
493523 process.exit(1);
src/runner/upgrade.ts added +42
@@ -0,0 +1,42 @@
1 /**
2 * An outside runner picks up new code between jobs, never mid-job. The forge names its build in
3 * every claim answer (`RUNNER_VERSION_HEADER`, `kernel/version.ts` `buildOf`). The runner keeps the
4 * first it heard; when a later answer names another, it takes no new job, finishes the one it
5 * holds, reports it, and exits 0, for its host to start it again from the current image
6 * (docs/features/runners.md). The forge's own children (`checks/runner_pool.ts`) are started
7 * again with the forge, so they turn this off.
8 *
9 * FORGE_RUNNER_EXIT_ON_UPGRADE `0`: keep running across forge versions. @default on
10 */
11
12 /** The response header a claim answer names the forge's build in. */
13 export const RUNNER_VERSION_HEADER = "x-forge-build";
14
15 /** Whether this runner exits when the forge's build changes. */
16 export const exitOnUpgrade = (env: Readonly<Record<string, string | undefined>>): boolean =>
17 env["FORGE_RUNNER_EXIT_ON_UPGRADE"] !== "0";
18
19 /** The forge's build as two claim answers name it: the first one heard, and a different one. */
20 export class BuildWatch {
21 #first: string | undefined;
22 #next: string | undefined;
23
24 /** Hear a claim answer's build; true the first time it differs from the first one heard. */
25 hear(build: string | null): boolean {
26 if (build === null || build === "") return false;
27 if (this.#first === undefined) {
28 this.#first = build;
29 return false;
30 }
31 if (build === this.#first || this.#next !== undefined) return false;
32 this.#next = build;
33 return true;
34 }
35
36 /** The line a runner says as it leaves for the new build, once one was heard. */
37 get leaving(): string | undefined {
38 return this.#next === undefined
39 ? undefined
40 : `the forge moved from ${this.#first} to ${this.#next}: no new job; exiting once the one in hand is reported, to start again from the current image`;
41 }
42 }
test/checks-runner-pool.test.ts +3
@@ -126,6 +126,7 @@ describe("startLocalPool", () => {
126126 for (const env of starts) {
127127 expect(Object.keys(env).sort()).toEqual([
128128 "FORGE_RUNNER_DIR",
129 "FORGE_RUNNER_EXIT_ON_UPGRADE",
129130 "FORGE_RUNNER_TOKEN",
130131 "FORGE_URL",
131132 "HOME",
@@ -133,6 +134,8 @@ describe("startLocalPool", () => {
133134 "PATH",
134135 ]);
135136 expect(env["FORGE_URL"]).toBe("http://localhost:1");
137 // Started again with the forge, a child never restarts itself on a new build.
138 expect(env["FORGE_RUNNER_EXIT_ON_UPGRADE"]).toBe("0");
136139 }
137140 // The crashed one's old token is gone, the new one opens a runner; two rows, not three.
138141 expect(listRunners(app.db).map((r) => r.name).sort()).toEqual(["local-1", "local-2"]);
test/runner-upgrade.test.ts added +160
@@ -0,0 +1,160 @@
1 /**
2 * An outside runner picks up new code between jobs, never mid-job (`runner/upgrade.ts`): the
3 * forge names its build in every claim answer, and when it changes the runner takes no new job,
4 * reports the one in hand, and ends for its host to start it from the current image.
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 { runRunner } from "../src/runner/main.ts";
11 import { RUNNER_VERSION_HEADER } from "../src/runner/upgrade.ts";
12
13 let root = "";
14 beforeAll(async () => {
15 root = await mkdtemp(join(tmpdir(), "forge-runner-upgrade-"));
16 });
17 afterAll(async () => {
18 await rm(root, { recursive: true, force: true });
19 });
20
21 /** A forge of claims only: `answer` says what the n-th claim gets. */
22 function fakeForge(answer: (n: number) => { build: string; job?: boolean }, onReport?: () => Promise<void>) {
23 const events: string[] = [];
24 let claims = 0;
25 const server = Bun.serve({
26 port: 0,
27 async fetch(req) {
28 const path = new URL(req.url).pathname;
29 if (path === "/api/v1/runner/claim") {
30 const a = answer(++claims);
31 events.push(`claim ${a.build}${a.job === true ? " job" : ""}`);
32 const headers = { [RUNNER_VERSION_HEADER]: a.build };
33 if (a.job !== true) return new Response(null, { status: 204, headers });
34 // A job whose commit is not one: the runner reports it abandoned at once.
35 const job = {
36 id: "j1",
37 run: "r1",
38 repo: "o/r",
39 commit: "nope",
40 depth: 1,
41 steps: [],
42 env: {},
43 limits: {},
44 timeoutS: 60,
45 egress: [],
46 egressMode: "report",
47 cell: "preferred",
48 cache: { repo: "o-r" },
49 };
50 return Response.json({ job, token: "forge_job_x", lease: 30 }, { headers });
51 }
52 if (path === "/api/v1/runner/jobs/j1") {
53 const body = (await req.json()) as { abandon?: string };
54 if (body.abandon === undefined) return new Response(null, { status: 200 });
55 await onReport?.();
56 events.push("reported");
57 return new Response(null, { status: 200 });
58 }
59 return new Response(null, { status: 404 });
60 },
61 });
62 return { url: `http://localhost:${server.port}`, events, claims: () => claims, stop: () => server.stop(true) };
63 }
64
65 test("an idle runner ends when a claim answer names a new build, saying both", async () => {
66 const forge = fakeForge((n) => ({ build: n === 1 ? "0.7.682+aaaaaaa" : "0.7.683+bbbbbbb" }));
67 const said: string[] = [];
68 const end = await runRunner({
69 forgeUrl: forge.url,
70 token: "forge_runner_x",
71 root: join(root, "idle"),
72 exitOnUpgrade: true,
73 say: (l) => said.push(l),
74 });
75 forge.stop();
76 expect(end.upgraded).toBe(true);
77 expect(forge.claims()).toBe(2);
78 expect(said.join("\n")).toContain("the forge moved from 0.7.682+aaaaaaa to 0.7.683+bbbbbbb");
79 });
80
81 test("a busy runner keeps its job: it reports it, and only then ends", async () => {
82 let release = (): void => {};
83 const reportHeld = new Promise<void>((resolve) => (release = resolve));
84 let arrived = (): void => {};
85 const reportArrived = new Promise<void>((resolve) => (arrived = resolve));
86 let heard = (): void => {};
87 const newBuildHeard = new Promise<void>((resolve) => (heard = resolve));
88 // Two slots: one takes the job on the old build; the other then hears the new one.
89 const forge = fakeForge(
90 (n) => (n === 1 ? { build: "old", job: true } : { build: "new" }),
91 () => {
92 arrived();
93 return reportHeld;
94 },
95 );
96 const said: string[] = [];
97 const ending = runRunner({
98 forgeUrl: forge.url,
99 token: "forge_runner_x",
100 root: join(root, "busy"),
101 jobs: 2,
102 exitOnUpgrade: true,
103 say: (l) => {
104 said.push(l);
105 if (l.includes("moved from old to new")) heard();
106 },
107 });
108 let ended = false;
109 void ending.then(() => (ended = true));
110 // The new build is heard while the job's report is held at the forge: the runner does not end.
111 await Promise.all([newBuildHeard, reportArrived]);
112 expect(ended).toBe(false);
113 release();
114 const end = await ending;
115 forge.stop();
116 expect(end.upgraded).toBe(true);
117 expect(forge.events.at(-1)).toBe("reported");
118 expect(forge.events.filter((e) => e.endsWith("job"))).toHaveLength(1);
119 });
120
121 test("a job claimed on the new build is run and reported before the runner ends", async () => {
122 // The first answer is empty on the old build; the second hands a job on the new one.
123 const forge = fakeForge((n) => (n === 1 ? { build: "old" } : { build: "new", job: true }));
124 const said: string[] = [];
125 const end = await runRunner({
126 forgeUrl: forge.url,
127 token: "forge_runner_x",
128 root: join(root, "new-job"),
129 exitOnUpgrade: true,
130 say: (l) => said.push(l),
131 });
132 forge.stop();
133 expect(end.upgraded).toBe(true);
134 expect(forge.events).toEqual(["claim old", "claim new job", "reported"]);
135 expect(said.join("\n")).toContain("the forge moved from old to new");
136 });
137
138 test("the same build keeps it running; and with the exit off (the forge's own children) a new one does too", async () => {
139 for (const [exitOnUpgrade, build] of [
140 [true, () => "same"],
141 [false, (n: number) => `b${n}`],
142 ] as const) {
143 const stop = new AbortController();
144 const forge = fakeForge((n) => {
145 if (n >= 5) stop.abort();
146 return { build: build(n) };
147 });
148 const end = await runRunner({
149 forgeUrl: forge.url,
150 token: "forge_runner_x",
151 root: join(root, `same-${exitOnUpgrade}`),
152 exitOnUpgrade,
153 signal: stop.signal,
154 say: () => {},
155 });
156 forge.stop();
157 expect(end.upgraded).toBe(false);
158 expect(forge.claims()).toBeGreaterThanOrEqual(5);
159 }
160 });

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

Keyboard shortcuts

Docs