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

An outside runner (a Mac) registers, claims a repository's labelled checks, and reports them as the pull's real check #18073

opened this in answer to

Merged 10h 4m ago, live in production

scout/forge:scout/18037-an-outside-runner-a-mac-registers-claims → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/18037-an-outside-runner-a-mac-registers-claims was merged into main as 1041b3a.

Review

Sign in to review this change.
24 files changed +820 −55
docs/features/outside-runner.md added +69
@@ -0,0 +1,69 @@
1 ---
2 topic: Ship and undo
3 row: Outside runner: a Mac that registers, claims a labelled check and reports it as the pull's check
4 ---
5 # An outside runner (#18037)
6
7 A machine the forge cannot reach (a Mac behind a router) takes checks by asking. The forge never
8 connects to it. It is the [runner protocol](runners.md) with four additions: labels, repositories,
9 a heartbeat and a pause. Nothing else is new: claim, log, report, give back and the job's git door
10 are the ones every runner uses.
11
12 ## What a repository says
13
14 ```json
15 { "check": { "run": "bun test", "label": "macos" } }
16 ```
17
18 `check.label` is one lower-case label. A check that names it goes only to a runner holding that
19 label and **never runs on the forge's own machine**, whatever `FORGE_CHECKS_PLACEMENT` says. With
20 no label, a repository behaves exactly as before. Only a pull's check and the default branch's push
21 check are offered. A step the forge cannot offer to a runner (the full tier on landing, a bisection
22 step) **fails in words** for a labelled check, naming the label; it is never run here, so a verdict
23 that was not the labelled machine's never lands code through `require_checks`.
24
25 ## The loop, as curl lines
26
27 An admin registers it once; the token is shown this once (`labels` and at least one `repos`, as
28 `owner/name`). It is the only credential the machine holds:
29
30 ```sh
31 curl -X POST -H "Authorization: Bearer $ADMIN_TOKEN" -H 'content-type: application/json' \
32 -d '{"name":"mac","labels":["macos","arm64","container"],"repos":["alice/lib"]}' $FORGE_URL/api/v1/admin/runners
33 ```
34
35 Each loop, with `RT` the runner token:
36
37 ```sh
38 curl -X POST -H "Authorization: Bearer $RT" -H 'content-type: application/json' -d '{"state":"idle"}' $FORGE_URL/api/v1/runner/heartbeat
39 curl -X POST -H "Authorization: Bearer $RT" -H 'content-type: application/json' -d '{"wait":25,"cells":true}' $FORGE_URL/api/v1/runner/claim
40 curl -X POST -H "Authorization: Bearer $JT" -H 'content-type: application/json' -d '{"step":"check","lines":["ran 3 tests"]}' $FORGE_URL/api/v1/runner/jobs/$JOB
41 curl -X POST -H "Authorization: Bearer $JT" -H 'content-type: application/json' -d '{"done":{"steps":[{"name":"check","ok":true,"ms":900}],"contained":true,"note":"container VM"}}' $FORGE_URL/api/v1/runner/jobs/$JOB
42 curl -X POST -H "Authorization: Bearer $JT" -H 'content-type: application/json' -d '{"interrupted":"the Mac went on battery"}' $FORGE_URL/api/v1/runner/jobs/$JOB
43 ```
44
45 - **Heartbeat** `{state: idle|busy|paused}` answers 204 and takes no labels: only the registration holds them. `paused` claims nothing until it
46 says otherwise; silence for 60 seconds reads as away.
47 - **Claim** answers 204 when nothing is queued for it, or `{job, token, lease}`: `job.id` is the run's
48 job, `job.commit` the commit, `job.steps` the commands, `job.env`, `job.timeoutS`, `job.label`.
49 `token` is the **fetch credential**: it fetches `job.commit` from
50 `$FORGE_URL/api/v1/runner/jobs/$JOB/git` by `git-upload-pack` (put it in git's environment, as
51 `http.extraHeader`, never argv), is read-only, serves that one repository's one commit, and
52 lasts 30 seconds, renewed by every report; any report, even `{}`, renews. It is no credential
53 anywhere else: no push, no account, no API.
54 - **Log and result** are the one report route. `done` with a step per command (`ok`, `error`) is
55 the pull's real check: it shows on the pull and the run page, and `require_checks` counts it. A
56 red stays red as the runner said it; a label has no machine of the forge's to re-run it on.
57 `contained` is what the runner says of its sandbox, shown as said, never proven by the forge.
58 - **Give back** is `{"interrupted": why}`: queued again, not a try. A claim whose runner goes
59 silent is queued again once; the second time the check fails with the reason in words.
60 - **No holder**: while no runner that is here, not paused, holds the label for the repository,
61 the check's log says so (`waiting: no runner holding the label "macos" …`), and after 15 minutes
62 the check fails and says that. It never sits queued without a word.
63
64 `POST /api/v1/admin/runners/{id}/pause` (`{reason?}`) and `/resume` stop and start a runner; `/revoke`
65 ends its token. Settings → Runners (Register, Pause, Resume, Revoke) and the terminal's Runners screen (`n` registers,
66 `p` pauses, `u` resumes, `x` revokes) register an outside runner with its labels and repositories, and list each with its labels, repositories and what its last heartbeat said.
67
68 Code: `src/checks/runner_jobs.ts` (labels in the claim), `src/checks/runner_step.ts` (the wait),
69 `src/http/api/runners.ts`, `src/tui/screens/runners.ts`. Test: `test/outside-runner.test.ts`.
src/actions/runners.ts +41 −6
@@ -12,6 +12,9 @@ import {
1212 deskOf,
1313 dropJob,
1414 enrolRunner,
15 LABEL_RE,
16 MAX_LABELS,
17 MAX_REPOS,
1518 lentFacts,
1619 listRunners,
1720 pauseRunner,
@@ -25,24 +28,55 @@ import {
2528 type RunnerResult,
2629 } from "../checks/runner_jobs.ts";
2730 import { isLocal } from "../checks/runner_pool.ts";
31 import { getRepo } from "../core/repos.ts";
2832 import type { User } from "../core/users.ts";
2933 import { err, ok, type Result } from "../kernel/result.ts";
3034
3135 const admin = (actor: User | undefined): actor is User =>
3236 actor !== undefined && actor.isAdmin && actor.kind === "user";
3337
38 /**
39 * An outside runner's enrolment (#18037): the labels it holds and the repositories (`owner/name`)
40 * it serves.
41 */
42 export interface OutsideInput {
43 readonly labels: readonly string[];
44 readonly repos: readonly string[];
45 }
46
47 /**
48 * Enrol a runner. With `outside` it holds labels and serves only the repositories it names, each
49 * of which must exist; `invalid` says what is wrong in words.
50 */
3451 export function enrol(
3552 app: App,
3653 actor: User | undefined,
3754 name: string,
3855 lend?: LendInput,
39 ): Result<{ runner: Enrolled; token: string }, "not_found"> {
56 outside?: OutsideInput,
57 ): Result<{ runner: Enrolled; token: string }, "not_found" | { invalid: string }> {
4058 if (!admin(actor)) return err("not_found");
41 const made = enrolRunner(app.db, name, actor.id, lend);
59 let held: { labels: string[]; repos: string[] } | undefined;
60 if (outside !== undefined && (outside.labels.length > 0 || outside.repos.length > 0)) {
61 if (lend !== undefined) return err({ invalid: "a lent runner takes no labels or repositories" });
62 if (outside.labels.length > MAX_LABELS || outside.labels.some((l) => !LABEL_RE.test(l)))
63 return err({ invalid: `labels: at most ${MAX_LABELS}, each lower-case letters, digits, . _ - (up to 32)` });
64 if (outside.repos.length === 0 || outside.repos.length > MAX_REPOS)
65 return err({ invalid: `repos: name 1 to ${MAX_REPOS} repositories as owner/name` });
66 const ids: string[] = [];
67 for (const full of outside.repos) {
68 const [owner, repoName, extra] = full.split("/");
69 const repo = owner === undefined || repoName === undefined || extra !== undefined ? undefined : getRepo(app.db, owner, repoName);
70 if (repo === undefined) return err({ invalid: `repos: ${full.slice(0, 80)} is not a repository here` });
71 ids.push(repo.id);
72 }
73 held = { labels: [...new Set(outside.labels)], repos: [...new Set(ids)] };
74 }
75 const made = enrolRunner(app.db, name, actor.id, lend, Date.now(), held);
4276 app.bus.append({
4377 kind: "runner.enrolled",
4478 actorId: actor.id,
45 payload: { id: made.runner.id, name: made.runner.name, ...(made.runner.scope === undefined ? {} : { scope: made.runner.scope }) },
79 payload: { id: made.runner.id, name: made.runner.name, ...(held === undefined ? {} : { labels: held.labels, repos: held.repos }), ...(made.runner.scope === undefined ? {} : { scope: made.runner.scope }) },
4680 });
4781 return ok(made);
4882 }
@@ -74,15 +108,16 @@ export function resume(app: App, actor: User | undefined, runnerId: string): Res
74108 }
75109
76110 /**
77 * An admin holds a runner: it claims nothing until resumed. The forge's own `local-N` is refused.
111 * An admin holds a runner: it claims nothing until resumed; a job it holds keeps its lease. The
112 * forge's own `local-N` is refused. `reason` is optional; the default names who held it.
78113 */
79 export function pause(app: App, actor: User | undefined, runnerId: string): Result<Enrolled, "not_found" | "local" | "revoked" | "paused"> {
114 export function pause(app: App, actor: User | undefined, runnerId: string, reason = ""): Result<Enrolled, "not_found" | "local" | "revoked" | "paused"> {
80115 const runner = enrolled(app, actor, runnerId);
81116 if (runner === undefined || !admin(actor)) return err("not_found");
82117 if (isLocal(runner)) return err("local");
83118 if (runner.revokedAt !== 0) return err("revoked");
84119 if (runner.paused !== "") return err("paused");
85 const why = `paused by ${actor.username}`;
120 const why = reason.trim().slice(0, 200) || `paused by ${actor.username}`;
86121 if (!pauseRunner(app.db, runnerId, why)) return err("not_found");
87122 app.bus.append({ kind: "runner.paused", actorId: actor.id, payload: { id: runnerId, name: runner.name, why } });
88123 return ok({ ...runner, paused: why });
src/apps/manifest.ts +11
@@ -543,8 +543,15 @@ export interface CheckManifest {
543543 readonly egress: readonly string[];
544544 /** `check.limits`: memory, CPU and disk, within the machine's maximum. */
545545 readonly limits: DeclaredLimits;
546 /**
547 * `check.label` (#18037): the one label of an outside runner (`macos`) the check needs. Only a
548 * runner holding it takes the check, and it never runs on the forge's own machine. Absent: as
549 * ever.
550 */
551 readonly label?: string | undefined;
546552 }
547553
554 const CHECK_LABEL = /^[a-z0-9][a-z0-9._-]{0,31}$/;
548555 const CHECK_TIMEOUT_DEFAULT = 20 * 60;
549556 export const CHECK_TIMEOUT_MAX = 2 * 60 * 60;
550557
@@ -592,7 +599,11 @@ export function parseCheck(
592599 if (!egress.ok) return egress;
593600 const limits = limitsField(check, "check");
594601 if (!limits.ok) return limits;
602 const label = check["label"];
603 if (label !== undefined && (typeof label !== "string" || !CHECK_LABEL.test(label)))
604 return invalid("forge.json: check.label must be a lower-case label such as macos (letters, digits, . _ -, at most 32)");
595605 return ok({
606 ...(label === undefined ? {} : { label }),
596607 run: run.value,
597608 fast: fast.value || null,
598609 full: full.value || run.value,
src/checks/lane_state.ts +2
@@ -69,6 +69,8 @@ export interface ChecksOptions {
6969 readonly checkStep?: typeof runStep | undefined;
7070 /** Test seam: what hands a check to a runner and waits on its answer (`runner_step.ts`). */
7171 readonly runnerStep?: typeof runRunnerStep | undefined;
72 /** How long a check naming a runner label waits for a holder of it. @default LABEL_WAIT_MS */
73 readonly labelWaitMs?: number | undefined;
7274 /** Test seam: what deepsec's review runs and installs with (`checks/deepsec_step.ts`). */
7375 readonly deepsec?: DeepsecDeps | undefined;
7476 /**
src/checks/runner_jobs.ts +100 −11
@@ -92,6 +92,8 @@ export interface RunnerJob {
9292 * verification names any, so its impact map, kept results and times reach the forge's stores.
9393 */
9494 readonly hands?: readonly string[];
95 /** The label `forge.json`'s check names: only a runner that holds it takes this job (#18037). */
96 readonly label?: string;
9597 }
9698
9799 /**
@@ -148,6 +150,12 @@ export interface Enrolled {
148150 readonly cpus: number;
149151 readonly memoryMiB: number;
150152 readonly hostCpus: number;
153 /** What an outside runner holds (`macos`, `arm64`): a job naming one goes only to a holder. */
154 readonly labels: readonly string[];
155 /** The repositories (ids) it serves; none listed is every one, as a runner always did. */
156 readonly repos: readonly string[];
157 /** What it last said in its heartbeat: `idle`, `busy` or `paused`; "" before one. */
158 readonly state: string;
151159 }
152160
153161 type RunnerRow = {
@@ -165,8 +173,21 @@ type RunnerRow = {
165173 cpus: number;
166174 memory_mib: number;
167175 host_cpus: number;
176 labels: string;
177 repos: string;
178 state: string;
179 };
180 const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus, labels, repos, state";
181
182 /** A JSON array of strings as kept in a column; anything else is none. */
183 const stringList = (raw: string): string[] => {
184 try {
185 const v: unknown = JSON.parse(raw);
186 return Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [];
187 } catch {
188 return [];
189 }
168190 };
169 const RUNNER_COLUMNS = "id, name, created_at, seen_at, scope, core_ms, day, day_core_ms, paused, revoked_at, jobs, cpus, memory_mib, host_cpus";
170191 const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => {
171192 const scope = readScope(r.name, r.scope, r.created_at);
172193 return {
@@ -183,9 +204,25 @@ const toEnrolled = (r: RunnerRow, now: number = Date.now()): Enrolled => {
183204 cpus: r.cpus,
184205 memoryMiB: r.memory_mib,
185206 hostCpus: r.host_cpus,
207 labels: stringList(r.labels),
208 repos: stringList(r.repos),
209 state: r.state,
186210 };
187211 };
188212
213 /**
214 * What an outside runner holds and says, in words for the page and the terminal; "" for any other.
215 */
216 export const outsideWords = (r: Pick<Enrolled, "labels" | "repos" | "state">): string =>
217 r.labels.length === 0
218 ? ""
219 : `labels ${r.labels.join(", ")} · serves ${r.repos.length} repositor${r.repos.length === 1 ? "y" : "ies"}${r.state === "" ? "" : ` · said ${r.state}`}`;
220
221 /** A label as `forge.json` and a runner write it: lower-case, at most 32 characters. */
222 export const LABEL_RE = /^[a-z0-9][a-z0-9._-]{0,31}$/;
223 export const MAX_LABELS = 8;
224 export const MAX_REPOS = 50;
225
189226 /** A name as it is kept: printable, at most 40 characters, "runner" when nothing is left. */
190227 export const runnerName = (raw: string): string =>
191228 raw.replace(/[^\x21-\x7e]/g, "").slice(0, 40) || "runner";
@@ -201,14 +238,24 @@ export function enrolRunner(
201238 createdBy: string,
202239 lend?: LendInput,
203240 now: number = Date.now(),
241 outside?: { readonly labels: readonly string[]; readonly repos: readonly string[] },
204242 ): { runner: Enrolled; token: string } {
205243 const runnerId = id();
206244 const token = `${RUNNER_TOKEN_PREFIX}${secret()}`;
207245 const kept = runnerName(lend === undefined ? name : lentName(runnerName(name)));
208246 const scope = readScope(kept, null, "") === undefined ? null : JSON.stringify(scopeFrom(lend ?? {}, now));
209247 db.query(
210 "INSERT INTO check_runner (id, name, token_hash, created_by, scope, salt) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
211 ).run(runnerId, kept, sha256(token), createdBy, scope, scope === null ? "" : secret());
248 "INSERT INTO check_runner (id, name, token_hash, created_by, scope, salt, labels, repos) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
249 ).run(
250 runnerId,
251 kept,
252 sha256(token),
253 createdBy,
254 scope,
255 scope === null ? "" : secret(),
256 JSON.stringify(outside?.labels ?? []),
257 JSON.stringify(outside?.repos ?? []),
258 );
212259 return { runner: getRunner(db, runnerId)!, token };
213260 }
214261
@@ -276,6 +323,33 @@ export function pauseRunner(db: Database, runnerId: string, why: string): boolea
276323 );
277324 }
278325
326 /**
327 * A runner's heartbeat (#18037): it is here, and says its state. The instant it asked is noted by
328 * its token's lookup. Labels are never taken from it: the admin's registration is their only
329 * source.
330 */
331 export function noteHeartbeat(db: Database, runnerId: string, said: { state: string }): void {
332 db.query("UPDATE check_runner SET state = ?2 WHERE id = ?1").run(runnerId, said.state);
333 }
334
335 /**
336 * Whether a runner that can take a job of this repository with this label is here now: asked
337 * within `SEEN_FRESH_MS`, not revoked, not paused, holding the label and serving the repository.
338 */
339 export function labelServed(db: Database, repoId: string, label: string, now: number): boolean {
340 return (
341 db
342 .query<{ n: number }, [number, string, string]>(
343 `SELECT COUNT(*) AS n FROM check_runner
344 WHERE seen_at > ?1 - ${SEEN_FRESH_MS} AND revoked_at = 0 AND paused = '' AND state != 'paused'
345 AND EXISTS (SELECT 1 FROM json_each(labels) WHERE value = ?3)
346 AND (repos = '[]' OR EXISTS (SELECT 1 FROM json_each(repos) WHERE value = ?2))
347 AND (scope IS NULL OR EXISTS (SELECT 1 FROM repo r WHERE r.id = ?2 AND r.visibility = 'public'))`,
348 )
349 .get(now, repoId, label)!.n > 0
350 );
351 }
352
279353 /** Let a paused runner claim again. False when it was not paused. */
280354 export function resumeRunner(db: Database, runnerId: string): boolean {
281355 return db.query("UPDATE check_runner SET paused = '' WHERE id = ?1 AND paused != ''").run(runnerId).changes > 0;
@@ -408,7 +482,7 @@ export function offerJob(
408482 ): RunnerJob {
409483 const job: RunnerJob = { ...input.job, id: id() };
410484 db.query(
411 "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
485 "INSERT INTO check_job (id, run_id, repo_id, dir, spec, needs_cell, author, label) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
412486 ).run(
413487 job.id,
414488 input.runId,
@@ -417,6 +491,7 @@ export function offerJob(
417491 JSON.stringify(job),
418492 job.cell === "required" ? 1 : 0,
419493 (input.author ?? "").toLowerCase(),
494 job.label ?? "",
420495 );
421496 return job;
422497 }
@@ -443,6 +518,9 @@ type ClaimRow = {
443518 ran: number;
444519 canary_at: number;
445520 box_id: string;
521 labels: string;
522 repos: string;
523 state: string;
446524 };
447525
448526 /**
@@ -457,10 +535,12 @@ export function claimJob(
457535 ): Claim | undefined {
458536 const me = db
459537 .query<ClaimRow, [string]>(
460 "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id FROM check_runner WHERE id = ?1",
538 "SELECT id, name, created_at, scope, day, day_core_ms, paused, revoked_at, salt, ran, canary_at, box_id, labels, repos, state FROM check_runner WHERE id = ?1",
461539 )
462540 .get(runner.id);
463 if (me === null || me.revoked_at !== 0 || me.paused !== "") return undefined;
541 // A runner that said `paused` in its heartbeat (a Mac on battery) takes nothing until it says
542 // otherwise.
543 if (me === null || me.revoked_at !== 0 || me.paused !== "" || me.state === "paused") return undefined;
464544 const kept = readScope(me.name, me.scope, me.created_at);
465545 // A game box's runner serves the box's repository's writers as they are now, not as they were
466546 // when it was enrolled.
@@ -472,26 +552,35 @@ export function claimJob(
472552 // own canaries; a runner this forge owns sees every job but a canary.
473553 // A runner enrolled for a game box (`games/lend.ts`) is held to that box's spare memory now,
474554 // which is 0 while a server wakes (`games/lend_fit.ts`); -1 for one that is not.
555 // A job naming a label goes only to a runner holding it, and a runner that lists repositories
556 // serves only those (#18037); both are `[]` for a runner as it always was.
557 const labels = me.labels;
558 const repos = me.repos;
475559 const spareMiB = me.box_id === "" ? -1 : boxSpareMiB(db, me.box_id, now);
476560 const queued =
477561 scope === undefined
478562 ? db
479 .query<{ id: string }, [number]>(
480 "SELECT id FROM check_job WHERE state = 'queued' AND canary_for IS NULL AND (needs_cell = 0 OR ?1 = 1) ORDER BY id LIMIT 8",
563 .query<{ id: string }, [number, string, string]>(
564 `SELECT id FROM check_job WHERE state = 'queued' AND canary_for IS NULL AND (needs_cell = 0 OR ?1 = 1)
565 AND (label = '' OR label IN (SELECT value FROM json_each(?2)))
566 AND (?3 = '[]' OR repo_id IN (SELECT value FROM json_each(?3)))
567 ORDER BY id LIMIT 8`,
481568 )
482 .all(runner.cells ? 1 : 0)
569 .all(runner.cells ? 1 : 0, labels, repos)
483570 : db
484 .query<{ id: string }, [string, string, number, number]>(
571 .query<{ id: string }, [string, string, number, number, string, string]>(
485572 `SELECT j.id FROM check_job j JOIN repo r ON r.id = j.repo_id
486573 WHERE j.state = 'queued' AND r.visibility = 'public' AND (j.canary_for IS NULL OR j.canary_for = ?1)
487574 AND (?3 = 0 OR j.author IN (SELECT value FROM json_each(?2)))
488575 -- A job that hands files back is this forge's own verification: never a lent runner's.
489576 AND json_extract(j.spec, '$.hands') IS NULL
577 AND (j.label = '' OR j.label IN (SELECT value FROM json_each(?5)))
578 AND (?6 = '[]' OR j.repo_id IN (SELECT value FROM json_each(?6)))
490579 -- A game box's runner (?4 >= 0, its spare memory now) takes only a job that declares memory and fits.
491580 AND (?4 < 0 OR COALESCE(json_extract(j.spec, '$.limits.memoryMiB'), 0) BETWEEN 1 AND ?4)
492581 ORDER BY j.id LIMIT 8`,
493582 )
494 .all(runner.id, JSON.stringify(scope.authors), scope.authors.length, spareMiB);
583 .all(runner.id, JSON.stringify(scope.authors), scope.authors.length, spareMiB, labels, repos);
495584 if (scope !== undefined && queued.length > 0 && canaryDue(saltOf(me), me.canary_at, me.ran)) {
496585 const canary = offerCanary(db, runner.id, queued[0]!.id, now, leaseMs);
497586 if (canary !== undefined) return canary;
src/checks/runner_step.ts +50 −8
@@ -24,6 +24,7 @@ import {
2424 deskOf,
2525 dropJob,
2626 handOverJob,
27 labelServed,
2728 jobSpec,
2829 lapseJobs,
2930 offerJob,
@@ -42,6 +43,8 @@ import { summariseCheckFailure } from "./summary.ts";
4243 export const RUNNER_WAIT_MS = 5_000;
4344 /** A job whose runner went silent this many times is not offered again. */
4445 export const MAX_CLAIMS = 2;
46 /** How long a check naming a label waits for a runner holding it before it fails, in words. */
47 export const LABEL_WAIT_MS = 15 * 60_000;
4548 /** How often a waiting check looks at its job when nothing woke it. */
4649 const LOOK_MS = 1_000;
4750
@@ -77,7 +80,11 @@ export type RunnerStepEnd =
7780 readonly start?: "warm" | "cold";
7881 readonly setupMs?: number;
7982 }
80 | { readonly taken: false; readonly why: string };
83 /**
84 * `final`: the check names a label, so the forge's own machine cannot stand in: `why` is its
85 * failure (#18037), not a reason to run here.
86 */
87 | { readonly taken: false; readonly why: string; readonly final?: true };
8188
8289 export interface RunnerStepInput {
8390 readonly runId: string;
@@ -93,6 +100,8 @@ export interface RunnerStepInput {
93100 readonly author?: string | undefined;
94101 /** @default RUNNER_WAIT_MS */
95102 readonly waitMs?: number | undefined;
103 /** How long a check naming a label waits for a runner holding it. @default LABEL_WAIT_MS */
104 readonly labelWaitMs?: number | undefined;
96105 /** Tests stand a clock in. @default Date.now */
97106 readonly now?: (() => number) | undefined;
98107 /**
@@ -150,8 +159,13 @@ export async function runRunnerStep(
150159 const adopted = desk.adopt.get(input.runId);
151160 if (adopted !== undefined) desk.adopt.delete(input.runId);
152161 const sent = adopted === undefined ? undefined : jobSpec(app.db, adopted);
162 // A check naming a label (#18037) cannot run on this machine: it waits for a runner that holds
163 // it, says so, and fails in words instead of running here.
164 const label = sent?.label ?? input.job.label ?? "";
165 const labelWaitMs = input.labelWaitMs ?? LABEL_WAIT_MS;
166 const fail = (why: string): RunnerStepEnd => (label === "" ? { taken: false, why } : { taken: false, why, final: true });
153167 // Nobody to offer it to: not a second is spent waiting.
154 if (sent === undefined && desk.claimers.size === 0 && !runnersAround(app.db, now()))
168 if (label === "" && sent === undefined && desk.claimers.size === 0 && !runnersAround(app.db, now()))
155169 return { taken: false, why: "no runner is connected" };
156170 const job =
157171 sent ??
@@ -194,6 +208,8 @@ export async function runRunnerStep(
194208 });
195209 let offeredAt = now();
196210 let holder = "";
211 let waitingSaid = false;
212 let seenClaims = 0;
197213 try {
198214 wakeClaimers(app);
199215 for (;;) {
@@ -215,7 +231,7 @@ export async function runRunnerStep(
215231 for (const lapsed of lapseJobs(app.db, now())) desk.held.delete(lapsed);
216232 const view = viewJob(app.db, job.id);
217233 if (view === undefined)
218 return { taken: false, why: "the job left the desk" };
234 return fail("the job left the desk");
219235 if (view.state === "queued" && holder !== "") {
220236 input.log(
221237 view.result?.startsWith("interrupted: ") === true
@@ -237,7 +253,7 @@ export async function runRunnerStep(
237253 const result = parseResult(view.result);
238254 const read = result === undefined ? undefined : readSteps(steps, result.steps);
239255 if (result === undefined || read === undefined)
240 return { taken: false, why: `runner ${holder} sent a result that does not match the job's steps` };
256 return fail(`runner ${holder} sent a result that does not match the job's steps`);
241257 return {
242258 taken: true,
243259 ...read,
@@ -253,10 +269,36 @@ export async function runRunnerStep(
253269 };
254270 }
255271 if (view.state === "returned")
256 return {
257 taken: false,
258 why: `runner ${holder} handed it back: ${view.result ?? ""}`,
259 };
272 return fail(`runner ${holder} handed it back: ${view.result ?? ""}`);
273 // Time a runner held the job is not time spent waiting for one.
274 if (view.claims !== seenClaims) {
275 seenClaims = view.claims;
276 offeredAt = now();
277 }
278 if (label !== "" && view.state === "queued") {
279 // Said on the check's log, and so on its pull, while no runner that could take it is here.
280 const served = labelServed(app.db, input.repoId, label, now());
281 if (!served && !waitingSaid) {
282 waitingSaid = true;
283 input.log(`waiting: no runner holding the label "${label}" is available for this repository; it waits up to ${Math.round(labelWaitMs / 60_000)} minutes`);
284 }
285 if (served && waitingSaid) {
286 waitingSaid = false;
287 input.log(`a runner holding the label "${label}" is available`);
288 }
289 const why =
290 view.claims >= MAX_CLAIMS
291 ? `runners holding the label "${label}" went silent ${view.claims} times while running it: the check failed, and was not run on this machine`
292 : now() - offeredAt >= labelWaitMs
293 ? `no runner holding the label "${label}" took it in ${Math.round(labelWaitMs / 60_000)} minutes: the check failed, and was not run on this machine`
294 : "";
295 if (why !== "") {
296 if (withdrawJob(app.db, job.id)) return fail(why);
297 continue;
298 }
299 await rest(LOOK_MS);
300 continue;
301 }
260302 if (
261303 view.state === "queued" &&
262304 (view.claims >= MAX_CLAIMS || now() - offeredAt >= waitMs)
src/checks/tier_runner.ts +28 −6
@@ -80,7 +80,17 @@ export async function tryRunner(
8080 // A runner that joined takes the steps (`runner_step.ts`, #13652): only a check that hands
8181 // back nothing but its log and its verdict, and only while a runner is connected. Not taken,
8282 // or an answer that is not the check's own verdict, and it runs here as it always has.
83 if (lane.placement.mode === "runner" && x.runId !== undefined && runnerTakes(x)) {
83 // A check naming a label (#18037) goes to a runner holding it whatever the placement, and is
84 // never run here.
85 const label = manifest.label ?? "";
86 if (label !== "" && !(x.runId !== undefined && runnerTakes(x))) {
outdated

HIGH: this branch needs runnerTakes(x). A labelled check that fails that test, or has no runId, falls through and runs on the forge's machine, against the label. Fail it in words here instead.

87 // Offered to no runner, and never run here: the label is the owner's word that this machine
88 // cannot be the one that says whether the code is good.
89 const error = `this check names the label "${label}" and cannot be offered to a runner here (${x.tier === "verify" || x.tier === "full" ? `the ${x.tier} tier runs on this machine only` : "a re-run of part of a check"}), so it was not run`;
90 write(error);
91 return { ok: false, error };
92 }
93 if ((lane.placement.mode === "runner" || label !== "") && x.runId !== undefined && runnerTakes(x)) {
8494 // The base's gate runs first there as here (#15291): the job carries the base commit and the
8595 // gate's blob id, and the check step writes the file from them (`withBaseGateFrom`).
8696 const baseGate = base === undefined ? undefined : await readFileAt(bare, base, "scripts/gate.ts", 1 << 20);
@@ -88,7 +98,7 @@ export async function tryRunner(
8898 const step = withBaseGateFrom(command, baseGate, base, blob?.ok ? blob.value.trim() : undefined);
8999 if (runsAsBaseGate(baseGate) && step === command) {
90100 write("placement: runner; the base's gate could not be named for it; running here");
91 return undefined;
101 return label === "" ? undefined : { ok: false, error: `the base's gate could not be named for the runner holding "${label}", and this check cannot run here` };
92102 }
93103 if (step !== command) write(`gate list: read from ${base!.slice(0, 7)}'s scripts/gate.ts, on the runner`);
94104 // Install scripts run only once the repository's review has passed (#3970), on a runner too:
@@ -97,7 +107,7 @@ export async function tryRunner(
97107 const install = installCommand(manifest.install, isQuarantined(app.db, repo.id));
98108 if (install === undefined) {
99109 write("placement: runner; the install command cannot be run without its scripts; running here");
100 return undefined;
110 return label === "" ? undefined : { ok: false, error: `the install command cannot be run without its scripts, and a check naming "${label}" cannot run here` };
101111 }
102112 const lines: string[] = [];
103113 // The shard count an admin set reaches a runner's check as it does one run here (#14844); the
@@ -159,11 +169,13 @@ export async function tryRunner(
159169 ...(seeds.length === 0 ? {} : { seeds }),
160170 // Main's whole verification hands back what it measured (`runner_hands.ts`).
161171 ...(handsTimesBack(x) ? { hands: HAND_FILES } : {}),
172 ...(label === "" ? {} : { label }),
162173 },
163174 log: write,
164175 output: lines,
165176 signal,
166 waitMs: lane.placement.waitMs,
177 waitMs: lane.placement.mode === "runner" ? lane.placement.waitMs : undefined,
178 ...(lane.options.labelWaitMs === undefined ? {} : { labelWaitMs: lane.options.labelWaitMs }),
167179 // A release stopping this forge leaves the job with its runner (`adoptRunnerJobs`).
168180 handingOver: () => lane.stopped,
169181 });
@@ -177,7 +189,7 @@ export async function tryRunner(
177189 if (sent !== undefined && sent.taken && !signal.aborted && handsTimesBack(x)) keepHands(app.config.dataDir, repo.id, run.id, write);
178190 if (sent === undefined || sent.taken || sent.why !== HANDED_OVER) dropHands(app.config.dataDir, run.id);
179191 const verify = x.tier === "verify";
180 if (sent === undefined) return undefined;
192 if (sent === undefined) return label === "" ? undefined : { ok: false, error: `no runner holding "${label}" gave a verdict, and a check naming it is not run on this machine` };
181193 // Handed over: no verdict here, and not run here either; the forge that comes up waits on it.
182194 if (!sent.taken && sent.why === HANDED_OVER) {
183195 write(HANDED_OVER);
@@ -185,7 +197,17 @@ export async function tryRunner(
185197 }
186198 // A verification's red is its own verdict, named by file for the bisection: never one or two
187199 // tests re-run here alone.
188 const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted, !verify) : sent.why;
200 // A check naming a label has no machine of the forge's to fall back on: the runner's answer
201 // stands as it said it, and one it could not give fails the check with its reason.
202 if (label !== "" && !sent.taken && sent.final === true) {
203 write(sent.why);
204 return { ok: false, error: sent.why };
205 }
206 const verdict = sent.taken ? runnerVerdict(sent, lines, signal.aborted, !verify && label === "") : sent.why;
207 if (typeof verdict === "string" && label !== "") {
208 write(`placement: runner ${sent.taken ? sent.runner : ""}; ${verdict}`);
209 return { ok: false, error: verdict };
210 }
189211 if (typeof verdict === "string") write(`placement: runner; ${verdict}; running here`);
190212 else if ("alone" in verdict) {
191213 write(`placement: runner; one or two tests failed on runner ${verdict.runner}: only they are re-run here, alone, never the whole check`);
src/contract/openapi/routes/getApiV1AdminRunners.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "The enrolled runners, each with when it last asked for work",
88 detail:
9 "The enrolled runners, each with when it last asked for work (seenAt, milliseconds; 0 for never); answers { items, next_cursor }",
9 "The enrolled runners, each with when it last asked for work (seenAt, milliseconds; 0 for never); state (idle, busy or paused: what its heartbeat last said), labels and repos (ids; none listed is every repository); answers { items, next_cursor }",
1010 auth: true,
1111 role: "admin",
1212 refuses: [404],
src/contract/openapi/routes/index.ts +1
@@ -499,6 +499,7 @@ export { route as postApiV1ReposOwnerNameSync } from "./postApiV1ReposOwnerNameS
499499 export { route as postApiV1ReposOwnerNameTransfer } from "./postApiV1ReposOwnerNameTransfer.ts";
500500 export { route as postApiV1ReposOwnerNameUpstreamCheck } from "./postApiV1ReposOwnerNameUpstreamCheck.ts";
501501 export { route as postApiV1RunnerClaim } from "./postApiV1RunnerClaim.ts";
502 export { route as postApiV1RunnerHeartbeat } from "./postApiV1RunnerHeartbeat.ts";
502503 export { route as postApiV1RunnerJobsId } from "./postApiV1RunnerJobsId.ts";
503504 export { route as postApiV1RunnerJobsIdGitGitUploadPack } from "./postApiV1RunnerJobsIdGitGitUploadPack.ts";
504505 export { route as postApiV1RunnerJobsIdHand } from "./postApiV1RunnerJobsIdHand.ts";
src/contract/openapi/routes/postApiV1AdminRunners.ts +4 −2
@@ -6,11 +6,13 @@ export const route: Route = {
66 summary:
77 "Enrol a runner: a machine that takes checks off this forge",
88 detail:
9 "Enrol a runner: a machine that takes checks off this forge when FORGE_CHECKS_PLACEMENT=runner (admin scope); answers its row and its token, shown this once. With lend ({ authors?, days?, coreMinPerDay? }) it is a lent runner another forge runs: named lent-…, public pulls only, in a cell, until it expires and within its core-minutes per day (docs/features/lent-runners.md)",
9 "Enrol a runner: a machine that takes checks off this forge when FORGE_CHECKS_PLACEMENT=runner (admin scope); answers its row and its token, shown this once. With lend ({ authors?, days?, coreMinPerDay? }) it is a lent runner another forge runs: named lent-…, public pulls only, in a cell, until it expires and within its core-minutes per day (docs/features/lent-runners.md). With labels (e.g. [\"macos\",\"arm64\"]) and repos (owner/name, at least one) it is an outside runner: it takes only a check whose forge.json check.label it holds, and only for those repositories (docs/features/outside-runner.md); 422 invalid_runner says what is wrong",
1010 auth: true,
1111 role: "admin",
12 body: { name: "string", lend: "object" },
12 body: { name: "string", lend: "object", labels: "array", repos: "array" },
1313 status: 201,
1414 reply: { id: "string", name: "string", createdAt: "string", seenAt: "integer", token: "string" },
1515 refuses: [404],
16 errorStatus: { 422: "labels or repos are not well-formed, or name a repository that is not here (invalid_runner)" },
17 refusals: { invalid_runner: "what is wrong with the labels or repos" },
1618 };
src/contract/openapi/routes/postApiV1AdminRunnersIdPause.ts +2 −1
@@ -5,9 +5,10 @@ export const route: Route = {
55 path: "/api/v1/admin/runners/{id}/pause",
66 summary: "Pause a runner: it claims no more work until resumed",
77 detail:
8 "Hold a runner (admin scope): its claim is refused and a job it holds finishes; POST …/resume lets it claim again. The paused text names who held it. 422 local for the forge's own local-N runner, revoked for a revoked one, paused when it is paused already; 404 when there is none",
8 "Hold a runner (admin scope; takes an optional reason): its claim is refused and a job it holds finishes; POST …/resume lets it claim again. The paused text names who held it. 422 local for the forge's own local-N runner, revoked for a revoked one, paused when it is paused already; 404 when there is none",
99 auth: true,
1010 role: "admin",
11 body: { reason: "string" },
1112 status: 200,
1213 reply: { id: "string", name: "string", paused: "string" },
1314 refuses: [404],
src/contract/openapi/routes/postApiV1RunnerHeartbeat.ts added +15
@@ -0,0 +1,15 @@
1 import type { Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: "/api/v1/runner/heartbeat",
6 summary: "A runner says it is here, its state. Takes a runner token as the bearer",
7 detail:
8 "A runner says it is available (runner token as the bearer, never an account's): state is idle, busy or paused (paused: it takes no job until it says otherwise, as a Mac on battery); labels are never taken from a runner: the admin's registration holds them. A runner silent for 60 seconds reads as away, and a check naming a label no available runner holds says so on its pull. Answers 204",
9 auth: false,
10 role: "anonymous",
11 body: { state: "string" },
12 alsoStatus: [204],
13 refusals: { unauthorized: "401: not a runner token this forge enrolled", invalid_heartbeat: "422: state is idle, busy or paused" },
14 errorStatus: { 401: "`unauthorized`: not a runner token this forge enrolled", 422: "`invalid_heartbeat`: the state is not what is asked" },
15 };
src/core/migration-pins/20261204054000-runner-labels.pin added +1
@@ -0,0 +1,1 @@
1 3f73178f741a60cb770c151fed9479850a03a106575960c59d5742b8b25b1c66
src/core/migrations/20261204054000-runner-labels.ts added +10
@@ -0,0 +1,10 @@
1 // An outside runner (#18037): labels it holds and the repositories it serves, both JSON arrays on
2 // `check_runner` ('[]' is today's runner: no labels, every repository), and the state it last said
3 // in its heartbeat. On `check_job`, the label its repository's `forge.json` check names ('' for
4 // none: a job any runner may take, as before). Additive.
5 export default `
6 ALTER TABLE check_runner ADD COLUMN labels TEXT NOT NULL DEFAULT '[]';
7 ALTER TABLE check_runner ADD COLUMN repos TEXT NOT NULL DEFAULT '[]';
8 ALTER TABLE check_runner ADD COLUMN state TEXT NOT NULL DEFAULT '';
9 ALTER TABLE check_job ADD COLUMN label TEXT NOT NULL DEFAULT '';
10 `;
src/http/api/runners.ts +26 −4
@@ -26,6 +26,7 @@ import {
2626 jobByToken,
2727 nextOffer,
2828 interruptJob,
29 noteHeartbeat,
2930 noteHeldReport,
3031 noteRunnerJobs,
3132 noteRunnerMachine,
@@ -126,8 +127,13 @@ export function runnerRoutes(router: Router<Handler>): void {
126127 const denied = accountAdmin(ctx, "admin");
127128 if (denied) return denied;
128129 const input = await body(ctx.request);
129 const made = enrol(ctx.app, ctx.auth.user, str(input.name), readLend(input.lend));
130 if (!made.ok) return notFound();
130 const strings = (v: unknown): string[] | undefined =>
131 v === undefined ? [] : Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined;
132 const labels = strings(input.labels);
133 const repos = strings(input.repos);
134 if (labels === undefined || repos === undefined) return apiError("invalid_runner", 422, "labels and repos are arrays of strings");
135 const made = enrol(ctx.app, ctx.auth.user, str(input.name), readLend(input.lend), { labels, repos });
136 if (!made.ok) return made.error === "not_found" ? notFound() : apiError("invalid_runner", 422, made.error.invalid);
131137 return json({ ...made.value.runner, token: made.value.token }, 201);
132138 });
133139
@@ -143,10 +149,11 @@ export function runnerRoutes(router: Router<Handler>): void {
143149 });
144150
145151 // Beside resume: an admin holds a runner; its running job finishes, it claims no more.
146 router.add("POST", "/api/v1/admin/runners/:id/pause", (ctx) => {
152 router.add("POST", "/api/v1/admin/runners/:id/pause", async (ctx) => {
147153 const denied = accountAdmin(ctx, "admin");
148154 if (denied) return denied;
149 const done = pause(ctx.app, ctx.auth.user, ctx.params.id!);
155 const input = await body(ctx.request);
156 const done = pause(ctx.app, ctx.auth.user, ctx.params.id!, str(input.reason));
150157 if (done.ok) return json({ id: done.value.id, name: done.value.name, paused: done.value.paused });
151158 if (done.error === "local") return apiError("local", 422, "a local-N runner is the forge's own; it cannot be paused");
152159 if (done.error === "revoked") return apiError("revoked", 422, "that runner is revoked");
@@ -224,6 +231,21 @@ export function runnerRoutes(router: Router<Handler>): void {
224231 return gone.ok ? new Response(null, { status: 204 }) : notFound();
225232 });
226233
234 // A runner says it is here, in what state, and which labels it holds (#18037). Silence past
235 // `SEEN_FRESH_MS` reads as away. Its claim and its reports say the same without the state.
236 router.add("POST", "/api/v1/runner/heartbeat", async (ctx) => {
237 const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now());
238 if (runner === undefined) return unauthorized();
239 const input = await boundedBody(ctx.request, STRANGER_MAX);
240 if (input === "too_large") return apiError("too_large", 413, `at most ${STRANGER_MAX} bytes`);
241 const state = str(input.state);
242 if (state !== "idle" && state !== "busy" && state !== "paused")
243 return apiError("invalid_heartbeat", 422, "state is idle, busy or paused");
outdated

HIGH: labels from the heartbeat replaces the runner's labels. A runner enrolled with no repositories serves every repository, so it can grant itself a label and claim any repository's labelled jobs. Labels come from the admin's registration only: drop this, or allow only a subset of the enrolled labels.

244 noteHeartbeat(ctx.app.db, runner.id, { state });
245 wakeClaimers(ctx.app);
246 return new Response(null, { status: 204 });
247 });
248
227249 // A runner asks for work. Held open until a job is offered or `wait` seconds pass (204).
228250 router.add("POST", "/api/v1/runner/claim", async (ctx) => {
229251 const runner = runnerByToken(ctx.app.db, bearer(ctx.request), Date.now());
src/http/lazy_lists.ts +3
@@ -30,6 +30,8 @@ export const SETTINGS_ROUTES = [
3030 ["POST", "/settings/runners/:id/remove"],
3131 ["POST", "/settings/runners/:id/revoke"],
3232 ["POST", "/settings/runners/:id/resume"],
33 ["POST", "/settings/runners/:id/pause"],
34 ["POST", "/settings/runners/register"],
3335 ["GET", "/settings/runners/lending/live"],
3436 ["POST", "/settings/runners/lending"],
3537 ["POST", "/settings/runners/lending/:id/stop"],
@@ -1302,6 +1304,7 @@ export const API_ROUTES = [
13021304 ["POST", "/api/v1/admin/lending/:id/resume"],
13031305 ["GET", "/api/v1/admin/runners"],
13041306 ["DELETE", "/api/v1/admin/runners/:id"],
1307 ["POST", "/api/v1/runner/heartbeat"],
13051308 ["POST", "/api/v1/runner/claim"],
13061309 ["POST", "/api/v1/runner/jobs/:id"],
13071310 ["GET", "/api/v1/runner/jobs/:id/seed"],
src/http/marks/settings.json +2
@@ -10,6 +10,8 @@
1010 "/settings/runners/:id/remove": "open",
1111 "/settings/runners/:id/revoke": "open",
1212 "/settings/runners/:id/resume": "open",
13 "/settings/runners/:id/pause": "open",
14 "/settings/runners/register": "open",
1315 "/settings/runners/lending/live": "open",
1416 "/settings/runners/lending": "open",
1517 "/settings/runners/lending/:id/stop": "open",
src/http/settings_routes.ts +3 −1
@@ -24,7 +24,7 @@ import { paymentsCsv, paymentsPage } from "../web/pages/payments.ts";
2424 import { billingPage, billingChange, billingGrant, billingSetLinks, billingSetPortal, billingMakeCode, billingRevokeCode, stripeConnect, stripeDisconnect, stripeSecret, orderRetry } from "../web/pages/billing.ts";
2525 import { economicsPage, economicsSet } from "../web/pages/economics.ts";
2626 import { trustedAdd, trustedPage, trustedRemove, trustedRevert, trustedStop } from "../web/pages/trusted.ts";
27 import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerRemove, runnerResume, runnerRevoke, runnersPage } from "../web/pages/runners.ts";
27 import { lendingLive, lendingOffer, lendingResume, lendingStop, lendingStopNow, runnerPause, runnerRegister, runnerRemove, runnerResume, runnerRevoke, runnersPage } from "../web/pages/runners.ts";
2828 import { usagePage } from "../web/pages/usage.ts";
2929 import { spendPage } from "../web/pages/spend-tab.ts";
3030 import { securityControlsPage } from "../web/pages/security_controls.ts";
@@ -174,6 +174,8 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
174174 router.add("POST", "/settings/runners/:id/remove", runnerRemove);
175175 router.add("POST", "/settings/runners/:id/revoke", runnerRevoke);
176176 router.add("POST", "/settings/runners/:id/resume", runnerResume);
177 router.add("POST", "/settings/runners/:id/pause", runnerPause);
178 router.add("POST", "/settings/runners/register", runnerRegister);
177179 router.add("GET", "/settings/runners/lending/live", lendingLive);
178180 router.add("POST", "/settings/runners/lending", lendingOffer);
179181 router.add("POST", "/settings/runners/lending/:id/stop", lendingStop);
src/tui/screens/runners.ts +43 −7
@@ -6,7 +6,7 @@
66 * offered it.
77 */
88
9 import { list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
9 import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1010 import { isLocal } from "../../checks/runner_pool.ts";
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
1212 import { proofByRunner, proofWords } from "../../games/lent_proof.ts";
@@ -14,7 +14,7 @@ import { cannotByRunner } from "../../games/lend_why.ts";
1414 import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts";
1515 import { lentLine, scopeLine } from "../../checks/lent_scope.ts";
1616 import { yieldNote, yieldState } from "../../checks/lent_yield.ts";
17 import { heldByRunner, lentIn, workByRunner, type Enrolled, runnerMachineWords } from "../../checks/runner_jobs.ts";
17 import { heldByRunner, lentIn, workByRunner, type Enrolled, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts";
1818 import type { Ctx, Screen } from "../app/app.ts";
1919 import { binding } from "../app/keys.ts";
2020 import { style } from "../term/style.ts";
@@ -35,7 +35,7 @@ function lendingLine(f: Session): string {
3535 }
3636
3737 /** A lent runner that still works: `x` revokes it rather than removing its ledger. */
38 const revocable = (r: Enrolled): boolean => r.scope !== undefined && r.revokedAt === 0;
38 const revocable = (r: Enrolled): boolean => (r.scope !== undefined || r.labels.length > 0) && r.revokedAt === 0;
3939
4040 const stateWords = (r: Enrolled, now: number): string =>
4141 r.revokedAt !== 0 ? "revoked" : r.paused !== "" ? "paused" : STATE_WORDS[runnerState(r.seenAt, now)];
@@ -78,7 +78,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
7878 const asked = r.seenAt === 0 ? "has not asked for work" : `last asked ${new Date(r.seenAt).toISOString().slice(0, 16).replace("T", " ")}`;
7979 return {
8080 title: `${r.name} ${stateWords(r, now)}${isLocal(r) ? " (the forge's own)" : ""}`,
81 meta: `${asked}${machine === "" ? "" : ` · ${machine}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`,
81 meta: `${asked}${machine === "" ? "" : ` · ${machine}`}${outsideWords(r) === "" ? "" : ` · ${outsideWords(r)}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`,
8282 // Under the row, where a narrow screen never gives it up as it does the meta's pieces.
8383 ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}),
8484 };
@@ -118,6 +118,37 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
118118 );
119119 };
120120
121 /** Register an outside runner: name, labels and repositories; its token is shown once. */
122 const register = (): void => {
123 ctx.push(
124 promptScreen(ctx, screen, {
125 title: "Register an outside runner",
126 label: "Name, labels (comma-separated), repositories (owner/name, comma-separated)",
127 placeholder: "mac macos,arm64 alice/lib",
128 hint: "The labels you give here are the only ones it can ever hold.",
129 onSubmit: (value) => {
130 const [name, labels, repos] = value.trim().split(/\s+/);
131 if (name === undefined || name === "" || labels === undefined || repos === undefined) return "Three words: a name, its labels and its repositories";
132 const split = (w: string): string[] => w.split(",").filter((x) => x !== "");
133 const made = enrol(f.app, f.user, name, undefined, { labels: split(labels), repos: split(repos) });
134 if (!made.ok) return made.error === "not_found" ? "Only a forge admin registers runners." : `Not registered: ${made.error.invalid}.`;
135 ctx.invalidate();
136 return Promise.resolve().then(() =>
137 ctx.push(
138 confirmScreen(ctx, screen, {
139 title: `Runner ${made.value.runner.name} registered`,
140 body: ["Its token, shown this once:", made.value.token],
141 actions: [{ label: "Done" }],
142 onChoose: () => {},
143 width: 80,
144 }),
145 ),
146 );
147 },
148 }),
149 );
150 };
151
121152 /** s, S and u on an offer: stop once its jobs finish, stop now, lend again. */
122153 const onOffer = (o: LendView, key: string): boolean => {
123154 if (key === "u") {
@@ -145,8 +176,9 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
145176 keys: [
146177 binding(["j", "k"], "move cursor"),
147178 binding(["x"], "revoke or remove a runner"),
148 binding(["p"], "pause a runner"),
179 binding(["p"], "pause"),
149180 binding(["u"], "resume"),
181 binding(["n"], "register an outside runner"),
150182 binding(["c"], "lend runners to a forge"),
151183 binding(["s"], "stop lending"),
152184 binding(["S"], "stop lending now"),
@@ -158,7 +190,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
158190 ? "Only a forge admin sees the runners."
159191 : entries().length === 0
160192 ? "No runner is enrolled; checks run on the forge's own machine. c lends runners to another forge."
161 : "The machines that take this forge's checks; x revokes a lent one or removes a hand-made one, p pauses, u resumes. c lends runners to another forge; on an offer s stops, S stops now.";
193 : "The machines that take this forge's checks; x revokes a lent or outside one or removes a hand-made one, p pauses, u resumes. c lends runners to another forge; on an offer s stops, S stops now.";
162194 const waiting = mayRunners(f) ? yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"])) : "";
163195 s.text(head!.x, head!.y, truncate(waiting === "" ? text : waiting, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
164196 const lent = mayRunners(f) ? [lentLine(lentIn(f.db, Date.now())), lendingLine(f)].filter((l) => l !== "").join(" · ") : "";
@@ -173,12 +205,16 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
173205 offer();
174206 return true;
175207 }
208 if (e.key === "n") {
209 register();
210 return true;
211 }
176212 const picked = all[state.index];
177213 if (picked?.kind === "offer") return e.key === "s" || e.key === "S" || e.key === "u" ? onOffer(picked.o, e.key) : false;
178214 const at = picked?.r;
179215 if (at === undefined || (e.key !== "x" && e.key !== "u" && e.key !== "p")) return false;
180216 if (e.key === "p") {
181 const held = pause(f.app, f.user, at.id);
217 const held = pause(f.app, f.user, at.id, "paused in the terminal");
182218 const why = { local: `${at.name} is the forge's own; it cannot be paused.`, revoked: "That runner is revoked.", paused: "That runner is paused already.", not_found: "That runner is not enrolled." };
183219 ctx.toast(held.ok ? `Runner ${at.name} is paused: u resumes it.` : why[held.error], held.ok ? "success" : "danger");
184220 ctx.invalidate();
src/web/pages/runners.ts +71 −7
@@ -9,14 +9,14 @@
99 * check answers rather than the admin gate's 403.
1010 */
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
12 import { list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
12 import { enrol, list, pause, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1313 import { isLocal } from "../../checks/runner_pool.ts";
1414 import { proofByRunner, proofWords } from "../../games/lent_proof.ts";
1515 import { cannotByRunner } from "../../games/lend_why.ts";
1616 import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts";
1717 import { lentLine, scopeFacts } from "../../checks/lent_scope.ts";
1818 import { yieldNote, yieldState } from "../../checks/lent_yield.ts";
19 import { heldByRunner, lentIn, workByRunner, type Enrolled, type RunnerWork, runnerMachineWords } from "../../checks/runner_jobs.ts";
19 import { heldByRunner, lentIn, workByRunner, type Enrolled, type RunnerWork, outsideWords, runnerMachineWords } from "../../checks/runner_jobs.ts";
2020 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
2121 import type { Ctx } from "../../http/context.ts";
2222 import { sshOn } from "../../settings/ssh.ts";
@@ -45,8 +45,8 @@ function runnerTrail(r: Enrolled) {
4545 html`<form class="row-fields" method="post" action="${HERE}/${r.id}/${verb}">
4646 ${btn(label, { size: "sm", variant: "outline", label: `${label} runner ${r.name}` })}
4747 </form>`;
48 if (r.scope === undefined || r.revokedAt !== 0) return form("remove", "Remove");
49 return html`${r.paused === "" ? "" : form("resume", "Resume")}${form("revoke", "Revoke")}`;
48 if ((r.scope === undefined && r.labels.length === 0) || r.revokedAt !== 0) return form("remove", "Remove");
49 return html`${r.paused === "" ? form("pause", "Pause") : form("resume", "Resume")}${form("revoke", "Revoke")}`;
5050 }
5151
5252 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string) {
@@ -67,7 +67,7 @@ function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, can
6767 : badge("Never asked", { variant: "outline", icon: "ban" })}`,
6868 meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`}
6969 · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`,
70 facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...scopeFacts(r, now)],
70 facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...(outsideWords(r) === "" ? [] : [{ label: "Outside", value: outsideWords(r) }]), ...scopeFacts(r, now)],
7171 trail: runnerTrail(r),
7272 });
7373 }
@@ -155,6 +155,70 @@ function lendingBlock(ctx: Ctx) {
155155 </section>`;
156156 }
157157
158 /**
159 * Register an outside runner (#18037), a Mac say: its name, the labels it holds and the
160 * repositories it serves. The owner's word here is the only source of its labels. Posts without
161 * script, through the same `enrol` the API calls.
162 */
163 function registerBlock() {
164 return html`<section class="settings-block" id="register">
165 <h2>Register an outside runner</h2>
166 <form method="post" action="${HERE}/register" id="register-runner">
167 <div class="field">
168 <label for="reg-name">Name</label>
169 <input class="input" id="reg-name" name="name" required maxlength="64" placeholder="mac" autocomplete="off" />
170 </div>
171 <div class="field">
172 <label for="reg-labels">Labels, separated by commas</label>
173 <input class="input mono" id="reg-labels" name="labels" placeholder="macos, arm64" autocomplete="off" />
174 </div>
175 <div class="field">
176 <label for="reg-repos">Repositories it serves, as owner/name, separated by commas</label>
177 <input class="input mono" id="reg-repos" name="repos" required placeholder="alice/lib" autocomplete="off" />
178 </div>
179 ${btn("Register runner", { label: "Register this outside runner" })}
180 </form>
181 </section>`;
182 }
183
184 // POST /settings/runners/register
185 export async function runnerRegister(ctx: Ctx): Promise<Response> {
186 const denied = admin(ctx);
187 if (denied) return denied;
188 const form = await readForm(ctx, "admin");
189 if (form instanceof Response) return form;
190 const words = (name: string): string[] => String(form.get(name) ?? "").split(",").map((w) => w.trim()).filter((w) => w !== "");
191 const made = enrol(ctx.app, ctx.auth.user, String(form.get("name") ?? ""), undefined, { labels: words("labels"), repos: words("repos") });
192 if (!made.ok)
193 return flashTo(ctx, `${HERE}#register`, { tone: "danger", message: made.error === "not_found" ? "Only a forge admin registers runners." : `Not registered: ${made.error.invalid}.` });
194 // Shown once, here, never kept in a flash or a URL.
195 const res = page({
196 ctx,
197 title: "Runner registered",
198 body: html`${pageHead("Runner registered", { sub: `${made.value.runner.name}: copy its token now; it is not shown again.` })}
199 <section class="settings-block"><p><code class="mono" id="runner-token">${made.value.token}</code></p>
200 <p class="muted small">Give it to the runner as its bearer token. <a href="${HERE}">Back to runners</a></p></section>`,
201 });
202 res.headers.set("cache-control", "no-store");
203 return res;
204 }
205
206 // POST /settings/runners/:id/pause
207 export async function runnerPause(ctx: Ctx): Promise<Response> {
208 const denied = admin(ctx);
209 if (denied) return denied;
210 const form = await readForm(ctx, "admin");
211 if (form instanceof Response) return form;
212 const done = pause(ctx.app, ctx.auth.user, ctx.params.id ?? "", "paused on the page");
213 return flashTo(
214 ctx,
215 HERE,
216 done.ok
217 ? { message: `Runner ${done.value.name} claims nothing until it is resumed.` }
218 : { tone: "danger", message: done.error === "not_found" ? "That runner is not enrolled." : "That runner is paused or revoked already." },
219 );
220 }
221
158222 // GET /settings/runners/lending/live
159223 export function lendingLive(ctx: Ctx): Response {
160224 if (!ctx.auth.user?.isAdmin || ctx.auth.user.kind !== "user") return fragment(html``, { status: 404 });
@@ -205,13 +269,13 @@ export function runnersPage(ctx: Ctx): Response {
205269 const body = html`<section class="settings-block">
206270 ${waiting === "" ? "" : html`<p class="muted small" id="lent-waiting">${waiting}</p>`}
207271 ${lent === "" ? "" : html`<p class="muted small" id="lent-line">${lent}</p>`}
208 <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>.</p>
272 <p class="muted small">Enrol one with <code>POST /api/v1/admin/runners</code>, or register a machine below.</p>
209273 ${seen.value.length === 0
210274 ? emptyList("runners")
211275 : html`<ul class="list setting-list" id="runner-list">
212276 ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? "", proofWords(proofs.get(r.id))))}
213277 </ul>`}
214 </section>${lendingBlock(ctx)}`;
278 </section>${registerBlock()}${lendingBlock(ctx)}`;
215279 notePhase(ctx.request, "render", performance.now() - rendering);
216280 return page({
217281 ctx,
test/openapi-errors.test.ts +1 −1
@@ -27,7 +27,7 @@ type Doc = {
2727
2828 const BASE = "http://localhost";
2929 /** Not called: these would end the session, stop the forge or reach beyond the test's own data. */
30 const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/;
30 const NOT_CALLED = /\/(sessions|maintenance|migrate|first-admin|(?<!runner\/)heartbeat|release|fleet-ops|drills|forges|sandbox|broker|admin\/(pinned|releases|accounts|settings))/;
3131 /** How many routes NOT_CALLED leaves out; a change to it changes this on purpose. */
3232 const SKIPPED = 57;
3333
test/outside-runner.test.ts added +288
@@ -0,0 +1,288 @@
1 /**
2 * #18037: an outside runner (a Mac) is registered for chosen repositories with labels, says it is
3 * here, claims a check whose forge.json names one of its labels, fetches the commit with the job's
4 * short-lived credential, streams its log and reports: that is the pull's real check. The forge
5 * never runs a labelled check itself.
6 */
7 import { beforeAll, describe, expect, test } from "bun:test";
8 import { mkdirSync } from "node:fs";
9 import { join } from "node:path";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { commitToBranch } from "../src/actions/repos.ts";
12 import { LEASE_MS, deskOf, lapseJobs, type RunnerJob } from "../src/checks/runner_jobs.ts";
13 import type { LaneState } from "../src/checks/lane_state.ts";
14 import type { Execution } from "../src/checks/local_runner.ts";
15 import { tryRunner, type RunnerCheck } from "../src/checks/tier_runner.ts";
16 import { startChecks } from "../src/checks/service.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { parseCheck } from "../src/apps/manifest.ts";
19 import { readRunLog } from "../src/runs/log.ts";
20 import { checkJson, checksForge } from "./helpers/checks-forge.ts";
21 import { gitClientEnv } from "./helpers/git-client.ts";
22 import { quietLogs } from "./helpers/globals.ts";
23
24 quietLogs();
25 const f = checksForge("forge-outside-runner-");
26 let adminToken = "";
27
28 const api = (path: string, token: string, body?: unknown, raw?: string): Promise<Response> =>
29 fetch(`${f.servers.url}${path}`, {
30 method: body === undefined && raw === undefined ? "GET" : "POST",
31 headers: { authorization: `Bearer ${token}`, "content-type": raw === undefined ? "application/json" : "text/plain" },
32 ...(body === undefined && raw === undefined ? {} : { body: raw ?? JSON.stringify(body) }),
33 });
34
35 /** A pull whose head declares `label` on the check (and nothing else): its head commit. */
36 async function labelledPull(branch: string, label: string): Promise<string> {
37 const made = await commitToBranch(f.app, f.alice, f.repo, {
38 branch,
39 message: `Label the check ${label}`,
40 files: [{ path: "forge.json", content: checkJson(`echo on-the-mac ${branch}`, `, "label": "${label}"`) }],
41 });
42 if (!made.ok) throw new Error(JSON.stringify(made.error));
43 const opened = await openPull(f.app, f.alice, f.repo, { title: branch, body: "", baseBranch: "main", headBranch: branch });
44 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
45 return made.value.commitOid;
46 }
47
48 const logOf = (runId: string): string => readRunLog(f.dataDir, runId).lines.join("\n");
49
50 async function register(name: string, labels: string[], repos: string[]): Promise<{ id: string; token: string }> {
51 const r = await api("/api/v1/admin/runners", adminToken, { name, labels, repos });
52 expect(r.status).toBe(201);
53 return (await r.json()) as { id: string; token: string };
54 }
55
56 type Claim = { job: RunnerJob; token: string; lease: { seconds: number } };
57
58 const claimWith = async (token: string): Promise<Claim> => {
59 const asked = api("/api/v1/runner/claim", token, { wait: 20, cells: true });
60 const r = await asked;
61 expect(r.status).toBe(200);
62 return (await r.json()) as Claim;
63 };
64
65 beforeAll(async () => {
66 // Placement stays `process`: a label alone sends a check to a runner. A label no runner holds
67 // fails after a second and a half.
68 await f.checks.stop();
69 f.checks = startChecks(f.app, { forgeUrl: f.servers.url, concurrency: 1, labelWaitMs: 1_500 });
70 adminToken = createToken(f.app.db, f.alice.id, "admin", "admin").token;
71 });
72
73 describe("forge.json's label", () => {
74 test("is one lower-case label; anything else is refused with the reason", () => {
75 const ok = parseCheck(checkJson("true", `, "label": "macos"`), undefined);
76 expect(ok.ok && ok.value?.label).toBe("macos");
77 const none = parseCheck(checkJson("true"), undefined);
78 expect(none.ok && none.value?.label).toBeUndefined();
79 for (const bad of ['"Mac OS"', "3", '""', `"${"a".repeat(33)}"`]) {
80 const r = parseCheck(checkJson("true", `, "label": ${bad}`), undefined);
81 expect(r.ok).toBe(false);
82 }
83 });
84 });
85
86 describe("registering", () => {
87 test("an owner registers a runner for chosen repositories; the token is shown once and listed rows carry labels and state", async () => {
88 const made = await register("mac", ["macos", "arm64"], ["alice/lib"]);
89 expect(made.token.startsWith("forge_runner_")).toBe(true);
90 const listed = (await (await api("/api/v1/admin/runners", adminToken)).json()) as { items: { id: string; labels: string[]; repos: string[]; state: string }[] };
91 const row = listed.items.find((r) => r.id === made.id)!;
92 expect(row.labels).toEqual(["macos", "arm64"]);
93 expect(row.repos).toEqual([f.repo.id]);
94 expect(JSON.stringify(listed)).not.toContain(made.token);
95 });
96
97 test("not anonymous, not a member, and only well-formed labels for repositories that exist", async () => {
98 const body = { name: "x", labels: ["macos"], repos: ["alice/lib"] };
99 expect((await fetch(`${f.servers.url}/api/v1/admin/runners`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })).status).not.toBe(201);
100 const bobToken = createToken(f.app.db, f.bob.id, "bob", "admin").token;
101 expect((await api("/api/v1/admin/runners", bobToken, body)).status).toBe(403);
102 for (const bad of [{ labels: ["Mac OS"], repos: ["alice/lib"] }, { labels: ["macos"], repos: [] }, { labels: ["macos"], repos: ["alice/nope"] }, { labels: "macos", repos: ["alice/lib"] }]) {
103 const r = await api("/api/v1/admin/runners", adminToken, { name: "x", ...bad });
104 expect(r.status).toBe(422);
105 }
106 });
107
108 test("a heartbeat names a state; a bad one is refused; a paused runner claims nothing", async () => {
109 const r = await register("beat", ["macos"], ["alice/lib"]);
110 expect((await api("/api/v1/runner/heartbeat", r.token, { state: "busy" })).status).toBe(204);
111 expect((await api("/api/v1/runner/heartbeat", r.token, { state: "asleep" })).status).toBe(422);
112 expect((await api("/api/v1/runner/heartbeat", "forge_runner_nope", { state: "idle" })).status).toBe(401);
113 expect((await api("/api/v1/runner/heartbeat", r.token, { state: "paused" })).status).toBe(204);
114 expect((await api("/api/v1/runner/claim", r.token, { wait: 0 })).status).toBe(204);
115 const row = ((await (await api("/api/v1/admin/runners", adminToken)).json()) as { items: { id: string; state: string; seenAt: number }[] }).items.find((x) => x.id === r.id)!;
116 expect(row.state).toBe("paused");
117 expect(row.seenAt).toBeGreaterThan(0);
118 // An admin's pause, beside resume.
119 expect((await api(`/api/v1/admin/runners/${r.id}/pause`, adminToken, { reason: "away" })).status).toBe(200);
120 expect((await api(`/api/v1/admin/runners/${r.id}/pause`, adminToken, {})).status).toBe(422);
121 expect((await api(`/api/v1/admin/runners/${r.id}/resume`, adminToken, {})).status).toBe(200);
122 expect((await api(`/api/v1/admin/runners/${r.id}/revoke`, adminToken, {})).status).toBe(200);
123 expect((await api("/api/v1/runner/heartbeat", r.token, { state: "idle" })).status).toBe(401);
124 });
125 });
126
127 describe("who holds a label", () => {
128 test("a heartbeat cannot give a runner labels: a legacy runner that sends some still claims no labelled job", async () => {
129 const legacy = await api("/api/v1/admin/runners", adminToken, { name: "legacy" });
130 expect(legacy.status).toBe(201);
131 const { id, token } = (await legacy.json()) as { id: string; token: string };
132 expect((await api("/api/v1/runner/heartbeat", token, { state: "idle", labels: ["macos"] })).status).toBe(204);
133 const row = ((await (await api("/api/v1/admin/runners", adminToken)).json()) as { items: { id: string; labels: string[] }[] }).items.find((x) => x.id === id)!;
134 expect(row.labels).toEqual([]);
135 const oid = await labelledPull("self-labelled", "macos");
136 await f.until(() => f.app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM check_job WHERE state = 'queued' AND label = 'macos'").get()!.n > 0, "the labelled job queued");
137 expect((await api("/api/v1/runner/claim", token, { wait: 0 })).status).toBe(204);
138 const run = await f.settled((r) => r.commitOid === oid, 30_000);
139 expect(run.state).toBe("failed");
140 }, 30_000);
141
142 test("the heartbeat's refusals have the API's shape: 401, 413 and 422", async () => {
143 const r = await register("shape", ["macos"], ["alice/lib"]);
144 const none = await api("/api/v1/runner/heartbeat", "forge_runner_nope", { state: "idle" });
145 expect(none.status).toBe(401);
146 expect(((await none.json()) as { error: string }).error).toBe("unauthorized");
147 const big = await api("/api/v1/runner/heartbeat", r.token, undefined, "x".repeat(1 << 20));
148 expect(big.status).toBe(413);
149 expect(((await big.json()) as { error: string }).error).toBe("too_large");
150 const bad = await api("/api/v1/runner/heartbeat", r.token, { state: "asleep" });
151 expect(bad.status).toBe(422);
152 expect(((await bad.json()) as { error: string }).error).toBe("invalid_heartbeat");
153 });
154 });
155
156 describe("a labelled check that no runner may be offered", () => {
157 test("fails in words and is never run here: the full tier, or no run to hang a job on", async () => {
158 const lane = { app: f.app, options: {}, placement: { mode: "process" } } as unknown as LaneState;
159 const made = async (x: { tier?: Execution["tier"]; runId?: string | undefined }): Promise<{ out: unknown; log: string[] }> => {
160 const log: string[] = [];
161 const out = await tryRunner(
162 lane,
163 { runId: "run-1", tier: "full", ...x } as Execution,
164 { manifest: { label: "macos" }, write: (l: string) => log.push(l), signal: new AbortController().signal } as unknown as RunnerCheck,
165 () => Promise.reject(new Error("offered to a runner")),
166 );
167 return { out, log };
168 };
169 for (const x of [{ tier: "full" as const }, { tier: "fast" as const, runId: undefined }]) {
170 const { out, log } = await made(x);
171 expect(out).toMatchObject({ ok: false });
172 expect((out as { error: string }).error).toContain('names the label "macos"');
173 expect(log.join("\n")).toContain("so it was not run");
174 }
175 });
176 });
177
178 describe("a labelled check", () => {
179 test("is claimed with the runner token, fetched with the job's credential, logged and reported: the pull's real check is green", async () => {
180 const mac = await register("mac-flow", ["macos", "arm64"], ["alice/lib"]);
181 expect((await api("/api/v1/runner/heartbeat", mac.token, { state: "idle", labels: ["macos", "arm64"] })).status).toBe(204);
182 const asked = claimWith(mac.token);
183 await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim");
184 const oid = await labelledPull("mac-flow", "macos");
185 const claim = await asked;
186 expect(claim.job.label).toBe("macos");
187 expect(claim.job.repo).toBe("alice/lib");
188 expect(claim.job.steps.at(-1)!.command).toContain("on-the-mac");
189 expect(claim.lease.seconds).toBe(LEASE_MS / 1000);
190 expect(claim.token.startsWith("forge_job_")).toBe(true);
191 // The commit, fetched by git with the short-lived credential in git's environment.
192 const dir = join(f.dataDir, "mac-fetch");
193 mkdirSync(dir);
194 const env = gitClientEnv({ GIT_CONFIG_COUNT: "1", GIT_CONFIG_KEY_0: "http.extraHeader", GIT_CONFIG_VALUE_0: `Authorization: Bearer ${claim.token}` });
195 await Bun.spawn(["git", "init", "--quiet", "--bare", dir], { env, stdout: "ignore", stderr: "ignore" }).exited;
196 const fetched = Bun.spawn(["git", "fetch", "--quiet", "--no-tags", "--depth=1", `${f.servers.url}/api/v1/runner/jobs/${claim.job.id}/git`, claim.job.commit], { cwd: dir, env, stdout: "ignore", stderr: "pipe" });
197 expect(await fetched.exited).toBe(0);
198 // Two log lines, then ok.
199 const door = `/api/v1/runner/jobs/${claim.job.id}`;
200 expect((await api(door, claim.token, { step: "check", lines: ["$ on-the-mac", "mac line one"] })).status).toBe(200);
201 expect((await api(door, claim.token, { step: "check", lines: ["mac line two"] })).status).toBe(200);
202 const done = await api(door, claim.token, { done: { steps: claim.job.steps.map((s) => ({ name: s.name, ok: true, ms: 5 })), contained: true, note: "container VM" } });
203 expect(done.status).toBe(200);
204 const run = await f.settled((r) => r.commitOid === oid, 30_000);
205 expect(run.state).toBe("ok");
206 expect(run.placement).toBe("runner");
207 const log = logOf(run.id);
208 expect(log).toContain("mac line one");
209 expect(log).toContain("mac line two");
210 expect(log).toContain("placement: runner mac-flow");
211 // After it, the credential is nothing.
212 expect((await api(door, claim.token, { lines: ["late"] })).status).toBe(404);
213 }, 30_000);
214
215 test("the runner token is refused a push and every route that is not a runner's; a runner serves only the repositories it was made for", async () => {
216 const mac = await register("mac-scope", ["macos"], ["alice/lib"]);
217 for (const path of ["/api/v1/user", "/api/v1/admin/runners"]) {
218 expect((await api(path, mac.token)).status).toBeGreaterThanOrEqual(401);
219 }
220 expect((await api("/api/v1/repos/alice/lib/issues", mac.token, { title: "x" })).status).toBeGreaterThanOrEqual(401);
221 const push = await fetch(`${f.servers.url}/alice/lib.git/info/refs?service=git-receive-pack`, { headers: { authorization: `Bearer ${mac.token}` } });
222 expect(push.status).toBeGreaterThanOrEqual(401);
223 const elsewhere = await register("mac-else", ["windows"], ["alice/lib"]);
224 // A label it does not hold is never offered to it: nothing to claim for a different label.
225 expect((await api("/api/v1/runner/claim", elsewhere.token, { wait: 0 })).status).toBe(204);
226 });
227
228 test("a claim whose runner goes silent is queued again once, then fails with the reason in words", async () => {
229 const mac = await register("mac-silent", ["macos"], ["alice/lib"]);
230 await api("/api/v1/runner/heartbeat", mac.token, { state: "idle" });
231 const asked = claimWith(mac.token);
232 await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim");
233 const oid = await labelledPull("mac-silent", "macos");
234 const first = await asked;
235 expect(lapseJobs(f.app.db, Date.now() + LEASE_MS + 1)).toEqual([first.job.id]);
236 deskOf(f.app).ears.get(first.job.id)?.wake();
237 expect((await api(`/api/v1/runner/jobs/${first.job.id}`, first.token, { lines: ["late"] })).status).toBe(404);
238 const second = await claimWith(mac.token);
239 expect(second.job.id).toBe(first.job.id);
240 expect(lapseJobs(f.app.db, Date.now() + LEASE_MS + 1)).toEqual([second.job.id]);
241 deskOf(f.app).ears.get(second.job.id)?.wake();
242 const run = await f.settled((r) => r.commitOid === oid, 30_000);
243 expect(run.state).toBe("failed");
244 const log = logOf(run.id);
245 expect(log).toContain("went silent: the job is queued again, and that is not a try");
246 expect(log).toContain('runners holding the label "macos" went silent 2 times while running it');
247 expect(log).toContain("not run on this machine");
248 }, 30_000);
249
250 test("a runner may give a claim back: it is queued again, and another claim takes it", async () => {
251 const mac = await register("mac-release", ["macos"], ["alice/lib"]);
252 await api("/api/v1/runner/heartbeat", mac.token, { state: "idle" });
253 const asked = claimWith(mac.token);
254 await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim");
255 const oid = await labelledPull("mac-release", "macos");
256 const first = await asked;
257 expect((await api(`/api/v1/runner/jobs/${first.job.id}`, first.token, { interrupted: "the Mac slept" })).status).toBe(200);
258 const again = await claimWith(mac.token);
259 expect(again.job.id).toBe(first.job.id);
260 await api(`/api/v1/runner/jobs/${again.job.id}`, again.token, { done: { steps: again.job.steps.map((s) => ({ name: s.name, ok: true, ms: 1 })), contained: true, note: "" } });
261 const run = await f.settled((r) => r.commitOid === oid, 30_000);
262 expect(run.state).toBe("ok");
263 }, 30_000);
264
265 test("a red from the runner stays red, however it ended, and is never run on the forge's machine", async () => {
266 const mac = await register("mac-red", ["macos"], ["alice/lib"]);
267 await api("/api/v1/runner/heartbeat", mac.token, { state: "idle" });
268 const asked = claimWith(mac.token);
269 await f.until(() => deskOf(f.app).claimers.size > 0, "the runner waiting in its claim");
270 const oid = await labelledPull("mac-red", "macos");
271 const claim = await asked;
272 await api(`/api/v1/runner/jobs/${claim.job.id}`, claim.token, {
273 done: { steps: [{ name: "check", ok: false, error: "check exited with code 1", ms: 3 }], contained: true, note: "" },
274 });
275 const run = await f.settled((r) => r.commitOid === oid, 30_000);
276 expect(run.state).toBe("failed");
277 expect(run.placement).not.toBe("process");
278 }, 30_000);
279
280 test("a label no available runner holds is said on the check, which then fails; it never sits queued without a word", async () => {
281 const oid = await labelledPull("no-holder", "plan9");
282 const run = await f.settled((r) => r.commitOid === oid, 30_000);
283 expect(run.state).toBe("failed");
284 const log = logOf(run.id);
285 expect(log).toContain('waiting: no runner holding the label "plan9" is available for this repository');
286 expect(log).toContain('no runner holding the label "plan9" took it');
287 }, 30_000);
288 });
test/settings-runners.test.ts +33
@@ -3,6 +3,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
33 import { mkdtemp, rm } from "node:fs/promises";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
67 import { list } from "../src/actions/runners.ts";
78 import { createApp, type App } from "../src/app.ts";
89 import { setLoadSource } from "../src/checks/lent_yield.ts";
@@ -251,3 +252,35 @@ describe("the runners page", () => {
251252 expect(state()).toMatchObject({ stoppedAt: "", stopNow: false });
252253 });
253254 });
255
256 describe("an outside runner, from the page", () => {
257 const form = (who: User, path: string, body: string, origin = servers.url) =>
258 fetch(`${servers.url}${path}`, {
259 method: "POST",
260 redirect: "manual",
261 headers: { cookie: cookie(who), origin, "content-type": "application/x-www-form-urlencoded" },
262 body,
263 });
264
265 test("the admin registers one with labels and repositories, sees its token once, and may pause and resume it", async () => {
266 const bad = await form(alice, "/settings/runners/register", "name=mac&labels=macos&repos=nobody%2Fnone");
267 expect(bad.status).toBe(303);
268 expect((list(app, alice) as unknown as { value: { name: string }[] }).value.some((r) => r.name === "mac")).toBe(false);
269 expect((await form(bob, "/settings/runners/register", "name=mac&labels=macos&repos=x%2Fy")).status).toBeGreaterThanOrEqual(403);
270 expect((await form(alice, "/settings/runners/register", "name=mac&labels=macos&repos=x%2Fy", "http://elsewhere.test")).status).toBe(403);
271 const repo = await createRepo(app, alice, { name: "mac-lib", visibility: "public" });
272 expect(repo.ok).toBe(true);
273 const ok = await form(alice, "/settings/runners/register", "name=mac&labels=macos%2C+arm64&repos=alice%2Fmac-lib");
274 expect(ok.status).toBe(200);
275 expect(ok.headers.get("cache-control")).toBe("no-store");
276 expect(await ok.text()).toContain("forge_runner_");
277 const row = ((list(app, alice) as unknown as { value: { name: string; labels: string[] }[] }).value.find((r) => r.name === "mac"))!;
278 expect(row.labels).toEqual(["macos", "arm64"]);
279 const made = enrolRunner(app.db, "pausable", alice.id, undefined, Date.now(), { labels: ["macos"], repos: [] }).runner;
280 expect(await (await get(alice)).text()).toContain(`/settings/runners/${made.id}/pause`);
281 expect((await form(alice, `/settings/runners/${made.id}/pause`, "")).status).toBe(303);
282 const page = await (await get(alice)).text();
283 expect(page).toContain(`/settings/runners/${made.id}/resume`);
284 expect(page).not.toContain(`/settings/runners/${made.id}/pause`);
285 });
286 });
test/tui-runners.test.ts +15
@@ -8,6 +8,7 @@ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
88 import { mkdtemp, rm } from "node:fs/promises";
99 import { tmpdir } from "node:os";
1010 import { join } from "node:path";
11 import { createRepo } from "../src/actions/repos.ts";
1112 import { createApp, type App } from "../src/app.ts";
1213 import { setLoadSource } from "../src/checks/lent_yield.ts";
1314 import { enrolRunner, listRunners } from "../src/checks/runner_jobs.ts";
@@ -175,3 +176,17 @@ describe("runners in the terminal", () => {
175176 expect(state().stoppedAt).toBe("");
176177 });
177178 });
179
180 describe("registering an outside runner in the terminal", () => {
181 test("n takes a name, labels and repositories; a repository that is not here is refused; the token is shown once; a non-admin registers nothing", async () => {
182 const made = await createRepo(app, ada, { name: "termlib", visibility: "public" });
183 expect(made.ok).toBe(true);
184 await drive(ada, ["n", "termbad macos ada/nope", ENTER]);
185 expect(names()).not.toContain("termbad");
186 const { text } = await drive(ada, ["n", "termmac macos,arm64 ada/termlib", ENTER]);
187 expect(text).toContain("forge_runner_");
188 expect(listRunners(app.db).find((r) => r.name === "termmac")).toMatchObject({ labels: ["macos", "arm64"] });
189 await drive(bob, ["n", "termbob macos ada/termlib", ENTER]);
190 expect(names()).not.toContain("termbob");
191 });
192 });

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

Keyboard shortcuts

Docs