From 0fb2700c4c74823451f4948c51be6cd6f633d16b Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Fri, 27 Nov 2026 18:43:29 -0800 Subject: [PATCH 1/3] feat(homelab): add idle RAM workspace agent pools gated on the route for this boot Why Woodpecker creates each workflow's workspace claim from its agent's storage settings, and the claim carries no workflow labels. The RAM workspace pool and its routing policy (earlier in this stack) can only serve a workflow that runs on an agent whose claims ask for ci-workspace-ram, so the RAM workspace needs agents of its own before the generator can route anything to it. After a reboot the ci-workspace-route ConfigMap still holds the previous boot's decision while the pool, its golden snapshot and every claim on it are gone. An agent that took work before the publisher ran again could send new claims to a snapshot that no longer exists, where they would sit Pending. What - Admission budget: two new compute pools, pr-ram (3) and main-ram (2), carved out of pr (12 -> 9) and main (10 -> 8). Total workflows (26), compute workflows (22), Kueue's pods quota and the admission proof are unchanged; the shared schema, CI_COMPUTE_WORKFLOWS and the budget check count the new pools. - Agents: Deployments for pr-ram and main-ram whose claims use ci-workspace-ram at the 12Gi RAM workspace size. Their mandatory !ci-pool label keeps them idle until the generator routes to them. - Boot gate: each RAM agent has a workspace-route-boot-gate init container (the shared kubectl script container, RuntimeDefault seccomp, no privilege escalation, emptyDir /tmp for kubectl's cache) that waits until the route ConfigMap's bootId is the node's own boot_id, logging which boot the route it read belongs to, and fails on an API error. The agent Role gains get on the ci-workspace-route ConfigMap by name; the agent NetworkPolicy already allows the Kubernetes API. The new agent containers also run under RuntimeDefault seccomp. - Docs: the CI admission explanation covers the RAM agent pools and the boot gate; the liskov runbook says how to read the gate's log. Verification - bunx turbo run build typecheck test lint --filter=@homelab/cdk8s --filter=homelab --filter=@shepherdjerred/root-scripts --filter=@shepherdjerred/docs-wiki --output-logs=errors-only --continue - bun run check-ci-admission-budget - bun run --cwd packages/homelab check:kubeconform - bunx turbo run jscpd quality-ratchet knip --filter=// - New tests: agent pools (RAM class, size, gate, seccomp; ordinary pools unchanged), the agent Role's named ConfigMap read, the boot gate script against a fake kubectl (immediate start, waiting through a missing and a stale route, failure on an API error), and the budget proof counting the RAM pools' slots. - Not run: verify:extended; no live deployment or rollout. The RAM agents connect idle once deployed; nothing routes to them until the next change. Co-Authored-By: Claude Opus 5.5 --- .../docs/explanation/homelab/ci-admission.md | 39 +++- .../cdk8s/src/misc/ci-admission-budget.json | 8 +- .../homelab/src/cdk8s/src/misc/woodpecker.ts | 11 +- .../src/resources/woodpecker/agent.test.ts | 173 ++++++++++++++---- .../cdk8s/src/resources/woodpecker/agent.ts | 78 +++++++- .../resources/woodpecker/ci-namespace.test.ts | 6 +- .../woodpecker/workspace-route.test.ts | 106 +++++++++-- .../resources/woodpecker/workspace-route.ts | 47 +++++ packages/homelab/src/talos/liskov/README.md | 7 + .../ci/check-ci-admission-budget.test.ts | 33 ++++ .../checks/ci/check-ci-admission-budget.ts | 14 +- scripts/lib/ci/admission-budget.ts | 6 + 12 files changed, 458 insertions(+), 70 deletions(-) diff --git a/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md b/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md index d5775ac9a5..b88d39efd2 100644 --- a/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md +++ b/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md @@ -129,11 +129,11 @@ completion slot. Mandatory agent labels keep a pool from taking unrelated workflows. All generated workflows use their assigned pool. The admission proof covers -every compute and gate slot in the budget. It also rejects a workflow routed -to a pool with no agent, which Woodpecker would hold forever. Its pod backstop -also includes compute services, so partially started workflows cannot fill -every slot before a step can run. The legacy pool has zero slots and no agent -Deployment. +every compute and gate slot in the budget, the RAM workspace pools' included. +It also rejects a workflow routed to a pool with no agent, which Woodpecker +would hold forever. Its pod backstop also includes compute services, so +partially started workflows cannot fill every slot before a step can run. The +legacy pool has zero slots and no agent Deployment. The reserve slightly reduces compute capacity. It buys predictable access for short verdict checks without increasing the total CPU, memory, or ephemeral @@ -388,6 +388,32 @@ stamping `publishedAt`, so `CIRamRouteStale` fires when the ConfigMap has not changed for 15 minutes: the routing policy would otherwise keep applying the last route it saw. +## RAM workspaces come from their own agents + +Woodpecker creates each workflow's workspace claim from its agent's settings, +and the claim carries no workflow labels. The only way to give a workflow a RAM +workspace is therefore to run it on an agent whose claims ask for +`ci-workspace-ram`. Two more agent pools, `pr-ram` and `main-ram`, do exactly +that, with the 12Gi RAM workspace size; the routing policy above then keeps +each claim on the pool or moves it to NVMe. + +Their slots come out of the pools beside them: pull requests keep 12 slots as +9 ordinary plus 3 RAM, and main keeps 10 as 8 plus 2. The compute total, the +pods backstop and the admission proof are unchanged. Like every pool, each +requires its own `ci-pool` label, so it takes only the workflows the generator +routes to it. + +A RAM agent also waits, at every start, for the route published on the node's +current boot. The route ConfigMap survives a reboot, but the pool, its golden +snapshot and every claim on it do not. Until the publisher runs again, a +`ready` route from the previous boot would send new claims to a snapshot that +no longer exists, and they would sit Pending. The publisher records the node's +boot ID with every decision, and each RAM agent's init container, +`workspace-route-boot-gate`, holds the agent until the published boot ID is the +node's own, logging which boot the route it read belongs to. The gate checks +only that the route is current; its state still decides between RAM and NVMe. +A failing API read fails the init container instead of waiting silently. + ## Workspaces do not accumulate Each workflow gets a workspace claim on the `ci-workspace` storage class. The @@ -502,8 +528,9 @@ kubelet eviction, whatever the queue says. runbook in `packages/homelab/src/talos/liskov/README.md` - Golden workspace clone policy: `resources/woodpecker/workspace-clone-policy.ts` -- RAM workspace route publisher and routing policy: +- RAM workspace route publisher, routing policy and agent boot gate: `resources/woodpecker/workspace-route.ts` +- RAM workspace agent pools: `resources/woodpecker/agent.ts` - Golden refresh and snapshot: `packages/temporal/src/activities/maintenance/ci-workspace-golden.ts` - RAM golden claim, seed candidate, and snapshot: diff --git a/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json b/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json index a59ac17940..f12de0e412 100644 --- a/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json +++ b/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json @@ -1,5 +1,5 @@ { - "$comment": "CI admission budget on the liskov CI node. cdk8s builds the Kueue ClusterQueue and the Woodpecker agent's workflow cap from this file, and scripts/checks/ci/check-ci-admission-budget.ts proves the generated pipeline fits it. Quotas sit below liskov's allocatable (29 CPU, ~91.5Gi) on purpose: CPU follows the same rule (every queue, 24 aggregate + 1 maintenance + 2 Delivery, plus about 2.0 of resident requests, <= 29), and every queue plus the requests resident outside Kueue (about 7Gi: buildkitd, the agents, node daemons) must fit the allocatable memory, so a pod Kueue admits can always schedule. Delivery's executor reserve (2 CPU, 8Gi) is a separate Kueue queue beside this budget, so computeQuota.memory gives up the same 8Gi. The quota is not where the overcommit lives: step requests are sized from measured usage (p90 memory, see the pipeline generator's tiers.ts), and limits stay the per-container backstop above them. The pool workflow caps are a backstop above Kueue's resource admission: an agent holds a workflow's slot while Kueue gates its pod, so the pr cap is sized so that Kueue, not the agent's first-in-first-out queue, orders waiting PR work. The pr cap of 12 was sized when the light checks shared it; they now have their own pool, which only leaves more of its slots to heavier workflows that Kueue still orders by priority. The main pool is 10 so 17-workflow main pipelines do not wait behind FIFO slots. The aggregate splits into compute, light and gate quotas. Short service-free PR checks in the light, scanner or contained tier route to the pr-light pool, whose lightQuota is reserved (no cohort, so verify can never borrow it) and holds every pr-light slot's largest pod at once: 4 slots x (500m CPU, 2Gi checkout memory, 2Gi ephemeral) = 2 CPU, 8Gi, 8Gi. Its CPU and 6Gi of its memory came out of computeQuota; the other 2Gi and its ephemeral storage came from node slack, so the aggregate grew by 2Gi of memory and to 68Gi of ephemeral storage. A pr-light workflow therefore waits only for one of its own slots, never for Kueue. The liskov RAM workspace pool (resources/ci-ram-pool.ts) keeps CI workspaces in memory that no container is charged for: its pod requests ramPool.memory, and computeQuota.memory (with the aggregate quota) gives up the same amount, so every queue, the requests resident outside Kueue and the pool together still fit the allocatable memory. That leaves computeQuota (51Gi) room for two verify pods beside a browser pod, not three.", + "$comment": "CI admission budget on the liskov CI node. cdk8s builds the Kueue ClusterQueue and the Woodpecker agent's workflow cap from this file, and scripts/checks/ci/check-ci-admission-budget.ts proves the generated pipeline fits it. Quotas sit below liskov's allocatable (29 CPU, ~91.5Gi) on purpose: CPU follows the same rule (every queue, 24 aggregate + 1 maintenance + 2 Delivery, plus about 2.0 of resident requests, <= 29), and every queue plus the requests resident outside Kueue (about 7Gi: buildkitd, the agents, node daemons) must fit the allocatable memory, so a pod Kueue admits can always schedule. Delivery's executor reserve (2 CPU, 8Gi) is a separate Kueue queue beside this budget, so computeQuota.memory gives up the same 8Gi. The quota is not where the overcommit lives: step requests are sized from measured usage (p90 memory, see the pipeline generator's tiers.ts), and limits stay the per-container backstop above them. The pool workflow caps are a backstop above Kueue's resource admission: an agent holds a workflow's slot while Kueue gates its pod, so the pr cap is sized so that Kueue, not the agent's first-in-first-out queue, orders waiting PR work. The pr cap of 12 was sized when the light checks shared it; they now have their own pool, which only leaves more of its slots to heavier workflows that Kueue still orders by priority. The main pool is 10 so 17-workflow main pipelines do not wait behind FIFO slots. Each is split between an ordinary pool and a -ram pool whose agent creates RAM workspace claims (pr 9 + pr-ram 3, main 8 + main-ram 2), so the totals, the pods quota and this proof stay the same; a -ram pool takes only the workflows the generator routes to it, but the proof charges its slots like any pr or main slot. The aggregate splits into compute, light and gate quotas. Short service-free PR checks in the light, scanner or contained tier route to the pr-light pool, whose lightQuota is reserved (no cohort, so verify can never borrow it) and holds every pr-light slot's largest pod at once: 4 slots x (500m CPU, 2Gi checkout memory, 2Gi ephemeral) = 2 CPU, 8Gi, 8Gi. Its CPU and 6Gi of its memory came out of computeQuota; the other 2Gi and its ephemeral storage came from node slack, so the aggregate grew by 2Gi of memory and to 68Gi of ephemeral storage. A pr-light workflow therefore waits only for one of its own slots, never for Kueue. The liskov RAM workspace pool (resources/ci-ram-pool.ts) keeps CI workspaces in memory that no container is charged for: its pod requests ramPool.memory, and computeQuota.memory (with the aggregate quota) gives up the same amount, so every queue, the requests resident outside Kueue and the pool together still fit the allocatable memory. That leaves computeQuota (51Gi) room for two verify pods beside a browser pod, not three.", "maxWorkflows": 31, "legacyMaxWorkflows": 0, "maxServicesPerWorkflow": 2, @@ -25,8 +25,10 @@ }, "ramPool": { "memory": "13Gi" }, "pools": { - "pr": { "maxWorkflows": 12, "queue": "default" }, - "main": { "maxWorkflows": 10, "queue": "default" }, + "pr": { "maxWorkflows": 9, "queue": "default" }, + "pr-ram": { "maxWorkflows": 3, "queue": "default" }, + "main": { "maxWorkflows": 8, "queue": "default" }, + "main-ram": { "maxWorkflows": 2, "queue": "default" }, "maintenance": { "maxWorkflows": 1, "queue": "default" }, "pr-light": { "maxWorkflows": 4, "queue": "ci-light" }, "review": { "maxWorkflows": 3, "queue": "ci-gates" }, diff --git a/packages/homelab/src/cdk8s/src/misc/woodpecker.ts b/packages/homelab/src/cdk8s/src/misc/woodpecker.ts index a9482e940e..46f7e30051 100644 --- a/packages/homelab/src/cdk8s/src/misc/woodpecker.ts +++ b/packages/homelab/src/cdk8s/src/misc/woodpecker.ts @@ -20,7 +20,16 @@ export const WOODPECKER_MAX_WORKFLOWS = CI_ADMISSION_BUDGET.legacyMaxWorkflows; export type CiAgentPool = keyof typeof CI_ADMISSION_BUDGET.pools; -/** Every pool whose pods queue for compute quota: PR, main and maintenance. */ +/** Pools whose agent creates RAM workspace claims instead of NVMe ones. */ +export const CI_RAM_WORKSPACE_POOLS = [ + "pr-ram", + "main-ram", +] as const satisfies readonly CiAgentPool[]; + +/** + * Every pool whose pods queue for compute quota: PR, main, their RAM + * workspace pools and maintenance. + */ export const CI_COMPUTE_WORKFLOWS = CI_ADMISSION_BUDGET.legacyMaxWorkflows + queueWorkflows(CI_ADMISSION_BUDGET.pools, "default"); diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts index 45a3936686..677d959483 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts @@ -5,6 +5,32 @@ import { z } from "zod"; import { CI_AGENT_MAX_WORKFLOWS_LABEL } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts"; import { createWoodpeckerAgent } from "./agent.ts"; import { CI_ADMISSION_BUDGET } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts"; +import { workspaceRouteBootGateScript } from "./workspace-route.ts"; + +const ContainerSchema = z.object({ + name: z.string(), + args: z.array(z.string()).optional(), + securityContext: z + .object({ + allowPrivilegeEscalation: z.boolean().optional(), + readOnlyRootFilesystem: z.boolean().optional(), + seccompProfile: z.object({ type: z.string() }).optional(), + }) + .loose() + .optional(), + volumeMounts: z + .array(z.object({ mountPath: z.string(), name: z.string() })) + .optional(), + env: z + .array( + z.object({ + name: z.string(), + value: z.string().optional(), + valueFrom: z.unknown().optional(), + }), + ) + .optional(), +}); const DeploymentSchema = z.object({ kind: z.literal("Deployment"), @@ -18,24 +44,27 @@ const DeploymentSchema = z.object({ template: z.object({ spec: z.object({ serviceAccountName: z.string(), + automountServiceAccountToken: z.boolean().optional(), affinity: z.unknown(), - containers: z.array( - z.object({ - env: z.array( - z.object({ - name: z.string(), - value: z.string().optional(), - valueFrom: z.unknown().optional(), - }), - ), - }), - ), + initContainers: z.array(ContainerSchema).optional(), + containers: z.array(ContainerSchema), + volumes: z + .array( + z.object({ name: z.string(), emptyDir: z.unknown().optional() }), + ) + .optional(), }), }), }), }); -function agents() { +const RoleSchema = z.object({ + kind: z.literal("Role"), + metadata: z.object({ name: z.string(), namespace: z.string() }), + rules: z.array(z.object({ resources: z.array(z.string()) }).loose()), +}); + +function manifests(): unknown[] { const app = new App(); createWoodpeckerAgent( new Chart(app, "woodpecker", { disableResourceNameHashes: true }), @@ -43,7 +72,11 @@ function agents() { return app .synthYaml() .split(/^---$/m) - .map((document): unknown => parse(document)) + .map((document): unknown => parse(document)); +} + +function agents() { + return manifests() .filter( (document) => z.object({ kind: z.literal("Deployment") }).safeParse(document).success, @@ -51,12 +84,22 @@ function agents() { .map((document) => DeploymentSchema.parse(document)); } +function agent(pool: string) { + const found = agents().find( + (entry) => entry.metadata.name === `woodpecker-woodpecker-agent-${pool}`, + ); + if (found === undefined) throw new Error(`missing ${pool} agent`); + return found; +} + function environment( - agent: z.infer, + deployment: z.infer, ): Map { - const container = agent.spec.template.spec.containers[0]; + const container = deployment.spec.template.spec.containers[0]; if (container === undefined) throw new Error("agent has no container"); - return new Map(container.env.map((entry) => [entry.name, entry.value])); + return new Map( + (container.env ?? []).map((entry) => [entry.name, entry.value]), + ); } describe("dedicated CI agent pools", () => { @@ -67,34 +110,37 @@ describe("dedicated CI agent pools", () => { .map((pool) => `woodpecker-woodpecker-agent-${pool}`) .toSorted(), ); - for (const [pool, cap, queue, volume] of [ - ["pr", "12", "default", "32Gi"], + for (const [pool, cap, queue, storageClass, volume] of [ + ["pr", "9", "default", "ci-workspace", "32Gi"], + ["pr-ram", "3", "default", "ci-workspace-ram", "12Gi"], // Light checks clone the golden snapshot too, but queue in their own // reserved ClusterQueue. - ["pr-light", "4", "ci-light", "32Gi"], - ["main", "10", "default", "32Gi"], + ["pr-light", "4", "ci-light", "ci-workspace", "32Gi"], + ["main", "8", "default", "ci-workspace", "32Gi"], + ["main-ram", "2", "default", "ci-workspace-ram", "12Gi"], // Maintenance workspaces clone the golden snapshot, so they keep the // compute workspace size rather than the gate's. - ["maintenance", "1", "default", "32Gi"], - ["review", "3", "ci-gates", "1G"], - ["completion", "1", "ci-gates", "1G"], + ["maintenance", "1", "default", "ci-workspace", "32Gi"], + ["review", "3", "ci-gates", "ci-workspace", "1G"], + ["completion", "1", "ci-gates", "ci-workspace", "1G"], ] as const) { - const agent = deployments.find( - (entry) => - entry.metadata.name === `woodpecker-woodpecker-agent-${pool}`, - ); - if (agent === undefined) throw new Error(`missing ${pool} agent`); - const env = environment(agent); + const deployment = agent(pool); + const env = environment(deployment); expect(env.get("WOODPECKER_MAX_WORKFLOWS")).toBe(cap); // The label kube-state-metrics exports for the disconnected-agent alert // must carry the same slot count the agent runs with. - expect(agent.metadata.labels?.[CI_AGENT_MAX_WORKFLOWS_LABEL]).toBe(cap); + expect(deployment.metadata.labels?.[CI_AGENT_MAX_WORKFLOWS_LABEL]).toBe( + cap, + ); expect(env.get("WOODPECKER_AGENT_LABELS")).toBe( `!ci-pool=${pool},kueue.x-k8s.io/priority-class=*`, ); expect(env.get("WOODPECKER_BACKEND_K8S_POD_LABELS")).toBe( JSON.stringify({ "kueue.x-k8s.io/queue-name": queue }), ); + expect(env.get("WOODPECKER_BACKEND_K8S_STORAGE_CLASS")).toBe( + storageClass, + ); expect(env.get("WOODPECKER_BACKEND_K8S_VOLUME_SIZE")).toBe(volume); } const legacy = deployments.find( @@ -104,11 +150,11 @@ describe("dedicated CI agent pools", () => { }); it("keeps every agent on liskov with the existing native-secret and pod guards", () => { - for (const agent of agents()) { - const env = environment(agent); - expect(agent.spec.replicas).toBe(1); - expect(agent.spec.strategy.type).toBe("Recreate"); - expect(agent.spec.template.spec.affinity).toEqual({ + for (const deployment of agents()) { + const env = environment(deployment); + expect(deployment.spec.replicas).toBe(1); + expect(deployment.spec.strategy.type).toBe("Recreate"); + expect(deployment.spec.template.spec.affinity).toEqual({ nodeAffinity: { requiredDuringSchedulingIgnoredDuringExecution: { nodeSelectorTerms: [ @@ -125,7 +171,7 @@ describe("dedicated CI agent pools", () => { }, }, }); - expect(agent.spec.template.spec.serviceAccountName).toBe( + expect(deployment.spec.template.spec.serviceAccountName).toBe( "woodpecker-agent", ); expect(env.get("WOODPECKER_BACKEND_K8S_NAMESPACE")).toBe("woodpecker-ci"); @@ -140,4 +186,59 @@ describe("dedicated CI agent pools", () => { ); } }); + + it("gates RAM workspace agents on the route published for this boot, and leaves the others ungated", () => { + for (const pool of ["pr-ram", "main-ram"]) { + const { spec } = agent(pool).spec.template; + expect(spec.automountServiceAccountToken).toBe(true); + expect(spec.initContainers).toHaveLength(1); + const [gate] = spec.initContainers ?? []; + expect(gate?.name).toBe("workspace-route-boot-gate"); + expect(gate?.args).toEqual([workspaceRouteBootGateScript()]); + expect(gate?.securityContext).toMatchObject({ + allowPrivilegeEscalation: false, + readOnlyRootFilesystem: true, + seccompProfile: { type: "RuntimeDefault" }, + }); + // kubectl caches discovery under /tmp, an emptyDir on a read-only root. + const tmp = gate?.volumeMounts?.find( + (mount) => mount.mountPath === "/tmp", + ); + expect( + spec.volumes?.find((volume) => volume.name === tmp?.name)?.emptyDir, + ).toBeDefined(); + expect(spec.containers[0]?.securityContext?.seccompProfile).toEqual({ + type: "RuntimeDefault", + }); + } + for (const pool of ["pr", "main", "review", "completion"]) { + const { spec } = agent(pool).spec.template; + expect(spec.initContainers).toBeUndefined(); + expect(spec.volumes).toBeUndefined(); + expect( + spec.containers[0]?.securityContext?.seccompProfile, + ).toBeUndefined(); + } + }); + + it("grants the agent only a read of the route ConfigMap, by name", () => { + const role = manifests() + .filter( + (document) => + z.object({ kind: z.literal("Role") }).safeParse(document).success, + ) + .map((document) => RoleSchema.parse(document)) + .find((entry) => entry.metadata.name === "woodpecker-agent"); + expect(role?.metadata.namespace).toBe("woodpecker-ci"); + expect( + role?.rules.filter((rule) => rule.resources.includes("configmaps")), + ).toEqual([ + { + apiGroups: [""], + resources: ["configmaps"], + resourceNames: ["ci-workspace-route"], + verbs: ["get"], + }, + ]); + }); }); diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts index 5bcbe1140e..668042e0aa 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts @@ -7,8 +7,10 @@ import { EnvValue, Node, NodeLabelQuery, + SeccompProfileType, Secret, ServiceAccount, + Volume, } from "cdk8s-plus-31"; import { KubeNetworkPolicy, @@ -32,21 +34,29 @@ import { } from "@shepherdjerred/homelab/cdk8s/src/misc/nodes.ts"; import { BATCH_PRIORITY } from "@shepherdjerred/homelab/cdk8s/src/misc/priority-classes.ts"; import { + CI_RAM_WORKSPACE_STORAGE_CLASS, + CI_RAM_WORKSPACE_VOLUME_SIZE, CI_WORKSPACE_STORAGE_CLASS, CI_WORKSPACE_VOLUME_SIZE, } from "@shepherdjerred/homelab/cdk8s/src/misc/storage/storage-classes.ts"; +import { kubectlScriptContainer } from "@shepherdjerred/homelab/cdk8s/src/misc/kubectl-script-container.ts"; import versions from "@shepherdjerred/homelab/cdk8s/src/versions.ts"; import { WOODPECKER_GRPC_PORT, WOODPECKER_MAX_WORKFLOWS, CI_AGENT_MAX_WORKFLOWS_LABEL, CI_ADMISSION_BUDGET, + CI_RAM_WORKSPACE_POOLS, type CiAgentPool, } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts"; import { WOODPECKER_CI_NAMESPACE, WOODPECKER_NAMESPACE, } from "@shepherdjerred/homelab/cdk8s/src/resources/argo-applications/ci/woodpecker-credentials.ts"; +import { + CI_WORKSPACE_ROUTE_CONFIG_MAP, + workspaceRouteBootGateScript, +} from "@shepherdjerred/homelab/cdk8s/src/resources/woodpecker/workspace-route.ts"; /** * RBAC for the agent's Kubernetes backend. @@ -56,7 +66,8 @@ import { * service, and step, and streams their logs back. The agent itself runs in the * control-plane namespace but is granted nothing there: its Role exists only * in the CI namespace, and step pods run under the tokenless `woodpecker-job` - * account with no API access at all. + * account with no API access at all. A RAM workspace agent's boot gate also + * reads the workspace route ConfigMap, by name. */ function createAgentRbac(chart: Chart): KubeServiceAccount { const serviceAccount = new KubeServiceAccount(chart, "woodpecker-agent-sa", { @@ -76,6 +87,12 @@ function createAgentRbac(chart: Chart): KubeServiceAccount { resources: ["persistentvolumeclaims", "services"], verbs: ["get", "list", "watch", "create", "delete"], }, + { + apiGroups: [""], + resources: ["configmaps"], + resourceNames: [CI_WORKSPACE_ROUTE_CONFIG_MAP], + verbs: ["get"], + }, ], }); @@ -121,6 +138,7 @@ export function createWoodpeckerAgent(chart: Chart) { "pr-light", "main", "maintenance", + ...CI_RAM_WORKSPACE_POOLS, "review", "completion", ]; @@ -129,7 +147,8 @@ export function createWoodpeckerAgent(chart: Chart) { ); // Agents serve nothing. Each holds a gRPC stream to the server and drives - // its step pods through the Kubernetes API, never the pod network. + // its step pods through the Kubernetes API, never the pod network. A RAM + // workspace agent's boot gate reads the route ConfigMap over the same API. new KubeNetworkPolicy(chart, "woodpecker-agent-netpol", { metadata: { name: "woodpecker-agent-netpol" }, spec: { @@ -149,6 +168,10 @@ export function createWoodpeckerAgent(chart: Chart) { return { deployment, serviceAccount, poolDeployments }; } +const RAM_WORKSPACE_POOLS: ReadonlySet = new Set( + CI_RAM_WORKSPACE_POOLS, +); + function createAgentDeployment( chart: Chart, serviceAccount: KubeServiceAccount, @@ -159,6 +182,7 @@ function createAgentDeployment( pool === undefined ? "woodpecker-agent" : `woodpecker-agent-${pool}`; const config = pool === undefined ? undefined : CI_ADMISSION_BUDGET.pools[pool]; + const ramWorkspace = pool !== undefined && RAM_WORKSPACE_POOLS.has(pool); const deployment = new Deployment(chart, id, { replicas: 1, strategy: DeploymentStrategy.recreate(), @@ -191,6 +215,8 @@ function createAgentDeployment( ); deployment.scheduling.tolerate(ciNodeTaintedNode()); + if (ramWorkspace) addRouteBootGate(chart, deployment, id); + deployment.addContainer( withCommonProps({ name: "woodpecker-agent", @@ -267,22 +293,36 @@ function createAgentDeployment( EnvValue.fromValue(BATCH_PRIORITY), // Per-workflow workspace claims land on the CI node's NVMe and are - // destroyed with the workflow. + // destroyed with the workflow. A RAM workspace pool's claims ask for + // the RAM pool instead; the workspace route policy + // (workspace-route.ts) keeps each there or, explicitly, moves it to + // NVMe. WOODPECKER_BACKEND_K8S_STORAGE_CLASS: EnvValue.fromValue( - CI_WORKSPACE_STORAGE_CLASS, + ramWorkspace + ? CI_RAM_WORKSPACE_STORAGE_CLASS + : CI_WORKSPACE_STORAGE_CLASS, ), WOODPECKER_BACKEND_K8S_STORAGE_RWX: EnvValue.fromValue("true"), // A ZFS quota, not a reservation, so the size costs nothing until a // workflow writes. Verify peaks above 13 GB before step scratch // (TMPDIR, tool homes) moves here off the node's OS disk. WOODPECKER_BACKEND_K8S_VOLUME_SIZE: EnvValue.fromValue( - config?.queue === "ci-gates" ? "1G" : CI_WORKSPACE_VOLUME_SIZE, + ramWorkspace + ? CI_RAM_WORKSPACE_VOLUME_SIZE + : config?.queue === "ci-gates" + ? "1G" + : CI_WORKSPACE_VOLUME_SIZE, ), }, securityContext: { ensureNonRoot: false, allowPrivilegeEscalation: false, readOnlyRootFilesystem: false, + // New agents meet the RuntimeDefault baseline; the older pools are + // still on the fleet policy's seccomp debt list. + ...(ramWorkspace + ? { seccompProfile: { type: SeccompProfileType.RUNTIME_DEFAULT } } + : {}), }, resources: { cpu: { request: Cpu.millis(100), limit: Cpu.millis(1000) }, @@ -295,3 +335,31 @@ function createAgentDeployment( return deployment; } + +/** + * Keeps a RAM workspace agent from taking work until the route publisher has + * published for this boot (`workspaceRouteBootGateScript`). The gate runs + * whenever the pod starts, so an agent that restarts after a reboot waits + * again; that is intended. + */ +function addRouteBootGate(chart: Chart, deployment: Deployment, id: string) { + const gateProps = kubectlScriptContainer( + "workspace-route-boot-gate", + workspaceRouteBootGateScript(), + ); + const gate = deployment.addInitContainer({ + ...gateProps, + securityContext: { + ...gateProps.securityContext, + allowPrivilegeEscalation: false, + seccompProfile: { type: SeccompProfileType.RUNTIME_DEFAULT }, + }, + }); + // kubectl's discovery cache; the root filesystem is read-only. + gate.mount( + "/tmp", + Volume.fromEmptyDir(chart, `${id}-route-gate-tmp`, "route-gate-tmp", { + sizeLimit: Size.mebibytes(64), + }), + ); +} diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts index 9366620e55..05e02711d3 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts @@ -73,9 +73,11 @@ const EnvSchema = z.array( const AGENT_DEPLOYMENTS = [ "completion", "main", + "main-ram", "maintenance", "pr", "pr-light", + "pr-ram", "review", ].map((pool) => `woodpecker-woodpecker-agent-${pool}`); @@ -359,8 +361,10 @@ describe("Woodpecker CI namespace", () => { expect(env.get("WOODPECKER_BACKEND_K8S_PRIORITY_CLASS")).toBe( "batch-low", ); + // A RAM workspace pool's claims ask for the RAM pool; the workspace + // route policy keeps each there or moves it to NVMe. expect(env.get("WOODPECKER_BACKEND_K8S_STORAGE_CLASS")).toBe( - "ci-workspace", + name.endsWith("-ram") ? "ci-workspace-ram" : "ci-workspace", ); }, ); diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.test.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.test.ts index 1fddbb5c74..da228bf374 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.test.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.test.ts @@ -11,6 +11,7 @@ import { CI_WORKSPACE_ROUTE_CONFIG_MAP, WORKSPACE_ROUTE_VARIABLES, createWorkspaceRoutePolicy, + workspaceRouteBootGateScript, workspaceRoutePublisherScript, } from "./workspace-route.ts"; import { CI_WORKSPACE_GOLDEN_CONFIG_MAP } from "./workspace-clone-policy.ts"; @@ -74,12 +75,33 @@ afterEach(async () => { await rm(directory, { recursive: true, force: true }); }); -async function publish(fixture: Fixture) { +/** A scratch directory holding the fake kubectl and a `boot-1` boot ID. */ +async function fakeNode(kubectl: string) { const dir = await mkdtemp(path.join(tmpdir(), "workspace-route-")); directories.push(dir); - await Bun.write(path.join(dir, "kubectl"), FAKE_KUBECTL); + await Bun.write(path.join(dir, "kubectl"), kubectl); await Bun.spawn(["chmod", "+x", path.join(dir, "kubectl")]).exited; await Bun.write(path.join(dir, "boot_id"), "boot-1\n"); + return dir; +} + +/** Runs a script with the node's fake kubectl first on PATH. */ +async function runOn(dir: string, script: string) { + const child = Bun.spawn(["bash", "-c", script], { + env: { ...Bun.env, PATH: `${dir}:${Bun.env["PATH"] ?? ""}` }, + stdout: "pipe", + stderr: "pipe", + }); + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), + new Response(child.stderr).text(), + child.exited, + ]); + return { exitCode, stdout, stderr }; +} + +async function publish(fixture: Fixture) { + const dir = await fakeNode(FAKE_KUBECTL); if (fixture.status !== undefined) { const stamp = Math.floor(Date.now() / 1000) - fixture.status.ageSeconds; await Bun.write( @@ -106,23 +128,12 @@ async function publish(fixture: Fixture) { heartbeatPath: path.join(dir, "heartbeat"), once: true, }); - const child = Bun.spawn(["bash", "-c", script], { - env: { ...Bun.env, PATH: `${dir}:${Bun.env["PATH"] ?? ""}` }, - stdout: "pipe", - stderr: "pipe", - }); - const [stdout, stderr, exitCode] = await Promise.all([ - new Response(child.stdout).text(), - new Response(child.stderr).text(), - child.exited, - ]); + const result = await runOn(dir, script); const applied = Bun.file(path.join(dir, "applied.yaml")); const heartbeat = Bun.file(path.join(dir, "heartbeat")); const kubectlLog = Bun.file(path.join(dir, "kubectl.log")); return { - exitCode, - stdout, - stderr, + ...result, heartbeat: (await heartbeat.exists()) ? await heartbeat.text() : undefined, kubectlCalls: (await kubectlLog.exists()) ? kubectlLines(await kubectlLog.text()) @@ -283,6 +294,71 @@ describe("workspace route publisher", () => { }); }); +/** + * A kubectl that answers successive reads of the route's boot ID from + * `published`, one line per read (`-` for no ConfigMap), holding the last. + */ +const FAKE_GATE_KUBECTL = `#!/usr/bin/env bash +set -euo pipefail +dir="$(cd "$(dirname "$0")" && pwd)" +if [[ " $* " != *" get configmap ${CI_WORKSPACE_ROUTE_CONFIG_MAP} "* ]]; then echo "unexpected kubectl $*" >&2; exit 2; fi +if [[ -f "$dir/fail" ]]; then echo "error: configmaps \\"${CI_WORKSPACE_ROUTE_CONFIG_MAP}\\" is forbidden" >&2; exit 1; fi +calls=$(( $(cat "$dir/calls") + 1 )) +echo "$calls" > "$dir/calls" +if (( calls > 20 )); then echo "the gate never stopped asking" >&2; exit 3; fi +line="$(sed -n "\${calls}p" "$dir/published")" +if [[ -z "$line" ]]; then line="$(tail -n 1 "$dir/published")"; fi +if [[ "$line" != "-" ]]; then printf '%s' "$line"; fi +`; + +async function gate(published: readonly string[], failing = false) { + const dir = await fakeNode(FAKE_GATE_KUBECTL); + await Bun.write(path.join(dir, "published"), `${published.join("\n")}\n`); + await Bun.write(path.join(dir, "calls"), "0\n"); + if (failing) await Bun.write(path.join(dir, "fail"), ""); + const script = workspaceRouteBootGateScript({ + bootIdPath: path.join(dir, "boot_id"), + cacheDir: path.join(dir, "cache"), + intervalSeconds: 0, + }); + const result = await runOn(dir, script); + const calls = await Bun.file(path.join(dir, "calls")).text(); + return { ...result, calls: Number(calls.trim()) }; +} + +describe("workspace route boot gate", () => { + test("starts the agent at once when the route was published for this boot", async () => { + const { exitCode, stdout, stderr, calls } = await gate(["boot-1"]); + expect(exitCode, stderr).toBe(0); + expect(calls).toBe(1); + expect(stdout).toContain( + "the workspace route is published for this boot (boot-1)", + ); + }); + + test("waits, saying why, through a missing route and one from the previous boot", async () => { + const { exitCode, stdout, stderr, calls } = await gate([ + "-", + "boot-0", + "boot-1", + ]); + expect(exitCode, stderr).toBe(0); + expect(calls).toBe(3); + expect(stdout.trim().split("\n")).toEqual([ + `waiting: ${CI_WORKSPACE_ROUTE_CONFIG_MAP} has no route for any boot yet, and this node booted as boot-1`, + `waiting: ${CI_WORKSPACE_ROUTE_CONFIG_MAP} was published for boot boot-0, but this node booted as boot-1; the RAM pool's route publisher has not run since the reboot`, + "the workspace route is published for this boot (boot-1); starting the agent", + ]); + }); + + test("fails loudly on an API error instead of waiting silently", async () => { + const { exitCode, stderr, calls } = await gate(["boot-1"], true); + expect(exitCode).not.toBe(0); + expect(calls).toBe(0); + expect(stderr).toContain("forbidden"); + }); +}); + describe("workspace route policy", () => { const manifests = renderAdmissionPolicies(createWorkspaceRoutePolicy); const kind = (name: string) => { diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.ts index 75fcc06635..ee013f5206 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/workspace-route.ts @@ -201,6 +201,53 @@ done` `.trim(); } +type BootGatePaths = { + readonly bootIdPath: string; + readonly cacheDir: string; + readonly intervalSeconds: number; +}; + +const PRODUCTION_BOOT_GATE: BootGatePaths = { + bootIdPath: PRODUCTION_PATHS.bootIdPath, + cacheDir: PRODUCTION_PATHS.cacheDir, + intervalSeconds: 5, +}; + +/** + * Holds a RAM workspace agent until the route publisher has published for the + * node's current boot. + * + * The route ConfigMap outlives a reboot, but the RAM pool, its golden snapshot + * and every claim on it do not. Until the publisher runs again, a `ready` + * route from the previous boot would send new claims to a snapshot that no + * longer exists, and they would sit Pending. The publisher records the node's + * boot ID with every decision, so an agent that starts only once the IDs match + * never acts on a stale route. A failing API call exits non-zero, so a broken + * grant shows as a failing init container rather than a silent wait. + */ +export function workspaceRouteBootGateScript( + paths: BootGatePaths = PRODUCTION_BOOT_GATE, +): string { + return ` +set -euo pipefail + +boot="$(cat "${paths.bootIdPath}")" +while true; do + published="$(kubectl --cache-dir="${paths.cacheDir}" -n "${WOODPECKER_CI_NAMESPACE}" get configmap ${CI_WORKSPACE_ROUTE_CONFIG_MAP} --ignore-not-found -o 'jsonpath={.data.bootId}')" + if [[ "$published" == "$boot" ]]; then + echo "the workspace route is published for this boot ($boot); starting the agent" + exit 0 + fi + if [[ -z "$published" ]]; then + echo "waiting: ${CI_WORKSPACE_ROUTE_CONFIG_MAP} has no route for any boot yet, and this node booted as $boot" + else + echo "waiting: ${CI_WORKSPACE_ROUTE_CONFIG_MAP} was published for boot $published, but this node booted as $boot; the RAM pool's route publisher has not run since the reboot" + fi + sleep ${String(paths.intervalSeconds)} +done +`.trim(); +} + const SNAPSHOT_GROUP = "snapshot.storage.k8s.io"; const MUTATION = "woodpecker-workspace-route.sjer.red"; const GUARD = "woodpecker-workspace-route-guard.sjer.red"; diff --git a/packages/homelab/src/talos/liskov/README.md b/packages/homelab/src/talos/liskov/README.md index 8a55a32494..f0bbb6defd 100644 --- a/packages/homelab/src/talos/liskov/README.md +++ b/packages/homelab/src/talos/liskov/README.md @@ -272,6 +272,13 @@ token, bounds each API call at 10 seconds, and is restarted when its last successful publish is a minute old; `CIRamRouteStale` fires when the ConfigMap has not changed for 15 minutes. +The RAM workspace agents (`woodpecker-woodpecker-agent-pr-ram` and `-main-ram` +in `woodpecker`) start only once that ConfigMap's `bootId` is liskov's current +boot ID, so after a reboot they sit in `Init` until the route container has +published once. Their `workspace-route-boot-gate` init container logs which +boot the route it read belongs to: +`kubectl -n woodpecker logs deploy/woodpecker-woodpecker-agent-pr-ram -c workspace-route-boot-gate`. + Any state but ONLINE fails the pod and fires `CIRamPoolUnavailable`; the pool is left for an operator. Its contents are disposable workspaces, so when `zpool clear` does not bring it back, recovery is: diff --git a/scripts/checks/ci/check-ci-admission-budget.test.ts b/scripts/checks/ci/check-ci-admission-budget.test.ts index 0b68081f06..4ce5d753a5 100644 --- a/scripts/checks/ci/check-ci-admission-budget.test.ts +++ b/scripts/checks/ci/check-ci-admission-budget.test.ts @@ -262,6 +262,39 @@ describe("pooled CI admission budget", () => { ).toEqual([expect.stringContaining("memory:")]); }); + test("counts the RAM workspace pools' slots in the compute proof", () => { + // 22 PR and main slots, the RAM workspace pools' included, of 2Gi + // services plus a 4Gi step fit the 51Gi compute quota; 12 more RAM + // workspace slots do not. Maintenance holds only its own workflows. + const largeServices = step({ + services: [{ name: "db", resources: { ...SMALL, memoryRequest: "2Gi" } }], + }); + expect( + Object.entries(budget.pools) + .filter(([, pool]) => pool.queue === "default") + .map(([name, pool]) => [name, pool.maxWorkflows]), + ).toEqual([ + ["pr", 9], + ["pr-ram", 3], + ["main", 8], + ["main-ram", 2], + ["maintenance", 1], + ]); + expect(pooledAdmissionBudgetViolations([largeServices], budget)).toEqual( + [], + ); + expect( + pooledAdmissionBudgetViolations([largeServices], { + ...budget, + maxWorkflows: budget.maxWorkflows + 12, + pools: { + ...budget.pools, + "pr-ram": { maxWorkflows: 15, queue: "default" }, + }, + }), + ).toEqual([expect.stringContaining("memory:")]); + }); + test("rejects budget growth and a mismatched workflow total", () => { expect( pooledAdmissionBudgetViolations([compute], { diff --git a/scripts/checks/ci/check-ci-admission-budget.ts b/scripts/checks/ci/check-ci-admission-budget.ts index 93827e105e..dbde18ead5 100644 --- a/scripts/checks/ci/check-ci-admission-budget.ts +++ b/scripts/checks/ci/check-ci-admission-budget.ts @@ -238,9 +238,16 @@ function unroutableViolations( * PR and main run the ordinary graph, which the step model routes once as a * pull request, so any of their slots may hold any of its workflows. That * includes the workflows a pull request routes to `pr-light`: a main push - * runs them in the main pool, against compute quota. + * runs them in the main pool, against compute quota. Their RAM workspace + * pools take the RAM-routed workflows of either event, which the step model + * routes only while the flag is on, so their slots are charged the same. */ -const SHARED_COMPUTE_POOLS: ReadonlySet = new Set(["pr", "main"]); +const SHARED_COMPUTE_POOLS: ReadonlySet = new Set([ + "pr", + "pr-ram", + "main", + "main-ram", +]); /** * The light reserve holds every `pr-light` slot at once, so Kueue never gates @@ -376,7 +383,8 @@ export function pooledAdmissionBudgetViolations( } // Old configurations still select the legacy agent. They retain their // services while the newly routed compute workflows start, so include both - // caps until that agent is drained and removed from the source. + // caps until that agent is drained and removed from the source. The RAM + // workspace pools share the compute queue, so their slots count too. const { shared, dedicated } = computeSlots(computeSteps, pools); violations.push( ...admissionBudgetViolations( diff --git a/scripts/lib/ci/admission-budget.ts b/scripts/lib/ci/admission-budget.ts index 38932fdc05..8ffafc95c5 100644 --- a/scripts/lib/ci/admission-budget.ts +++ b/scripts/lib/ci/admission-budget.ts @@ -40,10 +40,16 @@ export const PooledAdmissionBudgetSchema = AdmissionBudgetSchema.extend({ * requests this, and the compute quota gives it up. */ ramPool: z.object({ memory: z.string().min(1) }).strict(), + /** + * A `-ram` pool's agent creates RAM workspace claims; it shares the compute + * queue and takes only the workflows the generator routes to it. + */ pools: z .object({ pr: pool("default"), + "pr-ram": pool("default"), main: pool("default"), + "main-ram": pool("default"), // Temporal-dispatched maintenance (golden workspace, CI images, seeds, // release notes) has its own agent so it never waits behind the PR // backlog, but its pods still queue for compute quota. From 53f6b73864dd490b4b7cea2e0423d0da850aaafd Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Sat, 28 Nov 2026 01:20:47 -0800 Subject: [PATCH 2/3] fix(homelab): run RAM workspace agents only for pools the budget gives slots Why This branch carved pr-ram and main-ram out of the pr and main pools before anything routes work to them, so 5 of 22 compute slots would sit idle on agents nothing could use until the routing change merged. What - The admission budget keeps pr 12 and main 10; the routing change adds the -ram pools in the same change that routes work to them. - The shared schema makes pr-ram and main-ram optional, and computeWorkflows() counts the legacy agent and every default-queue pool, present or not, for CI_COMPUTE_WORKFLOWS and the admission proof. - createWoodpeckerAgent takes the budget and creates a RAM workspace agent only for a pool it lists; the boot gate, the route ConfigMap read and the RAM claim settings are unchanged. - Agent tests use a fixture budget with the RAM pools, and prove the real budget runs only the four ordinary agents; the budget test proves the compute proof with and without the RAM pools. - Wiki: a RAM agent runs only for a pool with slots, added with routing. Verification - bun run scripts/run-test.ts (packages/homelab/src/cdk8s) over src/resources/woodpecker, kueue-config, cluster-baseline and src/misc: 36 files, 258 tests pass. - bun vitest (scripts) checks/ci/check-ci-admission-budget.test.ts: 17 pass. - bun run check-ci-admission-budget: 61 generated steps across 2 graphs hold. - bunx turbo run typecheck lint for @homelab/cdk8s, root-scripts and woodpecker-config-extension: 33/33. - bunx lefthook run pre-commit: pass. - Not run: any live deployment; no live change was made. Co-Authored-By: Claude Opus 5.5 --- .../docs/explanation/homelab/ci-admission.md | 21 +++--- .../cdk8s/src/misc/ci-admission-budget.json | 8 +-- .../homelab/src/cdk8s/src/misc/woodpecker.ts | 5 +- .../src/resources/woodpecker/agent.test.ts | 69 ++++++++++++++++--- .../cdk8s/src/resources/woodpecker/agent.ts | 37 +++++++--- .../resources/woodpecker/ci-namespace.test.ts | 2 - .../ci/check-ci-admission-budget.test.ts | 55 ++++++++++----- .../checks/ci/check-ci-admission-budget.ts | 13 ++-- scripts/lib/ci/admission-budget.ts | 21 +++--- 9 files changed, 165 insertions(+), 66 deletions(-) diff --git a/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md b/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md index b88d39efd2..dd8b56d9fa 100644 --- a/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md +++ b/packages/docs/wiki/src/content/docs/explanation/homelab/ci-admission.md @@ -129,11 +129,11 @@ completion slot. Mandatory agent labels keep a pool from taking unrelated workflows. All generated workflows use their assigned pool. The admission proof covers -every compute and gate slot in the budget, the RAM workspace pools' included. -It also rejects a workflow routed to a pool with no agent, which Woodpecker -would hold forever. Its pod backstop also includes compute services, so -partially started workflows cannot fill every slot before a step can run. The -legacy pool has zero slots and no agent Deployment. +every compute and gate slot in the budget, the RAM workspace pools' included +whenever they have any. It also rejects a workflow routed to a pool with no +agent, which Woodpecker would hold forever. Its pod backstop also includes +compute services, so partially started workflows cannot fill every slot before +a step can run. The legacy pool has zero slots and no agent Deployment. The reserve slightly reduces compute capacity. It buys predictable access for short verdict checks without increasing the total CPU, memory, or ephemeral @@ -397,11 +397,12 @@ workspace is therefore to run it on an agent whose claims ask for that, with the 12Gi RAM workspace size; the routing policy above then keeps each claim on the pool or moves it to NVMe. -Their slots come out of the pools beside them: pull requests keep 12 slots as -9 ordinary plus 3 RAM, and main keeps 10 as 8 plus 2. The compute total, the -pods backstop and the admission proof are unchanged. Like every pool, each -requires its own `ci-pool` label, so it takes only the workflows the generator -routes to it. +A RAM agent runs only for a pool the admission budget gives slots, and those +slots come out of the ordinary pool beside it, so the compute total, the pods +backstop and the admission proof are unchanged. The budget gains the two pools +in the same change that routes work to them, so no slot sits idle on an agent +nothing routes to. Like every pool, each requires its own `ci-pool` label, so +it takes only the workflows the generator routes to it. A RAM agent also waits, at every start, for the route published on the node's current boot. The route ConfigMap survives a reboot, but the pool, its golden diff --git a/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json b/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json index f12de0e412..a59ac17940 100644 --- a/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json +++ b/packages/homelab/src/cdk8s/src/misc/ci-admission-budget.json @@ -1,5 +1,5 @@ { - "$comment": "CI admission budget on the liskov CI node. cdk8s builds the Kueue ClusterQueue and the Woodpecker agent's workflow cap from this file, and scripts/checks/ci/check-ci-admission-budget.ts proves the generated pipeline fits it. Quotas sit below liskov's allocatable (29 CPU, ~91.5Gi) on purpose: CPU follows the same rule (every queue, 24 aggregate + 1 maintenance + 2 Delivery, plus about 2.0 of resident requests, <= 29), and every queue plus the requests resident outside Kueue (about 7Gi: buildkitd, the agents, node daemons) must fit the allocatable memory, so a pod Kueue admits can always schedule. Delivery's executor reserve (2 CPU, 8Gi) is a separate Kueue queue beside this budget, so computeQuota.memory gives up the same 8Gi. The quota is not where the overcommit lives: step requests are sized from measured usage (p90 memory, see the pipeline generator's tiers.ts), and limits stay the per-container backstop above them. The pool workflow caps are a backstop above Kueue's resource admission: an agent holds a workflow's slot while Kueue gates its pod, so the pr cap is sized so that Kueue, not the agent's first-in-first-out queue, orders waiting PR work. The pr cap of 12 was sized when the light checks shared it; they now have their own pool, which only leaves more of its slots to heavier workflows that Kueue still orders by priority. The main pool is 10 so 17-workflow main pipelines do not wait behind FIFO slots. Each is split between an ordinary pool and a -ram pool whose agent creates RAM workspace claims (pr 9 + pr-ram 3, main 8 + main-ram 2), so the totals, the pods quota and this proof stay the same; a -ram pool takes only the workflows the generator routes to it, but the proof charges its slots like any pr or main slot. The aggregate splits into compute, light and gate quotas. Short service-free PR checks in the light, scanner or contained tier route to the pr-light pool, whose lightQuota is reserved (no cohort, so verify can never borrow it) and holds every pr-light slot's largest pod at once: 4 slots x (500m CPU, 2Gi checkout memory, 2Gi ephemeral) = 2 CPU, 8Gi, 8Gi. Its CPU and 6Gi of its memory came out of computeQuota; the other 2Gi and its ephemeral storage came from node slack, so the aggregate grew by 2Gi of memory and to 68Gi of ephemeral storage. A pr-light workflow therefore waits only for one of its own slots, never for Kueue. The liskov RAM workspace pool (resources/ci-ram-pool.ts) keeps CI workspaces in memory that no container is charged for: its pod requests ramPool.memory, and computeQuota.memory (with the aggregate quota) gives up the same amount, so every queue, the requests resident outside Kueue and the pool together still fit the allocatable memory. That leaves computeQuota (51Gi) room for two verify pods beside a browser pod, not three.", + "$comment": "CI admission budget on the liskov CI node. cdk8s builds the Kueue ClusterQueue and the Woodpecker agent's workflow cap from this file, and scripts/checks/ci/check-ci-admission-budget.ts proves the generated pipeline fits it. Quotas sit below liskov's allocatable (29 CPU, ~91.5Gi) on purpose: CPU follows the same rule (every queue, 24 aggregate + 1 maintenance + 2 Delivery, plus about 2.0 of resident requests, <= 29), and every queue plus the requests resident outside Kueue (about 7Gi: buildkitd, the agents, node daemons) must fit the allocatable memory, so a pod Kueue admits can always schedule. Delivery's executor reserve (2 CPU, 8Gi) is a separate Kueue queue beside this budget, so computeQuota.memory gives up the same 8Gi. The quota is not where the overcommit lives: step requests are sized from measured usage (p90 memory, see the pipeline generator's tiers.ts), and limits stay the per-container backstop above them. The pool workflow caps are a backstop above Kueue's resource admission: an agent holds a workflow's slot while Kueue gates its pod, so the pr cap is sized so that Kueue, not the agent's first-in-first-out queue, orders waiting PR work. The pr cap of 12 was sized when the light checks shared it; they now have their own pool, which only leaves more of its slots to heavier workflows that Kueue still orders by priority. The main pool is 10 so 17-workflow main pipelines do not wait behind FIFO slots. The aggregate splits into compute, light and gate quotas. Short service-free PR checks in the light, scanner or contained tier route to the pr-light pool, whose lightQuota is reserved (no cohort, so verify can never borrow it) and holds every pr-light slot's largest pod at once: 4 slots x (500m CPU, 2Gi checkout memory, 2Gi ephemeral) = 2 CPU, 8Gi, 8Gi. Its CPU and 6Gi of its memory came out of computeQuota; the other 2Gi and its ephemeral storage came from node slack, so the aggregate grew by 2Gi of memory and to 68Gi of ephemeral storage. A pr-light workflow therefore waits only for one of its own slots, never for Kueue. The liskov RAM workspace pool (resources/ci-ram-pool.ts) keeps CI workspaces in memory that no container is charged for: its pod requests ramPool.memory, and computeQuota.memory (with the aggregate quota) gives up the same amount, so every queue, the requests resident outside Kueue and the pool together still fit the allocatable memory. That leaves computeQuota (51Gi) room for two verify pods beside a browser pod, not three.", "maxWorkflows": 31, "legacyMaxWorkflows": 0, "maxServicesPerWorkflow": 2, @@ -25,10 +25,8 @@ }, "ramPool": { "memory": "13Gi" }, "pools": { - "pr": { "maxWorkflows": 9, "queue": "default" }, - "pr-ram": { "maxWorkflows": 3, "queue": "default" }, - "main": { "maxWorkflows": 8, "queue": "default" }, - "main-ram": { "maxWorkflows": 2, "queue": "default" }, + "pr": { "maxWorkflows": 12, "queue": "default" }, + "main": { "maxWorkflows": 10, "queue": "default" }, "maintenance": { "maxWorkflows": 1, "queue": "default" }, "pr-light": { "maxWorkflows": 4, "queue": "ci-light" }, "review": { "maxWorkflows": 3, "queue": "ci-gates" }, diff --git a/packages/homelab/src/cdk8s/src/misc/woodpecker.ts b/packages/homelab/src/cdk8s/src/misc/woodpecker.ts index 46f7e30051..dbb3545872 100644 --- a/packages/homelab/src/cdk8s/src/misc/woodpecker.ts +++ b/packages/homelab/src/cdk8s/src/misc/woodpecker.ts @@ -20,7 +20,10 @@ export const WOODPECKER_MAX_WORKFLOWS = CI_ADMISSION_BUDGET.legacyMaxWorkflows; export type CiAgentPool = keyof typeof CI_ADMISSION_BUDGET.pools; -/** Pools whose agent creates RAM workspace claims instead of NVMe ones. */ +/** + * Pools whose agent creates RAM workspace claims instead of NVMe ones. An + * agent runs for each only while the budget gives it slots. + */ export const CI_RAM_WORKSPACE_POOLS = [ "pr-ram", "main-ram", diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts index 677d959483..3b5ddd9c9e 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.test.ts @@ -2,9 +2,11 @@ import { describe, expect, it } from "vitest"; import { App, Chart } from "cdk8s"; import { parse } from "yaml"; import { z } from "zod"; -import { CI_AGENT_MAX_WORKFLOWS_LABEL } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts"; +import { + CI_ADMISSION_BUDGET, + CI_AGENT_MAX_WORKFLOWS_LABEL, +} from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts"; import { createWoodpeckerAgent } from "./agent.ts"; -import { CI_ADMISSION_BUDGET } from "@shepherdjerred/homelab/cdk8s/src/misc/woodpecker.ts"; import { workspaceRouteBootGateScript } from "./workspace-route.ts"; const ContainerSchema = z.object({ @@ -64,10 +66,27 @@ const RoleSchema = z.object({ rules: z.array(z.object({ resources: z.array(z.string()) }).loose()), }); -function manifests(): unknown[] { +/** + * A budget that gives the RAM workspace pools slots, carved out of the + * ordinary pools beside them, to exercise their agents. The routing change + * that sends work to them adds the same pools to the real budget. + */ +const RAM_POOLS_BUDGET: typeof CI_ADMISSION_BUDGET = { + ...CI_ADMISSION_BUDGET, + pools: { + ...CI_ADMISSION_BUDGET.pools, + pr: { maxWorkflows: 8, queue: "default" }, + "pr-ram": { maxWorkflows: 4, queue: "default" }, + main: { maxWorkflows: 8, queue: "default" }, + "main-ram": { maxWorkflows: 2, queue: "default" }, + }, +}; + +function manifests(budget = RAM_POOLS_BUDGET): unknown[] { const app = new App(); createWoodpeckerAgent( new Chart(app, "woodpecker", { disableResourceNameHashes: true }), + budget, ); return app .synthYaml() @@ -75,8 +94,8 @@ function manifests(): unknown[] { .map((document): unknown => parse(document)); } -function agents() { - return manifests() +function agents(budget = RAM_POOLS_BUDGET) { + return manifests(budget) .filter( (document) => z.object({ kind: z.literal("Deployment") }).safeParse(document).success, @@ -103,16 +122,50 @@ function environment( } describe("dedicated CI agent pools", () => { + it("runs a RAM workspace agent only for a pool the budget gives slots", () => { + const names = (budget: typeof CI_ADMISSION_BUDGET) => + agents(budget) + .map((deployment) => deployment.metadata.name) + .toSorted(); + const ordinary = [ + "completion", + "main", + "maintenance", + "pr", + "pr-light", + "review", + ].map((pool) => `woodpecker-woodpecker-agent-${pool}`); + const withoutRam = { + ...CI_ADMISSION_BUDGET, + pools: { + pr: CI_ADMISSION_BUDGET.pools.pr, + "pr-light": CI_ADMISSION_BUDGET.pools["pr-light"], + main: CI_ADMISSION_BUDGET.pools.main, + maintenance: CI_ADMISSION_BUDGET.pools.maintenance, + review: CI_ADMISSION_BUDGET.pools.review, + completion: CI_ADMISSION_BUDGET.pools.completion, + }, + }; + expect(names(withoutRam)).toEqual(ordinary); + expect(names(RAM_POOLS_BUDGET)).toEqual( + [ + ...ordinary, + "woodpecker-woodpecker-agent-main-ram", + "woodpecker-woodpecker-agent-pr-ram", + ].toSorted(), + ); + }); + it("uses only the mandatory-label pools after the legacy drain", () => { const deployments = agents(); expect(deployments.map((entry) => entry.metadata.name).toSorted()).toEqual( - Object.keys(CI_ADMISSION_BUDGET.pools) + Object.keys(RAM_POOLS_BUDGET.pools) .map((pool) => `woodpecker-woodpecker-agent-${pool}`) .toSorted(), ); for (const [pool, cap, queue, storageClass, volume] of [ - ["pr", "9", "default", "ci-workspace", "32Gi"], - ["pr-ram", "3", "default", "ci-workspace-ram", "12Gi"], + ["pr", "8", "default", "ci-workspace", "32Gi"], + ["pr-ram", "4", "default", "ci-workspace-ram", "12Gi"], // Light checks clone the golden snapshot too, but queue in their own // reserved ClusterQueue. ["pr-light", "4", "ci-light", "ci-workspace", "32Gi"], diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts index 668042e0aa..d84e6b5ead 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/agent.ts @@ -115,7 +115,17 @@ function createAgentRbac(chart: Chart): KubeServiceAccount { return serviceAccount; } -export function createWoodpeckerAgent(chart: Chart) { +type CiAdmissionBudget = typeof CI_ADMISSION_BUDGET; + +/** + * Agents for every pool the budget gives slots. A RAM workspace pool runs an + * agent only once the budget lists it, so its slots are never carved out of + * the ordinary pools before the generator routes work to it. + */ +export function createWoodpeckerAgent( + chart: Chart, + budget: CiAdmissionBudget = CI_ADMISSION_BUDGET, +) { const serviceAccount = createAgentRbac(chart); const serverSecretRef = Secret.fromSecretName( @@ -124,9 +134,10 @@ export function createWoodpeckerAgent(chart: Chart) { "woodpecker-server-credentials", ); + const context: AgentContext = { budget, serviceAccount, serverSecretRef }; const deployment = - CI_ADMISSION_BUDGET.legacyMaxWorkflows > 0 - ? createAgentDeployment(chart, serviceAccount, serverSecretRef) + budget.legacyMaxWorkflows > 0 + ? createAgentDeployment(chart, context) : undefined; // `maintenance` takes only the Temporal-dispatched maintenance workflows. // One slot of its own keeps the golden workspace refresh from waiting @@ -138,12 +149,14 @@ export function createWoodpeckerAgent(chart: Chart) { "pr-light", "main", "maintenance", - ...CI_RAM_WORKSPACE_POOLS, + ...CI_RAM_WORKSPACE_POOLS.filter( + (pool) => budget.pools[pool] !== undefined, + ), "review", "completion", ]; const poolDeployments = pools.map((pool) => - createAgentDeployment(chart, serviceAccount, serverSecretRef, pool), + createAgentDeployment(chart, context, pool), ); // Agents serve nothing. Each holds a gRPC stream to the server and drives @@ -172,16 +185,22 @@ const RAM_WORKSPACE_POOLS: ReadonlySet = new Set( CI_RAM_WORKSPACE_POOLS, ); +type AgentContext = { + readonly budget: CiAdmissionBudget; + readonly serviceAccount: KubeServiceAccount; + readonly serverSecretRef: ReturnType; +}; + function createAgentDeployment( chart: Chart, - serviceAccount: KubeServiceAccount, - serverSecretRef: ReturnType, + { budget, serviceAccount, serverSecretRef }: AgentContext, pool?: CiAgentPool, ) { const id = pool === undefined ? "woodpecker-agent" : `woodpecker-agent-${pool}`; - const config = - pool === undefined ? undefined : CI_ADMISSION_BUDGET.pools[pool]; + const config = pool === undefined ? undefined : budget.pools[pool]; + if (pool !== undefined && config === undefined) + throw new Error(`The CI admission budget has no ${pool} pool`); const ramWorkspace = pool !== undefined && RAM_WORKSPACE_POOLS.has(pool); const deployment = new Deployment(chart, id, { replicas: 1, diff --git a/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts b/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts index 05e02711d3..c486d9334f 100644 --- a/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts +++ b/packages/homelab/src/cdk8s/src/resources/woodpecker/ci-namespace.test.ts @@ -73,11 +73,9 @@ const EnvSchema = z.array( const AGENT_DEPLOYMENTS = [ "completion", "main", - "main-ram", "maintenance", "pr", "pr-light", - "pr-ram", "review", ].map((pool) => `woodpecker-woodpecker-agent-${pool}`); diff --git a/scripts/checks/ci/check-ci-admission-budget.test.ts b/scripts/checks/ci/check-ci-admission-budget.test.ts index 4ce5d753a5..77f95b8763 100644 --- a/scripts/checks/ci/check-ci-admission-budget.test.ts +++ b/scripts/checks/ci/check-ci-admission-budget.test.ts @@ -262,34 +262,53 @@ describe("pooled CI admission budget", () => { ).toEqual([expect.stringContaining("memory:")]); }); - test("counts the RAM workspace pools' slots in the compute proof", () => { + test("counts the RAM workspace pools' slots in the compute proof, and runs without them", () => { // 22 PR and main slots, the RAM workspace pools' included, of 2Gi // services plus a 4Gi step fit the 51Gi compute quota; 12 more RAM // workspace slots do not. Maintenance holds only its own workflows. const largeServices = step({ services: [{ name: "db", resources: { ...SMALL, memoryRequest: "2Gi" } }], }); - expect( - Object.entries(budget.pools) - .filter(([, pool]) => pool.queue === "default") - .map(([name, pool]) => [name, pool.maxWorkflows]), - ).toEqual([ - ["pr", 9], - ["pr-ram", 3], - ["main", 8], - ["main-ram", 2], - ["maintenance", 1], - ]); - expect(pooledAdmissionBudgetViolations([largeServices], budget)).toEqual( - [], + const { + "pr-ram": _prRam, + "main-ram": _mainRam, + ...ordinary + } = budget.pools; + const split = { + ...budget, + pools: { + ...ordinary, + pr: { maxWorkflows: 8, queue: "default" as const }, + "pr-ram": { maxWorkflows: 4, queue: "default" as const }, + main: { maxWorkflows: 8, queue: "default" as const }, + "main-ram": { maxWorkflows: 2, queue: "default" as const }, + }, + }; + // The split leaves the compute queue's slot total unchanged. + expect(queueWorkflows(split.pools, "default")).toBe(23); + expect(queueWorkflows(ordinary, "default")).toBe( + ordinary.pr.maxWorkflows + + ordinary.main.maxWorkflows + + ordinary.maintenance.maxWorkflows, ); expect( pooledAdmissionBudgetViolations([largeServices], { - ...budget, - maxWorkflows: budget.maxWorkflows + 12, + ...split, pools: { - ...budget.pools, - "pr-ram": { maxWorkflows: 15, queue: "default" }, + ...ordinary, + pr: { maxWorkflows: 12, queue: "default" as const }, + main: { maxWorkflows: 10, queue: "default" as const }, + }, + }), + ).toEqual([]); + expect(pooledAdmissionBudgetViolations([largeServices], split)).toEqual([]); + expect( + pooledAdmissionBudgetViolations([largeServices], { + ...split, + maxWorkflows: split.maxWorkflows + 12, + pools: { + ...split.pools, + "pr-ram": { maxWorkflows: 16, queue: "default" }, }, }), ).toEqual([expect.stringContaining("memory:")]); diff --git a/scripts/checks/ci/check-ci-admission-budget.ts b/scripts/checks/ci/check-ci-admission-budget.ts index dbde18ead5..3552d8d222 100644 --- a/scripts/checks/ci/check-ci-admission-budget.ts +++ b/scripts/checks/ci/check-ci-admission-budget.ts @@ -295,9 +295,10 @@ function computeSlots( pools: PooledAdmissionBudget["pools"], ): { shared: DedicatedSlots; dedicated: DedicatedSlots[] } { const pool = (step: AdmissionStep) => step.agentLabels?.["ci-pool"] ?? ""; - const dedicated = Object.entries(pools).filter( - ([name, entry]) => - entry.queue === "default" && !SHARED_COMPUTE_POOLS.has(name), + const dedicated = Object.entries(pools).flatMap(([name, entry]) => + entry?.queue === "default" && !SHARED_COMPUTE_POOLS.has(name) + ? [[name, entry] as const] + : [], ); const dedicatedNames = new Set(dedicated.map(([name]) => name)); return { @@ -322,7 +323,7 @@ export function pooledAdmissionBudgetViolations( const { pools } = budget; const violations: string[] = []; const steadyWorkflows = Object.values(pools).reduce( - (sum, pool) => sum + pool.maxWorkflows, + (sum, pool) => sum + (pool?.maxWorkflows ?? 0), 0, ); if (steadyWorkflows !== budget.maxWorkflows) { @@ -350,7 +351,9 @@ export function pooledAdmissionBudgetViolations( } const poolQueue = new Map( - Object.entries(pools).map(([name, pool]) => [name, pool.queue]), + Object.entries(pools).flatMap(([name, pool]) => + pool === undefined ? [] : [[name, pool.queue] as const], + ), ); violations.push(...unroutableViolations(steps, poolQueue)); const queueOf = (step: AdmissionStep) => diff --git a/scripts/lib/ci/admission-budget.ts b/scripts/lib/ci/admission-budget.ts index 8ffafc95c5..381a40a3fd 100644 --- a/scripts/lib/ci/admission-budget.ts +++ b/scripts/lib/ci/admission-budget.ts @@ -42,14 +42,15 @@ export const PooledAdmissionBudgetSchema = AdmissionBudgetSchema.extend({ ramPool: z.object({ memory: z.string().min(1) }).strict(), /** * A `-ram` pool's agent creates RAM workspace claims; it shares the compute - * queue and takes only the workflows the generator routes to it. + * queue and takes only the workflows the generator routes to it. Each is + * optional: a budget without one runs no RAM agent for it. */ pools: z .object({ pr: pool("default"), - "pr-ram": pool("default"), + "pr-ram": pool("default").optional(), main: pool("default"), - "main-ram": pool("default"), + "main-ram": pool("default").optional(), // Temporal-dispatched maintenance (golden workspace, CI images, seeds, // release notes) has its own agent so it never waits behind the PR // backlog, but its pods still queue for compute quota. @@ -75,13 +76,17 @@ export const PooledAdmissionBudgetSchema = AdmissionBudgetSchema.extend({ /** * Workflow slots whose pods join `queue`. Pods quotas and the admission proof * size each queue from this, so a pool added to the budget is counted in the - * queue it names rather than in a hard-coded list. + * queue it names rather than in a hard-coded list. An optional pool the budget + * leaves out counts nothing. */ export function queueWorkflows( - pools: Readonly>, + pools: Readonly< + Record + >, queue: PoolQueue, ): number { - return Object.values(pools) - .filter((entry) => entry.queue === queue) - .reduce((sum, entry) => sum + entry.maxWorkflows, 0); + return Object.values(pools).reduce( + (sum, entry) => (entry?.queue === queue ? sum + entry.maxWorkflows : sum), + 0, + ); } From dbb028e51383e430c434cdf3d83e47d3f831bf02 Mon Sep 17 00:00:00 2001 From: Jerred Shepherd Date: Sat, 28 Nov 2026 14:38:09 -0800 Subject: [PATCH 3/3] test(ci): give the RAM pool slot proof its own describe block Why Rebased onto main, whose pooled admission budget tests already sit near the 200-line function limit, the RAM workspace pool slot proof pushed the `pooled CI admission budget` block to 219 lines and failed the root-scripts lint. What - The RAM pool slot proof moves unchanged into its own `RAM workspace pools` describe block, which parses the budget itself. Verification - bunx eslint checks/ci/check-ci-admission-budget.test.ts (scripts): clean. - bun vitest checks/ci/check-ci-admission-budget.test.ts: 27 pass. - bunx lefthook run pre-commit: pass. - Not run: any live check; test-only change. Co-Authored-By: Claude Opus 5.5 --- .../ci/check-ci-admission-budget.test.ts | 111 ++++++++++-------- 1 file changed, 59 insertions(+), 52 deletions(-) diff --git a/scripts/checks/ci/check-ci-admission-budget.test.ts b/scripts/checks/ci/check-ci-admission-budget.test.ts index 77f95b8763..bddcdc3948 100644 --- a/scripts/checks/ci/check-ci-admission-budget.test.ts +++ b/scripts/checks/ci/check-ci-admission-budget.test.ts @@ -262,58 +262,6 @@ describe("pooled CI admission budget", () => { ).toEqual([expect.stringContaining("memory:")]); }); - test("counts the RAM workspace pools' slots in the compute proof, and runs without them", () => { - // 22 PR and main slots, the RAM workspace pools' included, of 2Gi - // services plus a 4Gi step fit the 51Gi compute quota; 12 more RAM - // workspace slots do not. Maintenance holds only its own workflows. - const largeServices = step({ - services: [{ name: "db", resources: { ...SMALL, memoryRequest: "2Gi" } }], - }); - const { - "pr-ram": _prRam, - "main-ram": _mainRam, - ...ordinary - } = budget.pools; - const split = { - ...budget, - pools: { - ...ordinary, - pr: { maxWorkflows: 8, queue: "default" as const }, - "pr-ram": { maxWorkflows: 4, queue: "default" as const }, - main: { maxWorkflows: 8, queue: "default" as const }, - "main-ram": { maxWorkflows: 2, queue: "default" as const }, - }, - }; - // The split leaves the compute queue's slot total unchanged. - expect(queueWorkflows(split.pools, "default")).toBe(23); - expect(queueWorkflows(ordinary, "default")).toBe( - ordinary.pr.maxWorkflows + - ordinary.main.maxWorkflows + - ordinary.maintenance.maxWorkflows, - ); - expect( - pooledAdmissionBudgetViolations([largeServices], { - ...split, - pools: { - ...ordinary, - pr: { maxWorkflows: 12, queue: "default" as const }, - main: { maxWorkflows: 10, queue: "default" as const }, - }, - }), - ).toEqual([]); - expect(pooledAdmissionBudgetViolations([largeServices], split)).toEqual([]); - expect( - pooledAdmissionBudgetViolations([largeServices], { - ...split, - maxWorkflows: split.maxWorkflows + 12, - pools: { - ...split.pools, - "pr-ram": { maxWorkflows: 16, queue: "default" }, - }, - }), - ).toEqual([expect.stringContaining("memory:")]); - }); - test("rejects budget growth and a mismatched workflow total", () => { expect( pooledAdmissionBudgetViolations([compute], { @@ -440,6 +388,65 @@ describe("pooled CI admission budget", () => { }); }); +/** + * The RAM workspace pools share the compute queue with pr and main, so the + * proof charges their slots like any of those. + */ +describe("RAM workspace pools", () => { + const budget = PooledBudgetSchema.parse(rawBudget); + test("counts the RAM workspace pools' slots in the compute proof, and runs without them", () => { + // 22 PR and main slots, the RAM workspace pools' included, of 2Gi + // services plus a 4Gi step fit the 51Gi compute quota; 12 more RAM + // workspace slots do not. Maintenance holds only its own workflows. + const largeServices = step({ + services: [{ name: "db", resources: { ...SMALL, memoryRequest: "2Gi" } }], + }); + const { + "pr-ram": _prRam, + "main-ram": _mainRam, + ...ordinary + } = budget.pools; + const split = { + ...budget, + pools: { + ...ordinary, + pr: { maxWorkflows: 8, queue: "default" as const }, + "pr-ram": { maxWorkflows: 4, queue: "default" as const }, + main: { maxWorkflows: 8, queue: "default" as const }, + "main-ram": { maxWorkflows: 2, queue: "default" as const }, + }, + }; + // The split leaves the compute queue's slot total unchanged. + expect(queueWorkflows(split.pools, "default")).toBe(23); + expect(queueWorkflows(ordinary, "default")).toBe( + ordinary.pr.maxWorkflows + + ordinary.main.maxWorkflows + + ordinary.maintenance.maxWorkflows, + ); + expect( + pooledAdmissionBudgetViolations([largeServices], { + ...split, + pools: { + ...ordinary, + pr: { maxWorkflows: 12, queue: "default" as const }, + main: { maxWorkflows: 10, queue: "default" as const }, + }, + }), + ).toEqual([]); + expect(pooledAdmissionBudgetViolations([largeServices], split)).toEqual([]); + expect( + pooledAdmissionBudgetViolations([largeServices], { + ...split, + maxWorkflows: split.maxWorkflows + 12, + pools: { + ...split.pools, + "pr-ram": { maxWorkflows: 16, queue: "default" }, + }, + }), + ).toEqual([expect.stringContaining("memory:")]); + }); +}); + /** * The light reserve must hold every pr-light slot's largest pod at once, so * Kueue never gates a light check and it waits only for one of its own