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

A check cell's declared memory is never silently clamped: forge.json says 8192, the cell enforced 4096 #3129

Parked opened this in answer to
Closed without merging

torque/forge:torque/3128-a-check-cell-s-declared-memory-is-never → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +703 −26
README.md +6
@@ -868,6 +868,12 @@ environment. Browsers resolve `*.localhost` to loopback, so a laptop forge
868868 needs no DNS at all; elsewhere point a wildcard at it and set
869869 `FORGE_APP_DOMAIN`.
870870
871 A `limits` block in `forge.json` (`app.limits`, `check.limits`) that asks
872 for more than the forge gives a cell is lowered to the forge's ceiling and
873 said where you look: one line under About on the repository's settings, the
874 terminal's About card (`I`), and a `warning:` line at the top of the check's
875 log ([docs/APPS.md](docs/APPS.md), #3128).
876
871877 The forge pill on an app's pages says where you are: its accessible name reads
872878 `notes, production` or `notes, preview of pull #7`, and pressing it opens a
873879 panel with the app, the environment, and a link home. The pull's title is shown
docs/APPS.md +17 −5
@@ -257,9 +257,20 @@ and 443 — `db.example.com:5432` names one other port instead. Without it an ap
257257 reaches the forge and nothing else; install, test and check steps also
258258 reach `registry.npmjs.org`. `limits` (MiB, cores, MiB) default to 512 MiB,
259259 1 core and 1 GiB for an app and 2 GiB, 2 cores and 4 GiB for a step, and
260 are capped by the machine (`FORGE_CELL_MEMORY_MAX_MIB`, default 4096; the
261 number of cores; `FORGE_CELL_DISK_MAX_MIB`, default 16384). A cell's `/tmp`
262 holds at most 256 MiB.
260 are capped by the machine: `FORGE_CELL_MEMORY_MAX_MIB`, by default 75% of
261 the pod's cgroup `memory.max` (or of the machine's memory where there is
262 none); the number of cores; `FORGE_CELL_DISK_MAX_MIB`, default 16384.
263
264 A declaration over a cap is lowered, never silently (#3128). The check's
265 log opens with a `warning:` line naming the field, the cap and where the
266 cap is set. The repository's settings say it in one line under the About
267 card, and so does the terminal's About card (`I`). `/system` shows the
268 memory cap. A cell stopped over a limit says which limit and where it is
269 set, and that is the check's summary: `over its 4096 MiB limit (set by
270 FORGE_CELL_MEMORY_MAX_MIB, the forge's ceiling; forge.json
271 check.limits.memory asks for 8192)`.
272
273 A cell's `/tmp` holds at most 256 MiB.
263274
264275 Memory is held twice. The watch reads every cell's resident memory once a
265276 second and stops one over its limit. Where the forge holds a delegated
@@ -267,8 +278,9 @@ cgroup v2 (`apps/cgroup.ts`), the kernel holds it as well: each cell runs
267278 in `<R>/cells/c<n>-<pid>` with `memory.max` set to its limit,
268279 `memory.swap.max` 0 and `memory.oom.group` 1, and the forge moves itself
269280 to `<R>/forge`. A check that allocates past its cap faster than a tick is
270 then OOM-killed alone (`check stopped: it reached its 8192 MiB memory cap,
271 and the kernel killed it`), never the forge or the other checks (#2410).
281 then OOM-killed alone (`check stopped: it reached its 8192 MiB memory cap
282 (set by forge.json check.limits.memory), and the kernel killed it`), never
283 the forge or the other checks (#2410).
272284 `R` is `/sys/fs/cgroup` when the forge is at its container's cgroup
273285 namespace root, or `FORGE_CELL_CGROUP` (a path, or `off`). The cgroup has to
274286 be writable by the forge's user. A container's `/sys/fs/cgroup` is
src/apps/contain.ts +202 −13
@@ -33,7 +33,7 @@ import {
3333 rmSync,
3434 statSync,
3535 } from "node:fs";
36 import { availableParallelism, tmpdir } from "node:os";
36 import { availableParallelism, tmpdir, totalmem } from "node:os";
3737 import { dirname, join } from "node:path";
3838 import { portInsteadOfSocket } from "../git/hook-address.ts";
3939 import { relay, startEgress, type Egress } from "./egress.ts";
@@ -46,10 +46,21 @@ export interface Limits {
4646 readonly cpus: number;
4747 /** Bytes on disk under the cell's writable directories, MiB. */
4848 readonly diskMiB: number;
49 /**
50 * Where each limit was set, in words a breach can quote (`resolveLimits`):
51 * the default, `forge.json`, or the machine's ceiling over a declaration.
52 */
53 readonly from?: LimitsFrom | undefined;
54 }
55
56 export interface LimitsFrom {
57 readonly memoryMiB: string;
58 readonly cpus: string;
59 readonly diskMiB: string;
4960 }
5061
5162 /** What `forge.json` may ask for (`app.limits`, `check.limits`). */
52 export type DeclaredLimits = Partial<Limits>;
63 export type DeclaredLimits = Partial<Omit<Limits, "from">>;
5364
5465 /** A long-lived app, and a step (install, test, check) that ends. */
5566 export const DEFAULT_LIMITS: Record<"app" | "step", Limits> = {
@@ -57,31 +68,205 @@ export const DEFAULT_LIMITS: Record<"app" | "step", Limits> = {
5768 step: { memoryMiB: 2048, cpus: 2, diskMiB: 4096 },
5869 };
5970
71 /** The most any declaration gets on this machine, and where each ceiling comes from. */
72 export interface Ceilings {
73 readonly memoryMiB: number;
74 readonly cpus: number;
75 readonly diskMiB: number;
76 readonly from: LimitsFrom;
77 }
78
79 /**
80 * The share of the host's memory one cell may be given when no operator
81 * set `FORGE_CELL_MEMORY_MAX_MIB`: the rest is the forge's own and its
82 * neighbours'. A fixed number here once killed checks that declared what
83 * the pod could give (#3128).
84 */
85 export const MEMORY_SHARE = 3 / 4;
86
87 const MIB = 1024 * 1024;
88
6089 /** The most any declaration gets on this machine. */
61 export function maxLimits(): Limits {
90 export function maxLimits(): Ceilings {
91 const memory = memoryCeiling();
92 const disk = positive(process.env["FORGE_CELL_DISK_MAX_MIB"]);
6293 return {
63 memoryMiB: positive(process.env["FORGE_CELL_MEMORY_MAX_MIB"]) ?? 4096,
94 memoryMiB: memory.mib,
6495 cpus: availableParallelism(),
65 diskMiB: positive(process.env["FORGE_CELL_DISK_MAX_MIB"]) ?? 16384,
96 diskMiB: disk ?? 16384,
97 from: {
98 memoryMiB: memory.from,
99 cpus: "the machine's core count",
100 diskMiB:
101 disk === undefined ? "the forge's 16384 MiB default" : "FORGE_CELL_DISK_MAX_MIB",
102 },
66103 };
67104 }
68105
106 /**
107 * A cell's memory ceiling, MiB, and where it comes from: the operator's
108 * `FORGE_CELL_MEMORY_MAX_MIB` when set, else `MEMORY_SHARE` of what the
109 * host can give — the pod's cgroup `memory.max` when it has one, the
110 * machine's memory when it has none.
111 */
112 export function memoryCeiling(
113 env: string | undefined = process.env["FORGE_CELL_MEMORY_MAX_MIB"],
114 host: { podBytes: number | undefined; machineBytes: number } = {
115 podBytes: podMemoryMax(),
116 machineBytes: totalmem(),
117 },
118 ): { mib: number; from: string } {
119 const set = positive(env);
120 if (set !== undefined) return { mib: set, from: "FORGE_CELL_MEMORY_MAX_MIB" };
121 const [bytes, whose] =
122 host.podBytes === undefined
123 ? [host.machineBytes, "the machine's memory"]
124 : [host.podBytes, "the pod's memory.max"];
125 const share = MEMORY_SHARE * 100;
126 return {
127 mib: Math.max(64, Math.floor((bytes * MEMORY_SHARE) / MIB)),
128 from: `${share}% of ${whose} (${Math.floor(bytes / MIB)} MiB)`,
129 };
130 }
131
132 let pod: { bytes: number | undefined } | undefined;
133
134 /** The pod's memory limit, read once (`podMemoryLimit`) until `forgetPodMemory`. */
135 function podMemoryMax(): number | undefined {
136 pod ??= { bytes: podMemoryLimit() };
137 return pod.bytes;
138 }
139
140 /** Read the pod's memory limit again on next use: for a test, or a pod resized in place. */
141 export function forgetPodMemory(): void {
142 pod = undefined;
143 }
144
145 /**
146 * The tightest `memory.max` between the forge's cgroup and the root of
147 * its cgroup namespace, bytes: the pod's limit, whichever level holds it
148 * (`apps/cgroup.ts` moves the forge into a `forge/` leaf whose own is
149 * `max`). `undefined` when no level sets one, or there is no cgroup v2.
150 */
151 export function podMemoryLimit(
152 read: (path: string) => string | undefined = readOrUndefined,
153 ): number | undefined {
154 const self = read("/proc/self/cgroup");
155 const line = self?.split("\n").find((l) => l.startsWith("0::"));
156 if (line === undefined) return undefined;
157 const parts = line.slice(3).trim().split("/").filter((p) => p !== "" && p !== "..");
158 let least: number | undefined;
159 for (let depth = parts.length; depth >= 0; depth--) {
160 const dir = ["/sys/fs/cgroup", ...parts.slice(0, depth)].join("/");
161 const n = Number(read(`${dir}/memory.max`)?.trim());
162 if (Number.isFinite(n) && n > 0 && (least === undefined || n < least)) least = n;
163 }
164 return least;
165 }
166
167 function readOrUndefined(path: string): string | undefined {
168 try {
169 return readFileSync(path, "utf8");
170 } catch {
171 return undefined;
172 }
173 }
174
69175 function positive(raw: string | undefined): number | undefined {
70176 const n = Number(raw);
71177 return Number.isFinite(n) && n > 0 ? n : undefined;
72178 }
73179
180 const FIELDS = [
181 { key: "memoryMiB", name: "memory", unit: " MiB" },
182 { key: "cpus", name: "cpus", unit: " cores" },
183 { key: "diskMiB", name: "disk", unit: " MiB" },
184 ] as const;
185
186 /** A declaration the machine's ceiling lowered: never silent (#3128). */
187 export interface Clamp {
188 /** The `forge.json` field: `check.limits.memory`. */
189 readonly field: string;
190 readonly declared: number;
191 readonly ceiling: number;
192 readonly unit: string;
193 /** Where the ceiling is set: `FORGE_CELL_MEMORY_MAX_MIB`, or the host's share. */
194 readonly from: string;
195 }
196
197 /** `forge.json`'s name for where `kind`'s limits are declared. */
198 const section = (kind: "app" | "step"): string => (kind === "app" ? "app.limits" : "check.limits");
199
200 /** Every declared limit over the machine's ceiling, as it will be lowered. */
201 export function limitClamps(
202 kind: "app" | "step",
203 declared: DeclaredLimits | undefined,
204 max: Ceilings = maxLimits(),
205 ): Clamp[] {
206 const out: Clamp[] = [];
207 for (const f of FIELDS) {
208 const asked = declared?.[f.key];
209 if (asked !== undefined && asked > max[f.key])
210 out.push({
211 field: `${section(kind)}.${f.name}`,
212 declared: asked,
213 ceiling: max[f.key],
214 unit: f.unit,
215 from: max.from[f.key],
216 });
217 }
218 return out;
219 }
220
221 /** One clamp as the warning line a check's log and a settings page show. */
222 export function clampWords(c: Clamp): string {
223 const ceiling = `${c.ceiling}${c.unit}`;
224 return (
225 `forge.json ${c.field} asks for ${c.declared}${c.unit}, ` +
226 `over this forge's ceiling of ${ceiling} (${c.from}); the cell gets ${ceiling}`
227 );
228 }
229
74230 /** The defaults for `kind`, raised or lowered by a declaration, never past the machine's maximum. */
75231 export function resolveLimits(
76232 kind: "app" | "step",
77233 declared: DeclaredLimits | undefined,
234 max: Ceilings = maxLimits(),
78235 ): Limits {
79236 const base = DEFAULT_LIMITS[kind];
80 const max = maxLimits();
237 const value: Record<keyof LimitsFrom, number> = {
238 memoryMiB: base.memoryMiB,
239 cpus: base.cpus,
240 diskMiB: base.diskMiB,
241 };
242 const from: Record<keyof LimitsFrom, string> = {
243 memoryMiB: "",
244 cpus: "",
245 diskMiB: "",
246 };
247 for (const f of FIELDS) {
248 const asked = declared?.[f.key];
249 const field = `forge.json ${section(kind)}.${f.name}`;
250 if (asked !== undefined && asked > max[f.key]) {
251 value[f.key] = max[f.key];
252 from[f.key] =
253 `set by ${max.from[f.key]}, the forge's ceiling; ${field} asks for ${asked}`;
254 } else if (asked !== undefined) {
255 value[f.key] = asked;
256 from[f.key] = `set by ${field}`;
257 } else if (base[f.key] > max[f.key]) {
258 value[f.key] = max[f.key];
259 from[f.key] = `set by ${max.from[f.key]}, the forge's ceiling`;
260 } else {
261 const whose = kind === "app" ? "an app" : "a step";
262 from[f.key] = `the forge's default for ${whose}; ${field} raises it`;
263 }
264 }
81265 return {
82 memoryMiB: Math.min(declared?.memoryMiB ?? base.memoryMiB, max.memoryMiB),
83 cpus: Math.min(declared?.cpus ?? base.cpus, max.cpus),
84 diskMiB: Math.min(declared?.diskMiB ?? base.diskMiB, max.diskMiB),
266 memoryMiB: value.memoryMiB,
267 cpus: value.cpus,
268 diskMiB: value.diskMiB,
269 from,
85270 };
86271 }
87272
@@ -376,7 +561,7 @@ export function openCell(
376561 // The kernel's kill leaves no watch tick behind: its count is the reason.
377562 const killed = (): string | undefined =>
378563 cgroup !== undefined && cgroup.oomKills() > 0
379 ? `reached its ${spec.limits.memoryMiB} MiB memory cap, and the kernel killed it`
564 ? `reached its ${spec.limits.memoryMiB} MiB memory cap${setBy(spec.limits.from?.memoryMiB)}, and the kernel killed it`
380565 : undefined;
381566 const watch = (pid: number, stop: (why: string) => void): void => {
382567 const cap: MemoryCap =
@@ -790,6 +975,10 @@ export function diskBytes(dirs: readonly string[]): number {
790975 return total;
791976 }
792977
978 /** ` (set by …)`: which limit stopped a cell and where it is set, when known. */
979 const setBy = (from: string | undefined): string =>
980 from === undefined ? "" : ` (${from})`;
981
793982 const mib = (bytes: number): string => `${Math.round(bytes / 1024 / 1024)} MiB`;
794983
795984 function tick(): void {
@@ -821,7 +1010,7 @@ function tick(): void {
8211010 entry.last = { ticks, kib };
8221011 if (kib > limits.memoryMiB * 1024) {
8231012 entry.breach(
824 `used ${mib(kib * 1024)} of memory, over its ${limits.memoryMiB} MiB limit`,
1013 `used ${mib(kib * 1024)} of memory, over its ${limits.memoryMiB} MiB limit${setBy(limits.from?.memoryMiB)}`,
8251014 );
8261015 continue;
8271016 }
@@ -837,7 +1026,7 @@ function tick(): void {
8371026 (ticks - oldest.ticks) / CLK_TCK / ((now - oldest.at) / 1000);
8381027 if (cores > limits.cpus) {
8391028 entry.breach(
840 `used ${cores.toFixed(1)} cores for ${Math.round((now - oldest.at) / 1000)}s, over its limit of ${limits.cpus}`,
1029 `used ${cores.toFixed(1)} cores for ${Math.round((now - oldest.at) / 1000)}s, over its limit of ${limits.cpus}${setBy(limits.from?.cpus)}`,
8411030 );
8421031 continue;
8431032 }
@@ -847,7 +1036,7 @@ function tick(): void {
8471036 const bytes = diskBytes(entry.writable);
8481037 if (bytes > limits.diskMiB * 1024 * 1024)
8491038 entry.breach(
850 `wrote ${mib(bytes)} to disk, over its ${limits.diskMiB} MiB limit`,
1039 `wrote ${mib(bytes)} to disk, over its ${limits.diskMiB} MiB limit${setBy(limits.from?.diskMiB)}`,
8511040 );
8521041 }
8531042 }
src/apps/declared_limits.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * What a commit's `forge.json` asks of its cells that this machine will
3 * not give: every `app.limits` and `check.limits` field over the ceiling
4 * (`apps/contain.ts` `limitClamps`). Read for the repository's settings
5 * and the terminal's About card, so a declaration lowered by the forge is
6 * seen before a check dies under it (#3128). A manifest that does not
7 * parse declares nothing here; the check and the deploy say why.
8 */
9
10 import { readFileAt } from "./checkout.ts";
11 import {
12 limitClamps,
13 maxLimits,
14 type Ceilings,
15 type Clamp,
16 type DeclaredLimits,
17 } from "./contain.ts";
18 import { parseCheck, parseManifest } from "./manifest.ts";
19
20 /** What one `forge.json` declares, per section; `undefined` where it declares none. */
21 export interface Declared {
22 readonly app: DeclaredLimits | undefined;
23 readonly check: DeclaredLimits | undefined;
24 }
25
26 /** The limits `forgeJson` declares, read as the deploy and the check read them. */
27 export function declaredLimits(
28 forgeJson: string | undefined,
29 packageJson: string | undefined,
30 ): Declared {
31 if (forgeJson === undefined) return { app: undefined, check: undefined };
32 const app = parseManifest(forgeJson, packageJson);
33 const check = parseCheck(forgeJson, packageJson);
34 return {
35 app: app.ok ? app.value.limits : undefined,
36 check: check.ok ? check.value?.limits : undefined,
37 };
38 }
39
40 /** Every declared limit the ceilings lower. */
41 export function declaredClamps(
42 declared: Declared,
43 max: Ceilings = maxLimits(),
44 ): Clamp[] {
45 return [
46 ...limitClamps("app", declared.app, max),
47 ...limitClamps("step", declared.check, max),
48 ];
49 }
50
51 /** One line for both doors, the settings page and the terminal; `""` when nothing is lowered. */
52 export function clampsLine(clamps: readonly Clamp[]): string {
53 if (clamps.length === 0) return "";
54 const each = clamps.map(
55 (c) =>
56 `forge.json ${c.field} asks for ${c.declared}${c.unit}, gets ${c.ceiling}${c.unit} (${c.from})`,
57 );
58 return `Lowered to this forge's ceiling: ${each.join("; ")}.`;
59 }
60
61 /** A commit's declarations never change: read once per commit, a few hundred kept. */
62 const CACHE_MAX = 256;
63 const cache = new Map<string, Declared>();
64
65 /** `declaredLimits` of the commit `oid` in the bare repository `dir`, cached by commit. */
66 export async function declaredAt(dir: string, oid: string): Promise<Declared> {
67 const key = `${dir}\0${oid}`;
68 const hit = cache.get(key);
69 if (hit !== undefined) return hit;
70 const [forgeJson, packageJson] = await Promise.all([
71 readFileAt(dir, oid, "forge.json"),
72 readFileAt(dir, oid, "package.json"),
73 ]);
74 const declared = declaredLimits(forgeJson, packageJson);
75 if (cache.size >= CACHE_MAX) cache.delete(cache.keys().next().value!);
76 cache.set(key, declared);
77 return declared;
78 }
79
80 /** `clampsLine` for the commit `oid`: the ceilings are read now, the declaration from cache. */
81 export async function clampsLineAt(dir: string, oid: string): Promise<string> {
82 return clampsLine(declaredClamps(await declaredAt(dir, oid)));
83 }
src/apps/process.ts +5
@@ -241,6 +241,11 @@ export function signalGroup(leader: number, signal: NodeJS.Signals): void {
241241 }
242242 }
243243
244 /** Whether `runStep`'s error for step `name` is its cell stopping it over a limit. */
245 export function cellStopped(name: string, error: string): boolean {
246 return error.startsWith(`${name} stopped: it `);
247 }
248
244249 /**
245250 * Run a step to completion, streaming its output. A non-zero exit, a
246251 * timeout, or an abort is an Err with the reason a person would want.
src/checks/service.ts +11 −1
@@ -64,7 +64,7 @@ import { exportTree, readFileAt } from "../apps/checkout.ts";
6464 import { parseCheck } from "../apps/manifest.ts";
6565 import { workerCpus } from "../core/capacity.ts";
6666 import { accountActive } from "../core/accounts.ts";
67 import { childEnv, runStep } from "../apps/process.ts";
67 import { cellStopped, childEnv, runStep } from "../apps/process.ts";
6868 import { noteReached } from "../apps/egress_report.ts";
6969 import {
7070 capacityCount,
@@ -75,6 +75,8 @@ import {
7575 } from "../core/capacity.ts";
7676 import {
7777 cellsAvailable,
78 clampWords,
79 limitClamps,
7880 resolveLimits,
7981 STEP_HOSTS,
8082 type CellSpec,
@@ -781,6 +783,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
781783 });
782784 write("placement: job");
783785 }
786 // A declaration the machine's ceiling lowers is said, never applied
787 // silently: a check killed under it names the same ceiling (#3128).
788 for (const clamp of limitClamps("step", manifest.limits))
789 write(`warning: ${clampWords(clamp)}`);
784790 const home = `${dir}.home`;
785791 const cell: CellSpec | undefined = cells?.ok
786792 ? {
@@ -895,6 +901,10 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
895901 } catch (error) {
896902 write(`order-dependent tests not filed: ${String(error)}`);
897903 }
904 // A cell stopped over a limit: the summary is which limit, and where
905 // it is set — never whatever line the killed process printed last.
906 if (!ran.ok && cellStopped("check", ran.error))
907 return { ok: false, error: ran.error };
898908 if (!ran.ok) {
899909 const { summary, detail } = summariseCheckFailure(
900910 checkLines,
src/tui/screens/about.ts +31 −5
@@ -25,7 +25,9 @@ import type { RepoFacts, RepoSource } from "../../view/source.ts";
2525 import type { Ctx, Screen } from "../app/app.ts";
2626 import { binding } from "../app/keys.ts";
2727 import { style } from "../term/style.ts";
28 import { truncate } from "../term/width.ts";
28 import { truncate, wrap } from "../term/width.ts";
29 import { clampsLineAt } from "../../apps/declared_limits.ts";
30 import { resolveOid } from "../../git/merge.ts";
2931 import { badge, card } from "../ui/widgets.ts";
3032 import type { Session } from "../session.ts";
3133 import { PIN_MARK, ago, drawFacts, plural } from "./common.ts";
@@ -54,6 +56,9 @@ export function aboutScreen(
5456 ...aboutFacts(f, src, facts, ref),
5557 ];
5658 let rows = factRows();
59 // The settings page's line, word for word: what the default branch's
60 // forge.json asks of its cells that this machine lowers (#3128).
61 let lowered = "";
5762 const cloneUrl = rows.find(([label]) => label.startsWith("clone"))?.[1] ?? "";
5863 return {
5964 title: "About",
@@ -72,14 +77,24 @@ export function aboutScreen(
7277 binding(["esc"], "close"),
7378 ];
7479 },
80 async load() {
81 if (repo === undefined) return;
82 const dir = f.dir(repo);
83 const tip = await resolveOid(dir, `refs/heads/${repo.defaultBranch}`);
84 if (tip === undefined) return;
85 lowered = await clampsLineAt(dir, tip);
86 ctx.invalidate();
87 },
7588 render(area, s) {
7689 parent.render(area, s);
7790 const c = ctx.theme.c;
7891 const w = Math.min(72, Math.max(30, area.w - 6));
79 // The frame, the badges, the description, a blank, and one row per
80 // fact — a card with empty rows under its last line reads as a card
81 // that lost something.
82 const h = Math.min(area.h, rows.length + 5);
92 // The card's text runs from one column in from its inner edge.
93 const notes = lowered === "" ? [] : wrap(lowered, Math.max(1, w - 5));
94 // The frame, the badges, the description, a blank, one row per fact
95 // and the lowered limits — a card with empty rows under its last
96 // line reads as a card that lost something.
97 const h = Math.min(area.h, rows.length + notes.length + 5);
8398 const r = {
8499 x: area.x + ((area.w - w) >> 1),
85100 y: area.y + ((area.h - h) >> 1),
@@ -153,6 +168,17 @@ export function aboutScreen(
153168 rows,
154169 c.card,
155170 );
171 notes.forEach((line, i) => {
172 const y = inner.y + 3 + rows.length + i;
173 if (y >= inner.y + inner.h) return;
174 s.text(
175 lead,
176 y,
177 truncate(line, Math.max(0, edge - lead)),
178 style(c.mutedFg, c.card),
179 edge,
180 );
181 });
156182 },
157183 key(e) {
158184 if (e.key === "y" && cloneUrl !== "") {
src/web/pages/settings.ts +10 −1
@@ -9,6 +9,7 @@
99 */
1010
1111 import { appLimitWords } from "../../actions/app_limit.ts";
12 import { clampsLineAt } from "../../apps/declared_limits.ts";
1213 import {
1314 deleteAppEnvVar,
1415 disableApp,
@@ -233,6 +234,12 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
233234 : [];
234235 if (!branches.includes(repo.defaultBranch))
235236 branches.unshift(repo.defaultBranch);
237 // What the default branch's forge.json asks of its cells that this
238 // machine lowers: said here, never applied silently (#3128).
239 const tip = refs.ok
240 ? refs.value.find((r) => r.name === `refs/heads/${repo.defaultBranch}`)?.oid
241 : undefined;
242 const lowered = tip === undefined ? "" : await clampsLineAt(dir, tip);
236243
237244 // The lead's About card owns the description and visibility; this form
238245 // sends them back unchanged, as that one does the gates below.
@@ -349,7 +356,9 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
349356 repo,
350357 "general",
351358 "Settings",
352 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
359 html`${lead}${lowered === ""
360 ? null
361 : html`<p class="small muted mt" id="limit-clamps">${lowered}</p>`}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
353362 ? html`<div class="mt">${proposals}</div>`
354363 : null}${secrets
355364 ? html`<div class="mt">${secrets}</div>`
src/web/pages/system.ts +4 −1
@@ -14,7 +14,7 @@ import { drawChart } from "../../boards/chart.ts";
1414 import { canSeeMemory, memoryHours } from "../../boards/memory.ts";
1515 import { telemetryReader } from "../../actions/telemetry.ts";
1616 import type { Ctx } from "../../http/context.ts";
17 import { memoryCapHolder } from "../../apps/contain.ts";
17 import { maxLimits, memoryCapHolder } from "../../apps/contain.ts";
1818 import { bytes, spark, span } from "../../system/format.ts";
1919 import { eventStream } from "../../http/sse.ts";
2020 import type { SystemView } from "../../system/view.ts";
@@ -153,6 +153,8 @@ export function systemPage(ctx: Ctx): Response {
153153 holder.by === "kernel"
154154 ? html`<p class="small" id="cell-caps" data-by="kernel">Each cell's memory is capped by the kernel (its own cgroup's <code>memory.max</code>): a cell over it is killed alone.</p>`
155155 : html`<p class="small" id="cell-caps" data-by="watch">Each cell's memory is watched once a second and the cell stopped over its cap; the kernel does not cap it (${holder.reason}).</p>`;
156 const ceiling = maxLimits();
157 const ceilingLine = html`<p class="small" id="cell-ceiling" data-mib="${String(ceiling.memoryMiB)}">No cell gets more than ${ceiling.memoryMiB} MiB of memory, whatever its <code>forge.json</code> asks (${ceiling.from.memoryMiB}).</p>`;
156158 const r = regions(v);
157159 const at = (id: string): Html => raw(r[id]!);
158160 const body = html`<div class="page-head">
@@ -170,6 +172,7 @@ export function systemPage(ctx: Ctx): Response {
170172 <div class="bt-grid" id="cores" aria-label="Per-core CPU, percent, with its last readings">${at("cores")}</div>
171173 <div class="bt-grid" id="mem">${at("mem")}</div>
172174 ${caps}
175 ${ceilingLine}
173176 <p class="small mono" id="temps">${at("temps")}</p>`,
174177 { head: html`<h2>Machine</h2>` },
175178 )}
test/cell-ceiling.test.ts added +181
@@ -0,0 +1,181 @@
1 /**
2 * A cell's declared memory is never silently clamped (#3128): the ceiling
3 * follows what the host can give unless an operator sets one, a
4 * declaration over it is lowered with a warning that names the ceiling
5 * and where it is set, and a cell stopped under it says which limit.
6 */
7
8 import { describe, expect, test } from "bun:test";
9 import {
10 clampWords,
11 forgetPodMemory,
12 maxLimits,
13 limitClamps,
14 MEMORY_SHARE,
15 memoryCeiling,
16 podMemoryLimit,
17 resolveLimits,
18 type Ceilings,
19 } from "../src/apps/contain.ts";
20 import { clampsLine, declaredClamps, declaredLimits } from "../src/apps/declared_limits.ts";
21 import { cellStopped } from "../src/apps/process.ts";
22
23 const MIB = 1024 * 1024;
24 const GIB = 1024 * MIB;
25
26 const ceilings = (memoryMiB: number, from = "FORGE_CELL_MEMORY_MAX_MIB"): Ceilings => ({
27 memoryMiB,
28 cpus: 8,
29 diskMiB: 16384,
30 from: { memoryMiB: from, cpus: "the machine's core count", diskMiB: "the forge's 16384 MiB default" },
31 });
32
33 describe("memoryCeiling", () => {
34 test("the operator's FORGE_CELL_MEMORY_MAX_MIB wins, and is named", () => {
35 expect(memoryCeiling("8192", { podBytes: 4 * GIB, machineBytes: 64 * GIB })).toEqual({
36 mib: 8192,
37 from: "FORGE_CELL_MEMORY_MAX_MIB",
38 });
39 });
40
41 test("with no env the ceiling follows the pod: 3/4 of a 16 GiB memory.max is 12288 MiB", () => {
42 expect(MEMORY_SHARE).toBe(0.75);
43 expect(memoryCeiling(undefined, { podBytes: 16 * GIB, machineBytes: 64 * GIB })).toEqual({
44 mib: 12288,
45 from: "75% of the pod's memory.max (16384 MiB)",
46 });
47 // A pod of 6 GiB: 4608 MiB, not the 4096 that once killed checks.
48 expect(memoryCeiling("", { podBytes: 6 * GIB, machineBytes: 64 * GIB }).mib).toBe(4608);
49 });
50
51 test("with no pod limit the ceiling follows the machine's memory", () => {
52 expect(memoryCeiling(undefined, { podBytes: undefined, machineBytes: 32 * GIB })).toEqual({
53 mib: 24576,
54 from: "75% of the machine's memory (32768 MiB)",
55 });
56 });
57
58 test("a value that is not a positive number is no setting", () => {
59 expect(memoryCeiling("lots", { podBytes: 8 * GIB, machineBytes: 64 * GIB }).mib).toBe(6144);
60 expect(memoryCeiling("-1", { podBytes: 8 * GIB, machineBytes: 64 * GIB }).mib).toBe(6144);
61 });
62 });
63
64 test("the pod's limit is read once, and read again after forgetPodMemory", () => {
65 const saved = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
66 delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
67 try {
68 forgetPodMemory();
69 const first = maxLimits();
70 expect(first.from.memoryMiB).toMatch(/^75% of the (pod's memory\.max|machine's memory) \(\d+ MiB\)$/);
71 forgetPodMemory();
72 expect(maxLimits()).toEqual(first);
73 } finally {
74 if (saved !== undefined) process.env["FORGE_CELL_MEMORY_MAX_MIB"] = saved;
75 forgetPodMemory();
76 }
77 });
78
79 describe("podMemoryLimit", () => {
80 const fs = (files: Record<string, string>) => (path: string) => files[path];
81
82 test("the forge's own leaf says max; the pod's limit is read from the level above", () => {
83 expect(
84 podMemoryLimit(
85 fs({
86 "/proc/self/cgroup": "0::/forge\n",
87 "/sys/fs/cgroup/forge/memory.max": "max\n",
88 "/sys/fs/cgroup/memory.max": `${16 * GIB}\n`,
89 }),
90 ),
91 ).toBe(16 * GIB);
92 });
93
94 test("the tightest level wins", () => {
95 expect(
96 podMemoryLimit(
97 fs({
98 "/proc/self/cgroup": "0::/a/b\n",
99 "/sys/fs/cgroup/a/b/memory.max": `${8 * GIB}\n`,
100 "/sys/fs/cgroup/a/memory.max": `${4 * GIB}\n`,
101 }),
102 ),
103 ).toBe(4 * GIB);
104 });
105
106 test("no cgroup v2, or no level with a limit: none", () => {
107 expect(podMemoryLimit(fs({ "/proc/self/cgroup": "4:memory:/x\n" }))).toBeUndefined();
108 expect(podMemoryLimit(fs({}))).toBeUndefined();
109 expect(
110 podMemoryLimit(fs({ "/proc/self/cgroup": "0::/\n", "/sys/fs/cgroup/memory.max": "max\n" })),
111 ).toBeUndefined();
112 });
113 });
114
115 describe("a declaration over the ceiling", () => {
116 test("forge.json 8192 with the ceiling 4096: lowered, and a visible warning names both and where the ceiling is set", () => {
117 const max = ceilings(4096);
118 const clamps = limitClamps("step", { memoryMiB: 8192 }, max);
119 expect(clamps).toHaveLength(1);
120 expect(clampWords(clamps[0]!)).toBe(
121 "forge.json check.limits.memory asks for 8192 MiB, over this forge's ceiling of 4096 MiB (FORGE_CELL_MEMORY_MAX_MIB); the cell gets 4096 MiB",
122 );
123 const limits = resolveLimits("step", { memoryMiB: 8192 }, max);
124 expect(limits.memoryMiB).toBe(4096);
125 expect(limits.from?.memoryMiB).toBe(
126 "set by FORGE_CELL_MEMORY_MAX_MIB, the forge's ceiling; forge.json check.limits.memory asks for 8192",
127 );
128 });
129
130 test("within the ceiling: given as declared, no warning, and forge.json named as the source", () => {
131 const max = ceilings(12288, "75% of the pod's memory.max (16384 MiB)");
132 expect(limitClamps("step", { memoryMiB: 8192 }, max)).toEqual([]);
133 const limits = resolveLimits("step", { memoryMiB: 8192 }, max);
134 expect(limits.memoryMiB).toBe(8192);
135 expect(limits.from?.memoryMiB).toBe("set by forge.json check.limits.memory");
136 });
137
138 test("undeclared: the default, and where to raise it", () => {
139 const limits = resolveLimits("app", undefined, ceilings(4096));
140 expect(limits.memoryMiB).toBe(512);
141 expect(limits.from?.memoryMiB).toBe(
142 "the forge's default for an app; forge.json app.limits.memory raises it",
143 );
144 });
145
146 test("declaredClamps reads both sections of a forge.json; one that does not parse declares nothing", () => {
147 const json = JSON.stringify({
148 app: { run: "bun run src/server.ts", limits: { memory: 6000, cpus: 16 } },
149 check: { run: "bun test", limits: { memory: 8192 } },
150 });
151 const max = ceilings(4096);
152 const clamps = declaredClamps(declaredLimits(json, undefined), max);
153 expect(clamps.map((c) => c.field)).toEqual([
154 "app.limits.memory",
155 "app.limits.cpus",
156 "check.limits.memory",
157 ]);
158 expect(declaredClamps(declaredLimits("{not json", undefined), max)).toEqual([]);
159 expect(declaredClamps(declaredLimits(undefined, undefined), max)).toEqual([]);
160 });
161
162 test("clampsLine: one sentence for both doors, empty when nothing is lowered", () => {
163 const max = ceilings(4096);
164 const json = JSON.stringify({ check: { run: "bun test", limits: { memory: 8192 } } });
165 expect(clampsLine(declaredClamps(declaredLimits(json, undefined), max))).toBe(
166 "Lowered to this forge's ceiling: forge.json check.limits.memory asks for 8192 MiB, gets 4096 MiB (FORGE_CELL_MEMORY_MAX_MIB).",
167 );
168 expect(clampsLine([])).toBe("");
169 });
170 });
171
172 test("a cell's stop is told from a step's own failure, so a check's summary names the limit", () => {
173 expect(
174 cellStopped(
175 "check",
176 "check stopped: it used 4105 MiB of memory, over its 4096 MiB limit (set by FORGE_CELL_MEMORY_MAX_MIB, the forge's ceiling; forge.json check.limits.memory asks for 8192)",
177 ),
178 ).toBe(true);
179 expect(cellStopped("check", "check exited with code 1 — boom")).toBe(false);
180 expect(cellStopped("check", "install stopped: it used 1 MiB")).toBe(false);
181 });
test/checks.test.ts +36
@@ -49,6 +49,7 @@ import { serve, type Servers } from "../src/http/server.ts";
4949 import { listEvents } from "../src/core/events.ts";
5050 import { readRunLog } from "../src/runs/log.ts";
5151 import { promote } from "./helpers/members.ts";
52 import { createSession } from "../src/core/sessions.ts";
5253
5354 const checkJson = (run: string, extra = ""): string =>
5455 `{"check": {"run": ${JSON.stringify(run)}, "install": ""${extra}}}\n`;
@@ -422,6 +423,41 @@ describe("checks", () => {
422423 );
423424 });
424425
426 test("forge.json 8192 MiB over a 4096 MiB ceiling: the check's log and the settings page say so (#3128)", async () => {
427 const saved = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
428 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";
429 try {
430 const declared = await commitToBranch(app, alice, repo, {
431 message: "Ask for more memory than the forge gives",
432 files: [
433 {
434 path: "forge.json",
435 content: checkJson("true", ', "limits": {"memory": 8192}'),
436 },
437 ],
438 });
439 if (!declared.ok) throw new Error(JSON.stringify(declared.error));
440 const run = await settled((r) => r.commitOid === declared.value.commitOid);
441 const warning =
442 "warning: forge.json check.limits.memory asks for 8192 MiB, over this forge's ceiling of 4096 MiB (FORGE_CELL_MEMORY_MAX_MIB); the cell gets 4096 MiB";
443 expect(readRunLog(dataDir, run.id).lines).toContain(warning);
444 const res = await fetch(`${servers.url}/alice/lib/settings`, {
445 headers: {
446 cookie: `forge_session=${createSession(app.db, alice.id).token}`,
447 },
448 });
449 expect(res.status).toBe(200);
450 const body = await res.text();
451 // One muted line under the About lead, not a card (pillar 0).
452 expect(body).toContain(
453 `<p class="small muted mt" id="limit-clamps">Lowered to this forge&#39;s ceiling: forge.json check.limits.memory asks for 8192 MiB, gets 4096 MiB (FORGE_CELL_MEMORY_MAX_MIB).</p>`,
454 );
455 } finally {
456 if (saved === undefined) delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
457 else process.env["FORGE_CELL_MEMORY_MAX_MIB"] = saved;
458 }
459 });
460
425461 test("a pull is checked when it opens and each time its branch moves; a failure names the exit", async () => {
426462 // A pull is checked by the base's check, not its own.
427463 const gate = await commitToBranch(app, alice, repo, {
test/system-telemetry.test.ts +2
@@ -303,6 +303,8 @@ describe("telemetry:read: the owner grants it, an agent reads with it, nobody el
303303 // Each check cell's memory beside its cap, and who holds the cap (#2410).
304304 expect(html).toContain('data-cap="8589934592" data-cap-by="kernel">of 8.0 GiB (kernel cap)');
305305 expect(html).toMatch(/id="cell-caps" data-by="(kernel|watch)"/);
306 // The memory ceiling every cell is held under, and where it is set (#3128).
307 expect(html).toMatch(/id="cell-ceiling" data-mib="\d+">No cell gets more than \d+ MiB of memory, whatever its <code>forge.json<\/code> asks \((FORGE_CELL_MEMORY_MAX_MIB|75% of the (pod&#39;s memory.max|machine&#39;s memory) \(\d+ MiB\))\)\.<\/p>/);
306308 // Built from the system's own parts: pills, meters and the process table grouped by kind (#2721), no style attribute (#2691).
307309 expect(html).toMatch(/id="summary"[^>]*>\s*<span class="pill"/);
308310 expect(html).toContain('<tbody data-kind="check"');
test/tui-limits-lowered.test.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * Both doors (#3128): the terminal's About card (`I`) says what the
3 * default branch's forge.json asks of its cells that this forge lowers,
4 * in the settings page's words, and says nothing when nothing is lowered.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App as Forge } from "../src/app.ts";
13 import type { User } from "../src/core/users.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17 import { settleApp, settleUntil } from "./helpers/tui.ts";
18 import { seedAdmin } from "./helpers/admin.ts";
19
20 quietLogs();
21
22 describe("lowered limits in the terminal's About card", () => {
23 let dataDir: string;
24 let forge: Forge;
25 let alice: User;
26 let saved: string | undefined;
27
28 beforeAll(async () => {
29 saved = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
30 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";
31 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-limits-"));
32 forge = createApp({ dataDir, port: 0 });
33 const a = await seedAdmin(forge, {
34 username: "alice",
35 email: "[email protected]",
36 password: "a-long-passphrase",
37 });
38 if (!a.ok) throw new Error("signup failed");
39 alice = a.value;
40 for (const [name, memory] of [
41 ["greedy", 8192],
42 ["modest", 1024],
43 ] as const) {
44 const made = await createRepo(forge, alice, { name, visibility: "public" });
45 if (!made.ok) throw new Error("repo failed");
46 const c = await commitToBranch(forge, alice, made.value, {
47 message: "Declare a check",
48 files: [
49 {
50 path: "forge.json",
51 content: JSON.stringify({ check: { run: "bun test", limits: { memory } } }),
52 },
53 ],
54 });
55 if (!c.ok) throw new Error("commit failed");
56 }
57 });
58
59 afterAll(async () => {
60 if (saved === undefined) delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
61 else process.env["FORGE_CELL_MEMORY_MAX_MIB"] = saved;
62 forge.close();
63 await rm(dataDir, { recursive: true, force: true });
64 });
65
66 async function about(name: string): Promise<{ text: string; stop: () => void }> {
67 const terminal = headlessTerminal(120, 40);
68 const { app } = createForgeApp(
69 forge,
70 {
71 sshUsername: "alice",
72 remoteAddress: "127.0.0.1",
73 fingerprint: "SHA256:test",
74 user: alice,
75 },
76 { terminal, exitHooks: false },
77 );
78 app.start();
79 const press = async (...keys: string[]): Promise<void> => {
80 for (const key of keys)
81 app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
82 await settleApp(app);
83 };
84 await settleApp(app);
85 await press("/");
86 for (const ch of name) await press(ch);
87 await press("enter", "enter");
88 await settleUntil(app, `alice/${name}`);
89 await press("I");
90 await settleUntil(app, "clone (http)");
91 await settleApp(app);
92 return { text: app.screen.toText(), stop: () => app.stop() };
93 }
94
95 test("forge.json 8192 over a 4096 ceiling: the card says so, naming where the ceiling is set", async () => {
96 const h = await about("greedy");
97 try {
98 const flat = h.text.replace(/[│\s]+/g, " ");
99 expect(flat).toContain(
100 "Lowered to this forge's ceiling: forge.json check.limits.memory asks for 8192 MiB, gets 4096 MiB (FORGE_CELL_MEMORY_MAX_MIB).",
101 );
102 } finally {
103 h.stop();
104 }
105 });
106
107 test("a declaration within the ceiling adds nothing to the card", async () => {
108 const h = await about("modest");
109 try {
110 expect(h.text).not.toContain("Lowered");
111 } finally {
112 h.stop();
113 }
114 });
115 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs