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 #1639

Closed opened this
Closed without merging

scout/forge:scout/1592-a-check-runs-as-a-cluster-job-when-check → main 8 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +1030 −6
docs/APPS.md +9
@@ -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. The pod mounts only that run's directory (by `subPath`), runs as a non-root user with a read-only root filesystem, no privilege escalation and every capability dropped. The forge does **not** enforce a pod's egress, so job placement refuses to run — the check fails saying why — until the operator sets `FORGE_CHECKS_EGRESS=policy`, stating that a NetworkPolicy for pods labelled `app.kubernetes.io/managed-by=forge` exists. With it set, the run records the sandbox as held "under the operator's NetworkPolicy". The run's page says where it ran (`a cluster job on <node>` or `a cell on the forge's machine`) and the terminal's run rows carry the job and its node. "Where checks run" is a choice in Settings → Capacity (the web page only; the terminal has no capacity screen). **Not yet tried against a real cluster:** the Job client is tested against a fake kube API and a stand-in, nothing more.
outdated

'a run's page shows its placement and node' is not true of this diff; also egress unenforced contradicts the trust-by-default direction.

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,13 @@ 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_EGRESS` | — | job placement: `policy` states a NetworkPolicy holds the pods' egress; without it job placement refuses to run |
1072 | `FORGE_CHECKS_IMAGE` | — | job placement: the image the check's pod runs |
1073 | `FORGE_CHECKS_CLAIM` | — | job placement: the claim holding `data/checks`, mounted in the pod |
1074 | `FORGE_CHECKS_NAMESPACE` | the pod's own | job placement: the namespace the Job is made in |
1075 | `FORGE_CHECKS_NODE_SELECTOR` | — | job placement: `key=value,…` the pod must land on |
1076 | `FORGE_CHECKS_TOLERATIONS` | — | job placement: `key[=value]:Effect,…` |
10681077 | `FORGE_CHECK_SHARDS` | the machine's cores | test shards per check (live: Settings → Capacity) |
10691078 | `FORGE_CELLS_EGRESS` | `enforce` | `report` lets undeclared egress through on 80/443 (live: Settings → Capacity) |
10701079 | `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 +89
@@ -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" });

Records placement only for process here; the page that should show it does not exist. Add the run-view consumer.

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,82 @@ 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 // Egress is the operator's NetworkPolicy (job placement does not
700 // run without FORGE_CHECKS_EGRESS=policy); the pod is unprivileged
701 // on its own subPath.
702 sandbox: {
703 enforced: true,
704 note: "a cluster job under the operator's NetworkPolicy",
705 },
706 });
707 const env: Record<string, string> = {
708 LANG: "C.UTF-8",
709 ...capacityEnv(app.db),
710 CI: "1",
711 FORGE_URL: options.forgeUrl,
712 FORGE_CHECK: id,
713 FORGE_COMMIT: x.commitOid,
714 ...(base === undefined
715 ? {}
716 : {
717 FORGE_CHECK_BASE: base,
718 FORGE_CHECK_LEARNED: readLearned(app.config.dataDir, x.pull!.id).join(","),
719 }),
720 FORGE_CELLS: "off",
721 };
722 const lines: string[] = [];
723 const script =
724 manifest.install === null ? command : `(${manifest.install}) && (${command})`;
725 const ran = await runJob(
726 client,
727 {
728 runId: id,
729 command: script,
730 cwd: dir,
731 mount: checksRoot(app.config.dataDir),
732 env,
733 settings: settings.value,
734 deadlineSeconds: manifest.timeout,
735 },
736 {
737 log: x.write,
738 onOutput: (line) => lines.push(line),
739 signal: x.signal,
740 onNode: (node) => {
741 if (x.runId !== undefined) noteRunProgress(app.db, x.runId, { node });
742 },
743 },
744 );
745 if (ran.ok) return { ok: true };
746 const { summary, detail } = summariseCheckFailure(lines, ran.error);
747 return { ok: false, error: summary, detail };
748 }
749
661750 // What starts a check: a branch moving, a pull opening, a fork's push
662751 // moving a pull's head. The commit checked is always the one the pull
663752 // proposes now.
src/cluster/jobs.ts added +434
@@ -0,0 +1,434 @@
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 { relative } from "node:path";
14 import { err, ok, type Result } from "../kernel/result.ts";
15
16 /** Where the cluster is told: image, namespace, claim, and where it may land. */
17 export interface JobSettings {
18 readonly image: string;
19 readonly namespace: string;
20 /** A claim holding the checkouts, mounted where the forge keeps them. */
21 readonly claim: string;
22 readonly nodeSelector: Readonly<Record<string, string>>;
23 readonly tolerations: readonly Toleration[];
24 }
25
26 export interface Toleration {
27 readonly key: string;
28 readonly operator: "Equal" | "Exists";
29 readonly value?: string;
30 readonly effect: "NoSchedule" | "PreferNoSchedule" | "NoExecute";
31 }
32
33 export interface JobSpec {
34 /** Names the Job. */
35 readonly runId: string;
36 readonly command: string;
37 readonly cwd: string;
38 /** The checkouts' root on the claim; only `cwd` below it is mounted. */
39 readonly mount: string;
40 readonly env: Readonly<Record<string, string>>;
41 readonly settings: JobSettings;
42 /** Seconds the Job may run before the cluster ends it. */
43 readonly deadlineSeconds: number;
44 }
45
46 export type JobPhase = "pending" | "running" | "succeeded" | "failed";
47
48 export interface JobStatus {
49 readonly phase: JobPhase;
50 /** The node the pod landed on; empty until it has one. */
51 readonly node: string;
52 readonly reason: string;
53 }
54
55 export interface JobClient {
56 create(manifest: object): Promise<Result<void, string>>;
57 status(name: string): Promise<Result<JobStatus, string>>;
58 /** Streams the pod's log line by line; resolves when the log ends or `signal` aborts. */
59 logs(name: string, onLine: (line: string) => void, signal: AbortSignal): Promise<void>;
60 delete(name: string): Promise<void>;
61 }
62
63 const NAME = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/;
64 const LABEL_KEY = /^([a-z0-9.-]+\/)?[A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?$/;
65 const LABEL_VALUE = /^([A-Za-z0-9]([-A-Za-z0-9_.]{0,61}[A-Za-z0-9])?)?$/;
66 const EFFECTS = ["NoSchedule", "PreferNoSchedule", "NoExecute"] as const;
67
68 /** A Job's name for a run: lowercase, dns-safe, at most 63 characters. */
69 export function jobName(runId: string): string {
70 const id = runId.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
71 return `forge-check-${id}`.slice(0, 63).replace(/-+$/, "");
72 }
73
74 /** `k=v,k2=v2` into a node selector; anything not a label is refused. */
75 export function parseNodeSelector(
76 text: string,
77 ): Result<Record<string, string>, string> {
78 const out: Record<string, string> = {};
79 for (const part of text.split(",").map((p) => p.trim()).filter((p) => p !== "")) {
80 const at = part.indexOf("=");
81 const key = at < 0 ? part : part.slice(0, at);
82 const value = at < 0 ? "" : part.slice(at + 1);
83 if (!LABEL_KEY.test(key) || !LABEL_VALUE.test(value))
84 return err(`node selector entry "${part.slice(0, 80)}" is not key=value`);
85 out[key] = value;
86 }
87 return ok(out);
88 }
89
90 /** `key=value:Effect` or `key:Effect`, comma separated, into tolerations. */
91 export function parseTolerations(text: string): Result<Toleration[], string> {
92 const out: Toleration[] = [];
93 for (const part of text.split(",").map((p) => p.trim()).filter((p) => p !== "")) {
94 const colon = part.lastIndexOf(":");
95 const head = colon < 0 ? part : part.slice(0, colon);
96 const effect = colon < 0 ? "" : part.slice(colon + 1);
97 const at = head.indexOf("=");
98 const key = at < 0 ? head : head.slice(0, at);
99 const value = at < 0 ? undefined : head.slice(at + 1);
100 const known = (EFFECTS as readonly string[]).includes(effect);
101 if (
102 !known ||
103 !LABEL_KEY.test(key) ||
104 (value !== undefined && !LABEL_VALUE.test(value))
105 )
106 return err(`toleration "${part.slice(0, 80)}" is not key[=value]:Effect`);
107 out.push(
108 value === undefined
109 ? { key, operator: "Exists", effect: effect as Toleration["effect"] }
110 : { key, operator: "Equal", value, effect: effect as Toleration["effect"] },
111 );
112 }
113 return ok(out);
114 }
115
116 /** The settings the environment names; a bad one is an error the check reports. */
117 export function jobSettings(
118 env: Record<string, string | undefined>,
119 ): Result<JobSettings, string> {
120 // The forge cannot enforce a pod's egress; the operator's NetworkPolicy
121 // does, and job placement does not run until they say one exists.
122 if ((env["FORGE_CHECKS_EGRESS"] ?? "").trim() !== "policy")
123 return err(
124 "checks.placement is job but FORGE_CHECKS_EGRESS=policy is not set: the forge does not enforce a pod's egress, so a NetworkPolicy for pods labelled app.kubernetes.io/managed-by=forge must exist first",
125 );
126 const image = (env["FORGE_CHECKS_IMAGE"] ?? "").trim();
127 if (image === "" || /\s/.test(image))
128 return err("checks.placement is job but FORGE_CHECKS_IMAGE is not set");
129 const namespace = (env["FORGE_CHECKS_NAMESPACE"] ?? "").trim() || readNamespace();
130 if (!NAME.test(namespace))
131 return err("checks.placement is job but the namespace is unknown (FORGE_CHECKS_NAMESPACE)");
132 const claim = (env["FORGE_CHECKS_CLAIM"] ?? "").trim();
133 if (!NAME.test(claim))
134 return err("checks.placement is job but FORGE_CHECKS_CLAIM is not set");
135 const selector = parseNodeSelector(env["FORGE_CHECKS_NODE_SELECTOR"] ?? "");
136 if (!selector.ok) return err(selector.error);
137 const tolerations = parseTolerations(env["FORGE_CHECKS_TOLERATIONS"] ?? "");
138 if (!tolerations.ok) return err(tolerations.error);
139 return ok({
140 image,
141 namespace,
142 claim,
143 nodeSelector: selector.value,
144 tolerations: tolerations.value,
145 });
146 }
147
148 /** The Job for one run: one pod, no retries, gone soon after it ends. */
149 export function jobManifest(spec: JobSpec): object {
150 const s = spec.settings;
151 // Only this run's directory is mounted, by subPath: one check cannot read
152 // or overwrite another pull's checkout.
153 const sub = relative(spec.mount, spec.cwd);
154 if (sub === "" || sub.startsWith("..") || sub.startsWith("/"))
155 throw new Error("the check's directory is outside the checks root");
156 const env = [
157 { name: "HOME", value: "/tmp" },
158 ...Object.entries(spec.env)
159 .filter(([name]) => name !== "HOME")
160 .map(([name, value]) => ({ name, value })),
161 ];
162 return {
163 apiVersion: "batch/v1",
164 kind: "Job",
165 metadata: {
166 name: jobName(spec.runId),
167 namespace: s.namespace,
168 labels: { "app.kubernetes.io/managed-by": "forge", "forge/check": jobName(spec.runId) },
169 },
170 spec: {
171 backoffLimit: 0,
172 activeDeadlineSeconds: Math.max(1, Math.ceil(spec.deadlineSeconds)),
173 ttlSecondsAfterFinished: 300,
174 template: {
175 metadata: { labels: { "forge/check": jobName(spec.runId) } },
176 spec: {
177 restartPolicy: "Never",
178 automountServiceAccountToken: false,
179 securityContext: {
180 runAsNonRoot: true,
181 runAsUser: 10001,
182 runAsGroup: 10001,
183 fsGroup: 10001,
184 seccompProfile: { type: "RuntimeDefault" },
185 },
186 ...(Object.keys(s.nodeSelector).length > 0 ? { nodeSelector: s.nodeSelector } : {}),
187 ...(s.tolerations.length > 0 ? { tolerations: s.tolerations } : {}),
188 containers: [
189 {
190 name: "check",
191 image: s.image,
192 command: ["/bin/sh", "-c", spec.command],
193 workingDir: spec.cwd,
194 env,
195 securityContext: {
196 allowPrivilegeEscalation: false,
197 readOnlyRootFilesystem: true,
198 capabilities: { drop: ["ALL"] },
199 },
200 volumeMounts: [
201 { name: "checks", mountPath: spec.cwd, subPath: sub },
202 { name: "scratch", mountPath: "/tmp" },
203 ],
204 },
205 ],
206 volumes: [
207 { name: "checks", persistentVolumeClaim: { claimName: s.claim } },
208 { name: "scratch", emptyDir: {} },
209 ],
210 },
211 },
212 },
213 };
214 }
215
216 export interface RunJobOptions {
217 readonly log: (line: string) => void;
218 /** Told each line of the pod's own output, apart from what `log` adds. */
219 readonly onOutput?: (line: string) => void;
220 readonly signal: AbortSignal;
221 /** Told the node once the pod has one. */
222 readonly onNode?: (node: string) => void;
223 /** @default 2000 */
224 readonly pollMs?: number;
225 /** How long the log may take to end once the pod has. @default 5000 */
226 readonly drainMs?: number;
227 }
228
229 const DRAIN_MS = 5000;
230
231 /** Run one Job to its verdict; the Job is deleted either way. */
232 export async function runJob(
233 client: JobClient,
234 spec: JobSpec,
235 options: RunJobOptions,
236 ): Promise<Result<void, string>> {
237 const name = jobName(spec.runId);
238 const created = await client.create(jobManifest(spec));
239 if (!created.ok) return err(`could not create the job: ${created.error}`);
240 options.log(`job ${name} created`);
241 const stop = new AbortController();
242 const forward = (): void => stop.abort();
243 options.signal.addEventListener("abort", forward, { once: true });
244 const following = client
245 .logs(
246 name,
247 (line) => {
248 options.onOutput?.(line);
249 options.log(line);
250 },
251 stop.signal,
252 )
253 .catch(() => undefined);
254 let node = "";
255 try {
256 for (;;) {
257 if (options.signal.aborted) return err("the check was stopped");
258 const status = await client.status(name);
259 if (!status.ok) return err(`could not read the job: ${status.error}`);
260 if (status.value.node !== "" && status.value.node !== node) {
261 node = status.value.node;
262 options.log(`running on ${node}`);
263 options.onNode?.(node);
264 }
265 if (status.value.phase === "succeeded") break;
266 if (status.value.phase === "failed") {
267 // The failure detail is built from the pod's output: drain it first.
268 await Promise.race([following, sleep(options.drainMs ?? DRAIN_MS, options.signal)]);
269 return err(status.value.reason || "the job failed");
270 }
271 await sleep(options.pollMs ?? 2000, options.signal);
272 }
273 // The log ends with the pod; give it a moment to drain.
274 await Promise.race([following, sleep(options.drainMs ?? DRAIN_MS, options.signal)]);
275 return ok(undefined);
276 } finally {
277 options.signal.removeEventListener("abort", forward);
278 stop.abort();
279 await client.delete(name).catch(() => undefined);
280 }
281 }
282
283 function sleep(ms: number, signal: AbortSignal): Promise<void> {
284 return new Promise((resolve) => {
285 if (signal.aborted) return resolve();
286 const done = (): void => {
287 clearTimeout(timer);
288 signal.removeEventListener("abort", done);
289 resolve();
290 };
291 const timer = setTimeout(done, ms);
292 signal.addEventListener("abort", done, { once: true });
293 });
294 }
295
296 const SA = "/var/run/secrets/kubernetes.io/serviceaccount";
297
298 function readNamespace(): string {
299 try {
300 return readFileSync(`${SA}/namespace`, "utf8").trim();
301 } catch {
302 return "";
303 }
304 }
305
306 /** The kube API as the pod's service account; undefined outside a cluster. */
307 export function kubeJobClient(
308 env: Record<string, string | undefined> = process.env,
309 namespace: string,
310 ): JobClient | undefined {
311 const host = env["KUBERNETES_SERVICE_HOST"];
312 const port = env["KUBERNETES_SERVICE_PORT"] ?? "443";
313 if (host === undefined || host === "" || !/^\d+$/.test(port)) return undefined;
314 let token: string;
315 let ca: string;
316 try {
317 token = readFileSync(`${SA}/token`, "utf8").trim();
318 ca = readFileSync(`${SA}/ca.crt`, "utf8");
319 } catch {
320 return undefined;
321 }
322 return kubeClient({
323 base: `https://${host.includes(":") ? `[${host}]` : host}:${port}`,
324 token,
325 ca,
326 namespace,
327 });
328 }
329
330 export interface KubeEndpoint {
331 readonly base: string;
332 readonly token: string;
333 readonly ca?: string;
334 readonly namespace: string;
335 /** Per request, apart from the log stream. @default 15000 */
336 readonly timeoutMs?: number;
337 }
338
339 /** The Job API at `base`; exported so a test can point it at a fake server. */
340 export function kubeClient(endpoint: KubeEndpoint): JobClient {
341 const { base, token, ca, namespace } = endpoint;
342 const jobs = `${base}/apis/batch/v1/namespaces/${namespace}/jobs`;
343 const pods = `${base}/api/v1/namespaces/${namespace}/pods`;
344 // A hung API must not hold a check slot outside the Job's deadline: every
345 // request but the log stream (which `signal` ends) has a timeout.
346 const call = (url: string, init: RequestInit = {}, stream = false): Promise<Response> =>
347 fetch(url, {
348 ...init,
349 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
350 ...(stream ? {} : { signal: AbortSignal.timeout(endpoint.timeoutMs ?? 15000) }),
351 ...(ca === undefined ? {} : { tls: { ca } }),
352 } as RequestInit);
353 const podOf = async (name: string): Promise<Record<string, any> | undefined> => {
354 const res = await call(`${pods}?labelSelector=${encodeURIComponent(`forge/check=${name}`)}`);
355 if (!res.ok) return undefined;
356 const body = (await res.json()) as { items?: Record<string, any>[] };
357 return body.items?.[0];
358 };
359 return {
360 async create(manifest) {
361 try {
362 const res = await call(jobs, { method: "POST", body: JSON.stringify(manifest) });
363 return res.ok ? ok(undefined) : err(`${res.status} ${(await res.text()).slice(0, 200)}`);
364 } catch (e) {
365 return err(`the cluster did not answer: ${(e as Error).name}`);
366 }
367 },
368 async status(name) {
369 try {
370 return await readStatus(name);
371 } catch (e) {
372 return err(`the cluster did not answer: ${(e as Error).name}`);
373 }
374 },
375 async logs(name, onLine, signal) {
376 await followLog(name, onLine, signal);
377 },
378 async delete(name) {
379 await call(`${jobs}/${name}?propagationPolicy=Background`, { method: "DELETE" });
380 },
381 };
382 async function readStatus(name: string): Promise<Result<JobStatus, string>> {
383 const res = await call(`${jobs}/${name}`);
384 if (!res.ok) return err(`${res.status}`);
385 const job = (await res.json()) as { status?: Record<string, any> };
386 const pod = await podOf(name);
387 const node = String(pod?.["spec"]?.["nodeName"] ?? "");
388 const st = job.status ?? {};
outdated

Stray block braces wrapping the function body; remove the extra nesting (same in followLog).

389 if ((st["succeeded"] ?? 0) > 0) return ok({ phase: "succeeded", node, reason: "" });
390 if ((st["failed"] ?? 0) > 0) {
391 const cond = (st["conditions"] as { reason?: string; message?: string }[] | undefined)?.find(
392 (c) => c.reason !== undefined,
393 );
394 const exit = pod?.["status"]?.["containerStatuses"]?.[0]?.["state"]?.["terminated"];
395 const why =
396 cond?.reason === "DeadlineExceeded"
397 ? "the job ran past its deadline"
398 : exit?.["exitCode"] !== undefined
399 ? `the check exited ${String(exit["exitCode"])}`
400 : cond?.message ?? "the job failed";
401 return ok({ phase: "failed", node, reason: String(why).slice(0, 200) });
402 }
403 return ok({ phase: (st["active"] ?? 0) > 0 ? "running" : "pending", node, reason: "" });
404 }
405 async function followLog(
406 name: string,
407 onLine: (line: string) => void,
408 signal: AbortSignal,
409 ): Promise<void> {
410 let pod: Record<string, any> | undefined;
411 while (!signal.aborted) {
412 pod = await podOf(name);
413 const phase = pod?.["status"]?.["phase"];
414 if (phase !== undefined && phase !== "Pending") break;
415 await sleep(1000, signal);
416 }
417 if (signal.aborted || pod === undefined) return;
418 const res = await call(
419 `${pods}/${encodeURIComponent(String(pod["metadata"]["name"]))}/log?follow=true`,
420 { signal },
421 true,
422 );
423 if (!res.ok || res.body === null) return;
424 const decoder = new TextDecoder();
425 let rest = "";
426 for await (const chunk of res.body as unknown as AsyncIterable<Uint8Array>) {
427 rest += decoder.decode(chunk, { stream: true });
428 const lines = rest.split("\n");
429 rest = lines.pop() ?? "";
430 for (const line of lines) onLine(line);
431 }
432 if (rest !== "") onLine(rest);
433 }
434 }
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 +23 −1
@@ -25,6 +25,14 @@ export const STOPPED_SUMMARY = "the forge stopped";
2525 /** The kinds that pass judgement on a commit: a preview's deploy, or a repository's own check. */
2626 export const CHECK_KINDS: readonly RunKind[] = ["deploy", "check"];
2727 export const RUN_KINDS: readonly RunKind[] = ["deploy", "agent", "check"];
28 /** Where a check ran, as a person says it; empty for a run that has no placement. */
29 export function placementText(run: Pick<Run, "placement" | "node">): string {
30 if (run.placement === "job")
31 return run.node === "" ? "a cluster job" : `a cluster job on ${run.node}`;
32 if (run.placement === "process") return "a cell on the forge's machine";
33 return "";
34 }
35
2836 export type RunState = "queued" | "running" | "ok" | "failed" | "cancelled";
2937
3038 export const RUN_TERMINAL: readonly RunState[] = ["ok", "failed", "cancelled"];
@@ -76,6 +84,10 @@ export interface Run {
7684 readonly sandboxEnforced: boolean | null;
7785 /** Why it was not, when it was not. */
7886 readonly sandboxNote: string;
87 /** For a check: `process` or `job`, as it ran; empty when unrecorded. */
88 readonly placement: string;
89 /** For a job: the cluster node its pod ran on. */
90 readonly node: string;
7991 /** A failed check's own detail, when its output was recognised; null otherwise. */
8092 readonly checkDetail: CheckDetail | null;
8193 readonly createdAt: string;
@@ -105,6 +117,8 @@ interface RunRow {
105117 turns: number;
106118 sandbox_enforced: number | null;
107119 sandbox_note: string;
120 placement: string;
121 node: string;
108122 check_detail: string;
109123 created_at: string;
110124 started_at: string | null;
@@ -133,6 +147,8 @@ const toRun = (r: RunRow): Run => ({
133147 sandboxEnforced:
134148 r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0,
135149 sandboxNote: r.sandbox_note,
150 placement: r.placement,
151 node: r.node,
136152 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
137153 createdAt: r.created_at,
138154 startedAt: r.started_at,
@@ -335,13 +351,17 @@ export function noteRunProgress(
335351 subscriptionId?: string | undefined;
336352 /** Whether the shell is held to the sandbox, and why not when it is not. */
337353 sandbox?: { enforced: boolean; note: string } | undefined;
354 /** Where a check ran, and the node when it was a job. */
355 placement?: "process" | "job" | undefined;
356 node?: string | undefined;
338357 },
339358 ): void {
340359 db.query(
341360 `UPDATE run SET session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd),
342361 branch = COALESCE(?4, branch), subscription_id = COALESCE(?5, subscription_id),
343362 sandbox_enforced = COALESCE(?6, sandbox_enforced),
344 sandbox_note = COALESCE(?7, sandbox_note)
363 sandbox_note = COALESCE(?7, sandbox_note),
364 placement = COALESCE(?8, placement), node = COALESCE(?9, node)
345365 WHERE id = ?1`,
346366 ).run(
347367 runId,
@@ -351,6 +371,8 @@ export function noteRunProgress(
351371 progress.subscriptionId ?? null,
352372 progress.sandbox === undefined ? null : progress.sandbox.enforced ? 1 : 0,
353373 progress.sandbox?.note.slice(0, 300) ?? null,
374 progress.placement ?? null,
375 progress.node?.slice(0, 253) ?? null,
354376 );
355377 }
356378
src/core/schema.ts +6
@@ -1639,6 +1639,12 @@ export const migrations: readonly string[] = [
16391639 ALTER TABLE run ADD COLUMN variant_group TEXT;
16401640 CREATE INDEX pull_variant_group ON pull(variant_group) WHERE variant_group IS NOT NULL;
16411641 `,
1642 // 79 — where a check ran (#1592): `placement` is `process` or `job`, `node`
1643 // the cluster node a job's pod landed on, empty for a process.
1644 `
1645 ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT '';
1646 ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT '';
1647 `,
16421648 ];
16431649
16441650 /**
src/tui/screens/runlist.ts +2 −1
@@ -13,7 +13,7 @@
1313
1414 import { getIssuesByIds, type Issue } from "../../core/issues.ts";
1515 import type { Repo } from "../../core/repos.ts";
16 import type { Run, RunState } from "../../core/runs.ts";
16 import { placementText, type Run, type RunState } from "../../core/runs.ts";
1717 import { getUsersByIds } from "../../core/users.ts";
1818 import type { Ctx } from "../app/app.ts";
1919 import type { Rect, Screen as Surface } from "../term/screen.ts";
@@ -108,6 +108,7 @@ export function runRows(
108108 meta: metaOf(
109109 run.commitOid === "" ? "" : run.commitOid.slice(0, 7),
110110 costText(run.costUsd),
111 run.placement === "job" ? placementText(run) : "",
111112 relTime(runWhen(run)),
112113 ),
113114 };
src/web/studio/run.ts +2 −2
@@ -26,7 +26,7 @@ import { page } from "../layout.ts";
2626 import { btn, sha } from "../ui.ts";
2727 import { previewCard } from "../pages/apps.ts";
2828 import { costText, durationText, runTitle, runTokens } from "../pages/runs.ts";
29 import { sandboxLine } from "./sandbox.ts";
29 import { placementLine, sandboxLine } from "./sandbox.ts";
3030 import { logBox, runVoice, RUN_TRANSCRIPT_CAP } from "./log.ts";
3131 import { changeHref, tellHref } from "./nouns.ts";
3232 import { unnamedRun, voiceFor, type Actor } from "./voice.ts";
@@ -160,7 +160,7 @@ export async function runView(
160160 )}
161161 </div>
162162 <p class="run-summary" id="run-summary">${run.summary}</p>
163 ${sandboxLine(run)}
163 ${placementLine(run)}${sandboxLine(run)}
164164 ${when(
165165 held.length > 0,
166166 () =>
src/web/studio/sandbox.ts +11 −2
@@ -5,9 +5,16 @@
55 * say nothing.
66 */
77
8 import type { Run } from "../../core/runs.ts";
8 import { placementText, type Run } from "../../core/runs.ts";
99 import { html, type Html } from "../html.ts";
1010
11 /** Where a check ran: a cell here, or a cluster job and its node. */
12 export function placementLine(run: Run): Html | null {
13 const where = placementText(run);
14 if (where === "") return null;
15 return html`<p class="muted small" id="run-placement">Ran in ${where}.</p>`;
16 }
17
1118 export function sandboxLine(run: Run): Html | null {
1219 if (run.sandboxEnforced === null) return null;
1320 const agent = run.kind === "agent";
@@ -15,7 +22,9 @@ export function sandboxLine(run: Run): Html | null {
1522 return html`<p class="muted small" id="run-sandbox">
1623 ${agent
1724 ? "Sandboxed: the shell was held to the policy."
18 : "Contained: the repository's code ran in a cell of its own, with limits."}
25 : run.placement === "job"
26 ? "Contained: the repository's code ran in an unprivileged pod, its egress held by the operator's NetworkPolicy."
27 : "Contained: the repository's code ran in a cell of its own, with limits."}
1928 </p>`;
2029 return html`<p class="error-note" id="run-sandbox">
2130 ${agent
test/check-job.test.ts added +445
@@ -0,0 +1,445 @@
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 kubeClient,
17 jobSettings,
18 parseNodeSelector,
19 parseTolerations,
20 runJob,
21 type JobClient,
22 type JobSpec,
23 type JobStatus,
24 } from "../src/cluster/jobs.ts";
25 import { setCapacity } from "../src/core/capacity.ts";
26 import { getRun, listRuns, type Run } from "../src/core/runs.ts";
27 import { createUser, type User } from "../src/core/users.ts";
28 import type { Repo } from "../src/core/repos.ts";
29 import { err, ok } from "../src/kernel/result.ts";
30 import { serve, type Servers } from "../src/http/server.ts";
31 import { runRows } from "../src/tui/screens/runlist.ts";
32 import { readRunLog } from "../src/runs/log.ts";
33
34 const settings = {
35 image: "oven/bun:1",
36 namespace: "forge",
37 claim: "checks",
38 nodeSelector: { pool: "ci" },
39 tolerations: [{ key: "ci", operator: "Exists" as const, effect: "NoSchedule" as const }],
40 };
41 const spec: JobSpec = {
42 runId: "01ABC",
43 command: "bun test",
44 cwd: "/data/checks/01ABC",
45 mount: "/data/checks",
46 env: { CI: "1" },
47 settings,
48 deadlineSeconds: 60,
49 };
50
51 /** A Job client that never leaves the process: records, scripts a verdict. */
52 function standIn(verdict: JobStatus, lines: string[] = []) {
53 const calls: string[] = [];
54 const created: object[] = [];
55 const client: JobClient = {
56 async create(m) {
57 calls.push("create");
58 created.push(m);
59 return ok(undefined);
60 },
61 async status() {
62 calls.push("status");
63 return ok(verdict);
64 },
65 async logs(_name, onLine) {
66 for (const l of lines) onLine(l);
67 },
68 async delete() {
69 calls.push("delete");
70 },
71 };
72 return { client, calls, created };
73 }
74
75 describe("the Job a check becomes", () => {
76 test("names are dns-safe and bounded", () => {
77 expect(jobName("01ABC_def")).toBe("forge-check-01abc-def");
78 expect(jobName("x".repeat(200)).length).toBeLessThanOrEqual(63);
79 });
80
81 test("the manifest carries placement, command, claim and no service account", () => {
82 const m = jobManifest(spec) as any;
83 const pod = m.spec.template.spec;
84 expect(pod.nodeSelector).toEqual({ pool: "ci" });
85 expect(pod.tolerations[0].key).toBe("ci");
86 expect(pod.containers[0].command).toEqual(["/bin/sh", "-c", "bun test"]);
87 expect(pod.containers[0].workingDir).toBe("/data/checks/01ABC");
88 expect(pod.volumes[0].persistentVolumeClaim.claimName).toBe("checks");
89 expect(pod.automountServiceAccountToken).toBe(false);
90 expect(m.spec.backoffLimit).toBe(0);
91 expect(m.spec.activeDeadlineSeconds).toBe(60);
92 });
93
94 test("the pod sees only its own run directory and is locked down", () => {
95 const pod = (jobManifest(spec) as any).spec.template.spec;
96 const c = pod.containers[0];
97 expect(c.volumeMounts[0]).toEqual({ name: "checks", mountPath: "/data/checks/01ABC", subPath: "01ABC" });
98 expect(c.volumeMounts.some((v: any) => v.mountPath === "/data/checks")).toBe(false);
99 expect(pod.securityContext.runAsNonRoot).toBe(true);
100 expect(c.securityContext.readOnlyRootFilesystem).toBe(true);
101 expect(c.securityContext.allowPrivilegeEscalation).toBe(false);
102 expect(c.securityContext.capabilities.drop).toEqual(["ALL"]);
103 expect(() => jobManifest({ ...spec, cwd: "/data/other" })).toThrow();
104 expect(() => jobManifest({ ...spec, cwd: "/data/checks" })).toThrow();
105 });
106
107 test("selectors and tolerations are validated at the boundary", () => {
108 expect(parseNodeSelector("pool=ci, zone=a").ok).toBe(true);
109 expect(parseNodeSelector("a b=c").ok).toBe(false);
110 expect(parseNodeSelector("k=v\nx").ok).toBe(false);
111 const t = parseTolerations("gpu=yes:NoSchedule,ci:NoExecute");
112 expect(t.ok && t.value.map((x) => x.operator)).toEqual(["Equal", "Exists"]);
113 expect(parseTolerations("ci:Whenever").ok).toBe(false);
114 expect(parseTolerations("ci").ok).toBe(false);
115 });
116
117 test("settings need an image, a claim and the operator's word that egress is held", () => {
118 expect(jobSettings({ FORGE_CHECKS_NAMESPACE: "forge", FORGE_CHECKS_CLAIM: "c", FORGE_CHECKS_EGRESS: "policy" }).ok).toBe(false);
119 const open = jobSettings({
120 FORGE_CHECKS_IMAGE: "img",
121 FORGE_CHECKS_NAMESPACE: "forge",
122 FORGE_CHECKS_CLAIM: "c",
123 });
124 expect(!open.ok && open.error).toContain("FORGE_CHECKS_EGRESS=policy");
125 const ok1 = jobSettings({
126 FORGE_CHECKS_EGRESS: "policy",
127 FORGE_CHECKS_IMAGE: "img",
128 FORGE_CHECKS_NAMESPACE: "forge",
129 FORGE_CHECKS_CLAIM: "c",
130 FORGE_CHECKS_NODE_SELECTOR: "pool=ci",
131 });
132 expect(ok1.ok && ok1.value.nodeSelector).toEqual({ pool: "ci" });
133 });
134 });
135
136 describe("runJob", () => {
137 test("a succeeded job passes, its log and node are reported, and it is deleted", async () => {
138 const { client, calls } = standIn({ phase: "succeeded", node: "n1", reason: "" }, ["hello"]);
139 const lines: string[] = [];
140 let node = "";
141 const r = await runJob(client, spec, {
142 log: (l) => lines.push(l),
143 signal: new AbortController().signal,
144 onNode: (n) => (node = n),
145 pollMs: 1,
146 });
147 expect(r.ok).toBe(true);
148 expect(lines).toContain("hello");
149 expect(node).toBe("n1");
150 expect(calls.at(-1)).toBe("delete");
151 });
152
153 test("a failed job is an error with the reason, and still deleted", async () => {
154 const { client, calls } = standIn({ phase: "failed", node: "", reason: "the check exited 1" });
155 const r = await runJob(client, spec, {
156 log: () => {},
157 signal: new AbortController().signal,
158 pollMs: 1,
159 });
160 expect(r).toEqual(err("the check exited 1"));
161 expect(calls).toContain("delete");
162 });
163
164 test("a failed job's late output is drained before the verdict returns", async () => {
165 const { client } = standIn({ phase: "failed", node: "", reason: "the check exited 1" });
166 client.logs = async (_n, onLine) => {
167 await new Promise((r) => setTimeout(r, 60));
168 onLine("1 fail: expected 2");
169 };
170 const out: string[] = [];
171 const r = await runJob(client, spec, {
172 log: () => {},
173 onOutput: (l) => out.push(l),
174 signal: new AbortController().signal,
175 pollMs: 1,
176 });
177 expect(r.ok).toBe(false);
178 expect(out).toEqual(["1 fail: expected 2"]);
179 });
180
181 test("an abort stops waiting and deletes the job", async () => {
182 const { client, calls } = standIn({ phase: "running", node: "", reason: "" });
183 const stop = new AbortController();
184 setTimeout(() => stop.abort(), 20);
185 const r = await runJob(client, spec, { log: () => {}, signal: stop.signal, pollMs: 5 });
186 expect(r.ok).toBe(false);
187 expect(calls).toContain("delete");
188 });
189 });
190
191 describe("checks.placement", () => {
192 let dataDir: string;
193 let app: App;
194 let servers: Servers;
195 let checks: ChecksHandle;
196 let alice: User;
197 let repo: Repo;
198 let verdict: JobStatus = { phase: "succeeded", node: "node-7", reason: "" };
199 let podOutput: string[] = ["from the pod"];
200 const created: object[] = [];
201 const saved: Record<string, string | undefined> = {};
202 const env = {
203 FORGE_CHECKS_IMAGE: "oven/bun:1",
204 FORGE_CHECKS_EGRESS: "policy",
205 FORGE_CHECKS_NAMESPACE: "forge",
206 FORGE_CHECKS_CLAIM: "checks",
207 FORGE_CHECKS_NODE_SELECTOR: "pool=ci",
208 };
209
210 const client: JobClient = {
211 async create(m) {
212 created.push(m);
213 return ok(undefined);
214 },
215 async status() {
216 return ok(verdict);
217 },
218 async logs(_n, onLine) {
219 for (const l of podOutput) onLine(l);
220 },
221 async delete() {},
222 };
223
224 const setPlacement = (value: string): void => {
225 setCapacity(app.db, "checks.placement", value, alice.id);
226 };
227
228 async function settled(oid: string): Promise<Run> {
229 const deadline = Date.now() + 30_000;
230 while (Date.now() < deadline) {
231 const run = listRuns(app.db, repo.id, { kind: "check", limit: 50 }).find(
232 (r) => r.commitOid === oid,
233 );
234 if (run && (run.state === "ok" || run.state === "failed")) return getRun(app.db, run.id)!;
235 await Bun.sleep(30);
236 }
237 throw new Error("check did not settle");
238 }
239
240 const push = async (message: string, command: string) => {
241 const r = await commitToBranch(app, alice, repo, {
242 message,
243 files: [
244 { path: "forge.json", content: `{"check": {"run": ${JSON.stringify(command)}, "install": ""}}\n` },
245 ],
246 });
247 if (!r.ok) throw new Error(JSON.stringify(r.error));
248 return r.value.commitOid;
249 };
250
251 beforeAll(async () => {
252 for (const [k, v] of Object.entries(env)) {
253 saved[k] = process.env[k];
254 process.env[k] = v;
255 }
256 dataDir = await mkdtemp(join(tmpdir(), "forge-check-job-"));
257 app = createApp({ dataDir, port: 0 });
258 servers = await serve(app);
259 checks = startChecks(app, { forgeUrl: servers.url, concurrency: 1, jobs: client });
260 const a = await createUser(app.db, {
261 trusted: true,
262 username: "alice",
263 email: "[email protected]",
264 password: "a-good-passphrase",
265 adminIfFirst: true,
266 });
267 if (!a.ok) throw new Error(a.error);
268 alice = a.value;
269 const made = await createRepo(app, alice, { name: "lib", visibility: "public" });
270 if (!made.ok) throw new Error(String(made.error));
271 repo = made.value;
272 });
273
274 afterAll(async () => {
275 await checks.stop();
276 servers.stop();
277 app.close();
278 for (const [k, v] of Object.entries(saved)) {
279 if (v === undefined) delete process.env[k];
280 else process.env[k] = v;
281 }
282 await rm(dataDir, { recursive: true, force: true });
283 });
284
285 test("process placement is unchanged: no job, placement recorded, no node", async () => {
286 const run = await settled(await push("process", "true"));
287 expect(run.state).toBe("ok");
288 expect(run.placement).toBe("process");
289 expect(run.node).toBe("");
290 expect(created).toHaveLength(0);
291 });
292
293 test("job placement: the verdict is the job's, with its log, node and placement", async () => {
294 setPlacement("job");
295 verdict = { phase: "succeeded", node: "node-7", reason: "" };
296 const run = await settled(await push("job ok", "echo never-run-here"));
297 expect(run.state).toBe("ok");
298 expect(run.placement).toBe("job");
299 expect(run.node).toBe("node-7");
300 expect(run.sandboxEnforced).toBe(true);
301 expect(run.sandboxNote).toContain("NetworkPolicy");
302 const web = await (await fetch(`${servers.url}/alice/lib/runs/${run.id}`)).text();
303 expect(web).toContain('id="run-placement"');
304 expect(web).toContain("a cluster job on node-7");
305 expect(web).toContain("NetworkPolicy");
306 const rows = runRows([run], new Map());
307 expect(rows[0]!.meta).toContain("a cluster job on node-7");
308 expect(created).toHaveLength(1);
309 const pod = (created[0] as any).spec.template.spec;
310 expect(pod.containers[0].command[2]).toBe("echo never-run-here");
311 expect(pod.nodeSelector).toEqual({ pool: "ci" });
312 const log = readRunLog(dataDir, run.id).lines.join("\n");
313 expect(log).toContain("from the pod");
314 });
315
316 test("job placement: a failed job fails the check with its reason", async () => {
317 setPlacement("job");
318 verdict = { phase: "failed", node: "node-8", reason: "the check exited 3" };
319 podOutput = [];
320 const run = await settled(await push("job fails", "false"));
321 podOutput = ["from the pod"];
322 expect(run.state).toBe("failed");
323 expect(run.summary).toContain("the check exited 3");
324 expect(run.node).toBe("node-8");
325 expect(readRunLog(dataDir, run.id).lines.join("\n")).toContain("running on node-8");
326 });
327
328 test("job placement does not run until the operator says egress is held", async () => {
329 setPlacement("job");
330 delete process.env["FORGE_CHECKS_EGRESS"];
331 created.length = 0;
332 try {
333 const run = await settled(await push("no policy", "true"));
334 expect(run.state).toBe("failed");
335 expect(run.summary).toContain("FORGE_CHECKS_EGRESS=policy");
336 expect(created).toHaveLength(0);
337 } finally {
338 process.env["FORGE_CHECKS_EGRESS"] = env.FORGE_CHECKS_EGRESS;
339 }
340 });
341
342 test("a process run's page says it ran in a cell, and the capacity page offers the choice", async () => {
343 setPlacement("process");
344 const run = await settled(await push("again", "true"));
345 const web = await (await fetch(`${servers.url}/alice/lib/runs/${run.id}`)).text();
346 expect(web).toContain("a cell on the forge");
347 expect(runRows([run], new Map())[0]!.meta).not.toContain("cluster");
348 const signin = await fetch(`${servers.url}/signin`, {
349 method: "POST",
350 redirect: "manual",
351 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
352 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
353 });
354 const cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
355 const cap = await (await fetch(`${servers.url}/settings/capacity`, { headers: { cookie } })).text();
356 expect(cap).toContain("Where checks run");
357 expect(cap).toContain("<option value=\"job\"");
358 });
359
360 test("job placement without an image fails the check plainly", async () => {
361 setPlacement("job");
362 delete process.env["FORGE_CHECKS_IMAGE"];
363 try {
364 const run = await settled(await push("no image", "true"));
365 expect(run.state).toBe("failed");
366 expect(run.summary).toContain("FORGE_CHECKS_IMAGE");
367 } finally {
368 process.env["FORGE_CHECKS_IMAGE"] = env.FORGE_CHECKS_IMAGE;
369 }
370 });
371 });
372
373 describe("the kube client against a fake API", () => {
374 let server: ReturnType<typeof Bun.serve>;
375 let job: Record<string, unknown> = {};
376 let pod: Record<string, unknown> = {};
377 let hang = false;
378 let seen: { method: string; path: string; auth: string | null }[] = [];
379 beforeAll(() => {
380 server = Bun.serve({
381 port: 0,
382 async fetch(req) {
383 const url = new URL(req.url);
384 seen.push({ method: req.method, path: url.pathname, auth: req.headers.get("authorization") });
385 if (hang) await new Promise((r) => setTimeout(r, 2000));
386 if (url.pathname.endsWith("/pods"))
387 return Response.json({ items: [pod] });
388 if (url.pathname.endsWith("/log")) return new Response("line one\nline two");
389 if (req.method === "POST") return new Response("denied", { status: 403 });
390 return Response.json(job);
391 },
392 });
393 });
394 afterAll(() => server.stop(true));
395 const client = (timeoutMs = 2000) =>
396 kubeClient({ base: `http://127.0.0.1:${server.port}`, token: "t0k", namespace: "forge", timeoutMs });
397 const podDone = (exitCode: number) => ({
398 metadata: { name: "p" },
399 spec: { nodeName: "n9" },
400 status: { phase: "Failed", containerStatuses: [{ state: { terminated: { exitCode } } }] },
401 });
402
403 test("status maps succeeded, running, exit codes and the deadline", async () => {
404 const c = client();
405 pod = podDone(0);
406 job = { status: { succeeded: 1 } };
407 expect(await c.status("x")).toEqual(ok({ phase: "succeeded", node: "n9", reason: "" }));
408 job = { status: { active: 1 } };
409 expect(await c.status("x")).toEqual(ok({ phase: "running", node: "n9", reason: "" }));
410 job = { status: {} };
411 expect((await c.status("x")) as any).toEqual(ok({ phase: "pending", node: "n9", reason: "" }));
412 pod = podDone(3);
413 job = { status: { failed: 1, conditions: [{ reason: "BackoffLimitExceeded" }] } };
414 expect(await c.status("x")).toEqual(ok({ phase: "failed", node: "n9", reason: "the check exited 3" }));
415 job = { status: { failed: 1, conditions: [{ reason: "DeadlineExceeded" }] } };
416 expect(await c.status("x")).toEqual(ok({ phase: "failed", node: "n9", reason: "the job ran past its deadline" }));
417 });
418
419 test("requests carry the token; a refused create is an error; logs stream by line", async () => {
420 const c = client();
421 seen = [];
422 pod = { metadata: { name: "p" }, status: { phase: "Running" } };
423 const created = await c.create({});
424 expect(created.ok).toBe(false);
425 expect(seen[0]!.auth).toBe("Bearer t0k");
426 const lines: string[] = [];
427 await c.logs("x", (l) => lines.push(l), new AbortController().signal);
428 expect(lines).toEqual(["line one", "line two"]);
429 await c.delete("x");
430 expect(seen.at(-1)!.method).toBe("DELETE");
431 });
432
433 test("a hung API is an error after the timeout, not a stalled slot", async () => {
434 hang = true;
435 try {
436 const t = Date.now();
437 const r = await client(50).status("x");
438 expect(r.ok).toBe(false);
439 expect(Date.now() - t).toBeLessThan(1000);
440 expect((await client(50).create({})).ok).toBe(false);
441 } finally {
442 hang = false;
443 }
444 });
445 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs