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

An idle forge drains and sleeps after a quiet period its owner can set #16903

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16855-an-idle-forge-drains-and-sleeps-after-a → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/16855-an-idle-forge-drains-and-sleeps-after-a was merged into main as 240362e.

Review

Sign in to review this change.
8 files changed +180 −9
docs/features/forge-sleep.md +1 −1
@@ -6,7 +6,7 @@ row: Hosted forges that scale to zero
66
77 A person (or their assistant, over the MCP `spawn` tool with their consent) makes a forge at `/forges/new`, the address `<name>--<this host>`. Free within the limits below; no payment path yet.
88
9 - **Sleep.** A forge with no request for `FORGE_CHILD_IDLE_S` (600) sleeps: a hosted child's App and apps close, a cell child's process stops. Data stays under `children/<bodyId>`. The next page load, `git push` or API call wakes it. The front router starts a sleeping cell forge once however many requests arrive (#16854): a browser's page load is held `wakeLimits.pageMs` (1.5 s), so a quick wake is never seen, then gets the plain "waking up" page (503, `retry-after`, reloads itself); an API call, a git client or a POST is held up to `wakeLimits.waitMs` (20 s) and never shown HTML. `test/front-wake.test.ts` wakes an asleep forge 20 times and holds the p95 under 1 s; a hosted one opens in-process.
9 - **Sleep.** A forge with no request for the quiet minutes an admin sets (`forges.idle_minutes` at `/admin/limits`, default 10, with its reason beside it; `FORGE_CHILD_IDLE_S` is read only while it is unset) drains and sleeps (#16855): `/forges` and the terminal's forges screen say when and what that means. A forge asleep with crew work due wakes when it falls due; an app's own timer does not wake it yet (#16918). Asleep means a hosted child's App and apps close, a cell child's process stops. Data stays under `children/<bodyId>`. The next page load, `git push` or API call wakes it. The front router starts a sleeping cell forge once however many requests arrive (#16854): a browser's page load is held `wakeLimits.pageMs` (1.5 s), so a quick wake is never seen, then gets the plain "waking up" page (503, `retry-after`, reloads itself); an API call, a git client or a POST is held up to `wakeLimits.waitMs` (20 s) and never shown HTML. `test/front-wake.test.ts` wakes an asleep forge 20 times and holds the p95 under 1 s; a hosted one opens in-process.
1010 - **Limits, each refused in words.** The admin limits `forges.per_person` (3) and `forges.storage_mb` (1000 MB), set at `/admin/limits` (the same list is on the terminal's limits screen), each refused in a sentence naming the limit and the person's use (site admins exempt), the capacity setting `children.awake` (default from memory, at least 8, one per 720 MiB above 2 GiB; boot default `FORGE_CHILD_AWAKE_MAX`; sleeping forges do not count, new ones do; at the ceiling the forge idle longest, quiet for 10 s, is put to sleep to make room, and a wake is refused only when every awake forge is in use), `FORGE_CHILD_WAKES_PER_HOUR` (20 per forge), the admin limit `forges.wakes_per_person_hour` (30 wakes an hour, counted against the forge's owner once someone has claimed it and against the forge itself until then, never against whoever sent it; a site admin's own forge is counted like anyone's; refused in a sentence that says whose wakes are spent, in how long the forge can be woken again, and the limit's name and where an admin raises it), plus the existing size/quota limits (`FORGE_CHILD_*_MIB`), and each cell's own disk cap.
1111 - **Owner.** `/forges` shows awake/asleep, size, last activity, with Stop (sleep now) and Remove (ledger and data).
1212 - **Secrets.** A child starts from `childEnv` and never sees this forge's model credential; the person brings their own or its crew stays off.
src/settings/limits.ts +9
@@ -59,6 +59,7 @@ export type LimitKey =
5959 | "spawn.birth_memory_mb"
6060 | "spawn.timers_max"
6161 | "forges.wakes_per_forge_hour"
62 | "forges.idle_minutes"
6263 | "forge.memory_floor_mb"
6364 | "drill.memory_mb"
6465 | "guest.storage_mb"
@@ -311,6 +312,14 @@ export const LIMITS: Record<LimitKey, LimitDef> = {
311312 max: 10_000,
312313 reason: "A stranger's visits can wake a sleeping forge again and again; one forge is woken this often at most. FORGE_CHILD_WAKES_PER_HOUR is read only while this is not set.",
313314 },
315 "forges.idle_minutes": {
316 label: "Quiet minutes before a forge sleeps",
317 unit: "minutes",
318 default: 10,
319 min: 1,
320 max: 10_080,
321 reason: "A forge nobody has asked for in this long drains and its process exits, so it costs no memory; the next visit wakes it and data stays. Shorter packs more forges on one machine, longer means fewer waking pages. FORGE_CHILD_IDLE_S is read only while this is not set.",
322 },
314323 "gifts.per_subscriber": {
315324 label: "Gifts a subscriber may give",
316325 unit: "gifts",
src/spawn/host.ts +3 −3
@@ -254,7 +254,7 @@ function working(parent: App, child: App): boolean {
254254 * closes, a cell child's process stops. Their data stays on disk; the next request
255255 * wakes them. Answers the names put to sleep.
256256 */
257 export async function sleepIdleChildren(parent: App, idleMs = idleAfterMs(), now = Date.now()): Promise<string[]> {
257 export async function sleepIdleChildren(parent: App, idleMs = idleAfterMs(process.env, parent.db), now = Date.now()): Promise<string[]> {
258258 const asleep: string[] = [];
259259 const cache = caches.get(parent);
260260 for (const [bodyId, child] of [...(cache ?? [])]) {
@@ -564,7 +564,7 @@ async function closeOne(parent: App, cache: Map<string, App>, bodyId: string, ch
564564
565565 function keepSweeping(parent: App): void {
566566 if (sweepers.has(parent)) return;
567 const every = Math.max(1000, Math.min(60_000, Math.floor(idleAfterMs() / 4)));
567 const every = Math.max(1000, Math.min(60_000, Math.floor(idleAfterMs(process.env, parent.db) / 4)));
568568 const timer = setInterval(() => void during("spawn-idle", async () => {
569569 await sleepLapsed(parent);
570570 await retireLapsedCloud(parent);
@@ -713,7 +713,7 @@ export function closeHostedChildren(parent: App): void {
713713 // The forges in use now are the ones the next boot starts; the rest stay asleep through a
714714 // release.
715715 const now = Date.now();
716 const inUse = [...(touched.get(parent)?.values() ?? [])].filter((m) => now - m.at < idleAfterMs()).map((m) => m.name);
716 const inUse = [...(touched.get(parent)?.values() ?? [])].filter((m) => now - m.at < idleAfterMs(process.env, parent.db)).map((m) => m.name);
717717 if (inUse.length > 0 || touched.has(parent)) rememberAwake(parent.config.dataDir, inUse);
718718 const sweeper = sweepers.get(parent);
719719 if (sweeper !== undefined) clearInterval(sweeper);
src/spawn/sleep.ts +19 −2
@@ -31,8 +31,25 @@ function settled(db: Database | undefined, key: LimitKey, env: Env, name: string
3131 return db !== undefined && limitIsSet(db, key) ? limitValue(db, key) : whole(env, name, fallback);
3232 }
3333
34 /** A forge quiet for this long sleeps: FORGE_CHILD_IDLE_S, ten minutes by default. */
35 export const idleAfterMs = (env: Env = process.env): number => whole(env, "FORGE_CHILD_IDLE_S", 600) * 1000;
34 /**
35 * A forge quiet for this long sleeps: the setting `forges.idle_minutes` when set, else
36 * FORGE_CHILD_IDLE_S, ten minutes by default.
37 */
38 export const idleAfterMs = (env: Env = process.env, db?: Database): number =>
39 db !== undefined && limitIsSet(db, "forges.idle_minutes")
40 ? limitValue(db, "forges.idle_minutes") * 60_000
41 : whole(env, "FORGE_CHILD_IDLE_S", 600) * 1000;
42
43 /**
outdated

Shorten to one plain sentence (docs/WRITING.md). The /admin/limits pointer is shown to non-admins who cannot use it; show it only to admins, or drop it.

44 * What sleeping means, in the one sentence the page and the terminal share: when, and that data
45 * stays.
46 */
47 export function sleepWords(idleMs: number): string {
48 const min = Math.round(idleMs / 60_000);
49 const after = min >= 120 && min % 60 === 0 ? `${min / 60} hours` : min === 1 ? "1 minute" : `${min} minutes`;
50 return `A forge nobody has asked for in ${after} goes to sleep; its data stays.`;
51 }
52
3653 /**
3754 * Most hosted forges awake at once from the environment alone (the capacity setting
3855 * `children.awake` is read where a database is at hand). A sleeping forge does not count.
src/tui/screens/forges.ts +6 −2
@@ -15,6 +15,7 @@ import { drawFacts, runAsync } from "./common.ts";
1515 import type { PaletteEntry } from "./entries.ts";
1616 import { clientRows } from "../../spawn/clients.ts";
1717 import { weekLine } from "../../spawn/client_week.ts";
18 import { idleAfterMs, sleepWords } from "../../spawn/sleep.ts";
1819 import { parseClientQuery, searchClients } from "../../spawn/client_search.ts";
1920 import { CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, nextClientState, type ClientState } from "../../spawn/client_state.ts";
2021 import { diskWords } from "../../spawn/disk_mount.ts";
@@ -143,10 +144,13 @@ export function withWeek(rows: readonly ClientRow[], lines: [string, string][],
143144 export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Session, from: ClientState | null = null): Screen {
144145 let state = from;
145146 let q = "";
147 // What sleeping means is the page's line too (`data-sleep`).
148 const withSleep = (l: [string, string][]): [string, string][] =>
149 rows.length === 0 || session === undefined ? l : [["", sleepWords(idleAfterMs(process.env, session.app.db))], ...l];
146150 const redraw = (): void => {
147 lines = withWeek(rows, stateLines(rows, state, session?.user?.isAdmin === true, Date.now(), q));
151 lines = withSleep(withWeek(rows, stateLines(rows, state, session?.user?.isAdmin === true, Date.now(), q)));
148152 };
149 let lines = withWeek(rows, stateLines(rows, state, session?.user?.isAdmin === true));
153 let lines = withSleep(withWeek(rows, stateLines(rows, state, session?.user?.isAdmin === true)));
150154 // Stop and Remove are the page's buttons, through the same actions (`spawn/manage.ts`).
151155 const choose = (title: string, act: (name: string) => void): void => {
152156 const items = rows.filter((r) => r.made).map((r) => ({ id: r.name, label: r.name, hint: r.awake === true ? "awake" : "asleep" }));
src/web/pages/forges.ts +2
@@ -41,6 +41,7 @@ import { archiveForge, archivedForges, restoreForge, type ArchiveRecord } from "
4141 import { rowActivityWords, sentWords } from "../../spawn/client_words.ts";
4242 import { CLIENT_STATES, CLIENT_STATE_EMPTY, CLIENT_STATE_WORDS, narrowByState, parseClientState, stateCounts } from "../../spawn/client_state.ts";
4343 import { weekLine } from "../../spawn/client_week.ts";
44 import { idleAfterMs, sleepWords } from "../../spawn/sleep.ts";
4445 import { parseClientQuery, searchClients } from "../../spawn/client_search.ts";
4546 import { claimedWords, isForgeSort, keepWords, SORT_WORDS, sortForges, type ForgeSort } from "../../spawn/keep_words.ts";
4647 import { CHILD_NAME } from "../../spawn/placement.ts";
@@ -302,6 +303,7 @@ export async function forgesPage(ctx: Ctx): Promise<Response> {
302303 })}
303304 ${over === undefined ? null : html`<p class="muted small" role="status" data-memory-over>${over}</p>`}
304305 ${receipt(ctx, everyone)}
306 ${everyone.length === 0 ? null : html`<p class="muted small" data-sleep>${sleepWords(idleAfterMs(process.env, ctx.app.db))}</p>`}

Principle 1 and 3: a three-sentence paragraph above the week line on every load. One sentence: when it sleeps, that data stays. Also no test covers this line; add one asserting data-sleep shows the set minutes.

305307 ${everyone.length === 0 ? null : html`<p class="muted small" data-week>${weekLine(everyone, now)}</p>`}
306308 ${everyone.length === 0
307309 ? html`<section class="settings-block">
test/clients-week-line.test.ts +29 −1
@@ -10,7 +10,12 @@ import { createUser } from "../src/core/users.ts";
1010 import { hostedPlacement } from "../src/spawn/placement.ts";
1111 import { clientRows } from "../src/spawn/clients.ts";
1212 import { forgesPage } from "../src/web/pages/forges.ts";
13 import { forgeLines, withWeek } from "../src/tui/screens/forges.ts";
13 import { forgeLines, forgesScreen, withWeek } from "../src/tui/screens/forges.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { headlessTerminal } from "../src/tui/term/terminal.ts";
16 import { setLimit } from "../src/settings/limits.ts";
17 import { sleepWords } from "../src/spawn/sleep.ts";
18 import { settleApp } from "./helpers/tui.ts";
1419 import { weekCounts, weekLine, weekStart, type WeekRow } from "../src/spawn/client_week.ts";
1520
1621 // Wednesday 2026-11-18 12:00 UTC; that week began Monday 2026-11-16 00:00 UTC.
@@ -107,3 +112,26 @@ describe("the week line on the page and in the terminal", () => {
107112 expect(withWeek([], forgeLines([]))).toEqual(forgeLines([]));
108113 });
109114 });
115
116 describe("the sleep line on the page and in the terminal (#16855)", () => {
117 test("/forges carries the set minutes in data-sleep, and nothing when the list is empty", async () => {
118 const { app, admin } = await forgeWith(["fresh"], []);
119 setLimit(app.db, "forges.idle_minutes", 7, "test");
120 expect(await pageOf(app, admin)).toContain(`<p class="muted small" data-sleep>${sleepWords(420_000)}</p>`);
121 expect(sleepWords(420_000)).toContain("in 7 minutes");
122 const empty = await forgeWith([], []);
123 expect(await pageOf(empty.app, empty.admin)).not.toContain("data-sleep");
124 });
125
126 test("the terminal's forges screen starts with the same words", async () => {
127 const { app, admin } = await forgeWith(["fresh"], []);
128 setLimit(app.db, "forges.idle_minutes", 7, "test");
129 const { app: tui, session } = createForgeApp(app, { sshUsername: admin.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: admin }, { terminal: headlessTerminal(160, 30), exitHooks: false });
130 tui.start();
131 await settleApp(tui);
132 tui.push(forgesScreen(tui.ctx, await clientRows(app), session));
133 await settleApp(tui);
134 expect(tui.screen.toText()).toContain(sleepWords(420_000));
135 tui.stop();
136 });
137 });
test/forge-idle-setting.test.ts added +111
@@ -0,0 +1,111 @@
1 /**

Missing: a page test for the data-sleep line, a terminal-screen test for the same words, and a sleep racing a request. Box 2's app timer wake is also untested because it is not built.

2 * The quiet period before a forge sleeps is a setting (#16855): it is read live, the sweep puts the
3 * forge to sleep with it, and a burst of requests after loses none.
4 */
5 import { afterAll, describe, expect, test } from "bun:test";
6 import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { cellChildren, type CellChild } from "../src/spawn/cell.ts";
11 import { answerFromCell, closeHostedChildren, provideCellsForTest, sleepIdleChildren } from "../src/spawn/host.ts";
12 import { cancelRestarts } from "../src/spawn/stopped.ts";
13 import { idleAfterMs, sleepWords } from "../src/spawn/sleep.ts";
14 import { setLimit } from "../src/settings/limits.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16
17 quietLogs();
18 const tmp = mkdtempSync(join(tmpdir(), "idle-setting-"));
19 const parents: App[] = [];
20 const upstream = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (r) => new Response(`up ${new URL(r.url).pathname}`) });
21 afterAll(() => {
22 provideCellsForTest();
23 for (const p of parents) {
24 cancelRestarts(p);
25 closeHostedChildren(p);
26 p.close();
27 }
28 upstream.stop(true);
29 rmSync(tmp, { recursive: true, force: true });
30 });
31
32 function parentWithAsleepForge() {
33 provideCellsForTest(() => Promise.resolve({ ok: true }));
34 const dataDir = join(tmp, "p");
35 mkdirSync(join(dataDir, "spawn"), { recursive: true });
36 writeFileSync(join(dataDir, "spawn", "kid.json"), JSON.stringify({ name: "kid", bodyId: "cell-idle", size: "small", done: true, placement: "cell" }));
37 const parent = createApp({ dataDir, url: "https://f.test" });
38 parents.push(parent);
39 const cells = cellChildren(parent) as unknown as { start: unknown; get: unknown; failure: unknown; sleepIdle: unknown };
40 let held: CellChild | undefined;
41 let starts = 0;
42 const sleepsAsked: number[] = [];
43 cells.start = async () => {
44 starts++;
45 await Promise.resolve(); // the burst is already in flight when the start settles
46 held = { bodyId: "cell-idle", name: "kid", size: "small", port: upstream.port!, limits: { memoryMiB: 1, cpus: 1, diskMiB: 1 }, pid: 1, exited: new Promise<number>(() => {}) } as CellChild;
47 return held;
48 };
49 cells.get = () => held;
50 cells.failure = () => undefined;
51 const gate = { open: () => {}, closed: Promise.resolve() as Promise<void> };
52 cells.sleepIdle = async (idleMs: number) => {
53 sleepsAsked.push(idleMs);
54 await gate.closed; // a drain that takes time, as a real process exit does
55 if (held === undefined) return [];
56 held = undefined; // the process exits
57 return ["kid"];
58 };
59 const hold = (): void => {
60 gate.closed = new Promise<void>((r) => (gate.open = r));
61 };
62 return { hold, release: () => gate.open(), parent, starts: () => starts, sleepsAsked, awake: () => held !== undefined };
63 }
64 const ask = (path: string): Request => new Request(`https://kid--f.test${path}`, { headers: { host: "kid--f.test", accept: "application/json" } });
65
66 describe("quiet minutes before a forge sleeps", () => {
67 test("the setting wins over the environment and the default stands without either", () => {
68 const parent = createApp({ dataDir: mkdtempSync(join(tmp, "s-")), url: "https://f.test" });
69 parents.push(parent);
70 expect(idleAfterMs({}, parent.db)).toBe(600_000);
71 expect(idleAfterMs({ FORGE_CHILD_IDLE_S: "120" }, parent.db)).toBe(120_000);
72 setLimit(parent.db, "forges.idle_minutes", 3, "test");
73 expect(idleAfterMs({ FORGE_CHILD_IDLE_S: "120" }, parent.db)).toBe(180_000);
74 });
75
76 test("the words say when, and what stays", () => {
77 expect(sleepWords(180_000)).toContain("in 3 minutes");
78 expect(sleepWords(60_000)).toContain("in 1 minute goes");
79 expect(sleepWords(7_200_000)).toContain("2 hours");
80 expect(sleepWords(600_000)).toContain("data stays");
81 });
82
83 test("the sweep sleeps a forge by the setting, and a burst of requests after it is all answered by one wake", async () => {
84 const f = parentWithAsleepForge();
85 setLimit(f.parent.db, "forges.idle_minutes", 3, "test");
86 // Wake it once, as a visit would.
87 expect(await (await answerFromCell(f.parent, ask("/first"))).text()).toBe("up /first");
88 expect(f.awake()).toBe(true);
89 await sleepIdleChildren(f.parent);
90 expect(f.sleepsAsked).toEqual([180_000]);
91 expect(f.awake()).toBe(false);
92 const paths = Array.from({ length: 12 }, (_, i) => `/r${i}`);
93 const bodies = await Promise.all(paths.map(async (p) => (await answerFromCell(f.parent, ask(p))).text()));
94 expect(bodies).toEqual(paths.map((p) => `up ${p}`));
95 expect(f.starts()).toBe(2);
96 });
97
98 test("requests that arrive while the sweep is putting the forge to sleep are all answered", async () => {
99 const f = parentWithAsleepForge();
100 expect(await (await answerFromCell(f.parent, ask("/first"))).text()).toBe("up /first");
101 f.hold();
102 const sweep = sleepIdleChildren(f.parent);
103 const during = Array.from({ length: 6 }, (_, i) => `/d${i}`);
104 const inFlight = during.map(async (p) => (await answerFromCell(f.parent, ask(p))).text());
105 f.release();
106 await sweep;
107 const after = Array.from({ length: 6 }, (_, i) => `/a${i}`);
108 const late = after.map(async (p) => (await answerFromCell(f.parent, ask(p))).text());
109 expect(await Promise.all([...inFlight, ...late])).toEqual([...during, ...after].map((p) => `up ${p}`));
110 });
111 });

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

Keyboard shortcuts

Docs