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

The release agent refuses a dark roll unless the owner said yes to that roll #951

Closed opened this in answer to
Closed without merging

torque/forge:torque/876-the-release-agent-refuses-a-dark-roll-un → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +943 −0
README.md +4
@@ -365,6 +365,10 @@ holds, where it goes, and the one command that restores it.
365365 grew up in switched off: what a host owes it, the moves in order, and what is
366366 given up.
367367
368 `docs/ops/RELEASE.md` is the release checklist: a release rolls only when a
369 second forge pod fits beside the first, and a roll that would go dark waits
370 for the owner's yes to that roll (`scripts/roll-preflight.ts`).
371
368372 ## Cloud accounts
369373
370374 **Settings → Cloud accounts** (admins) holds provider keys — Cloudflare,
docs/ops/RELEASE.md added +89
@@ -0,0 +1,89 @@
1 # Release checklist: the roll
2
3 A release never goes dark without the owner's yes to that roll (#876, part
4 of #873). The owner, 2026-10-06, after a three-minute dark roll: "that
5 should never happen … i should have the option to have it never go down."
6
7 The chart rolls with `maxSurge: 1, maxUnavailable: 0`
8 (`charts/app/templates/deployment.yaml`): the new pod comes up beside the old
9 one and the old one drains only once the new one is ready. The volume is
10 local-path, bound to one node, so the new pod must fit on **that node**. When
11 it does not, the only way through is to take the old pod down first — dark
12 for the drain plus the new pod's start: 3 min 33 s on v0.7.52.
13
14 ## Before every roll
15
16 The forge runs in namespace `$NS` as the Helm release `$REL` (the Deployment and its `app` label carry that name).
17
18 ```sh
19 POD=$(kubectl -n "$NS" get pod -l app="$REL" -o jsonpath='{.items[0].metadata.name}')
20 NODE=$(kubectl -n "$NS" get pod "$POD" -o jsonpath='{.spec.nodeName}')
21 kubectl get node "$NODE" -o json > node.json
22 kubectl get pods -A -o json --field-selector spec.nodeName="$NODE" > pods.json
23 # The forge's steady memory: the MEMORY column, read over a quiet minute
24 # (no crew run starting), not a peak and not a cold start.
25 kubectl -n "$NS" top pod "$POD" --no-headers
26
27 bun scripts/roll-preflight.ts --version 0.7.53 \
28 --node node.json --pods pods.json --pod "$NS/$POD" --steady 3712Mi \
29 --overlay path/to/the/gitops/helmrelease.yaml
30 ```
31
32 `--overlay` names every file of the gitops overlay that shapes this
33 deployment; it may be given more than once.
34
35 The rule (`scripts/roll.ts`), in whole millicores and bytes as the scheduler
36 counts them:
37
38 | quantity | is |
39 | --------- | ---------------------------------------------------------------- |
40 | free | node `status.allocatable` − the requests of every pod on it that has not Succeeded or Failed |
41 | need | cpu: the forge pod's request; memory: max(its request, its steady memory) |
42 | fits | free ≥ need, for cpu and for memory |
43 | short by | need − free, never below zero: the headroom that makes the roll zero-downtime |
44 | dark for | drain (180 s, the crew's) + start (35 s); at most the grace period (300 s) + the startup probe's ceiling (3 s × 60) + one readiness period (5 s) = 485 s |
45
46 Steady memory is in `need` because the request is a floor: a pod requesting
47 2 Gi that steadies at 3.5–4 Gi schedules on 2 Gi free and then both pods
48 hold more memory than the node has. Measured drain and start replace the
49 typical figures with `--drain-seconds` and `--start-seconds`.
50
51 ## What the exit code means
52
53 | exit | the agent |
54 | ---- | --------------------------------------------------------------------------------------------- |
55 | 0 | rolls |
56 | 3 | does **not** roll. Posts the report — the seconds it would be dark, what it is short by, the roll id — to the owner, and waits |
57 | 4 | does **not** roll. The overlay carries `maxSurge: 0` or `type: Recreate`; it comes out first |
58 | 2 | does not roll; the input was not what `kubectl` prints |
59
60 ## The owner's yes
61
62 A yes is to **one roll**: the owner's reply quotes the roll id from the
63 report. The agent re-runs the gate with `--yes <roll id>`. The id is the
64 release and the node's numbers it was judged on, so a yes never carries to
65 the next release, and if the node's numbers move before the roll the id
66 moves with them and the agent asks again. "yes", "always" or a yes from
67 anyone but the owner is no yes.
68
69 With exit 0 under `--yes`, the dark roll is a one-off patch on the live
70 deployment, undone as soon as the new pod is ready:
71
72 ```sh
73 kubectl -n "$NS" patch deploy "$REL" --type merge \
74 -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":0,"maxUnavailable":1}}}}'
75 # … the release rolls; wait for it …
76 kubectl -n "$NS" rollout status deploy/"$REL" --timeout=10m
77 kubectl -n "$NS" patch deploy "$REL" --type merge \
78 -p '{"spec":{"strategy":{"rollingUpdate":{"maxSurge":1,"maxUnavailable":0}}}}'
79 kubectl -n "$NS" get deploy "$REL" -o jsonpath='{.spec.strategy.rollingUpdate}'
80 # → {"maxSurge":1,"maxUnavailable":0}
81 ```
82
83 ## Never a standing value
84
85 `maxSurge: 0` (or `type: Recreate`) is never committed — not to this chart
86 and not to the gitops overlay. A standing no-surge turns every later roll,
87 settings-only rolls included, into a dark one that nobody said yes to.
88 `test/roll.test.ts` holds the chart to `maxSurge: 1, maxUnavailable: 0`; the
89 gate's `--overlay` holds the overlay to it at every roll.
scripts/gate.ts +1
@@ -38,6 +38,7 @@ export const GATE: readonly string[] = [
3838 "test/enterable-apps.test.ts",
3939 "test/event-order.test.ts",
4040 "test/returns.test.ts",
41 "test/roll.test.ts",
4142 "test/review-route.test.ts",
4243 "test/review-lines.test.ts",
4344 "test/review-gate.test.ts",
scripts/roll-preflight.ts added +153
@@ -0,0 +1,153 @@
1 /**
2 * The release checklist's roll gate (`docs/ops/RELEASE.md`, #876). Reads
3 * what `kubectl` printed, decides with `scripts/roll.ts`, prints the report
4 * the agent posts to the owner, and exits:
5 *
6 * 0 roll: a second forge pod fits, or the owner said yes to this roll id
7 * 3 do not roll: it would go dark and the owner has not said yes to it
8 * 4 do not roll: an overlay carries maxSurge 0 / Recreate as a standing value
9 * 2 the input is not what kubectl prints
10 *
11 * bun scripts/roll-preflight.ts --version 0.7.53 \
12 * --node node.json --pods pods.json --pod forge/forge-7d9c-abcde \
13 * --steady 3712Mi [--overlay helmrelease.yaml]… [--yes <roll id>] [--json]
14 *
15 * It runs nothing and reaches no cluster: the files are the agent's.
16 */
17
18 import { readFileSync } from "node:fs";
19 import {
20 DARK_TIMING,
21 decide,
22 parseQuantity,
23 preflight,
24 report,
25 standingNoSurge,
26 } from "./roll.ts";
27
28 export interface Args {
29 version: string;
30 node: string;
31 pods: string;
32 pod: string;
33 steady: string;
34 overlays: string[];
35 yes?: string;
36 json: boolean;
37 drainSeconds?: number;
38 startSeconds?: number;
39 }
40
41 const VALUED = new Set([
42 "--version",
43 "--node",
44 "--pods",
45 "--pod",
46 "--steady",
47 "--overlay",
48 "--yes",
49 "--drain-seconds",
50 "--start-seconds",
51 ]);
52
53 function seconds(flag: string, text: string): number {
54 if (!/^[0-9]{1,5}$/.test(text)) throw new Error(`${flag} wants whole seconds, not ${JSON.stringify(text)}`);
55 return Number(text);
56 }
57
58 export function parseArgs(argv: readonly string[]): Args {
59 const one: Record<string, string> = {};
60 const overlays: string[] = [];
61 let json = false;
62 for (let i = 0; i < argv.length; i++) {
63 const flag = argv[i] ?? "";
64 if (flag === "--json") {
65 json = true;
66 continue;
67 }
68 if (!VALUED.has(flag)) throw new Error(`unknown argument ${JSON.stringify(flag)}`);
69 const value = argv[++i];
70 if (value === undefined) throw new Error(`${flag} wants a value`);
71 if (flag === "--overlay") overlays.push(value);
72 else if (one[flag] !== undefined) throw new Error(`${flag} given twice`);
73 else one[flag] = value;
74 }
75 for (const f of ["--version", "--node", "--pods", "--pod", "--steady"])
76 if (one[f] === undefined) throw new Error(`${f} is required`);
77 const args: Args = {
78 version: one["--version"]!,
79 node: one["--node"]!,
80 pods: one["--pods"]!,
81 pod: one["--pod"]!,
82 steady: one["--steady"]!,
83 overlays,
84 json,
85 };
86 if (one["--yes"] !== undefined) args.yes = one["--yes"];
87 if (one["--drain-seconds"] !== undefined)
88 args.drainSeconds = seconds("--drain-seconds", one["--drain-seconds"]);
89 if (one["--start-seconds"] !== undefined)
90 args.startSeconds = seconds("--start-seconds", one["--start-seconds"]);
91 return args;
92 }
93
94 function readJson(path: string): unknown {
95 return JSON.parse(readFileSync(path, "utf8"));
96 }
97
98 /** The whole gate as a function of the arguments: exit code and output. */
99 export function run(argv: readonly string[]): { code: number; out: string } {
100 let args: Args;
101 try {
102 args = parseArgs(argv);
103 } catch (e) {
104 return { code: 2, out: `roll-preflight: ${(e as Error).message}` };
105 }
106 const standing: string[] = [];
107 for (const path of args.overlays) {
108 let text: string;
109 try {
110 text = readFileSync(path, "utf8");
111 } catch {
112 return { code: 2, out: `roll-preflight: cannot read overlay ${path}` };
113 }
114 for (const line of standingNoSurge(text)) standing.push(` ${path}: ${line}`);
115 }
116 if (standing.length > 0)
117 return {
118 code: 4,
119 out: [
120 "not rolling: no-surge is a standing value in the overlay; remove it first",
121 ...standing,
122 ].join("\n"),
123 };
124 try {
125 const steady = parseQuantity(args.steady);
126 if (steady === null) throw new Error(`--steady ${JSON.stringify(args.steady)} is not a quantity`);
127 const p = preflight({
128 version: args.version,
129 node: readJson(args.node),
130 pods: readJson(args.pods),
131 forgePod: args.pod,
132 steadyMemory: steady,
133 timing: {
134 ...DARK_TIMING,
135 ...(args.drainSeconds !== undefined ? { drainSeconds: args.drainSeconds } : {}),
136 ...(args.startSeconds !== undefined ? { startSeconds: args.startSeconds } : {}),
137 },
138 });
139 const d = decide(p, args.yes);
140 const out = args.json
141 ? JSON.stringify({ ...p, decision: d }, null, 2)
142 : report(p, d);
143 return { code: d.go ? 0 : 3, out };
144 } catch (e) {
145 return { code: 2, out: `roll-preflight: ${(e as Error).message}` };
146 }
147 }
148
149 if (import.meta.main) {
150 const { code, out } = run(process.argv.slice(2));
151 console.log(out);
152 process.exit(code);
153 }
scripts/roll.ts added +390
@@ -0,0 +1,390 @@
1 /**
2 * Whether a release can roll without going dark (#876, part of #873).
3 *
4 * The chart rolls with `maxSurge: 1, maxUnavailable: 0`: the new forge pod
5 * comes up beside the old one and the old one drains only once the new one
6 * is ready. Local-path storage binds the volume to one node, so the new pod
7 * must schedule on *that* node. When it cannot, the roll either sticks
8 * (the pod stays Pending and nothing changes) or — if someone sets
9 * `maxSurge: 0` — goes dark: the old pod drains first and nobody is served
10 * until the new one is ready. That cost 3 min 33 s on v0.7.52.
11 *
12 * Plain data in, plain data out. `scripts/roll-preflight.ts` reads what
13 * `kubectl` printed and prints what this decides; nothing here talks to a
14 * cluster.
15 *
16 * The rule, in the scheduler's own terms (NodeResourcesFit):
17 *
18 * free = node.status.allocatable − Σ requests of the pods on the node
19 * need.cpu = the forge pod's cpu request
20 * need.mem = max(the forge pod's memory request, its steady memory)
21 * fits ⇔ free.cpu ≥ need.cpu ∧ free.mem ≥ need.mem
22 *
23 * Steady memory is in `need` because the request (2 Gi) is a floor, not
24 * what the pod holds: a pod that steadies at 3.5–4 Gi schedules on 2 Gi
25 * free and then the node runs out of memory under both pods.
26 */
27
28 import { createHash } from "node:crypto";
29
30 /**
31 * Whole millicores and whole bytes, as the scheduler counts them (a
32 * quantity is rounded up to its unit, `Quantity.MilliValue`), so `4100m −
33 * 3100m` is exactly `1000m` and never a hair under it.
34 */
35 export interface Resources {
36 readonly milliCpu: number;
37 readonly memory: number;
38 }
39
40 const BINARY: Record<string, number> = {
41 Ki: 2 ** 10,
42 Mi: 2 ** 20,
43 Gi: 2 ** 30,
44 Ti: 2 ** 40,
45 Pi: 2 ** 50,
46 Ei: 2 ** 60,
47 };
48 const DECIMAL: Record<string, number> = {
49 n: 1e-9,
50 u: 1e-6,
51 m: 1e-3,
52 "": 1,
53 k: 1e3,
54 M: 1e6,
55 G: 1e9,
56 T: 1e12,
57 P: 1e15,
58 E: 1e18,
59 };
60
61 /**
62 * A Kubernetes resource quantity (`resource.Quantity`): `8130464Ki`, `2Gi`,
63 * `500m`, `1.5`, `12e6`. Answers the plain number (bytes, or cores), or
64 * null for anything that is not one — never a guess.
65 */
66 export function parseQuantity(text: unknown): number | null {
67 if (typeof text !== "string") return null;
68 const m = /^([0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:([eE][+-]?[0-9]{1,2})|(Ki|Mi|Gi|Ti|Pi|Ei|n|u|m|k|M|G|T|P|E))?$/.exec(
69 text.trim(),
70 );
71 if (!m) return null;
72 const base = Number(m[1]);
73 if (m[2]) return base * 10 ** Number(m[2].slice(1));
74 const suffix = m[3] ?? "";
75 const scale = BINARY[suffix] ?? DECIMAL[suffix];
76 return scale === undefined ? null : base * scale;
77 }
78
79 const ZERO: Resources = { milliCpu: 0, memory: 0 };
80
81 function add(a: Resources, b: Resources): Resources {
82 return { milliCpu: a.milliCpu + b.milliCpu, memory: a.memory + b.memory };
83 }
84
85 function max(a: Resources, b: Resources): Resources {
86 return { milliCpu: Math.max(a.milliCpu, b.milliCpu), memory: Math.max(a.memory, b.memory) };
87 }
88
89 function obj(v: unknown): Record<string, unknown> {
90 return v && typeof v === "object" && !Array.isArray(v)
91 ? (v as Record<string, unknown>)
92 : {};
93 }
94
95 function list(v: unknown): unknown[] {
96 return Array.isArray(v) ? v : [];
97 }
98
99 /** `{cpu, memory}` from a requests/allocatable map; absent reads as zero. */
100 function resources(map: unknown, where: string): Resources {
101 const m = obj(map);
102 const read = (key: "cpu" | "memory"): number => {
103 if (m[key] === undefined) return 0;
104 const n = parseQuantity(m[key]);
105 if (n === null || n < 0)
106 throw new Error(`${where}: ${key} ${JSON.stringify(m[key])} is not a quantity`);
107 return n;
108 };
109 return {
110 milliCpu: Math.ceil(read("cpu") * 1000 - 1e-6),
111 memory: Math.ceil(read("memory") - 1e-6),
112 };
113 }
114
115 /**
116 * What the scheduler reserves for a pod (Kubernetes ≥ 1.29, "Resource
117 * sharing within containers"): the containers and sidecars (init
118 * containers with `restartPolicy: Always`) summed; each plain init
119 * container, with the sidecars started before it, taken as a floor; plus
120 * the runtime class's overhead.
121 */
122 export function podRequest(pod: unknown): Resources {
123 const spec = obj(obj(pod)["spec"]);
124 const name = String(obj(obj(pod)["metadata"])["name"] ?? "?");
125 const req = (c: unknown) =>
126 resources(obj(obj(c)["resources"])["requests"], `pod ${name}`);
127 let sidecars = ZERO;
128 let initFloor = ZERO;
129 for (const c of list(spec["initContainers"])) {
130 if (obj(c)["restartPolicy"] === "Always") sidecars = add(sidecars, req(c));
131 else initFloor = max(initFloor, add(req(c), sidecars));
132 }
133 let sum = sidecars;
134 for (const c of list(spec["containers"])) sum = add(sum, req(c));
135 return add(max(sum, initFloor), resources(spec["overhead"], `pod ${name}`));
136 }
137
138 /** A pod the scheduler still counts against its node. */
139 function holdsNode(pod: unknown, node: string): boolean {
140 const phase = obj(obj(pod)["status"])["phase"];
141 return (
142 obj(obj(pod)["spec"])["nodeName"] === node &&
143 phase !== "Succeeded" &&
144 phase !== "Failed"
145 );
146 }
147
148 /**
149 * How long a roll without a surge pod is dark, in seconds. The old pod
150 * stops serving when it starts to drain; the new one cannot start until
151 * the old one is gone and then must pass its probes.
152 */
153 export interface DarkTiming {
154 /** Old pod's drain, typical: the crew drains three minutes (`crew/dispatch.ts`). */
155 readonly drainSeconds: number;
156 /** New pod from scheduled to ready, typical. */
157 readonly startSeconds: number;
158 /** Ceiling on the drain: the chart's `terminationGracePeriodSeconds`. */
159 readonly graceSeconds: number;
160 /** Ceiling on start: the chart's startupProbe period × failureThreshold, plus one readiness period. */
161 readonly startCeilingSeconds: number;
162 }
163
164 /**
165 * The defaults, from the chart (`charts/app/templates/deployment.yaml`,
166 * cross-checked by `test/roll.test.ts`) and from v0.7.52's dark roll:
167 * 213 s dark = 180 s drain + 33 s start.
168 */
169 export const DARK_TIMING: DarkTiming = {
170 drainSeconds: 180,
171 startSeconds: 35,
172 graceSeconds: 300,
173 startCeilingSeconds: 3 * 60 + 5,
174 };
175
176 export interface PreflightInput {
177 /** The release about to roll, `0.7.53` or `v0.7.53`. */
178 readonly version: string;
179 /** `kubectl get node <node> -o json`. */
180 readonly node: unknown;
181 /** `kubectl get pods -A -o json` (other nodes' pods are ignored). */
182 readonly pods: unknown;
183 /** The running forge pod, `namespace/name`. */
184 readonly forgePod: string;
185 /** Its steady memory in bytes (`kubectl top pod`, over a quiet minute). */
186 readonly steadyMemory: number;
187 readonly timing?: DarkTiming;
188 }
189
190 export interface Preflight {
191 readonly version: string;
192 readonly node: string;
193 readonly allocatable: Resources;
194 readonly requested: Resources;
195 readonly podsOnNode: number;
196 readonly free: Resources;
197 readonly forgeRequest: Resources;
198 readonly steadyMemory: number;
199 readonly need: Resources;
200 /** Would the scheduler place the surge pod at all (requests only)? */
201 readonly schedulable: boolean;
202 /** Would it place it *and* would both pods' steady memory fit? */
203 readonly fits: boolean;
204 /** What more must be free on this node for the roll to be zero-downtime. */
205 readonly shortfall: Resources;
206 /** If rolled dark anyway: typical and worst seconds without service. */
207 readonly darkSeconds: { readonly typical: number; readonly worst: number };
208 /** Names this roll under these numbers; the owner's yes quotes it. */
209 readonly rollId: string;
210 readonly timing: DarkTiming;
211 }
212
213 const VERSION = /^v?([0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,6}(?:-[0-9A-Za-z.-]{1,40})?)$/;
214 const POD = /^([a-z0-9]([-a-z0-9]{0,61}[a-z0-9])?)\/([a-z0-9]([-a-z0-9.]{0,251}[a-z0-9])?)$/;
215
216 /**
217 * A roll's name: the version and the node's numbers it was judged on. A yes
218 * for it is a yes for this release under this pressure, never the next
219 * release and never a standing yes.
220 */
221 export function rollId(p: {
222 version: string;
223 node: string;
224 free: Resources;
225 need: Resources;
226 }): string {
227 const mib = (n: number) => Math.round(n / 2 ** 20);
228 const text = JSON.stringify([
229 p.version,
230 p.node,
231 mib(p.free.memory),
232 p.free.milliCpu,
233 mib(p.need.memory),
234 p.need.milliCpu,
235 ]);
236 return createHash("sha256").update(text).digest("hex").slice(0, 12);
237 }
238
239 /** Decide. Throws on input that is not what `kubectl` prints. */
240 export function preflight(input: PreflightInput): Preflight {
241 const v = VERSION.exec(input.version.trim());
242 if (!v?.[1]) throw new Error(`version ${JSON.stringify(input.version)} is not x.y.z`);
243 const version = v[1];
244 const pod = POD.exec(input.forgePod.trim());
245 if (!pod) throw new Error(`forge pod ${JSON.stringify(input.forgePod)} is not namespace/name`);
246 const [ns, podName] = [pod[1], pod[3]];
247 if (!Number.isFinite(input.steadyMemory) || input.steadyMemory <= 0)
248 throw new Error("steady memory must be a positive quantity");
249 const timing = input.timing ?? DARK_TIMING;
250
251 const nodeName = obj(obj(input.node)["metadata"])["name"];
252 if (typeof nodeName !== "string" || nodeName === "")
253 throw new Error("node: no metadata.name — is it `kubectl get node -o json`?");
254 const allocatable = resources(
255 obj(obj(input.node)["status"])["allocatable"],
256 `node ${nodeName}`,
257 );
258 if (allocatable.memory <= 0 || allocatable.milliCpu <= 0)
259 throw new Error(`node ${nodeName}: no status.allocatable cpu and memory`);
260
261 const items = list(obj(input.pods)["items"]);
262 const forge = items.find((p) => {
263 const m = obj(obj(p)["metadata"]);
264 return m["namespace"] === ns && m["name"] === podName;
265 });
266 if (!forge) throw new Error(`pods: no ${ns}/${podName} in the list`);
267 if (obj(obj(forge)["spec"])["nodeName"] !== nodeName)
268 throw new Error(`${ns}/${podName} is not on node ${nodeName}: the volume's node is the one to judge`);
269
270 const onNode = items.filter((p) => holdsNode(p, nodeName));
271 const requested = onNode.reduce<Resources>((s, p) => add(s, podRequest(p)), ZERO);
272 const free = {
273 milliCpu: allocatable.milliCpu - requested.milliCpu,
274 memory: allocatable.memory - requested.memory,
275 };
276 const forgeRequest = podRequest(forge);
277 const need = {
278 milliCpu: forgeRequest.milliCpu,
279 memory: Math.max(forgeRequest.memory, input.steadyMemory),
280 };
281 const schedulable =
282 free.milliCpu >= forgeRequest.milliCpu && free.memory >= forgeRequest.memory;
283 const fits = free.milliCpu >= need.milliCpu && free.memory >= need.memory;
284 const shortfall = {
285 milliCpu: Math.max(0, need.milliCpu - free.milliCpu),
286 memory: Math.max(0, need.memory - free.memory),
287 };
288 return {
289 version,
290 node: nodeName,
291 allocatable,
292 requested,
293 podsOnNode: onNode.length,
294 free,
295 forgeRequest,
296 steadyMemory: input.steadyMemory,
297 need,
298 schedulable,
299 fits,
300 shortfall,
301 darkSeconds: {
302 typical: timing.drainSeconds + timing.startSeconds,
303 worst: timing.graceSeconds + timing.startCeilingSeconds,
304 },
305 rollId: rollId({ version, node: nodeName, free, need }),
306 timing,
307 };
308 }
309
310 /** What the agent may do: roll, or wait for the owner. */
311 export type Decision =
312 | { readonly go: true; readonly dark: false }
313 | { readonly go: true; readonly dark: true }
314 | { readonly go: false; readonly why: string };
315
316 /**
317 * A roll that fits goes. One that does not goes only with the owner's yes
318 * to exactly its id — a yes to another id (another release, or this one
319 * under other numbers) is no yes.
320 */
321 export function decide(p: Preflight, ownerYes: string | undefined): Decision {
322 if (p.fits) return { go: true, dark: false };
323 if (ownerYes !== undefined && ownerYes.trim() === p.rollId)
324 return { go: true, dark: true };
325 return {
326 go: false,
327 why:
328 ownerYes === undefined
329 ? "a second forge pod does not fit: waiting for the owner's yes to this roll"
330 : `the owner's yes names roll ${JSON.stringify(ownerYes.trim()).slice(0, 40)}, not ${p.rollId}`,
331 };
332 }
333
334 const gib = (n: number) => `${(n / 2 ** 30).toFixed(2)} GiB`;
335 const cores = (milli: number) => `${(milli / 1000).toFixed(2)} cpu`;
336
337 /** The report the agent posts to the owner, as plain lines. */
338 export function report(p: Preflight, d: Decision): string {
339 const row = (label: string, r: Resources, extra = "") =>
340 ` ${label.padEnd(20)}${gib(r.memory).padStart(11)} ${cores(r.milliCpu).padStart(10)}${extra}`;
341 const head = p.fits
342 ? `roll v${p.version} on ${p.node}: zero-downtime — a second forge pod fits`
343 : `roll v${p.version} on ${p.node}: DARK — a second forge pod does not fit` +
344 (p.schedulable ? " beside the first once both hold their steady memory" : "");
345 const lines = [
346 head,
347 row("node allocatable", p.allocatable),
348 row("requested now", p.requested, ` (${p.podsOnNode} pods)`),
349 row("free", p.free),
350 row(
351 "surge pod needs",
352 p.need,
353 ` (request ${gib(p.forgeRequest.memory)}, steady ${gib(p.steadyMemory)})`,
354 ),
355 ];
356 if (!p.fits) {
357 const t = p.timing;
358 lines.push(
359 row("short by", p.shortfall),
360 ` dark for about ${p.darkSeconds.typical} s (drain ${t.drainSeconds} s + start ${t.startSeconds} s), at most ${p.darkSeconds.worst} s`,
361 ` zero-downtime needs ${gib(p.shortfall.memory)} and ${cores(p.shortfall.milliCpu)} more free on ${p.node}` +
362 " (a larger node, or fewer requests on this one)",
363 ` roll id ${p.rollId}`,
364 );
365 }
366 if (d.go && d.dark)
367 lines.push(`rolling dark: the owner said yes to roll ${p.rollId}`);
368 else if (d.go) lines.push("rolling");
369 else lines.push(`not rolling: ${d.why}`);
370 return lines.join("\n");
371 }
372
373 /**
374 * Lines of a manifest or values file that make no-surge a standing value:
375 * `maxSurge: 0` (or `0%`) or `type: Recreate`. A dark roll the owner said
376 * yes to is a one-off patch, undone after the roll; it never lives in the
377 * chart or the gitops overlay.
378 */
379 export function standingNoSurge(text: string): string[] {
380 const found: string[] = [];
381 for (const line of text.split("\n")) {
382 const code = line.replace(/#.*$/, "");
383 if (
384 /\bmaxSurge["']?\s*[:=]\s*["']?0+%?["']?(?![0-9.%])/.test(code) ||
385 /\btype["']?\s*:\s*["']?Recreate\b/.test(code)
386 )
387 found.push(line.trim());
388 }
389 return found;
390 }
test/capacity.test.ts +17
@@ -21,6 +21,7 @@ import { enableApp } from "../src/actions/apps.ts";
2121 import { AppsRuntime } from "../src/apps/runtime.ts";
2222 import { startChecks, type ChecksHandle } from "../src/checks/service.ts";
2323 import {
24 CAPACITY,
2425 capacityChanges,
2526 capacityCount,
2627 noteBooted,
@@ -39,6 +40,22 @@ import { EGRESS_REPORTED } from "../src/kernel/vitals.ts";
3940 import { serve, type Servers } from "../src/http/server.ts";
4041 import { readRunLog } from "../src/runs/log.ts";
4142
43 // The boot defaults these tests expect are the fallbacks, so the
44 // environment they run in must not say otherwise: the forge's own check
45 // runs with FORGE_CHECK_SHARDS=2, which would be the shard default here.
46 const saved = new Map<string, string | undefined>();
47 beforeAll(() => {
48 for (const { env } of Object.values(CAPACITY)) {
49 saved.set(env, process.env[env]);
50 delete process.env[env];
51 }
52 });
53 afterAll(() => {
54 for (const [env, value] of saved)
55 if (value === undefined) delete process.env[env];
56 else process.env[env] = value;
57 });
58
4259 describe("capacity: only a forge admin reads or changes it", () => {
4360 let dataDir: string;
4461 let app: App;
test/roll.test.ts added +289
@@ -0,0 +1,289 @@
1 /**
2 * The roll gate (#876): a release that would go dark does not roll unless
3 * the owner said yes to that roll, and no-surge is never a standing value.
4 * Every number below is worked by hand in the comment beside it.
5 */
6
7 import { describe, expect, test } from "bun:test";
8 import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { run } from "../scripts/roll-preflight.ts";
12 import {
13 DARK_TIMING,
14 decide,
15 parseQuantity,
16 podRequest,
17 preflight,
18 report,
19 standingNoSurge,
20 } from "../scripts/roll.ts";
21
22 const Mi = 2 ** 20;
23
24 const container = (cpu: string, memory: string) => ({
25 name: "c",
26 resources: { requests: { cpu, memory } },
27 });
28
29 function pod(
30 ns: string,
31 name: string,
32 spec: Record<string, unknown>,
33 phase = "Running",
34 nodeName = "droplet",
35 ) {
36 return {
37 metadata: { namespace: ns, name },
38 spec: { nodeName, ...spec },
39 status: { phase },
40 };
41 }
42
43 // Requests on node "droplet" (Running and Pending pods only):
44 // forge 1 cpu 2048 Mi
45 // two-box 1.5 cpu 3072 Mi (1000m/2Gi + 500m/1Gi)
46 // init-heavy 0.5 cpu 512 Mi (max(init 500m/512Mi, main 100m/256Mi))
47 // overhead 0.1 cpu 128 Mi (no container requests, runtime overhead)
48 // ─────────────────────────────────
49 // requested 3.1 cpu 5760 Mi
50 // Not counted: a Succeeded job (4 Gi) and a pod on another node (4 Gi).
51 const PODS = {
52 items: [
53 pod("forge", "forge-abc", { containers: [container("1", "2Gi")] }),
54 pod("db", "two-box", {
55 containers: [container("1000m", "2Gi"), container("500m", "1Gi")],
56 }),
57 pod("ops", "init-heavy", {
58 initContainers: [container("500m", "512Mi")],
59 containers: [container("100m", "256Mi")],
60 }),
61 pod("ops", "overhead", {
62 containers: [{ name: "c" }],
63 overhead: { cpu: "100m", memory: "128Mi" },
64 }),
65 pod("ops", "done-job", { containers: [container("1", "4Gi")] }, "Succeeded"),
66 pod("ops", "elsewhere", { containers: [container("1", "4Gi")] }, "Running", "other"),
67 ],
68 };
69
70 const node = (cpu: string, memory: string) => ({
71 metadata: { name: "droplet" },
72 status: { allocatable: { cpu, memory } },
73 });
74
75 const STEADY = 3712 * Mi; // 3.625 GiB, what the forge holds once warm
76
77 function judge(cpu: string, memory: string, version = "0.7.53") {
78 return preflight({
79 version,
80 node: node(cpu, memory),
81 pods: PODS,
82 forgePod: "forge/forge-abc",
83 steadyMemory: STEADY,
84 });
85 }
86
87 describe("quantities", () => {
88 test("parse as kubectl prints them", () => {
89 expect(parseQuantity("8130464Ki")).toBe(8130464 * 1024);
90 expect(parseQuantity("2Gi")).toBe(2 * 2 ** 30);
91 expect(parseQuantity("1G")).toBe(1e9);
92 expect(parseQuantity("500m")).toBe(0.5);
93 expect(parseQuantity("1.5")).toBe(1.5);
94 expect(parseQuantity("12e6")).toBe(12e6);
95 expect(parseQuantity("250000n")).toBeCloseTo(0.00025, 12);
96 });
97 test("refuse what is not a quantity", () => {
98 for (const bad of ["", "Gi", "2 Gi", "-1", "1Zi", "1e", "0x10", "1Gi;rm"])
99 expect(parseQuantity(bad)).toBeNull();
100 expect(parseQuantity(5)).toBeNull();
101 });
102 });
103
104 describe("a pod's request, as the scheduler reckons it", () => {
105 test("init floor, sidecars summed, overhead added", () => {
106 // sidecar 100m/64Mi runs throughout; plain init 2 cpu/1Gi runs after it,
107 // so its floor is 2.1 cpu / 1088 Mi; containers + sidecar = 0.6 / 576 Mi.
108 // max → 2.1 cpu / 1088 Mi, + overhead 50m/32Mi → 2.15 cpu / 1120 Mi.
109 const r = podRequest(
110 pod("x", "y", {
111 initContainers: [
112 { ...container("100m", "64Mi"), restartPolicy: "Always" },
113 container("2", "1Gi"),
114 ],
115 containers: [container("500m", "512Mi")],
116 overhead: { cpu: "50m", memory: "32Mi" },
117 }),
118 );
119 expect(r.milliCpu).toBe(2150);
120 expect(r.memory).toBe(1120 * Mi);
121 });
122 });
123
124 describe("preflight", () => {
125 test("the 8 GB droplet: dark, with the shortfall and the seconds", () => {
126 // allocatable 3.9 cpu / 7680 Mi − requested 3.1 / 5760 → free 0.8 / 1920 Mi
127 // need: cpu 1, memory max(2048, 3712) = 3712 Mi
128 // short: 0.2 cpu, 3712 − 1920 = 1792 Mi = 1.75 GiB
129 const p = judge("3900m", "7680Mi");
130 expect(p.podsOnNode).toBe(4);
131 expect(p.requested.milliCpu).toBe(3100);
132 expect(p.requested.memory).toBe(5760 * Mi);
133 expect(p.free.milliCpu).toBe(800);
134 expect(p.free.memory).toBe(1920 * Mi);
135 expect(p.need).toEqual({ milliCpu: 1000, memory: 3712 * Mi });
136 expect(p.schedulable).toBe(false);
137 expect(p.fits).toBe(false);
138 expect(p.shortfall.milliCpu).toBe(200);
139 expect(p.shortfall.memory).toBe(1792 * Mi);
140 // 180 s drain + 35 s start; worst 300 s grace + 3 s × 60 + 5 s
141 expect(p.darkSeconds).toEqual({ typical: 215, worst: 485 });
142 const text = report(p, decide(p, undefined));
143 expect(text).toContain("DARK");
144 expect(text).toContain("1.75 GiB");
145 expect(text).toContain("about 215 s");
146 expect(text).toContain(p.rollId);
147 expect(text).toContain("not rolling");
148 });
149
150 test("schedulable on requests is not enough: steady memory decides", () => {
151 // allocatable 4.1 cpu / 8704 Mi → free 1.0 / 2944 Mi: the request
152 // (1 / 2048) fits, the steady 3712 Mi does not: short 768 Mi = 0.75 GiB
153 const p = judge("4100m", "8704Mi");
154 expect(p.schedulable).toBe(true);
155 expect(p.fits).toBe(false);
156 expect(p.shortfall).toEqual({ milliCpu: 0, memory: 768 * Mi });
157 expect(decide(p, undefined).go).toBe(false);
158 });
159
160 test("room for two pods rolls without asking", () => {
161 // 16 Gi / 8 cpu → free 10624 Mi / 4.9 cpu ≥ 3712 Mi / 1 cpu
162 const p = judge("8", "16Gi");
163 expect(p.fits).toBe(true);
164 expect(p.shortfall).toEqual({ milliCpu: 0, memory: 0 });
165 expect(decide(p, undefined)).toEqual({ go: true, dark: false });
166 expect(report(p, decide(p, undefined))).toContain("zero-downtime");
167 });
168
169 test("the owner's yes covers that roll and no other", () => {
170 const p = judge("3900m", "7680Mi");
171 expect(decide(p, p.rollId)).toEqual({ go: true, dark: true });
172 // the next release under the same pressure is a new roll
173 const next = judge("3900m", "7680Mi", "0.7.54");
174 expect(next.rollId).not.toBe(p.rollId);
175 expect(decide(next, p.rollId).go).toBe(false);
176 // so is this release once the node's numbers move
177 const moved = judge("3900m", "7000Mi");
178 expect(decide(moved, p.rollId).go).toBe(false);
179 // a blanket word is no yes
180 for (const word of ["yes", "", "*", "true"]) expect(decide(p, word).go).toBe(false);
181 // and judging the same numbers again names the same roll
182 expect(judge("3900m", "7680Mi", "v0.7.53").rollId).toBe(p.rollId);
183 });
184
185 test("input that is not kubectl's is refused, not guessed", () => {
186 expect(() => judge("3900m", "7680Mi", "latest")).toThrow(/version/);
187 expect(() =>
188 preflight({ version: "0.7.53", node: node("4", "8Gi"), pods: PODS, forgePod: "forge/nope", steadyMemory: STEADY }),
189 ).toThrow(/no forge\/nope/);
190 expect(() =>
191 preflight({ version: "0.7.53", node: node("4", "8Gi"), pods: PODS, forgePod: "ops/elsewhere", steadyMemory: STEADY }),
192 ).toThrow(/not on node/);
193 expect(() =>
194 preflight({ version: "0.7.53", node: {}, pods: PODS, forgePod: "forge/forge-abc", steadyMemory: STEADY }),
195 ).toThrow(/metadata.name/);
196 expect(() =>
197 preflight({ version: "0.7.53", node: node("4", "lots"), pods: PODS, forgePod: "forge/forge-abc", steadyMemory: STEADY }),
198 ).toThrow(/not a quantity/);
199 });
200 });
201
202 describe("no-surge is never a standing value", () => {
203 test("found where it is written", () => {
204 expect(standingNoSurge(" maxSurge: 0")).toHaveLength(1);
205 expect(standingNoSurge(`maxSurge: "0%"`)).toHaveLength(1);
206 expect(standingNoSurge("rollingUpdate: {maxSurge: 0, maxUnavailable: 1}")).toHaveLength(1);
207 expect(standingNoSurge(`{"maxSurge":0}`)).toHaveLength(1);
208 expect(standingNoSurge(" type: Recreate")).toHaveLength(1);
209 expect(standingNoSurge("maxSurge: 1\nmaxSurge: 10\nmaxSurge: 25%\n# maxSurge: 0")).toEqual([]);
210 });
211
212 const deployment = readFileSync(
213 join(import.meta.dir, "../charts/app/templates/deployment.yaml"),
214 "utf8",
215 );
216
217 test("the chart surges one and never takes the only pod down", () => {
218 expect(standingNoSurge(deployment)).toEqual([]);
219 expect(
220 standingNoSurge(readFileSync(join(import.meta.dir, "../charts/app/values.yaml"), "utf8")),
221 ).toEqual([]);
222 expect(deployment).toMatch(/maxSurge: 1\n\s*maxUnavailable: 0\n/);
223 });
224
225 test("the dark-seconds ceilings are the chart's own", () => {
226 const n = (re: RegExp) => Number(re.exec(deployment)?.[1]);
227 expect(n(/terminationGracePeriodSeconds: (\d+)/)).toBe(DARK_TIMING.graceSeconds);
228 const startup = /startupProbe:[\s\S]*?periodSeconds: (\d+)\s*\n\s*failureThreshold: (\d+)/.exec(deployment);
229 const readiness = n(/readinessProbe:[\s\S]*?periodSeconds: (\d+)/);
230 expect(Number(startup?.[1]) * Number(startup?.[2]) + readiness).toBe(
231 DARK_TIMING.startCeilingSeconds,
232 );
233 });
234 });
235
236 describe("the gate the release agent runs", () => {
237 const dir = mkdtempSync(join(tmpdir(), "roll-"));
238 const file = (name: string, body: unknown) => {
239 const path = join(dir, name);
240 writeFileSync(path, typeof body === "string" ? body : JSON.stringify(body));
241 return path;
242 };
243 const tight = file("node.json", node("3900m", "7680Mi"));
244 const roomy = file("roomy.json", node("8", "16Gi"));
245 const pods = file("pods.json", PODS);
246 const args = (n: string) => [
247 "--version", "0.7.53", "--node", n, "--pods", pods,
248 "--pod", "forge/forge-abc", "--steady", "3712Mi",
249 ];
250
251 test("exits 3 and waits when the roll would go dark", () => {
252 const r = run(args(tight));
253 expect(r.code).toBe(3);
254 expect(r.out).toContain("waiting for the owner's yes");
255 });
256
257 test("exits 0 with the owner's yes to this roll id", () => {
258 const id = judge("3900m", "7680Mi").rollId;
259 const r = run([...args(tight), "--yes", id]);
260 expect(r.code).toBe(0);
261 expect(r.out).toContain(`the owner said yes to roll ${id}`);
262 expect(run([...args(tight), "--yes", "0123456789ab"]).code).toBe(3);
263 });
264
265 test("exits 0 when there is room", () => {
266 expect(run(args(roomy)).code).toBe(0);
267 });
268
269 test("measured timings replace the defaults", () => {
270 const r = run([...args(tight), "--json", "--drain-seconds", "20", "--start-seconds", "40"]);
271 expect(r.code).toBe(3);
272 expect(JSON.parse(r.out).darkSeconds.typical).toBe(60);
273 });
274
275 test("exits 4 when an overlay carries no-surge, even with room", () => {
276 const overlay = file("hr.yaml", "spec:\n strategy:\n rollingUpdate:\n maxSurge: 0\n");
277 const r = run([...args(roomy), "--overlay", overlay]);
278 expect(r.code).toBe(4);
279 expect(r.out).toContain("maxSurge: 0");
280 });
281
282 test("exits 2 on input it does not understand", () => {
283 expect(run([...args(tight), "--force"]).code).toBe(2);
284 expect(run(args(tight).slice(2)).code).toBe(2);
285 expect(run([...args(tight).slice(0, -1), "lots"]).code).toBe(2);
286 expect(run([...args(tight), "--drain-seconds", "-5"]).code).toBe(2);
287 expect(run([...args(tight), "--overlay", join(dir, "missing.yaml")]).code).toBe(2);
288 });
289 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs