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

A forge runs anywhere: a stated footprint, proven on a 1-CPU, 512 MiB machine #12093

Parked opened this in answer to
Closed without merging

mason/forge:mason/12092-a-forge-runs-anywhere-a-stated-footprint → main 8 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
11 files changed +226 −5
docs/features/footprint.md added +11
@@ -0,0 +1,11 @@
1 # What a forge costs (#12092)
2
3 A forge is one process and one thread. Pages and git need nothing else: Chromium (looks), the crew's AI tool and a large page cache are optional, and `/system` ("What the forge costs") says which are off and why.
4
5 The stated budget (`BUDGET` in `src/system/footprint.ts`) for a 1-CPU, 512 MiB machine: 256 MiB resident at rest, the first page within 5 s of start, and an empty forge's data under 64 MiB. A reading over it is shown as "Over budget", never hidden.
6
7 The release proof reads the footprint once the new version answers `/healthz`, before the smoke checks load it, and keeps it in `release/proof.json` (`footprint`). `/system` shows this process's last reading, else the proof's. Runs on x86 and ARM: the reading names the architecture.
8
9 Small pods (#12092): a cell is given at most the pod's `memory.max` less 192 MiB (`FORGE_OWN_MIB` in `src/apps/contain.ts`), so on a 384 MiB pod the check is what dies, never the forge. `/system` and `/api/v1/health` read the pod's limit, not the host's memory.
10
11 Not done yet: cutting the largest holders (the measured ~170 MiB at rest and ~380 MiB after a first hour are over the budget), a launcher-free start (`bun src/main.ts` saves 15 MiB), lazy-loading what a small forge never uses, an ARM image, and starting the serve/work split only on machines with cores (there is no split today).
src/apps/contain.ts +14 −1
@@ -122,6 +122,13 @@ export const POD_MEMORY_FILE = "/sys/fs/cgroup/memory.max";
122122 /** The share of the pod's memory a single cell may be given. */
123123 export const POD_MEMORY_SHARE = 0.75;
124124
125 /**
126 * What the forge itself needs inside its pod, MiB, measured at about 170 at
127 * rest and 200 under a first hour's work (#12092): a cell is never given the
128 * pod's memory down to this, so on a small machine the check dies, not the forge.
129 */
130 export const FORGE_OWN_MIB = 192;
131
125132 /**
126133 * The most memory one cell gets, MiB: `FORGE_CELL_MEMORY_MAX_MIB` when set,
127134 * else a share of the pod's own `memory.max`, else 4096 where the host
@@ -156,6 +163,12 @@ function ceiling(
156163 return own < machine.mib ? { mib: own, from: "size" } : machine;
157164 }
158165
166 /** A share of the pod's bytes for one cell, never more than the pod less the forge's own room. */
167 export function podShareMiB(bytes: number): number {
168 const mib = bytes / 1048576;
169 return Math.max(1, Math.floor(Math.min(mib * POD_MEMORY_SHARE, mib - FORGE_OWN_MIB)));
170 }
171
159172 function machineCeiling(
160173 env: string | undefined,
161174 podFile: string,
@@ -165,7 +178,7 @@ function machineCeiling(
165178 try {
166179 const bytes = Number(readFileSync(podFile, "utf8").trim());
167180 if (Number.isFinite(bytes) && bytes > 0)
168 return { mib: Math.max(1, Math.floor((bytes * POD_MEMORY_SHARE) / 1048576)), from: "pod" };
181 return { mib: podShareMiB(bytes), from: "pod" };
169182 } catch {
170183 // no cgroup v2 here, or "max" (unlimited): the fixed default below
171184 }
src/kernel/vitals.ts +5 −4
@@ -13,7 +13,7 @@ import { statSync } from "node:fs";
1313 import { readDisk, type DiskReading } from "./disk_reading.ts";
1414 import { DISK_FLOOR, roomy } from "../spawn/disk_floor.ts";
1515 import { dirname } from "node:path";
16 import { freemem, totalmem } from "node:os";
16 import { freemem } from "node:os";
1717 import { refusedInternal, type RefusedLedger } from "./internal_refused.ts";
1818 import { recentErrors, redactSecrets, type ErrorLedger, type ErrorLine } from "./log.ts";
1919 import {
@@ -39,7 +39,7 @@ import { running as runningVersion } from "./version.ts";
3939 import { rollbackNeed } from "../release/launch.ts";
4040 import { behindStanding } from "../release/behind.ts";
4141 import { newestDrills } from "../core/domain_drills.ts";
42 import { capacityValue } from "../core/capacity.ts";
42 import { capacityValue, memoryLimitBytes } from "../core/capacity.ts";
4343 import { unwrittenFor, SILENT_AFTER_S } from "../http/access_log.ts";
4444 import { DOMAINS } from "./domains.ts";
4545 import { domainDrillNeeds } from "./domain_drill.ts";
@@ -605,8 +605,9 @@ export function vitals(input: VitalsInput): Vitals {
605605 disk,
606606 memory: {
607607 rssBytes: process.memoryUsage().rss,
608 hostFreeBytes: freemem(),
609 hostTotalBytes: totalmem(),
608 // The pod's own limit where one is set: a forge in 512 MiB is not on a 64 GiB host (#12092).
609 hostFreeBytes: Math.min(freemem(), Math.max(0, memoryLimitBytes() - process.memoryUsage().rss)),
610 hostTotalBytes: memoryLimitBytes(),
610611 },
611612 queue,
612613 lane,
src/main.ts +3
@@ -96,6 +96,7 @@ import { configProblem, dataDirOf, preflight } from "./kernel/preflight.ts";
9696 import { running } from "./kernel/version.ts";
9797 import { record as recordDegraded } from "./kernel/degraded_history.ts";
9898 import { vitals } from "./kernel/vitals.ts";
99 import { markReady, readFootprint, keepFootprint } from "./system/footprint.ts";
99100 import { proveRunning } from "./release/prove.ts";
100101 import { walkJourney } from "./release/journey.ts";
101102 import { proberKey } from "./release/prober.ts";
@@ -411,6 +412,7 @@ await warmFlow(app);
411412 await warmPlans(app);
412413 await warmDisplays(app).catch(() => undefined);
413414 const servers = await serve(app);
415 markReady();
414416 // The home's picture is read by a worker from here, so the first page finds it (web/pages/home_flow.ts).
415417 warmHome(app);
416418 warmBoards(app);
@@ -798,6 +800,7 @@ proveRunning({
798800 url: forgeUrl,
799801 token: process.env["FORGE_TOKEN"],
800802 journey: walkJourney,
803 footprint: async () => keepFootprint(await readFootprint(app.config.dataDir)),
801804 proberKey: proberKey(app.hookSecret),
802805 // The first app's production host: it must never answer as the forge (#6726).
803806 appHost: (() => {
src/release/prove.ts +12
@@ -28,6 +28,7 @@ import { UNSTAMPED } from "../kernel/version.ts";
2828 import { ownProbeHeaders } from "../kernel/probe.ts";
2929 import type { Log } from "../kernel/log.ts";
3030 import { during } from "../perf/jobs.ts";
31 import type { Footprint } from "../system/footprint.ts";
3132
3233 /** How long the public URL has to answer as the new version. */
3334 export const GIVE_UP_MS = 10 * 60_000;
@@ -60,6 +61,11 @@ export interface Proof {
6061 /** The failure was the give-up: ten minutes already spent polling; only its first retry skips the backoff (#10168). */
6162 readonly gaveUp?: boolean;
6263 /** A stranger's journey walked on the public URL after the smoke checks (#11158); its timings, in ms, for the release card. */
64 /**
65 * What the forge cost at rest when this version first answered, before the
66 * smoke checks loaded it (#12092).
67 */
68 readonly footprint?: Footprint;
6369 readonly journey?: { readonly readyMs: number | null; readonly firstActivityMs: number | null; readonly screens: readonly string[] };
6470 /** A person asked for it to be proven again now: the next tick does, whatever the backoff says. */
6571 readonly retryNow?: boolean;
@@ -237,6 +243,8 @@ export interface ProveOptions {
237243 readonly signal?: AbortSignal;
238244 /** Walks the stranger's journey after the smoke checks; the forge passes `walkJourney`, and a test its own. Without it no walk runs. */
239245 readonly journey?: typeof walkJourney;
246 /** Reads the footprint; the proof records it as soon as the version answers, before any load. */
247 readonly footprint?: () => Promise<Footprint>;
240248 /**
241249 * This boot's prober key (`release/prober.ts`), handed to the journey so the forge's rate
242250 * limits know it.
@@ -266,6 +274,7 @@ export async function proveRelease(o: ProveOptions): Promise<Proof | undefined>
266274 const baseFetch = o.fetch ?? fetch;
267275 const doFetch = ((url, init) => baseFetch(url, o.signal ? { ...init, signal: init?.signal ? AbortSignal.any([init.signal, o.signal]) : o.signal } : init)) as typeof fetch;
268276 const failedBefore = last?.version === o.version && !last.ok ? last : undefined;
277 let measured: Footprint | undefined;
269278 const finish = (failure?: string, slow = false, gaveUp = false, walked?: JourneyResult): Proof => {
270279 if (o.signal?.aborted) throw new Error("the proof was aborted as hung");
271280 const at = new Date(now()).toISOString();
@@ -273,6 +282,7 @@ export async function proveRelease(o: ProveOptions): Promise<Proof | undefined>
273282 version: o.version,
274283 at,
275284 ok: failure === undefined,
285 ...(measured === undefined ? {} : { footprint: measured }),
276286 ...(walked === undefined ? {} : { journey: { readyMs: walked.readyMs, firstActivityMs: walked.firstActivityMs, screens: walked.screens } }),
277287 ...(failure === undefined
278288 ? {}
@@ -304,6 +314,8 @@ export async function proveRelease(o: ProveOptions): Promise<Proof | undefined>
304314 }
305315 await sleep(POLL_MS);
306316 }
317 // At rest: the version answers and nothing has loaded it yet.
318 measured = await o.footprint?.().catch(() => undefined);
307319 const failures = await smoke(o.url, o.token ?? "", {
308320 fetch: doFetch,
309321 anonymousBoard: true,
src/system/footprint.ts added +116
@@ -0,0 +1,116 @@
1 /**
2 * What a forge costs (#12092): memory at rest, disk, time from start to the
3 * first page, the machine it stands on, and what is switched off because a
4 * small machine cannot afford it. One process, one thread is the shape; the
5 * budget below is stated so growth past it shows. The release proof records
6 * a reading (`release/prove.ts`) and /system shows the last one.
7 */
8 import { arch, availableParallelism } from "node:os";
9 import { memoryLimitBytes } from "../core/capacity.ts";
10 import { findChromium } from "../looks/capture.ts";
11 import { treeBytes } from "./largest_dirs.ts";
12
13 const MIB = 1024 * 1024;
14
15 /**
16 * What a forge may cost on a 1-CPU, 512 MiB machine; a reading over it is
17 * shown as over, never hidden.
18 */
19 export const BUDGET = { restBytes: 256 * MIB, readyMs: 5_000, emptyDiskBytes: 64 * MIB } as const;
20
21 /** One part of the forge that is optional, whether it is on, and why in words. */
22 export interface Optional {
23 readonly name: string;
24 readonly on: boolean;
25 readonly why: string;
26 }
27
28 /** One reading of the footprint; every number is measured, none guessed. */
29 export interface Footprint {
30 readonly at: string;
31 readonly arch: string;
32 readonly cpus: number;
33 readonly machineBytes: number;
34 /** Resident memory of this process, the one that serves pages and git. */
35 readonly rssBytes: number;
36 readonly heapBytes: number;
37 /** Seconds this process has run when read. */
38 readonly ageSeconds: number;
39 /** Start to the listener answering, in ms; null until it is up. */
40 readonly readyMs: number | null;
41 /** Bytes of the data directory on disk; null when it could not be walked. */
42 readonly diskBytes: number | null;
43 readonly threads: number;
44 readonly optional: readonly Optional[];
45 readonly withinBudget: boolean;
46 }
47
48 let readyMs: number | null = null;
49
50 /** Called once the listener is up: the time since this process started, kept for every reading. */
51 export function markReady(uptimeSeconds: number = process.uptime()): void {
52 if (readyMs === null) readyMs = Math.round(uptimeSeconds * 1000);
53 }
54
55 /** The optional parts and whether each is on. `env` and `which` are a test's to hand in. */
56 export function optionals(
57 cpus: number,
58 machineBytes: number,
59 chromium: string | null = findChromium() ?? null,
60 crewTool: string | null = Bun.which(process.env["FORGE_CLAUDE"] ?? "claude"),
61 ): Optional[] {
62 const small = cpus <= 1 || machineBytes <= 1024 * MIB;
63 return [
64 {
65 name: "Chromium (looks)",
66 on: chromium !== null,
67 why: chromium === null ? "no Chromium on this machine, so pages are served without pictures; pages and git do not need it" : "found, and started only for a picture, one at a time",
68 },
69 {
70 name: "Crew AI tool",
71 on: crewTool !== null,
72 why: crewTool === null ? "Claude Code is not on PATH or at FORGE_CLAUDE, so assigned work waits; pages and git do not need it" : "found, and run only while a crew run is working",
73 },
74 {
75 name: "Serve/work threads",
76 on: false,
77 why: small ? `${cpus} CPU and ${Math.round(machineBytes / MIB)} MiB: one process, one thread` : "one process, one thread is the default; this machine has room to split",
78 },
79 ];
80 }
81
82 /** Reads the footprint now; the data directory's walk is asynchronous, off the loop. */
83 export async function readFootprint(dataDir: string, now: () => number = Date.now): Promise<Footprint> {
84 const mem = process.memoryUsage();
85 const cpus = availableParallelism();
86 const machineBytes = memoryLimitBytes();
87 const diskBytes = await treeBytes(dataDir).catch(() => null);
88 return {
89 at: new Date(now()).toISOString(),
90 arch: arch(),
91 cpus,
92 machineBytes,
93 rssBytes: mem.rss,
94 heapBytes: mem.heapUsed,
95 ageSeconds: Math.round(process.uptime()),
96 readyMs,
97 diskBytes,
98 threads: 1,
99 optional: optionals(cpus, machineBytes),
100 withinBudget: mem.rss <= BUDGET.restBytes && (readyMs ?? 0) <= BUDGET.readyMs,
101 };
102 }
103
104 /** The last reading kept in this process, for /system; the proof and the page both write it. */
105 let last: Footprint | null = null;
106 export const keepFootprint = (f: Footprint): Footprint => (last = f);
107 export const lastFootprint = (): Footprint | null => last;
108
109 const mib = (n: number): string => `${(n / MIB).toFixed(n < 10 * MIB ? 1 : 0)} MiB`;
110
111 /** The reading as one sentence a person can check against the budget. */
112 export function footprintWords(f: Footprint): string {
113 const disk = f.diskBytes === null ? "disk not read" : `${mib(f.diskBytes)} on disk`;
114 const ready = f.readyMs === null ? "not yet up" : `first page ${f.readyMs} ms after start`;
115 return `${mib(f.rssBytes)} resident after ${f.ageSeconds} s, ${disk}, ${ready}; budget ${mib(BUDGET.restBytes)}, ${BUDGET.readyMs} ms (${f.arch}, ${f.cpus} CPU, ${mib(f.machineBytes)}).`;
116 }
src/system/largest_dirs.ts +6
@@ -134,3 +134,9 @@ export function largestDirsCache(
134134 }
135135
136136 export const largestDirs = largestDirsCache();
137
138 /** Everything under the data directory on its own volume, as `du -x` counts it; asynchronous. */
139 export async function treeBytes(dataDir: string): Promise<number> {
140 const root = await lstat(dataDir);
141 return onDisk(root) + (await sizeOf(dataDir, root.dev));
142 }
src/web/pages/system.ts +17
@@ -47,6 +47,8 @@ import { KEPT_PAGE_BYTES, keptPageStats } from "./kept_page.ts";
4747 import { COLUMN_BYTES, PARTS_BYTES, keptPartsStats, treeCacheStats } from "./tree_cache.ts";
4848 import { featureHealth, type FeatureHealth } from "../../system/feature_health.ts";
4949 import { egressReportedLine } from "../../system/egress_line.ts";
50 import { lastFootprint, footprintWords, BUDGET, type Footprint } from "../../system/footprint.ts";
51 import { lastProof } from "../../release/prove.ts";
5052 import { BREAK_STEPS, MACHINES, declaredFooting, footing, offMachine, whereWords, type Footing, type Machine } from "../../system/footing.ts";
5153 import { laneWords, readOffsiteLane, type OffsiteLane } from "../../snapshot/offsite_lane.ts";
5254 import { badge, chartBox, disclosure, meter, pill, row, time } from "../ui.ts";
@@ -289,6 +291,20 @@ export function footingSection(f: Footing): Html {
289291 ${(Object.keys(MACHINES) as Machine[]).map((m) => html`<p class="small muted" data-machine="${m}"><span class="mono">${m}</span>: ${MACHINES[m]}</p>`)}`, { id: "sys-footing-more" })}</section>`;
290292 }
291293
294 /**
295 * What the forge costs (#12092): the last reading at rest (this process's, else
296 * the release proof's), the stated budget, and what is switched off and why.
297 */
298 export function footprintSection(f: Footprint | null): Html {
299 if (f === null)
300 return html`<section class="settings-block" id="sys-footprint"><h2>What the forge costs</h2><p class="small muted">Not read yet: the release proof reads it once this version answers. Budget at rest: ${Math.round(BUDGET.restBytes / 1048576)} MiB, first page within ${BUDGET.readyMs} ms.</p></section>`;
301 return html`<section class="settings-block" id="sys-footprint" data-within="${String(f.withinBudget)}"><h2>What the forge costs</h2>
302 <p class="small">${f.withinBudget ? "Within budget. " : "Over budget. "}${footprintWords(f)} One process, ${f.threads} thread.</p>
303 <ul class="list" aria-label="Optional parts">${f.optional.map((o) =>
304 row({ title: o.name, facts: [{ label: o.on ? "On" : "Off", value: o.why }], data: { optional: o.name, on: String(o.on) } }),
305 )}</ul></section>`;
306 }
307
292308 /**
293309 * The off-site backup lane (#11805): where the forge's own mirror pass
294310 * writes, whether it seals what it writes, when it last succeeded, and the
@@ -533,6 +549,7 @@ export async function systemPage(ctx: Ctx): Promise<Response> {
533549 <div class="js-only small muted">Sort by <button class="btn" data-size="sm" type="button" data-sort="cpu" aria-pressed="true"><kbd>c</kbd> CPU</button>
534550 <button class="btn" data-size="sm" type="button" data-sort="mem" aria-pressed="false"><kbd>m</kbd> memory</button></div>
535551 <div id="sys-procs" data-live-hold>${at("sys-procs")}</div></section>
552 ${footprintSection(lastFootprint() ?? lastProof(ctx.app.config.dataDir)?.footprint ?? null)}
536553 ${footingSection(standsOn)}
537554 ${offsiteSection(timePhase(ctx.request, "offsite", () => readOffsiteLane(ctx.app.config.dataDir, ctx.app.db)))}
538555 ${featuresSection(timePhase(ctx.request, "features", () => featureHealth(ctx.app, reader)))}
test/footprint.test.ts added +34
@@ -0,0 +1,34 @@
1 import { expect, test } from "bun:test";
2 import { mkdtempSync, writeFileSync } from "node:fs";
3 import { join } from "node:path";
4 import { tmpdir } from "node:os";
5 import { BUDGET, footprintWords, markReady, optionals, readFootprint } from "../src/system/footprint.ts";
6 import { footprintSection } from "../src/web/pages/system.ts";
7 import { proveRelease, lastProof } from "../src/release/prove.ts";
8
9 test("a small machine says what is off and why", () => {
10 const o = optionals(1, 512 * 1024 * 1024, null, null);
11 expect(o.map((x) => [x.name, x.on])).toEqual([["Chromium (looks)", false], ["Crew AI tool", false], ["Serve/work threads", false]]);
12 expect(o[2]!.why).toContain("one process, one thread");
13 });
14
15 test("a reading is measured: memory, disk, first page", async () => {
16 const dir = mkdtempSync(join(tmpdir(), "fp-"));
17 writeFileSync(join(dir, "a"), "x".repeat(10_000));
18 markReady(1.5);
19 const f = await readFootprint(dir);
20 expect(f.rssBytes).toBeGreaterThan(0);
21 expect(f.diskBytes).toBeGreaterThanOrEqual(10_000);
22 expect(f.readyMs).not.toBeNull();
23 expect(f.threads).toBe(1);
24 expect(footprintWords(f)).toContain("resident");
25 expect(String(footprintSection({ ...f, rssBytes: BUDGET.restBytes + 1, withinBudget: false }))).toContain("Over budget");
26 });
27
28 test("the release proof records the footprint at rest", async () => {
29 const dir = mkdtempSync(join(tmpdir(), "fp-"));
30 const fp = await readFootprint(dir);
31 const fetcher = (async () => new Response("ok", { headers: { "x-forge-version": "1.0.0" } })) as unknown as typeof fetch;
32 await proveRelease({ dataDir: dir, version: "1.0.0", url: "http://x.test", fetch: fetcher, giveUpMs: 1, sleep: async () => {}, footprint: async () => fp }).catch(() => {});
33 expect(lastProof(dir)?.footprint?.rssBytes).toBe(fp.rssBytes);
34 });
test/memory-ceiling.test.ts +7
@@ -19,6 +19,13 @@ describe("the memory ceiling is never a silent clamp (#3128)", () => {
1919 expect(memoryCeiling(undefined, "/nonexistent/memory.max")).toBe(4096);
2020 });
2121
22 test("a small pod leaves the forge its own room: the check dies, not the forge (#12092)", () => {
23 expect(memoryCeiling(undefined, pod(String(384 * 1048576)))).toBe(192);
24 expect(memoryCeiling(undefined, pod(String(512 * 1048576)))).toBe(320);
25 expect(memoryCeiling(undefined, pod(String(256 * 1048576)))).toBe(64);
26 expect(memoryCeiling(undefined, pod(String(2048 * 1048576)))).toBe(1536);
27 });
28
2229 test("a declared memory above the ceiling produces a warning; within it, none", () => {
2330 const saved = process.env["FORGE_CELL_MEMORY_MAX_MIB"];
2431 process.env["FORGE_CELL_MEMORY_MAX_MIB"] = "4096";
test/system-parts.test.ts +1
@@ -54,6 +54,7 @@ test("one <h2> per part, each in a settings-block, and no card", async () => {
5454 "Largest under the forge's data",
5555 "Database size",
5656 "Processes",
57 "What the forge costs",
5758 "What the forge stands on",
5859 "Off-site backup",
5960 "Loop lag, last 20 minutes",

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs