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

Closed opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +522 −11
README.md +22
@@ -776,3 +776,25 @@ In the forge itself: a pull's check runs `fast` when the manifest has one, in a
776776 ## Limits
777777
778778 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.
779
780 ### Where a check runs
781
782 `checks.placement` (Settings → Capacity, or `FORGE_CHECKS_PLACEMENT`) is
783 `process` by default: the check runs here, in a cell. Set to `job`, the
784 check's command (after `install`) runs as a Kubernetes Job through
785 `src/cluster/jobs.ts`, in the image `FORGE_CHECKS_IMAGE`, on nodes chosen by
786 `FORGE_CHECKS_NODE_SELECTOR` (JSON object) and `FORGE_CHECKS_TOLERATIONS`
787 (JSON list). The Job's log is written into the run's log when it ends, and the
788 run records `placement` and `node`, and the run page shows them. The image
789 must have `git` and `sh`. An init step fetches exactly the pull's head commit
790 from the forge (`FORGE_URL`, so the pod must reach it) with a read-only token
791 of the repository's owner that expires with the check and is deleted when it
792 ends; the token is in the init container only, and the check fails unless HEAD
793 is that commit. The pod has no service-account token, runs non-root with no
794 privilege escalation and a read-only root (only `/work` and `/tmp` are
795 writable). An abort (cancel, new push, budget) deletes the Job.
796
797 Not done: egress restriction (a cluster NetworkPolicy on the Job's pods is the
798 operator's to add), the fast tier checks the head, not the head merged into the
799 base, the `ro` token is per-account and not per-repository, the log is not live
800 while it runs, and the node is not in MCP or the tty.
scripts/gate.ts +1
@@ -40,6 +40,7 @@ export const GATE: readonly string[] = [
4040 "test/chaos.test.ts",
4141 "test/flow-stage.test.ts",
4242 "test/cluster-jobs.test.ts",
43 "test/check-placement.test.ts",
4344 "test/fuzz-found.test.ts",
4445 "test/fuzz-parsers.test.ts",
4546 "test/attach-look.test.ts",
src/checks/placement.ts added +153
@@ -0,0 +1,153 @@
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.
outdated

High: the Job gets no checkout, so the verdict covers the image's code and not commitOid. A green result here lands a pull whose code never ran. The Job needs the tree for this commit, for example an initContainer that fetches with a short-lived read-only token. Until then, job placement must fail the check rather than pass it.

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: {
outdated

High: this runs the image's code, not commitOid, yet the result is reported as this commit's verdict. Fetch the commit into the pod (init container plus an emptyDir working directory) before install && command, or refuse job placement until that exists.

107 runId: string;
outdated

High: this spec becomes a pod running untrusted pull code with the default ServiceAccount token mounted, no securityContext and no egress limit. Add automountServiceAccountToken: false, run as non-root, set no privilege escalation and drop all capabilities, and add a label selected by a deny-egress NetworkPolicy. Test that each of these is in the manifest.

108 commitOid: string;
109 forgeUrl: string;
110 install: string | null;
outdated

High: install comes from the pull's branch and runs here with no cell. Nothing turns off the service-account token mount (automountServiceAccountToken: false is missing), there is no securityContext (runAsNonRoot, allowPrivilegeEscalation false, readOnlyRootFilesystem) and there is no egress restriction. In process mode the cell enforces all of these; the Job needs them in cluster/jobs.ts manifest(), with a test that asserts them.

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: {
132 FORGE_REPO_URL: x.repoUrl,
133 FORGE_COMMIT: x.commitOid,
134 FORGE_AUTH: Buffer.from(x.auth).toString("base64"),
135 },
136 },
137 };
138 try {
139 const r = await runJob(spec, { timeoutMs: x.timeoutMs, ...opts });
140 const node = r.node ?? "";
141 if (r.cancelled) return { ok: false, error: "the check job was cancelled", lines: r.lines, node };
142 if (r.timedOut) return { ok: false, error: `the check job ran past ${Math.round(x.timeoutMs / 1000)}s`, lines: r.lines, node };
143 if (r.exitCode === 0) return { ok: true, error: "", lines: r.lines, node };
144 return {
145 ok: false,
146 error: r.exitCode === null ? "the check job ended without an exit code" : `the check job exited ${r.exitCode}`,
147 lines: r.lines,
148 node,
149 };
150 } catch (e) {
151 return { ok: false, error: `the check job could not run: ${e instanceof Error ? e.message : String(e)}`, lines: [], node: "" };
152 }
153 }
src/checks/service.ts +49
@@ -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,49 @@ 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") {
562 if (x.runId !== undefined)
563 noteRunProgress(app.db, x.runId, {
564 placement: { placement: "job", node: "" },
565 });
outdated

Medium: nothing reaches the run's log until the Job ends, but the issue asks for the log to stream. Pass a line callback through runJob, or poll the pod log while it runs, so write gets lines as they arrive.

outdated

High: the abort signal never reaches runCheckJob/runJob. A cancelled run, a new push to the pull, or the budget abort leaves the Job polling and the pod running until the timeout. Pass the signal through, delete the Job on abort, and add a test that shows the Job is deleted after an abort.

566 const placed = jobPlacement();
567 if (!placed.ok) return { ok: false, error: placed.error };
568 write(`placement: job (${placed.value.image})`);
569 // The Job fetches the commit with a read-only token of the repository's
570 // owner that expires with the check and is deleted when it ends.
571 const token = createToken(app.db, repo.ownerId, `check:${run.id}`, "ro", {
572 expiresAt: new Date(Date.now() + manifest.timeout * 1000 + 10 * 60_000).toISOString(),
573 });
574 const job = await runCheckJob(
575 {
576 runId: run.id,
577 commitOid: x.commitOid,
578 forgeUrl: options.forgeUrl,
579 repoUrl: `${options.forgeUrl.replace(/\/+$/, "")}/${repo.ownerName}/${repo.name}.git`,
580 auth: `${repo.ownerName}:${token.token}`,
581 install: manifest.install,
582 command,
583 timeoutMs: manifest.timeout * 1000,
584 placement: placed.value,
585 },
586 { ...options.job, signal },
587 ).finally(() => revokeToken(app.db, token.id));
588 if (x.runId !== undefined && job.node !== "")
589 noteRunProgress(app.db, x.runId, {
590 placement: { placement: "job", node: job.node },
591 });
592 if (job.node !== "") write(`node: ${job.node}`);
593 for (const line of job.lines) write(line);
594 if (job.ok) return { ok: true };
595 const { summary, detail } = summariseCheckFailure(job.lines, job.error);
596 return { ok: false, error: summary, detail };
597 }
598 if (x.runId !== undefined)
599 noteRunProgress(app.db, x.runId, {
600 placement: { placement: "process", node: "" },
601 });
553602 // The fast tier diffs what the pull changes against the base's tip,
554603 // which the clone is given as a repository of its own: `origin/main` is
555604 // not a ref there.
src/cluster/jobs.ts +66 −7
@@ -26,6 +26,12 @@ 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.
33 */
34 checkout?: { command: string[]; env: Record<string, string> };
2935 };
3036
3137 export type JobResult = {
@@ -33,6 +39,10 @@ export type JobResult = {
3339 exitCode: number | null;
3440 lines: string[];
3541 timedOut: boolean;
42 /** True when `signal` aborted before the Job ended. */
43 cancelled?: boolean;
44 /** The node the pod was scheduled on, when it got one. */
45 node?: string | undefined;
3646 };
3747
3848 export type Credentials = { server: string; token: string; ca?: string; namespace: string };
@@ -47,6 +57,8 @@ export type JobOptions = {
4757 sleep?: (ms: number) => Promise<void>;
4858 /** The most log bytes read; the rest of the log is left unread. */
4959 maxLogBytes?: number;
60 /** When it aborts the Job is deleted and the result is `cancelled`. */
61 signal?: AbortSignal;
5062 };
5163
5264 /** The service account the pod runs as; throws when there is none. */
@@ -69,10 +81,26 @@ export function manifest(spec: JobSpec): object {
6981 if (typeof spec.image !== "string" || !spec.image || /\s/.test(spec.image)) throw new Error("image is required");
7082 if (!Array.isArray(spec.command) || !spec.command.length || spec.command.some((c) => typeof c !== "string"))
7183 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 });
84 const envList = (o: Record<string, string>) =>
85 Object.entries(o).map(([name, value]) => {
86 if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || typeof value !== "string") throw new Error(`bad env ${name}`);
87 return { name, value };
88 });
89 const env = envList({ HOME: "/tmp", ...spec.env });
90 // The pod is repository code's, so it is given the least: no service
91 // account token, no root, no new privileges, no writable root filesystem;
92 // only /work and /tmp are written to.
93 const hardened = {
94 allowPrivilegeEscalation: false,
95 readOnlyRootFilesystem: true,
96 runAsNonRoot: true,
97 capabilities: { drop: ["ALL"] },
98 };
99 const mounts = [
100 { name: "work", mountPath: "/work" },
101 { name: "tmp", mountPath: "/tmp" },
102 ];
103 const checkout = spec.checkout;
76104 return {
77105 apiVersion: "batch/v1",
78106 kind: "Job",
@@ -84,9 +112,32 @@ export function manifest(spec: JobSpec): object {
84112 metadata: { labels: { "job-name": spec.name } },
85113 spec: {
86114 restartPolicy: "Never",
115 automountServiceAccountToken: false,
116 securityContext: { runAsNonRoot: true, runAsUser: 10001, runAsGroup: 10001, seccompProfile: { type: "RuntimeDefault" } },
117 volumes: [
118 { name: "work", emptyDir: {} },
119 { name: "tmp", emptyDir: {} },
120 ],
121 ...(checkout === undefined
122 ? {}
123 : {
124 initContainers: [
125 {
126 name: "checkout",
127 image: spec.image,
128 command: checkout.command,
129 workingDir: "/work",
130 env: envList({ HOME: "/tmp", ...checkout.env }),
131 securityContext: hardened,
132 volumeMounts: mounts,
133 },
134 ],
135 }),
87136 nodeSelector: spec.nodeSelector ?? {},
88137 tolerations: spec.tolerations ?? [],
89 containers: [{ name: "job", image: spec.image, command: spec.command, env }],
138 containers: [
139 { name: "job", image: spec.image, command: spec.command, env, workingDir: "/work", securityContext: hardened, volumeMounts: mounts },
140 ],
90141 },
91142 },
92143 },
@@ -97,6 +148,7 @@ export function manifest(spec: JobSpec): object {
97148 type Job = { status?: { succeeded?: number; failed?: number } };
98149 type Pod = {
99150 metadata?: { name?: string };
151 spec?: { nodeName?: string };
100152 status?: { containerStatuses?: { state?: { terminated?: { exitCode?: number } } }[] };
101153 };
102154 type PodList = { items?: Pod[] };
@@ -152,16 +204,20 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
152204 const deadline = now() + timeoutMs;
153205 let done: "succeeded" | "failed" | null = null;
154206 while (!done) {
207 if (opts.signal?.aborted) return { exitCode: null, lines: [], timedOut: false, cancelled: true };
155208 const job = await json<Job>("GET", jobPath);
156209 if ((job.status?.succeeded ?? 0) > 0) done = "succeeded";
157210 else if ((job.status?.failed ?? 0) > 0) done = "failed";
158 else if (now() >= deadline) return { exitCode: null, lines: await logLines(), timedOut: true };
211 else if (now() >= deadline) {
212 const pod = await findPod().catch(() => undefined);
213 return { exitCode: null, lines: await logLines(pod?.metadata?.name), timedOut: true, node: nodeOf(pod) };
214 }
159215 else await sleep(pollMs);
160216 }
161217 const pod = await findPod();
162218 const code: unknown = pod?.status?.containerStatuses?.[0]?.state?.terminated?.exitCode;
163219 const exitCode = typeof code === "number" ? code : done === "succeeded" ? 0 : null;
164 return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false };
220 return { exitCode, lines: await logLines(pod?.metadata?.name), timedOut: false, node: nodeOf(pod) };
165221 } finally {
166222 if (created) {
167223 try {
@@ -191,6 +247,9 @@ export async function runJob(spec: JobSpec, opts: JobOptions = {}): Promise<JobR
191247 }
192248 }
193249
250 const nodeOf = (pod?: Pod): string | undefined =>
251 typeof pod?.spec?.nodeName === "string" ? pod.spec.nodeName : undefined;
252
194253 /** Read a body chunk by chunk, stopping at `max` bytes; the rest is never held. */
195254 async function readCapped(body: ReadableStream<Uint8Array>, max: number): Promise<string> {
196255 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 +15 −1
@@ -76,6 +76,10 @@ export interface Run {
7676 readonly sandboxEnforced: boolean | null;
7777 /** Why it was not, when it was not. */
7878 readonly sandboxNote: string;
79 /** For a check: `process` or `job`; 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
src/core/schema.ts +6
@@ -1688,6 +1688,12 @@ export const migrations: readonly string[] = [
16881688 CREATE TRIGGER thought_no_delete BEFORE DELETE ON thought
16891689 BEGIN SELECT RAISE(ABORT, 'a thought is never deleted'); END;
16901690 `,
1691 // 82 — where a check ran (#1692): `placement` is process or job, `node`
1692 // the cluster node a job ran on; both empty until a check records them.
1693 `
1694 ALTER TABLE run ADD COLUMN placement TEXT NOT NULL DEFAULT '';
1695 ALTER TABLE run ADD COLUMN node TEXT NOT NULL DEFAULT '';
1696 `,
16911697 ];
16921698
16931699 /**
src/http/mcp.ts +1 −1
@@ -1793,7 +1793,7 @@ const TOOLS: readonly Tool[] = [
17931793 properties: {
17941794 key: {
17951795 type: "string",
1796 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "cells.egress", "guard_new_accounts"],
1796 enum: ["crew.concurrency", "checks.concurrency", "checks.shards", "checks.placement", "cells.egress", "guard_new_accounts"],
17971797 },
17981798 value: { type: "string", maxLength: 16 },
17991799 dryRun: { type: "boolean", description: "Plan only (the default). Send false to change it." },
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)}
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 +170
@@ -0,0 +1,170 @@
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 } 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 fetch = async (url: string, init: any) => {
29 const path = new URL(url).pathname;
30 if (init.method === "POST") { bodies.push(JSON.parse(init.body)); return Response.json({}); }
31 if (init.method === "DELETE") return Response.json({});
32 if (path.endsWith("/log")) return new Response(log);
33 if (path.endsWith("/pods"))
34 return Response.json({ items: [{ metadata: { name: "p1" }, spec: { nodeName: "n1" }, status: { containerStatuses: [{ state: { terminated: { exitCode: exit } } }] } }] });
35 return Response.json({ status: exit === 0 ? { succeeded: 1 } : { failed: 1 } });
36 };
37 return { fetch, bodies };
38 }
39 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" };
40
41 test("a passing job is a passing verdict with its log and node", async () => {
42 const k = kube(0, "ok\n");
43 const r = await runCheckJob(base, { fetch: k.fetch, credentials, ...clock() });
44 expect(r).toEqual({ ok: true, error: "", lines: ["ok"], node: "n1" });
45 const pod = k.bodies[0].spec.template.spec;
46 expect(pod.nodeSelector).toEqual({ pool: "ci" });
47 expect(pod.tolerations).toEqual([{ key: "ci", operator: "Exists" }]);
48 expect(pod.containers[0].command).toEqual(["sh", "-c", "bun test"]);
49 expect(pod.containers[0].env.map((e: any) => e.name).sort()).toEqual(["CI", "FORGE_CHECK", "FORGE_COMMIT", "FORGE_URL", "HOME"]);
50 });
51
52 test("the job fetches this commit with the credential in the checkout step only", async () => {
53 const k = kube(0, "");
54 await runCheckJob(base, { fetch: k.fetch, credentials, ...clock() });
55 const pod = k.bodies[0].spec.template.spec;
56 const init = pod.initContainers[0];
57 expect(init.command[2]).toContain('test "$(git rev-parse HEAD)" = "$FORGE_COMMIT"');
58 const env = Object.fromEntries(init.env.map((e: any) => [e.name, e.value]));
59 expect(env.FORGE_COMMIT).toBe("a".repeat(40));
60 expect(env.FORGE_REPO_URL).toBe("http://f/o/r.git");
61 expect(Buffer.from(env.FORGE_AUTH, "base64").toString()).toBe("o:forge_tok");
62 expect(JSON.stringify(pod.containers)).not.toContain("forge_tok");
63 expect(JSON.stringify(pod.containers)).not.toContain(env.FORGE_AUTH);
64 });
65
66 test("a cancelled run is a failing verdict", async () => {
67 const k = kube(0, "");
68 const ac = new AbortController();
69 ac.abort();
70 const r = await runCheckJob(base, { fetch: k.fetch, credentials, ...clock(), signal: ac.signal });
71 expect(r).toMatchObject({ ok: false, error: "the check job was cancelled" });
72 });
73
74 test("a failing job is a failing verdict naming the exit code; install runs first", async () => {
75 const k = kube(3, "boom\n");
76 const r = await runCheckJob({ ...base, install: "bun install" }, { fetch: k.fetch, credentials, ...clock() });
77 expect(r).toMatchObject({ ok: false, error: "the check job exited 3", lines: ["boom"], node: "n1" });
78 expect(k.bodies[0].spec.template.spec.containers[0].command[2]).toBe("bun install && bun test");
79 });
80
81 test("a cluster that cannot be reached is a failing verdict, not a throw", async () => {
82 const r = await runCheckJob(base, { credentials: undefined as never, fetch: async () => { throw new Error("down"); } });
83 expect(r.ok).toBe(false);
84 expect(r.error).toContain("could not run");
85 });
86
87 test("job settings are validated; names are DNS labels", () => {
88 expect(jobPlacement({}).ok).toBe(false);
89 expect(jobPlacement({ FORGE_CHECKS_IMAGE: "img", FORGE_CHECKS_NODE_SELECTOR: "[1]" }).ok).toBe(false);
90 expect(jobPlacement({ FORGE_CHECKS_IMAGE: "img", FORGE_CHECKS_TOLERATIONS: '[{"effect":"Bogus"}]' }).ok).toBe(false);
91 const ok = jobPlacement({
92 FORGE_CHECKS_IMAGE: "img",
93 FORGE_CHECKS_NODE_SELECTOR: '{"pool":"ci"}',
94 FORGE_CHECKS_TOLERATIONS: '[{"key":"ci","operator":"Exists","evil":1}]',
95 });
96 expect(ok).toEqual({ ok: true, value: { image: "img", nodeSelector: { pool: "ci" }, tolerations: [{ key: "ci", operator: "Exists" }] } });
97 expect(jobName("01ARZ_3NDEK/TSV")).toBe("check-01arz-3ndek-tsv");
98 expect(jobName("X".repeat(80)).length).toBeLessThanOrEqual(53);
99 });
100
101 let dataDir: string;
102 let app: App;
103 let checks: ChecksHandle;
104 let standIn: (url: string, init: any) => Promise<Response> = async () => { throw new Error("no cluster"); };
105
106 beforeAll(async () => {
107 dataDir = await mkdtemp(join(tmpdir(), "forge-placement-"));
108 app = createApp({ dataDir, port: 0 });
109 checks = startChecks(app, {
110 forgeUrl: "http://forge.test",
111 concurrency: 1,
112 job: { credentials, pollMs: 1, fetch: (u, i) => standIn(u, i) },
113 });
114 });
115 afterAll(async () => {
116 await checks.stop();
117 app.close();
118 await rm(dataDir, { recursive: true, force: true });
119 });
120
121 async function runCheckOf(name: string) {
122 const u = await createUser(app.db, { trusted: true, username: name, email: `${name}@forge.local`, password: "a-good-passphrase", adminIfFirst: true });
123 if (!u.ok) throw new Error(u.error);
124 const made = await createRepo(app, u.value, { name, visibility: "public" });
125 if (!made.ok) throw new Error(String(made.error));
126 const pushed = await commitToBranch(app, u.value, made.value, {
127 message: "check",
128 files: [{ path: "forge.json", content: `{"check": {"run": "echo hi", "install": ""}}\n` }],
129 });
130 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
131 const deadline = Date.now() + 30_000;
132 for (;;) {
133 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"));
134 if (run || Date.now() > deadline) return run;
135 await Bun.sleep(100);
136 }
137 }
138
139 test("placement defaults to process, and a process check records it", async () => {
140 expect(capacityValue(app.db, "checks.placement")).toBe("process");
141 const run = await runCheckOf("alice");
142 expect(run?.state).toBe("ok");
143 expect(run?.placement).toBe("process");
144 expect(run?.node).toBe("");
145 }, 40_000);
146
147 test("with placement job the check goes to the cluster and the run records it", async () => {
148 setCapacity(app.db, "checks.placement", "job", "alice");
149 const run = await runCheckOf("bob");
150 // No image is set here: the verdict is a failure that says so, and never a local run.
151 expect(run?.state).toBe("failed");
152 expect(run?.placement).toBe("job");
153 expect(run?.summary).toContain("FORGE_CHECKS_IMAGE");
154 }, 40_000);
155
156 test("a successful job runs end to end: node written back, token made for the fetch and gone after", async () => {
157 process.env["FORGE_CHECKS_IMAGE"] = "img:1";
158 const k = kube(0, "all green\n");
159 standIn = k.fetch;
160 const run = await runCheckOf("carol");
161 delete process.env["FORGE_CHECKS_IMAGE"];
162 expect(run?.state).toBe("ok");
163 expect(run?.placement).toBe("job");
164 expect(run?.node).toBe("n1");
165 const init = k.bodies[0].spec.template.spec.initContainers[0];
166 const env = Object.fromEntries(init.env.map((e: any) => [e.name, e.value]));
167 expect(env.FORGE_REPO_URL).toBe("http://forge.test/carol/carol.git");
168 expect(env.FORGE_COMMIT).toBe(run!.commitOid);
169 expect(app.db.query("SELECT count(*) AS n FROM token WHERE name LIKE 'check:%'").get()).toEqual({ n: 0 });
170 }, 40_000);
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