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

A check runs as a cluster Job when checks.placement is job, through a stand-in Job client in tests #1630

Closed opened this
Closed without merging

scout/forge:scout/1592-a-check-runs-as-a-cluster-job-when-check → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +762 −1
docs/APPS.md +8
@@ -358,6 +358,8 @@ A `check` that is present and wrong fails with the reason, so a commit is
358358 never silently unchecked. A check under way when the forge restarts is
359359 queued again, and the forge that carries on runs it from the start.
360360
361 With `checks.placement: job` the check's commands run as one cluster Job (`src/cluster/jobs.ts`, the kube API over the service account, no dependency): the checkout is on the claim, the pod's log streams into the run's, the Job is deleted when it ends, and the run records `placement` and `node`. The default, `process`, is unchanged.
362
361363 Checks share `FORGE_CHECKS_CONCURRENCY` slots (default `1`), and when one
362364 frees, it goes to the most recently requested check waiting, not the one
363365 queued longest — a fresh push is never stuck behind pulls that queued hours
@@ -1065,6 +1067,12 @@ a link to the milestone (`docs/PLANNING.md`); its progress never does.
10651067 | `FORGE_PREVIEW_IDLE_DAYS` | `3` | days a pull may sit untouched before its preview sleeps; `0` = never |
10661068 | `FORGE_CREW_CONCURRENCY` | `2` | agent runs at once (live: Settings → Capacity) |
10671069 | `FORGE_CHECKS_CONCURRENCY` | `1` | checks at once (live: Settings → Capacity) |
1070 | `FORGE_CHECKS_PLACEMENT` | `process` | `process` or `job`: where a check runs (live: Settings → Capacity) |
1071 | `FORGE_CHECKS_IMAGE` | — | job placement: the image the check's pod runs |
1072 | `FORGE_CHECKS_CLAIM` | — | job placement: the claim holding `data/checks`, mounted in the pod |
1073 | `FORGE_CHECKS_NAMESPACE` | the pod's own | job placement: the namespace the Job is made in |
1074 | `FORGE_CHECKS_NODE_SELECTOR` | — | job placement: `key=value,…` the pod must land on |
1075 | `FORGE_CHECKS_TOLERATIONS` | — | job placement: `key[=value]:Effect,…` |
10681076 | `FORGE_CHECK_SHARDS` | the machine's cores | test shards per check (live: Settings → Capacity) |
10691077 | `FORGE_CELLS_EGRESS` | `enforce` | `report` lets undeclared egress through on 80/443 (live: Settings → Capacity) |
10701078 | `FORGE_CREW_BUDGET_USD` | `5` | spend per run unless the agent says otherwise |
scripts/gate.ts +1
@@ -94,6 +94,7 @@ export const GATE: readonly string[] = [
9494 "test/limits.test.ts",
9595 "test/guard-new-accounts.test.ts",
9696 "test/checks.test.ts",
97 "test/check-job.test.ts",
9798 "test/dependencies.test.ts",
9899 "test/map-closing.test.ts",
99100 "test/autonomy.test.ts",
src/checks/service.ts +83
@@ -55,6 +55,7 @@ import { childEnv, runStep } from "../apps/process.ts";
5555 import { noteReached } from "../apps/egress_report.ts";
5656 import {
5757 capacityCount,
58 capacityValue,
5859 noteBooted,
5960 capacityEnv,
6061 egressSetting,
@@ -66,6 +67,7 @@ import {
6667 type CellSpec,
6768 } from "../apps/contain.ts";
6869 import { summariseCheckFailure } from "./summary.ts";
70 import { jobSettings, kubeJobClient, runJob, type JobClient } from "../cluster/jobs.ts";
6971 import type { CheckDetail } from "../core/runs.ts";
7072
7173 const log = createLog("checks");
@@ -77,6 +79,8 @@ export interface ChecksOptions {
7779 readonly forgeUrl: string;
7880 /** How long a check may run before it is killed. @default BUDGETS.gate */
7981 readonly budgetMs?: number | undefined;
82 /** The cluster's Job API; the service account's when absent. Tests stand one in. */
83 readonly jobs?: JobClient | undefined;
8084 }
8185
8286 export interface ChecksHandle {
@@ -566,6 +570,15 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
566570 return { ok: false, error: given.error };
567571 }
568572 }
573 if (capacityValue(app.db, "checks.placement") === "job") {
574 try {
575 return await runAsJob(x, run.id, dir, manifest, command, base);
576 } finally {
577 if (existsSync(dir)) rmSync(dir, { recursive: true, force: true });
578 }
579 }
580 if (x.runId !== undefined)
581 noteRunProgress(app.db, x.runId, { placement: "process" });
569582 // The check is repository code: it runs in a cell of its own
570583 // (`apps/contain.ts`), its checkout and a home its only places to write,
571584 // the forge, the registry and what it declared its only way out.
@@ -658,6 +671,76 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
658671 }
659672 }
660673
674 /**
675 * The check's commands as one cluster Job: the checkout is on the claim
676 * the pod mounts, the log streams into the run's, the verdict is the
677 * Job's. The pod gets the check's environment, not the forge's.
678 */
679 async function runAsJob(
680 x: Execution,
681 id: string,
682 dir: string,
683 manifest: { install: string | null; timeout: number },
684 command: string,
685 base: string | undefined,
686 ): Promise<
687 | { ok: true }
688 | { ok: false; error: string; detail?: CheckDetail | undefined }
689 > {
690 const settings = jobSettings(process.env);
691 if (!settings.ok) return { ok: false, error: settings.error };
692 const client =
693 options.jobs ?? kubeJobClient(process.env, settings.value.namespace);
694 if (client === undefined)
695 return { ok: false, error: "checks.placement is job but this forge is not in a cluster" };
696 if (x.runId !== undefined)
697 noteRunProgress(app.db, x.runId, {
698 placement: "job",
699 sandbox: { enforced: true, note: "a cluster job" },
700 });
701 const env: Record<string, string> = {
702 LANG: "C.UTF-8",
703 ...capacityEnv(app.db),
704 CI: "1",
705 FORGE_URL: options.forgeUrl,
706 FORGE_CHECK: id,
707 FORGE_COMMIT: x.commitOid,
708 ...(base === undefined
709 ? {}
710 : {
711 FORGE_CHECK_BASE: base,
712 FORGE_CHECK_LEARNED: readLearned(app.config.dataDir, x.pull!.id).join(","),
713 }),
714 FORGE_CELLS: "off",
715 };
716 const lines: string[] = [];
717 const script =
718 manifest.install === null ? command : `(${manifest.install}) && (${command})`;
719 const ran = await runJob(
720 client,
721 {
722 runId: id,
723 command: script,
724 cwd: dir,
725 mount: checksRoot(app.config.dataDir),
726 env,
727 settings: settings.value,
728 deadlineSeconds: manifest.timeout,
729 },
730 {
731 log: x.write,
732 onOutput: (line) => lines.push(line),
733 signal: x.signal,
734 onNode: (node) => {
735 if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { node });
736 },
737 },
738 );
739 if (ran.ok) return { ok: true };
740 const { summary, detail } = summariseCheckFailure(lines, ran.error);
741 return { ok: false, error: summary, detail };
742 }
743
661744 // What starts a check: a branch moving, a pull opening, a fork's push
662745 // moving a pull's head. The commit checked is always the one the pull
663746 // proposes now.
src/cluster/jobs.ts added +350
@@ -0,0 +1,350 @@
1 /**
2 * A check as a cluster Job (#1592): `checks.placement: job` runs the
3 * check's commands in a pod of their own instead of a cell on the forge's
4 * machine, so the queue is the cluster's to spread. No dependency — the
5 * kube API over the pod's service account, with `fetch`.
6 *
7 * `JobClient` is the whole surface the forge uses; tests stand in for it.
8 * `runJob` is the orchestration: create, follow the log into the run's log,
9 * wait for the verdict, and delete the Job whatever happened.
10 */
11
12 import { readFileSync } from "node:fs";
13 import { err, ok, type Result } from "../kernel/result.ts";
14
15 /** Where the cluster is told: image, namespace, claim, and where it may land. */
16 export interface JobSettings {
17 readonly image: string;
18 readonly namespace: string;
19 /** A claim holding the checkouts, mounted where the forge keeps them. */
20 readonly claim: string;
21 readonly nodeSelector: Readonly<Record<string, string>>;
22 readonly tolerations: readonly Toleration[];
23 }
24
25 export interface Toleration {
26 readonly key: string;
27 readonly operator: "Equal" | "Exists";
28 readonly value?: string;
29 readonly effect: "NoSchedule" | "PreferNoSchedule" | "NoExecute";
30 }
31
32 export interface JobSpec {
33 /** Names the Job. */
34 readonly runId: string;
35 readonly command: string;
36 readonly cwd: string;
37 /** The checkouts' root, where the claim is mounted. */
38 readonly mount: string;
39 readonly env: Readonly<Record<string, string>>;
40 readonly settings: JobSettings;
41 /** Seconds the Job may run before the cluster ends it. */
42 readonly deadlineSeconds: number;
43 }
44
45 export type JobPhase = "pending" | "running" | "succeeded" | "failed";
46
47 export interface JobStatus {
48 readonly phase: JobPhase;
49 /** The node the pod landed on; empty until it has one. */
50 readonly node: string;
51 readonly reason: string;
52 }
53
54 export interface JobClient {
55 create(manifest: object): Promise<Result<void, string>>;
56 status(name: string): Promise<Result<JobStatus, string>>;
57 /** Streams the pod's log line by line; resolves when the log ends or `signal` aborts. */
58 logs(name: string, onLine: (line: string) => void, signal: AbortSignal): Promise<void>;
59 delete(name: string): Promise<void>;
60 }
61
62 const NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
63 const LABEL_KEY = /^([a-z0-9.-]+\/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/;
64 const LABEL_VALUE = /^([A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$/;
65 const EFFECTS = ["NoSchedule", "PreferNoSchedule", "NoExecute"] as const;
66
67 /** A Job's name for a run: lowercase, dns-safe, at most 63 characters. */
68 export function jobName(runId: string): string {
69 const id = runId.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
70 return `forge-check-${id}`.slice(0, 63).replace(/-+$/, "");
71 }
72
73 /** `k=v,k2=v2` into a node selector; anything not a label is refused. */
74 export function parseNodeSelector(
75 text: string,
76 ): Result<Record<string, string>, string> {
77 const out: Record<string, string> = {};
78 for (const part of text.split(",").map((p) => p.trim()).filter((p) => p !== "")) {
79 const at = part.indexOf("=");
80 const key = at < 0 ? part : part.slice(0, at);
81 const value = at < 0 ? "" : part.slice(at + 1);
82 if (!LABEL_KEY.test(key) || !LABEL_VALUE.test(value))
83 return err(`node selector entry "${part.slice(0, 80)}" is not key=value`);
84 out[key] = value;
85 }
86 return ok(out);
87 }
88
89 /** `key=value:Effect` or `key:Effect`, comma separated, into tolerations. */
90 export function parseTolerations(text: string): Result<Toleration[], string> {
91 const out: Toleration[] = [];
92 for (const part of text.split(",").map((p) => p.trim()).filter((p) => p !== "")) {
93 const colon = part.lastIndexOf(":");
94 const head = colon < 0 ? part : part.slice(0, colon);
95 const effect = colon < 0 ? "" : part.slice(colon + 1);
96 const at = head.indexOf("=");
97 const key = at < 0 ? head : head.slice(0, at);
98 const value = at < 0 ? undefined : head.slice(at + 1);
99 const known = (EFFECTS as readonly string[]).includes(effect);
100 if (
101 !known ||
102 !LABEL_KEY.test(key) ||
103 (value !== undefined && !LABEL_VALUE.test(value))
104 )
105 return err(`toleration "${part.slice(0, 80)}" is not key[=value]:Effect`);
106 out.push(
107 value === undefined
108 ? { key, operator: "Exists", effect: effect as Toleration["effect"] }
109 : { key, operator: "Equal", value, effect: effect as Toleration["effect"] },
110 );
111 }
112 return ok(out);
113 }
114
115 /** The settings the environment names; a bad one is an error the check reports. */
116 export function jobSettings(
117 env: Record<string, string | undefined>,
118 ): Result<JobSettings, string> {
119 const image = (env["FORGE_CHECKS_IMAGE"] ?? "").trim();
120 if (image === "" || /\s/.test(image))
121 return err("checks.placement is job but FORGE_CHECKS_IMAGE is not set");
122 const namespace = (env["FORGE_CHECKS_NAMESPACE"] ?? "").trim() || readNamespace();
123 if (!NAME.test(namespace))
124 return err("checks.placement is job but the namespace is unknown (FORGE_CHECKS_NAMESPACE)");
125 const claim = (env["FORGE_CHECKS_CLAIM"] ?? "").trim();
126 if (!NAME.test(claim))
127 return err("checks.placement is job but FORGE_CHECKS_CLAIM is not set");
128 const selector = parseNodeSelector(env["FORGE_CHECKS_NODE_SELECTOR"] ?? "");
129 if (!selector.ok) return err(selector.error);
130 const tolerations = parseTolerations(env["FORGE_CHECKS_TOLERATIONS"] ?? "");
131 if (!tolerations.ok) return err(tolerations.error);
132 return ok({
133 image,
134 namespace,
135 claim,
136 nodeSelector: selector.value,
137 tolerations: tolerations.value,
138 });
139 }
140
141 /** The Job for one run: one pod, no retries, gone soon after it ends. */
142 export function jobManifest(spec: JobSpec): object {
143 const s = spec.settings;
144 return {
145 apiVersion: "batch/v1",
146 kind: "Job",
147 metadata: {
148 name: jobName(spec.runId),
149 namespace: s.namespace,
150 labels: { "app.kubernetes.io/managed-by": "forge", "forge/check": jobName(spec.runId) },
151 },
152 spec: {
153 backoffLimit: 0,
154 activeDeadlineSeconds: Math.max(1, Math.ceil(spec.deadlineSeconds)),
155 ttlSecondsAfterFinished: 300,
156 template: {
157 metadata: { labels: { "forge/check": jobName(spec.runId) } },
158 spec: {
159 restartPolicy: "Never",
160 automountServiceAccountToken: false,
161 ...(Object.keys(s.nodeSelector).length > 0 ? { nodeSelector: s.nodeSelector } : {}),
162 ...(s.tolerations.length > 0 ? { tolerations: s.tolerations } : {}),
163 containers: [
164 {
165 name: "check",
166 image: s.image,
167 command: ["/bin/sh", "-c", spec.command],
168 workingDir: spec.cwd,
169 env: Object.entries(spec.env).map(([name, value]) => ({ name, value })),
170 volumeMounts: [{ name: "checks", mountPath: spec.mount }],
171 },
172 ],
173 volumes: [{ name: "checks", persistentVolumeClaim: { claimName: s.claim } }],
174 },
175 },
176 },
177 };
178 }
179
180 export interface RunJobOptions {
181 readonly log: (line: string) => void;
182 /** Told each line of the pod's own output, apart from what `log` adds. */
183 readonly onOutput?: (line: string) => void;
184 readonly signal: AbortSignal;
185 /** Told the node once the pod has one. */
186 readonly onNode?: (node: string) => void;
187 /** @default 2000 */
188 readonly pollMs?: number;
189 }
190
191 /** Run one Job to its verdict; the Job is deleted either way. */
192 export async function runJob(
193 client: JobClient,
194 spec: JobSpec,
195 options: RunJobOptions,
196 ): Promise<Result<void, string>> {
197 const name = jobName(spec.runId);
198 const created = await client.create(jobManifest(spec));
199 if (!created.ok) return err(`could not create the job: ${created.error}`);
200 options.log(`job ${name} created`);
201 const stop = new AbortController();
202 const forward = (): void => stop.abort();
203 options.signal.addEventListener("abort", forward, { once: true });
204 const following = client
205 .logs(
206 name,
207 (line) => {
208 options.onOutput?.(line);
209 options.log(line);
210 },
211 stop.signal,
212 )
213 .catch(() => undefined);
214 let node = "";
215 try {
216 for (;;) {
217 if (options.signal.aborted) return err("the check was stopped");
218 const status = await client.status(name);
219 if (!status.ok) return err(`could not read the job: ${status.error}`);
220 if (status.value.node !== "" && status.value.node !== node) {
221 node = status.value.node;
222 options.log(`running on ${node}`);
223 options.onNode?.(node);
224 }
225 if (status.value.phase === "succeeded") break;
226 if (status.value.phase === "failed")
227 return err(status.value.reason || "the job failed");
228 await sleep(options.pollMs ?? 2000, options.signal);
229 }
230 // The log ends with the pod; give it a moment to drain.
231 await Promise.race([following, sleep(5000, options.signal)]);
232 return ok(undefined);
233 } finally {
234 options.signal.removeEventListener("abort", forward);
235 stop.abort();
236 await client.delete(name).catch(() => undefined);
237 }
238 }
239
240 function sleep(ms: number, signal: AbortSignal): Promise<void> {
241 return new Promise((resolve) => {
242 if (signal.aborted) return resolve();
243 const done = (): void => {
244 clearTimeout(timer);
245 signal.removeEventListener("abort", done);
246 resolve();
247 };
248 const timer = setTimeout(done, ms);
249 signal.addEventListener("abort", done, { once: true });
250 });
251 }
252
253 const SA = "/var/run/secrets/kubernetes.io/serviceaccount";
254
255 function readNamespace(): string {
256 try {
257 return readFileSync(`${SA}/namespace`, "utf8").trim();
258 } catch {
259 return "";
260 }
261 }
262
263 /** The kube API as the pod's service account; undefined outside a cluster. */
264 export function kubeJobClient(
265 env: Record<string, string | undefined> = process.env,
266 namespace: string,
267 ): JobClient | undefined {
268 const host = env["KUBERNETES_SERVICE_HOST"];
269 const port = env["KUBERNETES_SERVICE_PORT"] ?? "443";
270 if (host === undefined || host === "" || !/^\d+$/.test(port)) return undefined;
271 let token: string;
272 let ca: string;
273 try {
274 token = readFileSync(`${SA}/token`, "utf8").trim();
275 ca = readFileSync(`${SA}/ca.crt`, "utf8");
276 } catch {
277 return undefined;
278 }
279 const base = `https://${host.includes(":") ? `[${host}]` : host}:${port}`;
280 const jobs = `${base}/apis/batch/v1/namespaces/${namespace}/jobs`;
281 const pods = `${base}/api/v1/namespaces/${namespace}/pods`;
282 const call = (url: string, init: RequestInit = {}): Promise<Response> =>
283 fetch(url, {
284 ...init,
285 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
286 tls: { ca },
287 } as RequestInit);
288 const podOf = async (name: string): Promise<Record<string, any> | undefined> => {
289 const res = await call(`${pods}?labelSelector=${encodeURIComponent(`forge/check=${name}`)}`);
290 if (!res.ok) return undefined;
291 const body = (await res.json()) as { items?: Record<string, any>[] };
292 return body.items?.[0];
293 };
294 return {
295 async create(manifest) {
296 const res = await call(jobs, { method: "POST", body: JSON.stringify(manifest) });
297 return res.ok ? ok(undefined) : err(`${res.status} ${(await res.text()).slice(0, 200)}`);
298 },
299 async status(name) {
300 const res = await call(`${jobs}/${name}`);
301 if (!res.ok) return err(`${res.status}`);
302 const job = (await res.json()) as { status?: Record<string, any> };
303 const pod = await podOf(name);
304 const node = String(pod?.["spec"]?.["nodeName"] ?? "");
305 const st = job.status ?? {};
306 if ((st["succeeded"] ?? 0) > 0) return ok({ phase: "succeeded", node, reason: "" });
307 if ((st["failed"] ?? 0) > 0) {
308 const cond = (st["conditions"] as { reason?: string; message?: string }[] | undefined)?.find(
309 (c) => c.reason !== undefined,
310 );
311 const exit = pod?.["status"]?.["containerStatuses"]?.[0]?.["state"]?.["terminated"];
312 const why =
313 cond?.reason === "DeadlineExceeded"
314 ? "the job ran past its deadline"
315 : exit?.["exitCode"] !== undefined
316 ? `the check exited ${String(exit["exitCode"])}`
317 : cond?.message ?? "the job failed";
318 return ok({ phase: "failed", node, reason: String(why).slice(0, 200) });
319 }
320 return ok({ phase: (st["active"] ?? 0) > 0 ? "running" : "pending", node, reason: "" });
321 },
322 async logs(name, onLine, signal) {
323 let pod: Record<string, any> | undefined;
324 while (!signal.aborted) {
325 pod = await podOf(name);
326 const phase = pod?.["status"]?.["phase"];
327 if (phase !== undefined && phase !== "Pending") break;
328 await sleep(1000, signal);
329 }
330 if (signal.aborted || pod === undefined) return;
331 const res = await call(
332 `${pods}/${encodeURIComponent(String(pod["metadata"]["name"]))}/log?follow=true`,
333 { signal },
334 );
335 if (!res.ok || res.body === null) return;
336 const decoder = new TextDecoder();
337 let rest = "";
338 for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
339 rest += decoder.decode(chunk, { stream: true });
340 const lines = rest.split("\n");
341 rest = lines.pop() ?? "";
342 for (const line of lines) onLine(line);
343 }
344 if (rest !== "") onLine(rest);
345 },
346 async delete(name) {
347 await call(`${jobs}/${name}?propagationPolicy=Background`, { method: "DELETE" });
348 },
349 };
350 }
src/core/capacity.ts +8
@@ -19,6 +19,7 @@ export type CapacityKey =
1919 | "crew.concurrency"
2020 | "checks.concurrency"
2121 | "checks.shards"
22 | "checks.placement"
2223 | "children.max"
2324 | "cells.egress"
2425 | "guard_new_accounts";
@@ -59,6 +60,13 @@ export const CAPACITY: Record<CapacityKey, Definition> = {
5960 fallback: "",
6061 help: "How many parallel shards a check's test run uses (handed to checks and crew shells as FORGE_CHECK_SHARDS). Empty: as many as the machine has cores.",
6162 },
63 "checks.placement": {
64 label: "Where checks run",
65 env: "FORGE_CHECKS_PLACEMENT",
66 kind: { type: "choice", values: ["process", "job"] },
67 fallback: "process",
68 help: "process runs a check in a cell on this machine; job runs it as a cluster Job (image, claim, node selector and tolerations from FORGE_CHECKS_*). Takes effect on the next check started.",
69 },
6270 "children.max": {
6371 label: "Forges this one may send",
6472 env: "FORGE_CHILDREN_MAX",
src/core/runs.ts +15 −1
@@ -76,6 +76,10 @@ export interface Run {
7676 readonly sandboxEnforced: boolean | null;
7777 /** Why it was not, when it was not. */
7878 readonly sandboxNote: string;
79 /** For a check: `process` or `job`, as it ran; empty when unrecorded. */
80 readonly placement: string;
81 /** For a job: the cluster node its pod ran on. */
82 readonly node: string;
7983 /** A failed check's own detail, when its output was recognised; null otherwise. */
8084 readonly checkDetail: CheckDetail | null;
8185 readonly createdAt: string;
@@ -105,6 +109,8 @@ interface RunRow {
105109 turns: number;
106110 sandbox_enforced: number | null;
107111 sandbox_note: string;
112 placement: string;
113 node: string;
108114 check_detail: string;
109115 created_at: string;
110116 started_at: string | null;
@@ -133,6 +139,8 @@ const toRun = (r: RunRow): Run => ({
133139 sandboxEnforced:
134140 r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0,
135141 sandboxNote: r.sandbox_note,
142 placement: r.placement,
143 node: r.node,
136144 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
137145 createdAt: r.created_at,
138146 startedAt: r.started_at,
@@ -335,13 +343,17 @@ export function noteRunProgress(
335343 subscriptionId?: string | undefined;
336344 /** Whether the shell is held to the sandbox, and why not when it is not. */
337345 sandbox?: { enforced: boolean; note: string } | undefined;
346 /** Where a check ran, and the node when it was a job. */
347 placement?: "process" | "job" | undefined;
348 node?: string | undefined;
338349 },
339350 ): void {
340351 db.query(
341352 `UPDATE run SET session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd),
342353 branch = COALESCE(?4, branch), subscription_id = COALESCE(?5, subscription_id),
343354 sandbox_enforced = COALESCE(?6, sandbox_enforced),
344 sandbox_note = COALESCE(?7, sandbox_note)
355 sandbox_note = COALESCE(?7, sandbox_note),
356 placement = COALESCE(?8, placement), node = COALESCE(?9, node)
345357 WHERE id = ?1`,
346358 ).run(
347359 runId,
@@ -351,6 +363,8 @@ export function noteRunProgress(
351363 progress.subscriptionId ?? null,
352364 progress.sandbox === undefined ? null : progress.sandbox.enforced ? 1 : 0,
353365 progress.sandbox?.note.slice(0, 300) ?? null,
366 progress.placement ?? null,
367 progress.node?.slice(0, 253) ?? null,
354368 );
355369 }
356370
src/core/schema.ts +6
@@ -1614,6 +1614,12 @@ export const migrations: readonly string[] = [
16141614 PRIMARY KEY (key, issue_id)
16151615 );
16161616 `,
1617 // 77 — where a check ran (#1592): `placement` is `process` or `job`, `node`
1618 // the cluster node a job's pod landed on, empty for a process.
1619 `
1620 ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT '';
1621 ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT '';
1622 `,
16171623 ];
16181624
16191625 /**
test/check-job.test.ts added +291
@@ -0,0 +1,291 @@
1 /**
2 * A check as a cluster Job (#1592): `checks.placement: job` reaches a
3 * verdict through a stand-in Job client; process placement is unchanged.
4 */
5
6 import { afterAll, beforeAll, describe, 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 { createApp, type App } from "../src/app.ts";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { startChecks, type ChecksHandle } from "../src/checks/service.ts";
13 import {
14 jobManifest,
15 jobName,
16 jobSettings,
17 parseNodeSelector,
18 parseTolerations,
19 runJob,
20 type JobClient,
21 type JobSpec,
22 type JobStatus,
23 } from "../src/cluster/jobs.ts";
24 import { setCapacity } from "../src/core/capacity.ts";
25 import { getRun, listRuns, type Run } from "../src/core/runs.ts";
26 import { createUser, type User } from "../src/core/users.ts";
27 import type { Repo } from "../src/core/repos.ts";
28 import { err, ok } from "../src/kernel/result.ts";
29 import { serve, type Servers } from "../src/http/server.ts";
30 import { readRunLog } from "../src/runs/log.ts";
31
32 const settings = {
33 image: "oven/bun:1",
34 namespace: "forge",
35 claim: "checks",
36 nodeSelector: { pool: "ci" },
37 tolerations: [{ key: "ci", operator: "Exists" as const, effect: "NoSchedule" as const }],
38 };
39 const spec: JobSpec = {
40 runId: "01ABC",
41 command: "bun test",
42 cwd: "/data/checks/01ABC",
43 mount: "/data/checks",
44 env: { CI: "1" },
45 settings,
46 deadlineSeconds: 60,
47 };
48
49 /** A Job client that never leaves the process: records, scripts a verdict. */
50 function standIn(verdict: JobStatus, lines: string[] = []) {
51 const calls: string[] = [];
52 const created: object[] = [];
53 const client: JobClient = {
54 async create(m) {
55 calls.push("create");
56 created.push(m);
57 return ok(undefined);
58 },
59 async status() {
60 calls.push("status");
61 return ok(verdict);
62 },
63 async logs(_name, onLine) {
64 for (const l of lines) onLine(l);
65 },
66 async delete() {
67 calls.push("delete");
68 },
69 };
70 return { client, calls, created };
71 }
72
73 describe("the Job a check becomes", () => {
74 test("names are dns-safe and bounded", () => {
75 expect(jobName("01ABC_def")).toBe("forge-check-01abc-def");
76 expect(jobName("x".repeat(200)).length).toBeLessThanOrEqual(63);
77 });
78
79 test("the manifest carries placement, command, claim and no service account", () => {
80 const m = jobManifest(spec) as any;
81 const pod = m.spec.template.spec;
82 expect(pod.nodeSelector).toEqual({ pool: "ci" });
83 expect(pod.tolerations[0].key).toBe("ci");
84 expect(pod.containers[0].command).toEqual(["/bin/sh", "-c", "bun test"]);
85 expect(pod.containers[0].workingDir).toBe("/data/checks/01ABC");
86 expect(pod.volumes[0].persistentVolumeClaim.claimName).toBe("checks");
87 expect(pod.automountServiceAccountToken).toBe(false);
88 expect(m.spec.backoffLimit).toBe(0);
89 expect(m.spec.activeDeadlineSeconds).toBe(60);
90 });
91
92 test("selectors and tolerations are validated at the boundary", () => {
93 expect(parseNodeSelector("pool=ci, zone=a").ok).toBe(true);
94 expect(parseNodeSelector("a b=c").ok).toBe(false);
95 expect(parseNodeSelector("k=v\nx").ok).toBe(false);
96 const t = parseTolerations("gpu=yes:NoSchedule,ci:NoExecute");
97 expect(t.ok && t.value.map((x) => x.operator)).toEqual(["Equal", "Exists"]);
98 expect(parseTolerations("ci:Whenever").ok).toBe(false);
99 expect(parseTolerations("ci").ok).toBe(false);
100 });
101
102 test("settings need an image and a claim", () => {
103 expect(jobSettings({ FORGE_CHECKS_NAMESPACE: "forge", FORGE_CHECKS_CLAIM: "c" }).ok).toBe(false);
104 const ok1 = jobSettings({
105 FORGE_CHECKS_IMAGE: "img",
106 FORGE_CHECKS_NAMESPACE: "forge",
107 FORGE_CHECKS_CLAIM: "c",
108 FORGE_CHECKS_NODE_SELECTOR: "pool=ci",
109 });
110 expect(ok1.ok && ok1.value.nodeSelector).toEqual({ pool: "ci" });
111 });
112 });
113
114 describe("runJob", () => {
115 test("a succeeded job passes, its log and node are reported, and it is deleted", async () => {
116 const { client, calls } = standIn({ phase: "succeeded", node: "n1", reason: "" }, ["hello"]);
117 const lines: string[] = [];
118 let node = "";
119 const r = await runJob(client, spec, {
120 log: (l) => lines.push(l),
121 signal: new AbortController().signal,
122 onNode: (n) => (node = n),
123 pollMs: 1,
124 });
125 expect(r.ok).toBe(true);
126 expect(lines).toContain("hello");
127 expect(node).toBe("n1");
128 expect(calls.at(-1)).toBe("delete");
129 });
130
131 test("a failed job is an error with the reason, and still deleted", async () => {
132 const { client, calls } = standIn({ phase: "failed", node: "", reason: "the check exited 1" });
133 const r = await runJob(client, spec, {
134 log: () => {},
135 signal: new AbortController().signal,
136 pollMs: 1,
137 });
138 expect(r).toEqual(err("the check exited 1"));
139 expect(calls).toContain("delete");
140 });
141
142 test("an abort stops waiting and deletes the job", async () => {
143 const { client, calls } = standIn({ phase: "running", node: "", reason: "" });
144 const stop = new AbortController();
145 setTimeout(() => stop.abort(), 20);
146 const r = await runJob(client, spec, { log: () => {}, signal: stop.signal, pollMs: 5 });
147 expect(r.ok).toBe(false);
148 expect(calls).toContain("delete");
149 });
150 });
151
152 describe("checks.placement", () => {
153 let dataDir: string;
154 let app: App;
155 let servers: Servers;
156 let checks: ChecksHandle;
157 let alice: User;
158 let repo: Repo;
159 let verdict: JobStatus = { phase: "succeeded", node: "node-7", reason: "" };
160 let podOutput: string[] = ["from the pod"];
161 const created: object[] = [];
162 const saved: Record<string, string | undefined> = {};
163 const env = {
164 FORGE_CHECKS_IMAGE: "oven/bun:1",
165 FORGE_CHECKS_NAMESPACE: "forge",
166 FORGE_CHECKS_CLAIM: "checks",
167 FORGE_CHECKS_NODE_SELECTOR: "pool=ci",
168 };
169
170 const client: JobClient = {
171 async create(m) {
172 created.push(m);
173 return ok(undefined);
174 },
175 async status() {
176 return ok(verdict);
177 },
178 async logs(_n, onLine) {
179 for (const l of podOutput) onLine(l);
180 },
181 async delete() {},
182 };
183
184 const setPlacement = (value: string): void => {
185 setCapacity(app.db, "checks.placement", value, alice.id);
186 };
187
188 async function settled(oid: string): Promise<Run> {
189 const deadline = Date.now() + 30_000;
190 while (Date.now() < deadline) {
191 const run = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).find(
192 (r) => r.commitOid === oid,
193 );
194 if (run && (run.state === "ok" || run.state === "failed")) return getRun(app.db, run.id)!;
195 await Bun.sleep(30);
196 }
197 throw new Error("check did not settle");
198 }
199
200 const push = async (message: string, command: string) => {
201 const r = await commitToBranch(app, alice, repo, {
202 message,
203 files: [
204 { path: "forge.json", content: `{"check": {"run": ${JSON.stringify(command)}, "install": ""}}\n` },
205 ],
206 });
207 if (!r.ok) throw new Error(JSON.stringify(r.error));
208 return r.value.commitOid;
209 };
210
211 beforeAll(async () => {
212 for (const [k, v] of Object.entries(env)) {
213 saved[k] = process.env[k];
214 process.env[k] = v;
215 }
216 dataDir = await mkdtemp(join(tmpdir(), "forge-check-job-"));
217 app = createApp({ dataDir, port: 0 });
218 servers = await serve(app);
219 checks = startChecks(app, { forgeUrl: servers.url, concurrency: 1, jobs: client });
220 const a = await createUser(app.db, {
221 trusted: true,
222 username: "alice",
223 email: "[email protected]",
224 password: "a-good-passphrase",
225 adminIfFirst: true,
226 });
227 if (!a.ok) throw new Error(a.error);
228 alice = a.value;
229 const made = await createRepo(app, alice, { name: "lib", visibility: "public" });
230 if (!made.ok) throw new Error(String(made.error));
231 repo = made.value;
232 });
233
234 afterAll(async () => {
235 await checks.stop();
236 servers.stop();
237 app.close();
238 for (const [k, v] of Object.entries(saved)) {
239 if (v === undefined) delete process.env[k];
240 else process.env[k] = v;
241 }
242 await rm(dataDir, { recursive: true, force: true });
243 });
244
245 test("process placement is unchanged: no job, placement recorded, no node", async () => {
246 const run = await settled(await push("process", "true"));
247 expect(run.state).toBe("ok");
248 expect(run.placement).toBe("process");
249 expect(run.node).toBe("");
250 expect(created).toHaveLength(0);
251 });
252
253 test("job placement: the verdict is the job's, with its log, node and placement", async () => {
254 setPlacement("job");
255 verdict = { phase: "succeeded", node: "node-7", reason: "" };
256 const run = await settled(await push("job ok", "echo never-run-here"));
257 expect(run.state).toBe("ok");
258 expect(run.placement).toBe("job");
259 expect(run.node).toBe("node-7");
260 expect(created).toHaveLength(1);
261 const pod = (created[0] as any).spec.template.spec;
262 expect(pod.containers[0].command[2]).toBe("echo never-run-here");
263 expect(pod.nodeSelector).toEqual({ pool: "ci" });
264 const log = readRunLog(dataDir, run.id).lines.join("\n");
265 expect(log).toContain("from the pod");
266 });
267
268 test("job placement: a failed job fails the check with its reason", async () => {
269 setPlacement("job");
270 verdict = { phase: "failed", node: "node-8", reason: "the check exited 3" };
271 podOutput = [];
272 const run = await settled(await push("job fails", "false"));
273 podOutput = ["from the pod"];
274 expect(run.state).toBe("failed");
275 expect(run.summary).toContain("the check exited 3");
276 expect(run.node).toBe("node-8");
277 expect(readRunLog(dataDir, run.id).lines.join("\n")).toContain("running on node-8");
278 });
279
280 test("job placement without an image fails the check plainly", async () => {
281 setPlacement("job");
282 delete process.env["FORGE_CHECKS_IMAGE"];
283 try {
284 const run = await settled(await push("no image", "true"));
285 expect(run.state).toBe("failed");
286 expect(run.summary).toContain("FORGE_CHECKS_IMAGE");
287 } finally {
288 process.env["FORGE_CHECKS_IMAGE"] = env.FORGE_CHECKS_IMAGE;
289 }
290 });
291 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs