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

The settings page shows the cell memory limit the machine enforces, and where the cut comes from, beside forge.json's figure #3136

Closed opened this
Closed without merging

scout/forge:scout/3135-the-settings-page-shows-the-cell-memory → main 3 commits fork 7 threads · 7 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
7 files changed +322 −5
README.md +2
@@ -221,6 +221,8 @@ The repository's settings page is one more door: a writer sees their proposal
221221 tokens one to a line (child, origin, expires, last used) with Revoke, and a
222222 form that mints one and shows its secret once; others see no section.
223223
224 The check cell's memory is on the same page under **Check cell**, and in the terminal on a repository's About card (`I`, for an admin): the limit the machine enforces, read from `forge.json` on the default branch. When `check.limits.memory` asks for more than the machine's ceiling it shows both numbers and where the cut comes from (`FORGE_CELL_MEMORY_MAX_MIB`, else a share of the pod's memory); otherwise one number. The ceiling is read once and kept (`src/apps/check-memory.ts`).
225
224226 - **MCP**: the `proposal_tokens` tool with `repo` and a `verb`: `mint`
225227 (`child`, `origin`, optionally `childRepo`), `list` (the ones you minted for
226228 the repository) or `revoke` (`id`).
src/apps/check-memory.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * The check cell's memory in words: what forge.json asks for and what the
3 * machine holds the cell to. One number when they agree; both, and where the
4 * cut comes from, when forge.json asks for more. The settings page and the
5 * terminal say the same sentence.
6 */
7
8 import { readFileAt } from "./checkout.ts";
9 import { memoryCeilingSource, POD_MEMORY_SHARE, resolveLimits, type Limits } from "./contain.ts";
10 import { parseCheck } from "./manifest.ts";
11
12 interface Held {
13 readonly limits: Limits;
14 readonly from: "env" | "pod" | "default";
15 }
16
17 const held = new Map<string, Held>();
18
19 /**
20 * The limits a check cell gets for a declared memory. `resolveLimits` reads
21 * the pod's cgroup file, so the answer is kept per (env, declaration) and the
22 * file is read once, not on every request.
23 */
24 function cellLimits(declared: number | undefined): Held {
25 const env = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
26 const key = `${env ?? ""}|${declared ?? ""}`;
27 let kept = held.get(key);
28 if (!kept) {
29 kept = {
30 limits: resolveLimits("step", declared === undefined ? undefined : { memoryMiB: declared }),
31 from: memoryCeilingSource(env),
32 };
33 if (held.size >= 64) held.clear();
34 held.set(key, kept);
outdated

This sentence always names FORGE_CELL_MEMORY_MAX_MIB for a cut, whether or not it is set. Pick the source from the environment (env var versus the pod share) and say that one.

35 }
36 return kept;
37 }
38
39 /** Where the ceiling a cut was held to comes from, in words. */
40 export function ceilingWords(from: "env" | "pod" | "default"): string {
41 return from === "env"
42 ? "the machine's ceiling, FORGE_CELL_MEMORY_MAX_MIB"
43 : from === "pod"
44 ? `${Math.round(POD_MEMORY_SHARE * 100)}% of the pod's memory.max`
45 : "the machine's default ceiling; the pod states no memory limit";
46 }
47
48 /** The sentence for a declared memory; with none declared it says the default holds. Only validated numbers enter it. */
49 export function checkMemoryWords(declared: number | undefined): string {
50 const { limits: cell, from } = cellLimits(declared);
51 if (declared === undefined) return `The check cell holds ${cell.memoryMiB} MiB (the default; forge.json declares none).`;
52 if (cell.memorySource !== "ceiling") return `The check cell holds ${cell.memoryMiB} MiB.`;
53 return `forge.json asks ${declared} MiB; the cell holds ${cell.memoryMiB} MiB (${ceilingWords(from)}).`;
54 }
55
56 /**
57 * The sentence for the check forge.json declares at `oid`. `undefined` when
58 * it declares none; `null` when it declares one that cannot be read.
59 */
60 export async function checkMemoryAt(
61 dir: string,
62 oid: string | undefined,
63 ): Promise<string | null | undefined> {
64 if (oid === undefined) return undefined;
65 const [forgeJson, packageJson] = await Promise.all([
66 readFileAt(dir, oid, "forge.json"),
67 readFileAt(dir, oid, "package.json"),
68 ]);
69 const check = parseCheck(forgeJson, packageJson);
70 if (!check.ok) return null;
71 return check.value === undefined ? undefined : checkMemoryWords(check.value.limits.memoryMiB);
72 }
src/apps/contain.ts +18 −3
@@ -83,16 +83,31 @@ export function memoryCeiling(
8383 env: string | undefined,
8484 podFile = "/sys/fs/cgroup/memory.max",
8585 ): number {
86 return ceiling(env, podFile).mib;
87 }
88
89 /** Where the ceiling comes from: the variable, the pod's `memory.max`, or the fixed default. */
90 export function memoryCeilingSource(
91 env: string | undefined,
92 podFile = "/sys/fs/cgroup/memory.max",
93 ): "env" | "pod" | "default" {
94 return ceiling(env, podFile).from;
95 }
96
97 function ceiling(
98 env: string | undefined,
99 podFile: string,
100 ): { mib: number; from: "env" | "pod" | "default" } {
86101 const set = positive(env);
87 if (set !== undefined) return set;
102 if (set !== undefined) return { mib: set, from: "env" };
88103 try {
89104 const bytes = Number(readFileSync(podFile, "utf8").trim());
90105 if (Number.isFinite(bytes) && bytes > 0)
91 return Math.max(1, Math.floor((bytes * POD_MEMORY_SHARE) / 1048576));
106 return { mib: Math.max(1, Math.floor((bytes * POD_MEMORY_SHARE) / 1048576)), from: "pod" };
92107 } catch {
93108 // no cgroup v2 here, or "max" (unlimited): the fixed default below
94109 }
95 return 4096;
110 return { mib: 4096, from: "default" };
96111 }
97112
98113 /** The line saying a declared memory limit is cut to the machine's ceiling; none when it is not. */
src/tui/screens/about.ts +23 −1
@@ -19,13 +19,16 @@ import { audienceFor } from "../../core/audience.ts";
1919 import { isPinned } from "../../core/pins.ts";
2020 import { parentReleases, releasesSentence } from "../../core/parent_releases.ts";
2121 import { running } from "../../kernel/version.ts";
22 import { checkMemoryAt } from "../../apps/check-memory.ts";
23 import { repoDir } from "../../git/repos.ts";
24 import { listRefs } from "../../git/read.ts";
2225 import { updateRepoSettings } from "../../actions/repos.ts";
2326 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
2427 import type { RepoFacts, RepoSource } from "../../view/source.ts";
2528 import type { Ctx, Screen } from "../app/app.ts";
2629 import { binding } from "../app/keys.ts";
2730 import { style } from "../term/style.ts";
28 import { truncate } from "../term/width.ts";
31 import { truncate, wrap } from "../term/width.ts";
2932 import { badge, card } from "../ui/widgets.ts";
3033 import type { Session } from "../session.ts";
3134 import { PIN_MARK, ago, drawFacts, plural } from "./common.ts";
@@ -49,11 +52,30 @@ export function aboutScreen(
4952 let repo = localRepo(src);
5053 const may = (): boolean =>
5154 repo !== undefined && f.user !== undefined && canAdmin(f.db, repo, f.user);
55 let cell: [string, string][] = [];
5256 const factRows = (): [string, string][] => [
5357 ...archivedRow(repo),
5458 ...aboutFacts(f, src, facts, ref),
59 ...cell,
5560 ];
5661 let rows = factRows();
62 // An admin also sees the check cell's memory, read once from forge.json.
63 if (may() && repo !== undefined) {
64 const at = repo;
65 void (async () => {

Add a catch so a failed read leaves the card unchanged. Also add a test that a non-admin sees no check cell row.

66 const refs = await listRefs(repoDir(f.app.reposRoot, at.ownerName, at.name), "refs/heads/");
67 const tip = refs.ok
68 ? refs.value.find((r) => r.name === `refs/heads/${at.defaultBranch}`)?.oid
69 : undefined;
70 const words = await checkMemoryAt(repoDir(f.app.reposRoot, at.ownerName, at.name), tip);
71 if (words === undefined) return;
72 cell = wrap(words ?? "forge.json's check could not be read", 50).map(
73 (line, i): [string, string] => [i === 0 ? "check cell" : "", line],
74 );
75 rows = factRows();
76 ctx.invalidate();
77 })();
78 }
5779 const cloneUrl = rows.find(([label]) => label.startsWith("clone"))?.[1] ?? "";
5880 return {
5981 title: "About",
src/web/pages/settings.ts +19 −1
@@ -105,6 +105,7 @@ import {
105105 import { cutWaveFor } from "../../actions/cut_wave.ts";
106106 import { proposalTokensSection } from "./proposal-tokens.ts";
107107 import { secretsSection } from "./secrets.ts";
108 import { checkMemoryAt } from "../../apps/check-memory.ts";
108109 import { saveGrants } from "./subscriptions.ts";
109110
110111 type Section =
@@ -231,6 +232,10 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
231232 const branches = refs.ok
232233 ? refs.value.map((r) => r.name.replace("refs/heads/", "")).sort()
233234 : [];
235 const tip = refs.ok
236 ? refs.value.find((r) => r.name === `refs/heads/${repo.defaultBranch}`)?.oid
237 : undefined;
238 const cellMemory = await checkMemoryAt(dir, tip);
234239 if (!branches.includes(repo.defaultBranch))
235240 branches.unshift(repo.defaultBranch);
236241
@@ -314,6 +319,17 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
314319 </form>`,
315320 { head: html`${icon("branch")}<h2>Branch and gates</h2>` },
316321 );
322 const cell =
323 cellMemory === undefined
324 ? null
325 : card(
326 html`<p data-check-memory>${
327 cellMemory === null

The <p data-check-memory> is plain text in a card, which is fine on a 360px phone. The clock icon is a judgment call; DESIGN.md does not name one for this card, so it passes.

328 ? "forge.json's check could not be read, so no limit is shown."
329 : cellMemory
330 }</p>`,
331 { head: html`${icon("clock")}<h2>Check cell</h2>` },
332 );
317333 const secrets = secretsSection(ctx, "repo", `${repo.ownerName}/${repo.name}`);
318334 const wave = card(
319335 html`<form method="post" action="${base}/settings/wave">
@@ -349,7 +365,9 @@ export async function settingsPage(ctx: Ctx): Promise<Response> {
349365 repo,
350366 "general",
351367 "Settings",
352 html`${lead}<div class="mt">${body}</div><div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
368 html`${lead}<div class="mt">${body}</div>${cell
369 ? html`<div class="mt">${cell}</div>`
370 : null}<div class="mt">${wave}</div><div class="mt">${archive}</div>${proposals
353371 ? html`<div class="mt">${proposals}</div>`
354372 : null}${secrets
355373 ? html`<div class="mt">${secrets}</div>`
test/settings-check-memory.test.ts added +122
@@ -0,0 +1,122 @@
1 /** #3135: the settings page shows the check cell's memory the machine enforces, beside forge.json's. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
9 import { serve, type Servers } from "../src/http/server.ts";
10 import { adminCookie } from "./helpers/admin.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14
15 let dir = "";
16 let app: App;
17 let servers: Servers;
18 let cookie = "";
19 const saved = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
20
21 const check = (limits: string) =>
22 `{"check":{"run":"true","limits":${limits}}}`;
23
24 beforeAll(async () => {
25 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";
26 dir = await mkdtemp(join(tmpdir(), "forge-cellmem-"));
27 app = createApp({ dataDir: dir, port: 0 });
28 servers = await serve(app);
29 cookie = await adminCookie(app, { username: "olive", email: "[email protected]", password: "settings-password" });
30 }, 60_000);
31
32 afterAll(async () => {
33 if (saved === undefined) delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
34 else process.env["FORGE_CELL_MEMORY_MAX_MIB"] = saved;
35 servers.stop();
36 app.close();
37 await rm(dir, { recursive: true, force: true });
38 });
39
40 async function repoWith(name: string, forgeJson: string): Promise<string> {
41 const res = await fetch(`${servers.url}/new`, {
42 method: "POST",
43 headers: { cookie },
44 body: new URLSearchParams({ name, visibility: "private", description: "x" }),
45 redirect: "manual",
46 });
47 expect(res.status).toBeLessThan(400);
48 const { getRepo } = await import("../src/core/repos.ts");
49 const { getUserByName } = await import("../src/core/users.ts");
50 const owner = getUserByName(app.db, "olive");
51 const repo = getRepo(app.db, "olive", name);
52 if (!owner || !repo) throw new Error("setup");
53 const c = await commitToBranch(app, owner, repo, {
54 message: "forge.json",
55 files: [{ path: "forge.json", content: forgeJson }],
56 });
57 expect(c.ok).toBe(true);
58 return await (await fetch(`${servers.url}/olive/${name}/settings`, { headers: { cookie } })).text();
59 }
60
61 test("a declared limit above the ceiling shows both numbers and the source", async () => {
62 const body = await repoWith("over", check('{"memory":8192}'));
63 expect(body).toContain("forge.json asks 8192 MiB");
64 expect(body).toContain("4096 MiB");
65 expect(body).toContain("FORGE_CELL_MEMORY_MAX_MIB");
66 });
67
68 test("a declared limit below the ceiling shows one number and no warning", async () => {
69 const body = await repoWith("under", check('{"memory":1024}'));
70 expect(body).toContain("1024 MiB");
71 expect(body).not.toContain("forge.json asks");
72 expect(body).not.toContain("FORGE_CELL_MEMORY_MAX_MIB");
73 });
74
75 test("with no ceiling set and nothing declared, the default is named", async () => {
76 delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
77 try {
78 const body = await repoWith("plain", '{"check":{"run":"true"}}');
79 expect(body).toContain("2048 MiB (the default; forge.json declares none)");
80 expect(body).not.toContain("forge.json asks");
81 } finally {
82 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";
83 }
84 });
85
86 test("an unreadable check says so instead of vanishing", async () => {
87 const body = await repoWith("broken", '{"check":{"run":"true","limits":{"memory":"<b>x</b>"}}}');
88 expect(body).toContain("forge.json&#39;s check could not be read");
89 expect(body).not.toContain("<b>x</b>");
90 });
91
92 test("with no variable set, a cut is blamed on the pod, not on the variable", async () => {
93 delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
94 try {
95 const { memoryCeiling } = await import("../src/apps/contain.ts");
96 // A host whose pod holds more than the manifest maximum has nothing to cut.
97 if (memoryCeiling(undefined) >= 65536) return;
98 const body = await repoWith("pod", check('{"memory":65536}'));
99 expect(body).toContain("forge.json asks 65536 MiB");
100 expect(body).toMatch(/75% of the pod(&#39;|')s memory\.max|the pod states no memory limit/);
101 expect(body).not.toContain("FORGE_CELL_MEMORY_MAX_MIB");
102 } finally {
103 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";

This early return makes the test vacuous on a host with a large pod. Make it deterministic.

104 }
105 });
106
107 test("the ceiling's origin is named from the environment, then the pod file", async () => {
108 const { memoryCeilingSource } = await import("../src/apps/contain.ts");
109 const { writeFile } = await import("node:fs/promises");
110 const pod = join(dir, "memory.max");
111 await writeFile(pod, String(8192 * 1048576));
112 expect(memoryCeilingSource("2048", pod)).toBe("env");
113 expect(memoryCeilingSource(undefined, pod)).toBe("pod");
114 expect(memoryCeilingSource(undefined, join(dir, "absent"))).toBe("default");
115 });
116
117 test("each origin has its own words", async () => {
118 const { ceilingWords } = await import("../src/apps/check-memory.ts");
119 expect(ceilingWords("env")).toContain("FORGE_CELL_MEMORY_MAX_MIB");
120 expect(ceilingWords("pod")).toBe("75% of the pod's memory.max");
121 expect(ceilingWords("default")).not.toContain("FORGE_CELL_MEMORY_MAX_MIB");
122 });
test/tui-check-memory.test.ts added +66
@@ -0,0 +1,66 @@
1 /** #3135: About, in the terminal, says the check cell's memory in the settings page's words. */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
8 import { createApp, type App as Forge } from "../src/app.ts";
9 import type { User } from "../src/core/users.ts";
10 import { createForgeApp } from "../src/tui/forge.ts";
11 import { headlessTerminal } from "../src/tui/term/terminal.ts";
12 import { quietLogs } from "./helpers/globals.ts";
13 import { settleApp, settleUntil } from "./helpers/tui.ts";
14 import { seedAdmin } from "./helpers/admin.ts";
15
16 quietLogs();
17
18 let dataDir = "";
19 let forge: Forge;
20 let alice: User;
21 const saved = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
22
23 beforeAll(async () => {
24 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";
25 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-cellmem-"));
26 forge = createApp({ dataDir, port: 0 });
27 const a = await seedAdmin(forge, { username: "alice", email: "[email protected]", password: "a-long-passphrase" });
28 if (!a.ok) throw new Error("signup failed");
29 alice = a.value;
30 const made = await createRepo(forge, alice, { name: "beacon", visibility: "public" });
31 if (!made.ok) throw new Error("repo failed");
32 const c = await commitToBranch(forge, alice, made.value, {
33 message: "forge.json",
34 files: [{ path: "forge.json", content: '{"check":{"run":"true","limits":{"memory":8192}}}' }],
35 });
36 if (!c.ok) throw new Error("commit failed");
37 });
38
39 afterAll(async () => {
40 if (saved === undefined) delete process.env["FORGE_CELL_MEMORY_MAX_MIB"];
41 else process.env["FORGE_CELL_MEMORY_MAX_MIB"] = saved;
42 await rm(dataDir, { recursive: true, force: true });
43 });
44
45 test("About shows the cut and its source to an admin", async () => {
46 const terminal = headlessTerminal(160, 40);
47 const { app } = createForgeApp(
48 forge,
49 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice },
50 { terminal, exitHooks: false },
51 );
52 app.start();
53 const press = async (...keys: string[]) => {
54 for (const key of keys) app.dispatch({ type: "key", key, ctrl: false, alt: false, shift: false });
55 await settleApp(app);
56 };
57 await settleApp(app);
58 await press("/");
59 for (const ch of "beacon") await press(ch);
60 await press("enter");
61 await press("enter");
62 await settleUntil(app, "alice/beacon");
63 await press("I");
64 await settleUntil(app, "forge.json asks 8192 MiB");
65 expect(app.screen.toText()).toContain("FORGE_CELL_MEMORY_MAX_MIB");
66 });

Only the admin path is tested. Add the non-admin case: it must not show "check cell".

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs