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

A check runs as a cluster Job when checks.placement is job; the run records node and placement; process stays the default and unchanged #1733

Closed opened this
Closed without merging

scout/forge:scout/1692-a-check-runs-as-a-cluster-job-when-check → main 12 commits fork 6 threads · 6 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
38 files changed +603 −13
.bash_profile added
No content changes.
.bashrc added
No content changes.
.claude/agents added
No content changes.
.claude/commands added
No content changes.
.claude/hooks added
No content changes.
.claude/launch.json added
No content changes.
.claude/loop.md added
No content changes.
.claude/output-styles added
No content changes.
.claude/routines added
No content changes.
.claude/scheduled_tasks.json added
No content changes.
.claude/settings.json added
No content changes.
.claude/settings.local.json added
No content changes.
.claude/skills added
No content changes.
.claude/workflows added
No content changes.
.gitconfig added
No content changes.
.gitmodules added
No content changes.
.idea added
No content changes.
.mcp.json added
No content changes.
.profile added
No content changes.
.ripgreprc added
No content changes.
.vscode added
No content changes.
.zprofile added
No content changes.
.zshrc added
No content changes.
README.md +26
@@ -832,6 +832,32 @@ In the forge itself: a pull's check runs `fast` when the manifest has one, in a
832832
833833 Every limit the owner can hit is declared in `src/settings/limits.ts` with its default, bounds and reason, and changed live by a forge admin at `/admin/limits`, `PUT /api/v1/admin/limits/:key` or the `limits` MCP tool (never by an agent). Each change is kept with who made it.
834834
835 ### Where a check runs
836
837 `checks.placement` (Settings → Capacity, or `FORGE_CHECKS_PLACEMENT`) is
838 `process` by default: the check runs here, in a cell. Set to `job`, the
839 check's command (after `install`) runs as a Kubernetes Job through
840 `src/cluster/jobs.ts`, in the image `FORGE_CHECKS_IMAGE`, on nodes chosen by
841 `FORGE_CHECKS_NODE_SELECTOR` (JSON object) and `FORGE_CHECKS_TOLERATIONS`
842 (JSON list). The Job's log is written into the run's log when it ends, and the
843 run records `placement` and `node`, and the run page shows them. The image
844 must have `git` and `sh`. An init step fetches exactly the pull's head commit
845 from the forge (`FORGE_URL`, so the pod must reach it) with a read-only token
846 of the repository's owner that lives at most 15 minutes and is revoked when
847 the check ends; it travels in a Secret (deleted with the Job) that only the
848 init container reads, and the check fails unless HEAD is that commit. A job
849 check is refused while `cells.egress` is `enforce`, since a Job's network is
850 not held the way a cell's is: set it to `report` to use job placement. The
851 pod has no service-account token, runs non-root with no privilege escalation
852 and a read-only root (only `/work` and `/tmp` are writable). The runner needs
853 rights to create and delete Jobs and Secrets. An abort (cancel, new push, budget) deletes the Job.
854
855 Not done: a NetworkPolicy so job checks could run under `enforce`, the fast
856 tier checks the head, not the head merged into the base, the `ro` token is
857 per-account and not per-repository (tokens have no narrower scope), and the log
858 is not live while it runs. The run page, the terminal's run list and run events
859 (`placement`, `node`) all say where a check ran.
860
835861 ## Choosing among variants
836862
837863 A tell with `variants: n` starts n builders whose pulls share a variant group.
scripts/gate.ts +1
@@ -46,6 +46,7 @@ export const GATE: readonly string[] = [
4646 "test/chaos.test.ts",
4747 "test/flow-stage.test.ts",
4848 "test/cluster-jobs.test.ts",
49 "test/check-placement.test.ts",
4950 "test/fuzz-found.test.ts",
5051 "test/fuzz-parsers.test.ts",
5152 "test/attach-look.test.ts",
src/actions/runs.ts +2
@@ -40,6 +40,8 @@ export function runPayload(run: Run): Record<string, unknown> {
4040 commitOid: run.commitOid,
4141 reason: run.reason,
4242 summary: run.summary,
43 placement: run.placement,
44 node: run.node,
4345 costUsd: run.costUsd,
4446 turns: run.turns,
4547 ...(run.issueId === null ? {} : { issueId: run.issueId }),
src/checks/placement.ts added +151
@@ -0,0 +1,151 @@
1 /**
2 * Where a check runs: here, in a cell (`process`, the default), or as a
3 * Kubernetes Job (`job`, `cluster/jobs.ts`). The setting is
4 * `checks.placement` (`core/capacity.ts`); the Job's image, node selector
5 * and tolerations come from `FORGE_CHECKS_IMAGE`,
6 * `FORGE_CHECKS_NODE_SELECTOR` (a JSON object of strings) and
7 * `FORGE_CHECKS_TOLERATIONS` (a JSON list). Plain data in, plain data out.
8 */
9 import { runJob, type JobOptions, type JobSpec, type Toleration } from "../cluster/jobs.ts";
10
11 export type JobPlacement = {
12 image: string;
13 nodeSelector: Record<string, string>;
14 tolerations: Toleration[];
15 };
16
17 const OPERATORS = ["Exists", "Equal"];
18 const EFFECTS = ["NoSchedule", "PreferNoSchedule", "NoExecute"];
19
20 const isText = (v: unknown): v is string => typeof v === "string" && v.length <= 253 && !/[\x00-\x1f]/.test(v);
21
22 /** The Job settings in `env`, or the reason they are unusable. */
23 export function jobPlacement(
24 env: Record<string, string | undefined> = process.env,
25 ): { ok: true; value: JobPlacement } | { ok: false; error: string } {
26 const image = (env["FORGE_CHECKS_IMAGE"] ?? "").trim();
27 if (image === "" || /\s/.test(image) || image.length > 300)
28 return { ok: false, error: "FORGE_CHECKS_IMAGE names no image" };
29 let selector: unknown = {};
30 let tolerations: unknown = [];
31 try {
32 if ((env["FORGE_CHECKS_NODE_SELECTOR"] ?? "").trim() !== "")
33 selector = JSON.parse(env["FORGE_CHECKS_NODE_SELECTOR"]!);
34 if ((env["FORGE_CHECKS_TOLERATIONS"] ?? "").trim() !== "")
35 tolerations = JSON.parse(env["FORGE_CHECKS_TOLERATIONS"]!);
36 } catch {
37 return { ok: false, error: "FORGE_CHECKS_NODE_SELECTOR and FORGE_CHECKS_TOLERATIONS must be JSON" };
38 }
39 if (
40 typeof selector !== "object" ||
41 selector === null ||
42 Array.isArray(selector) ||
43 !Object.entries(selector).every(([k, v]) => isText(k) && isText(v))
44 )
45 return { ok: false, error: "FORGE_CHECKS_NODE_SELECTOR must be an object of strings" };
46 if (!Array.isArray(tolerations) || tolerations.length > 20 || !tolerations.every(validToleration))
47 return { ok: false, error: "FORGE_CHECKS_TOLERATIONS must be a list of tolerations" };
48 const nodeSelector = Object.fromEntries(Object.entries(selector as Record<string, string>));
49 return { ok: true, value: { image, nodeSelector, tolerations: tolerations.map(pickToleration) } };
50 }
51
52 function validToleration(t: unknown): boolean {
53 if (typeof t !== "object" || t === null || Array.isArray(t)) return false;
54 const o = t as Record<string, unknown>;
55 return (
56 (o["key"] === undefined || isText(o["key"])) &&
57 (o["value"] === undefined || isText(o["value"])) &&
58 (o["operator"] === undefined || OPERATORS.includes(o["operator"] as string)) &&
59 (o["effect"] === undefined || EFFECTS.includes(o["effect"] as string))
60 );
61 }
62
63 /** Only the four fields a toleration has; nothing else a setting carries reaches the manifest. */
64 function pickToleration(t: unknown): Toleration {
65 const o = t as Toleration;
66 return {
67 ...(o.key === undefined ? {} : { key: o.key }),
68 ...(o.operator === undefined ? {} : { operator: o.operator }),
69 ...(o.value === undefined ? {} : { value: o.value }),
70 ...(o.effect === undefined ? {} : { effect: o.effect }),
71 };
72 }
73
74 /** A DNS label for a run: `check-` and the run's id, lowered and cleaned. */
75 export function jobName(runId: string): string {
76 const id = runId.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
77 return `check-${id}`.slice(0, 53).replace(/-+$/, "");
78 }
79
80 export type JobCheck = {
81 /** A verdict: true when the command exited 0. */
82 ok: boolean;
83 error: string;
84 lines: string[];
85 node: string;
86 };
87
88 /**
89 * The step that puts exactly `commit` in `/work`: a fetch of that object with
90 * the credential in an environment only this step has, then a refusal unless
91 * HEAD is the commit. A check that did not get the commit's tree fails.
92 */
93 export const CHECKOUT = [
94 "sh",
95 "-c",
96 'git init -q . && git -c "http.extraHeader=Authorization: Basic $FORGE_AUTH" fetch -q --depth 1 "$FORGE_REPO_URL" "$FORGE_COMMIT" && git checkout -q FETCH_HEAD && test "$(git rev-parse HEAD)" = "$FORGE_COMMIT"',
97 ];
98
99 /**
100 * Run one check command as a Job: the commit's tree is fetched with `auth`
101 * (a read-only credential the caller makes and revokes), then `install`
102 * (when there is one) and the command, under `sh -c`, with the few variables
103 * a check is told. The command never sees the credential.
104 */
105 export async function runCheckJob(
106 x: {
107 runId: string;
108 commitOid: string;
109 forgeUrl: string;
110 install: string | null;
111 command: string;
112 timeoutMs: number;
113 placement: JobPlacement;
114 /** Where the commit is fetched from, and the `user:token` that may read it. */
115 repoUrl: string;
116 auth: string;
117 env?: Record<string, string>;
118 },
119 opts: JobOptions = {},
120 ): Promise<JobCheck> {
121 const script = x.install === null ? x.command : `${x.install} && ${x.command}`;
122 const spec: JobSpec = {
123 name: jobName(x.runId),
124 image: x.placement.image,
125 command: ["sh", "-c", script],
126 env: { ...x.env, CI: "1", FORGE_URL: x.forgeUrl, FORGE_CHECK: x.runId, FORGE_COMMIT: x.commitOid },
127 nodeSelector: x.placement.nodeSelector,
128 tolerations: x.placement.tolerations,
129 checkout: {
130 command: CHECKOUT,
131 env: { FORGE_REPO_URL: x.repoUrl, FORGE_COMMIT: x.commitOid },
132 // A Secret, not a literal in the pod spec: pods are readable in the namespace.
133 secret: { FORGE_AUTH: Buffer.from(x.auth).toString("base64") },
outdated

Medium: the credential is a literal env value in the pod spec, so anyone with get pods in the namespace can read it, and it stays in the API server until the Job is deleted. Use a Secret that is deleted with the Job, and read it with valueFrom.secretKeyRef in the init container.

134 },
135 };
136 try {
137 const r = await runJob(spec, { timeoutMs: x.timeoutMs, ...opts });
138 const node = r.node ?? "";
139 if (r.cancelled) return { ok: false, error: "the check job was cancelled", lines: r.lines, node };
140 if (r.timedOut) return { ok: false, error: `the check job ran past ${Math.round(x.timeoutMs / 1000)}s`, lines: r.lines, node };
141 if (r.exitCode === 0) return { ok: true, error: "", lines: r.lines, node };
142 return {
143 ok: false,
144 error: r.exitCode === null ? "the check job ended without an exit code" : `the check job exited ${r.exitCode}`,
145 lines: r.lines,
146 node,
147 };
148 } catch (e) {
149 return { ok: false, error: `the check job could not run: ${e instanceof Error ? e.message : String(e)}`, lines: [], node: "" };
150 }
151 }
src/checks/service.ts +57
@@ -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,9 @@ import {
6667 type CellSpec,
6768 } from "../apps/contain.ts";
6869 import { summariseCheckFailure } from "./summary.ts";
70 import { createToken, revokeToken } from "../core/tokens.ts";
71 import type { JobOptions } from "../cluster/jobs.ts";
72 import { jobPlacement, runCheckJob } from "./placement.ts";
6973 import type { CheckDetail } from "../core/runs.ts";
7074
7175 const log = createLog("checks");
@@ -77,6 +81,8 @@ export interface ChecksOptions {
7781 readonly forgeUrl: string;
7882 /** How long a check may run before it is killed. @default BUDGETS.gate */
7983 readonly budgetMs?: number | undefined;
84 /** The kube client, credentials and clock of a `job` check; tests stand in. */
85 readonly job?: JobOptions | undefined;
8086 }
8187
8288 export interface ChecksHandle {
@@ -550,6 +556,57 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
550556 : x.tier === "fast"
551557 ? (manifest.fast ?? manifest.run)
552558 : manifest.run;
559 // `checks.placement: job` hands the command to the cluster; the run
560 // records where it went and on which node. `process` is everything below.
561 if (capacityValue(app.db, "checks.placement") === "job") {

High: this branch skips cells.egress. The process path below passes egressMode: egressSetting(app.db) to the cell; the Job gets no network restriction at all. When egress is enforce, either create a NetworkPolicy for this Job (DNS and the forge host only) and delete it with the Job, or fail the check with a reason. Add a test for it.

562 if (x.runId !== undefined)
563 noteRunProgress(app.db, x.runId, {
564 placement: { placement: "job", node: "" },
565 });
566 // A process check is held to `cells.egress`; a Job has no such hold
567 // here, so under `enforce` repository code is not handed the network.
568 if (egressSetting(app.db) === "enforce")
569 return {
570 ok: false,
571 error: "job placement needs cells.egress set to report: a cluster job's network is not held",
outdated

Medium: an account-wide ro token can read every private repository of the owner. Give it the narrowest scope there is: this repository, read-only git.

572 };
573 const placed = jobPlacement();
574 if (!placed.ok) return { ok: false, error: placed.error };
575 write(`placement: job (${placed.value.image})`);
576 // The Job fetches the commit with a read-only token of the repository's
577 // owner (tokens have no narrower scope). It lives only as long as a pod
578 // needs to start and fetch, and is revoked when the check ends.
579 const token = createToken(app.db, repo.ownerId, `check:${run.id}`, "ro", {
580 expiresAt: new Date(Date.now() + Math.min(manifest.timeout * 1000, 15 * 60_000)).toISOString(),
581 });
582 const job = await runCheckJob(
583 {
584 runId: run.id,
585 commitOid: x.commitOid,

x.commitOid is the pull head. The process path checks run.commitOid: the head merged into the base for fast, and the unreferenced "full gate on land" commit for checks.gate. As written, the job judges a different tree from the one that lands. Use run.commitOid and make it fetchable (see below).

586 forgeUrl: options.forgeUrl,
587 repoUrl: `${options.forgeUrl.replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}.git`,

This is always the base repository's URL. bare may be pullDir, the head repository of a sealed cross-repo pull, and the gate's merge commit lives only there with no ref pointing at it. Expose the commit under a temporary ref in bare and fetch from that repository's URL with a token of its owner.

588 auth: `${repo.ownerName}:${token.token}`,
589 install: manifest.install,
590 command,
591 timeoutMs: manifest.timeout * 1000,
592 placement: placed.value,
593 },
594 { ...options.job, signal },
595 ).finally(() => revokeToken(app.db, token.id));
596 if (x.runId !== undefined && job.node !== "")
597 noteRunProgress(app.db, x.runId, {
598 placement: { placement: "job", node: job.node },
599 });
600 if (job.node !== "") write(`node: ${job.node}`);
601 for (const line of job.lines) write(line);
602 if (job.ok) return { ok: true };
603 const { summary, detail } = summariseCheckFailure(job.lines, job.error);
604 return { ok: false, error: summary, detail };
605 }
606 if (x.runId !== undefined)
607 noteRunProgress(app.db, x.runId, {
608 placement: { placement: "process", node: "" },
609 });
553610 // The fast tier diffs what the pull changes against the base's tip,
554611 // which the clone is given as a repository of its own: `origin/main` is
555612 // not a ref there.
src/cluster/jobs.ts +101 −7
@@ -26,6 +26,14 @@ export type JobSpec = {
2626 env?: Record<string, string>;
2727 nodeSelector?: Record<string, string>;
2828 tolerations?: Toleration[];
29 /**
30 * A step that fills `/work` before the command runs, in a container of its
31 * own: its `env` (a credential, say) is never the command's. The command
32 * runs in `/work`. A step that exits non-zero fails the Job. `secret` is
33 * env the pod spec must not carry in plain text: it is made a Secret of the
34 * Job's name, read with `secretKeyRef`, and deleted with the Job.
35 */
36 checkout?: { command: string[]; env: Record<string, string>; secret?: Record<string, string> };
2937 };
3038
3139 export type JobResult = {
@@ -33,6 +41,10 @@ export type JobResult = {
3341 exitCode: number | null;
3442 lines: string[];
3543 timedOut: boolean;
44 /** True when `signal` aborted before the Job ended. */
45 cancelled?: boolean;
46 /** The node the pod was scheduled on, when it got one. */
47 node?: string | undefined;
3648 };
3749
3850 export type Credentials = { server: string; token: string; ca?: string; namespace: string };
@@ -47,6 +59,8 @@ export type JobOptions = {
4759 sleep?: (ms: number) => Promise<void>;
4860 /** The most log bytes read; the rest of the log is left unread. */
4961 maxLogBytes?: number;
62 /** When it aborts the Job is deleted and the result is `cancelled`. */
63 signal?: AbortSignal;
5064 };
5165
5266 /** The service account the pod runs as; throws when there is none. */
@@ -63,16 +77,41 @@ export function serviceAccount(dir = SA_DIR, env: Record<string, string | undefi
6377 };
6478 }
6579
80 /** The Secret that holds a checkout step's `secret` env; null when there is none. */
81 export function secretManifest(spec: JobSpec): object | null {
82 const secret = spec.checkout?.secret;
83 if (secret === undefined || Object.keys(secret).length === 0) return null;
84 for (const [k, v] of Object.entries(secret))
85 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k) || typeof v !== "string") throw new Error(`bad secret ${k}`);
86 return { apiVersion: "v1", kind: "Secret", metadata: { name: spec.name }, type: "Opaque", stringData: secret };
87 }
88
6689 /** The Job manifest for a spec, or the reason it is refused. */
6790 export function manifest(spec: JobSpec): object {
6891 if (!NAME.test(spec.name ?? "")) throw new Error("job name must be a DNS label of at most 53 characters");
6992 if (typeof spec.image !== "string" || !spec.image || /\s/.test(spec.image)) throw new Error("image is required");
7093 if (!Array.isArray(spec.command) || !spec.command.length || spec.command.some((c) => typeof c !== "string"))
7194 throw new Error("command must be a non-empty list of strings");
72 const env = Object.entries(spec.env ?? {}).map(([name, value]) => {
73 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string") throw new Error(`bad env ${name}`);
74 return { name, value };
75 });
95 const envList = (o: Record<string, string>) =>
96 Object.entries(o).map(([name, value]) => {
97 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string") throw new Error(`bad env ${name}`);
98 return { name, value };
99 });
100 const env = envList({ HOME: "/tmp", ...spec.env });
101 // The pod is repository code's, so it is given the least: no service
102 // account token, no root, no new privileges, no writable root filesystem;
103 // only /work and /tmp are written to.
104 const hardened = {
105 allowPrivilegeEscalation: false,
106 readOnlyRootFilesystem: true,
107 runAsNonRoot: true,
108 capabilities: { drop: ["ALL"] },
109 };
110 const mounts = [
111 { name: "work", mountPath: "/work" },
112 { name: "tmp", mountPath: "/tmp" },
113 ];
114 const checkout = spec.checkout;
76115 return {
77116 apiVersion: "batch/v1",
78117 kind: "Job",
@@ -84,9 +123,38 @@ export function manifest(spec: JobSpec): object {
84123 metadata: { labels: { "job-name": spec.name } },
85124 spec: {
86125 restartPolicy: "Never",
126 automountServiceAccountToken: false,
127 securityContext: { runAsNonRoot: true, runAsUser: 10001, runAsGroup: 10001, seccompProfile: { type: "RuntimeDefault" } },
128 volumes: [
129 { name: "work", emptyDir: {} },
130 { name: "tmp", emptyDir: {} },
131 ],
132 ...(checkout === undefined
133 ? {}
134 : {
135 initContainers: [
136 {
137 name: "checkout",
138 image: spec.image,
139 command: checkout.command,
140 workingDir: "/work",
141 env: [
142 ...envList({ HOME: "/tmp", ...checkout.env }),
143 ...Object.keys(checkout.secret ?? {}).map((name) => ({
144 name,
145 valueFrom: { secretKeyRef: { name: spec.name, key: name } },
146 })),
147 ],
148 securityContext: hardened,
149 volumeMounts: mounts,
150 },
151 ],
152 }),
87153 nodeSelector: spec.nodeSelector ?? {},
88154 tolerations: spec.tolerations ?? [],
89 containers: [{ name: "job", image: spec.image, command: spec.command, env }],
155 containers: [
156 { name: "job", image: spec.image, command: spec.command, env, workingDir: "/work", securityContext: hardened, volumeMounts: mounts },
157 ],
90158 },
91159 },
92160 },
@@ -97,12 +165,14 @@ export function manifest(spec: JobSpec): object {
97165 type Job = { status?: { succeeded?: number; failed?: number } };
98166 type Pod = {
99167 metadata?: { name?: string };
168 spec?: { nodeName?: string };
100169 status?: { containerStatuses?: { state?: { terminated?: { exitCode?: number } } }[] };
101170 };
102171 type PodList = { items?: Pod[] };
103172
104173 export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobResult> {
105174 const body = JSON.stringify(manifest(spec));
175 const secretBody = secretManifest(spec);
106176 const cred = opts.credentials ?? serviceAccount();
107177 const doFetch = opts.fetch ?? ((u, i) => fetch(u, i as RequestInit));
108178 const now = opts.now ?? Date.now;
@@ -132,7 +202,17 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
132202
133203 const jobPath = `/apis/batch/v1/namespaces/${ns}/jobs/${name}`;
134204 let created = false;
205 let secretMade = false;
135206 try {
207 if (secretBody !== null) {
208 // Made first, so the init container finds it; deleted below in every case.
209 secretMade = true;
210 const s = await call("POST", `/api/v1/namespaces/${ns}/secrets`, JSON.stringify(secretBody));
211 if (!s.ok) {
212 secretMade = s.status >= 500;
213 throw new Error(`kube POST secret ${s.status}`);
214 }
215 }
136216 // Only a Job this call made is this call's to delete: a 4xx (409
137217 // AlreadyExists above all) means the API made nothing; anything else
138218 // (a 5xx, a dropped connection) may have, so it is deleted.
@@ -152,17 +232,28 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
152232 const deadline = now() + timeoutMs;
153233 let done: "succeeded" | "failed" | null = null;
154234 while (!done) {
235 if (opts.signal?.aborted) return { exitCode: null, lines: [], timedOut: false, cancelled: true };
155236 const job = await json<Job>("GET", jobPath);
156237 if ((job.status?.succeeded ?? 0) > 0) done = "succeeded";
157238 else if ((job.status?.failed ?? 0) > 0) done = "failed";
158 else if (now() >= deadline) return { exitCode: null, lines: await logLines(), timedOut: true };
239 else if (now() >= deadline) {
240 const pod = await findPod().catch(() => undefined);
241 return { exitCode: null, lines: await logLines(pod?.metadata?.name), timedOut: true, node: nodeOf(pod) };
242 }
159243 else await sleep(pollMs);
160244 }
161245 const pod = await findPod();
162246 const code: unknown = pod?.status?.containerStatuses?.[0]?.state?.terminated?.exitCode;
163247 const exitCode = typeof code === "number" ? code : done === "succeeded" ? 0 : null;
164 return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false };
248 return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false, node: nodeOf(pod) };
165249 } finally {
250 if (secretMade) {
251 try {
252 await call("DELETE", `/api/v1/namespaces/${ns}/secrets/${name}`);
253 } catch {
254 // the token in it expires on its own
255 }
256 }
166257 if (created) {
167258 try {
168259 await call("DELETE", `${jobPath}?propagationPolicy=Background`);
@@ -191,6 +282,9 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
191282 }
192283 }
193284
285 const nodeOf = (pod?: Pod): string | undefined =>
286 typeof pod?.spec?.nodeName === "string" ? pod.spec.nodeName : undefined;
287
194288 /** Read a body chunk by chunk, stopping at `max` bytes; the rest is never held. */
195289 async function readCapped(body: ReadableStream<Uint8Array>, max: number): Promise<string> {
196290 const reader = body.getReader();
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 here, in a cell; job runs it as a Kubernetes Job (image, node selector and tolerations from FORGE_CHECKS_IMAGE, FORGE_CHECKS_NODE_SELECTOR, FORGE_CHECKS_TOLERATIONS). Takes effect on the next check.",
69 },
6270 "children.max": {
6371 label: "Forges this one may send",
6472 env: "FORGE_CHILDREN_MAX",
src/core/runs.ts +21 −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`; empty until it is recorded. */
80 readonly placement: string;
81 /** For a check run as a job: the cluster node it ran on; empty otherwise. */
82 readonly node: string;
7983 /** A failed check's own detail, when its output was recognised; null otherwise. */
8084 readonly checkDetail: CheckDetail | null;
8185 /** The variant group this run belongs to; null for an ordinary run. */
@@ -107,6 +111,8 @@ interface RunRow {
107111 turns: number;
108112 sandbox_enforced: number | null;
109113 sandbox_note: string;
114 placement: string;
115 node: string;
110116 check_detail: string;
111117 variant_group: string | null;
112118 created_at: string;
@@ -136,6 +142,8 @@ const toRun = (r: RunRow): Run => ({
136142 sandboxEnforced:
137143 r.sandbox_enforced === null ? null : r.sandbox_enforced !== 0,
138144 sandboxNote: r.sandbox_note,
145 placement: r.placement,
146 node: r.node,
139147 checkDetail: r.check_detail ? (JSON.parse(r.check_detail) as CheckDetail) : null,
140148 variantGroup: r.variant_group,
141149 createdAt: r.created_at,
@@ -342,13 +350,17 @@ export function noteRunProgress(
342350 subscriptionId?: string | undefined;
343351 /** Whether the shell is held to the sandbox, and why not when it is not. */
344352 sandbox?: { enforced: boolean; note: string } | undefined;
353 /** Where a check ran, and on which node when it was a job. */
354 placement?: { placement: "process" | "job"; node: string } | undefined;
345355 },
346356 ): void {
347357 db.query(
348358 `UPDATE run SET session_id = COALESCE(?2, session_id), cost_usd = COALESCE(?3, cost_usd),
349359 branch = COALESCE(?4, branch), subscription_id = COALESCE(?5, subscription_id),
350360 sandbox_enforced = COALESCE(?6, sandbox_enforced),
351 sandbox_note = COALESCE(?7, sandbox_note)
361 sandbox_note = COALESCE(?7, sandbox_note),
362 placement = COALESCE(?8, placement),
363 node = COALESCE(?9, node)
352364 WHERE id = ?1`,
353365 ).run(
354366 runId,
@@ -358,6 +370,8 @@ export function noteRunProgress(
358370 progress.subscriptionId ?? null,
359371 progress.sandbox === undefined ? null : progress.sandbox.enforced ? 1 : 0,
360372 progress.sandbox?.note.slice(0, 300) ?? null,
373 progress.placement?.placement ?? null,
374 progress.placement?.node.slice(0, 253) ?? null,
361375 );
362376 }
363377
@@ -1069,3 +1083,9 @@ export function listRunning(
10691083 issue: r.issue_number,
10701084 }));
10711085 }
1086
1087 /** Where a check ran when it was a cluster Job (#1692), as a phrase; empty for a local run. */
1088 export function placedOn(run: { placement: string; node: string }): string {
1089 if (run.placement !== "job") return "";
1090 return run.node === "" ? "cluster job" : `cluster job on ${run.node}`;
1091 }
src/core/schema.ts +6
@@ -1741,6 +1741,12 @@ export const migrations: readonly string[] = [
17411741 ALTER TABLE repo ADD COLUMN decisions_by TEXT NOT NULL DEFAULT 'me'
17421742 CHECK (decisions_by IN ('me', 'decider', 'decider_tell'));
17431743 `,
1744 // 86 — where a check ran (#1692): `placement` is process or job, `node`
1745 // the cluster node a job ran on; both empty until a check records them.
1746 `
1747 ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT '';
1748 ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT '';
1749 `,
17441750 ];
17451751
17461752 /**
src/http/mcp.ts +1 −1
@@ -1929,7 +1929,7 @@ const TOOLS: readonly Tool[] = [
19291929 properties: {
19301930 key: {
19311931 type: "string",
1932 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
1932 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "checks.placement", "cells.egress", "guard_new_accounts"],
19331933 },
19341934 value: { type: "string", maxLength: 16 },
19351935 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
src/tui/screens/runlist.ts +4 −2
@@ -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 { placedOn, 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";
@@ -104,7 +104,9 @@ export function runRows(
104104 title: `${run.state.padEnd(9)} ${runTitle(run, names, set)}${about === undefined ? "" : ` · #${about.number} ${about.title}`}`,
105105 ...(tone === undefined ? {} : { tone }),
106106 ...(runHollow(run.state) ? { hollow: true } : {}),
107 secondary: run.summary === "" ? run.reason : run.summary,
107 secondary: [run.summary === "" ? run.reason : run.summary, placedOn(run)]
108 .filter((t) => t !== "")
109 .join(" · "),
108110 meta: metaOf(
109111 run.commitOid === "" ? "" : run.commitOid.slice(0, 7),
110112 costText(run.costUsd),
src/web/studio/run.ts +2 −1
@@ -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";
@@ -161,6 +161,7 @@ export async function runView(
161161 </div>
162162 <p class="run-summary" id="run-summary">${run.summary}</p>
163163 ${sandboxLine(run)}
164 ${placementLine(run)}

Low: the page shows placement and node, but the tty run view and MCP do not. Both doors should show it.

164165 ${when(
165166 held.length > 0,
166167 () =>
src/web/studio/sandbox.ts +8
@@ -26,3 +26,11 @@ export function sandboxLine(run: Run): Html | null {
2626 : html` (${run.sandboxNote})`}.
2727 </p>`;
2828 }
29
30 /** Where a check ran when it was a cluster Job (#1692); nothing for a local one. */
31 export function placementLine(run: Run): Html | null {
32 if (run.placement !== "job") return null;
33 return html`<p class="muted small" id="run-placement">
34 Ran as a cluster job${run.node === "" ? "" : html` on node <code>${run.node}</code>`}.
35 </p>`;
36 }
test/check-placement.test.ts added +194
@@ -0,0 +1,194 @@
1 /**
2 * A check runs as a cluster Job when `checks.placement` is job (#1692): it
3 * reaches a verdict through a stand-in kube client, its log and node come
4 * back, and the default, process, is unchanged.
5 */
6
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { jobName, jobPlacement, runCheckJob } from "../src/checks/placement.ts";
14 import { startChecks, type ChecksHandle } from "../src/checks/service.ts";
15 import { capacityValue, setCapacity } from "../src/core/capacity.ts";
16 import { listRuns, placedOn } from "../src/core/runs.ts";
17 import { createUser } from "../src/core/users.ts";
18
19 process.env["FORGE_CELLS"] = "off";
20
21 const credentials = { server: "https://k", token: "t", namespace: "forge" };
22 const placement = { image: "img:1", nodeSelector: { pool: "ci" }, tolerations: [{ key: "ci", operator: "Exists" as const }] };
23 const clock = () => { let t = 0; return { now: () => t, sleep: async (ms: number) => { t += ms; } }; };
24
25 /** A stand-in kube API whose one pod ran on node `n1` and exited `exit`. */
26 function kube(exit: number, log: string) {
27 const bodies: any[] = [];
28 const calls: string[] = [];
29 const fetch = async (url: string, init: any) => {
30 const path = new URL(url).pathname;
31 calls.push(`${init.method} ${path}`);
32 if (init.method === "POST") { bodies.push(JSON.parse(init.body)); return Response.json({}); }
33 if (init.method === "DELETE") return Response.json({});
34 if (path.endsWith("/log")) return new Response(log);
35 if (path.endsWith("/pods"))
36 return Response.json({ items: [{ metadata: { name: "p1" }, spec: { nodeName: "n1" }, status: { containerStatuses: [{ state: { terminated: { exitCode: exit } } }] } }] });
37 return Response.json({ status: exit === 0 ? { succeeded: 1 } : { failed: 1 } });
38 };
39 return { fetch, bodies, calls };
40 }
41 const jobs = (k: { bodies: any[] }) => k.bodies.filter((b) => b.kind === "Job");
42 const base = { runId: "01ABC", commitOid: "a".repeat(40), forgeUrl: "http://f", install: null, command: "bun test", timeoutMs: 5000, placement, repoUrl: "http://f/o/r.git", auth: "o:forge_tok" };
43
44 test("a passing job is a passing verdict with its log and node", async () => {
45 const k = kube(0, "ok\n");
46 const r = await runCheckJob(base, { fetch: k.fetch, credentials, ...clock() });
47 expect(r).toEqual({ ok: true, error: "", lines: ["ok"], node: "n1" });
48 const pod = jobs(k)[0].spec.template.spec;
49 expect(pod.nodeSelector).toEqual({ pool: "ci" });
50 expect(pod.tolerations).toEqual([{ key: "ci", operator: "Exists" }]);
51 expect(pod.containers[0].command).toEqual(["sh", "-c", "bun test"]);
52 expect(pod.containers[0].env.map((e: any) => e.name).sort()).toEqual(["CI", "FORGE_CHECK", "FORGE_COMMIT", "FORGE_URL", "HOME"]);
53 });
54
55 test("the job fetches this commit with the credential in the checkout step only", async () => {
56 const k = kube(0, "");
57 await runCheckJob(base, { fetch: k.fetch, credentials, ...clock() });
58 const pod = jobs(k)[0].spec.template.spec;
59 const init = pod.initContainers[0];
60 expect(init.command[2]).toContain('test "$(git rev-parse HEAD)" = "$FORGE_COMMIT"');
61 const env = Object.fromEntries(init.env.map((e: any) => [e.name, e.value]));
62 expect(env.FORGE_COMMIT).toBe("a".repeat(40));
63 expect(env.FORGE_REPO_URL).toBe("http://f/o/r.git");
64 expect(JSON.stringify(pod)).not.toContain("forge_tok");
65 expect(init.env.find((e: any) => e.name === "FORGE_AUTH").valueFrom.secretKeyRef.key).toBe("FORGE_AUTH");
66 const secret = k.bodies.find((b) => b.kind === "Secret");
67 expect(Buffer.from(secret.stringData.FORGE_AUTH, "base64").toString()).toBe("o:forge_tok");
68 expect(k.calls).toContain("DELETE /api/v1/namespaces/forge/secrets/" + jobName("01ABC"));
69 });
70
71 test("a cancelled run is a failing verdict", async () => {
72 const k = kube(0, "");
73 const ac = new AbortController();
74 ac.abort();
75 const r = await runCheckJob(base, { fetch: k.fetch, credentials, ...clock(), signal: ac.signal });
76 expect(r).toMatchObject({ ok: false, error: "the check job was cancelled" });
77 });
78
79 test("a failing job is a failing verdict naming the exit code; install runs first", async () => {
80 const k = kube(3, "boom\n");
81 const r = await runCheckJob({ ...base, install: "bun install" }, { fetch: k.fetch, credentials, ...clock() });
82 expect(r).toMatchObject({ ok: false, error: "the check job exited 3", lines: ["boom"], node: "n1" });
83 expect(jobs(k)[0].spec.template.spec.containers[0].command[2]).toBe("bun install && bun test");
84 });
85
86 test("a cluster that cannot be reached is a failing verdict, not a throw", async () => {
87 const r = await runCheckJob(base, { credentials: undefined as never, fetch: async () => { throw new Error("down"); } });
88 expect(r.ok).toBe(false);
89 expect(r.error).toContain("could not run");
90 });
91
92 test("job settings are validated; names are DNS labels", () => {
93 expect(jobPlacement({}).ok).toBe(false);
94 expect(jobPlacement({ FORGE_CHECKS_IMAGE: "img", FORGE_CHECKS_NODE_SELECTOR: "[1]" }).ok).toBe(false);
95 expect(jobPlacement({ FORGE_CHECKS_IMAGE: "img", FORGE_CHECKS_TOLERATIONS: '[{"effect":"Bogus"}]' }).ok).toBe(false);
96 const ok = jobPlacement({
97 FORGE_CHECKS_IMAGE: "img",
98 FORGE_CHECKS_NODE_SELECTOR: '{"pool":"ci"}',
99 FORGE_CHECKS_TOLERATIONS: '[{"key":"ci","operator":"Exists","evil":1}]',
100 });
101 expect(ok).toEqual({ ok: true, value: { image: "img", nodeSelector: { pool: "ci" }, tolerations: [{ key: "ci", operator: "Exists" }] } });
102 expect(jobName("01ARZ_3NDEK/TSV")).toBe("check-01arz-3ndek-tsv");
103 expect(jobName("X".repeat(80)).length).toBeLessThanOrEqual(53);
104 });
105
106 let dataDir: string;
107 let app: App;
108 let checks: ChecksHandle;
109 let standIn: (url: string, init: any) => Promise<Response> = async () => { throw new Error("no cluster"); };
110
111 beforeAll(async () => {
112 dataDir = await mkdtemp(join(tmpdir(), "forge-placement-"));
113 app = createApp({ dataDir, port: 0 });
114 checks = startChecks(app, {
115 forgeUrl: "http://forge.test",
116 concurrency: 1,
117 job: { credentials, pollMs: 1, fetch: (u, i) => standIn(u, i) },
118 });
119 });
120 afterAll(async () => {
121 await checks.stop();
122 app.close();
123 await rm(dataDir, { recursive: true, force: true });
124 });
125
126 async function runCheckOf(name: string) {
127 const u = await createUser(app.db, { trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: true });
128 if (!u.ok) throw new Error(u.error);
129 const made = await createRepo(app, u.value, { name, visibility: "public" });
130 if (!made.ok) throw new Error(String(made.error));
131 const pushed = await commitToBranch(app, u.value, made.value, {
132 message: "check",
133 files: [{ path: "forge.json", content: `{"check": {"run": "echo hi", "install": ""}}\n` }],
134 });
135 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
136 const deadline = Date.now() + 30_000;
137 for (;;) {
138 const run = listRuns(app.db, made.value.id, { kind: "check", limit: 10 }).find((r) => r.commitOid === pushed.value.commitOid && (r.state === "ok" || r.state === "failed"));
139 if (run || Date.now() > deadline) return run;
140 await Bun.sleep(100);
141 }
142 }
143
144 test("placement defaults to process, and a process check records it", async () => {
145 expect(capacityValue(app.db, "checks.placement")).toBe("process");
146 const run = await runCheckOf("alice");
147 expect(run?.state).toBe("ok");
148 expect(run?.placement).toBe("process");
149 expect(run?.node).toBe("");
150 }, 40_000);
151
152 test("with placement job the check goes to the cluster and the run records it", async () => {
153 setCapacity(app.db, "checks.placement", "job", "alice");
154 setCapacity(app.db, "cells.egress", "report", "alice");
155 const run = await runCheckOf("bob");
156 // No image is set here: the verdict is a failure that says so, and never a local run.
157 expect(run?.state).toBe("failed");
158 expect(run?.placement).toBe("job");
159 expect(run?.summary).toContain("FORGE_CHECKS_IMAGE");
160 }, 40_000);
161
162 test("a successful job runs end to end: node written back, token made for the fetch and gone after", async () => {
163 process.env["FORGE_CHECKS_IMAGE"] = "img:1";
164 const k = kube(0, "all green\n");
165 standIn = k.fetch;
166 const run = await runCheckOf("carol");
167 delete process.env["FORGE_CHECKS_IMAGE"];
168 expect(run?.state).toBe("ok");
169 expect(run?.placement).toBe("job");
170 expect(run?.node).toBe("n1");
171 const init = jobs(k)[0].spec.template.spec.initContainers[0];
172 const env = Object.fromEntries(init.env.map((e: any) => [e.name, e.value]));
173 expect(env.FORGE_REPO_URL).toBe("http://forge.test/carol/carol.git");
174 expect(env.FORGE_COMMIT).toBe(run!.commitOid);
175 expect(app.db.query("SELECT count(*) AS n FROM token WHERE name LIKE 'check:%'").get()).toEqual({ n: 0 });
176 }, 40_000);
177
178 test("with cells.egress enforce a job check is refused and nothing reaches the cluster", async () => {
179 setCapacity(app.db, "cells.egress", "enforce", "alice");
180 process.env["FORGE_CHECKS_IMAGE"] = "img:1";
181 const k = kube(0, "");
182 standIn = k.fetch;
183 const run = await runCheckOf("dave");
184 delete process.env["FORGE_CHECKS_IMAGE"];
185 expect(run?.state).toBe("failed");
186 expect(run?.summary).toContain("cells.egress");
187 expect(k.calls).toEqual([]);
188 }, 40_000);
189
190 test("a run names where it ran for the terminal and the event payload", () => {
191 expect(placedOn({ placement: "job", node: "n1" })).toBe("cluster job on n1");
192 expect(placedOn({ placement: "job", node: "" })).toBe("cluster job");
193 expect(placedOn({ placement: "process", node: "" })).toBe("");
194 });
test/cluster-jobs.test.ts +21 −1
@@ -32,7 +32,7 @@ test("a Job succeeds: exit code and log lines come back, the Job is deleted", as
3232 expect(k.calls.every((c) => c.auth === "Bearer tok")).toBe(true);
3333 const sent = JSON.parse(k.calls[0]!.body!);
3434 expect(sent.spec.template.spec.nodeSelector).toEqual({ pool: "ci" });
35 expect(sent.spec.template.spec.containers[0].env).toEqual([{ name: "A", value: "b" }]);
35 expect(sent.spec.template.spec.containers[0].env).toEqual([{ name: "HOME", value: "/tmp" }, { name: "A", value: "b" }]);
3636 });
3737
3838 test("a Job fails: the container's exit code is reported, the Job is deleted", async () => {
@@ -86,3 +86,23 @@ test("a log larger than the cap comes back truncated, by bytes, and is asked for
8686 expect(r.lines).toEqual(["ééééé"]);
8787 expect(k.calls.some((c) => c.url.endsWith("/log?limitBytes=10"))).toBe(true);
8888 });
89
90 test("the pod is held down: no service-account token, non-root, no escalation, read-only root", () => {
91 const pod = (manifest({ ...spec, checkout: { command: ["true"], env: { T: "secret" } } }) as any).spec.template.spec;
92 expect(pod.automountServiceAccountToken).toBe(false);
93 expect(pod.securityContext).toMatchObject({ runAsNonRoot: true, seccompProfile: { type: "RuntimeDefault" } });
94 for (const c of [...pod.containers, ...pod.initContainers])
95 expect(c.securityContext).toEqual({ allowPrivilegeEscalation: false, readOnlyRootFilesystem: true, runAsNonRoot: true, capabilities: { drop: ["ALL"] } });
96 // the credential is the checkout step's alone
97 expect(JSON.stringify(pod.containers)).not.toContain("secret");
98 expect(pod.initContainers[0].env.some((e: any) => e.name === "T")).toBe(true);
99 });
100
101 test("an abort ends the wait and deletes the Job", async () => {
102 const k = kube([{}]);
103 const ac = new AbortController();
104 const sleep = async () => { ac.abort(); };
105 const r = await runJob(spec, { fetch: k.fetch, credentials, now: () => 0, sleep, signal: ac.signal, timeoutMs: 1e9 });
106 expect(r).toMatchObject({ cancelled: true, exitCode: null });
107 expect(deleted(k.calls)).toBe(1);
108 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs