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

A front router wakes an asleep forge on its first request and says "waking…" while it does #16882

Merged opened this

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

Merged

scout/forge:scout/16854-a-front-router-wakes-an-asleep-forge-on → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/16854-a-front-router-wakes-an-asleep-forge-on was merged into main as 2d3e9b2.

Review

Sign in to review this change.
3 files changed +118 −3
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. A page for a sleeping cell forge answers a plain "waking up" page at once (git and API calls wait up to 4 s) (503, `retry-after`, reloads itself); a hosted one opens in-process.
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.
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/spawn/host.ts +13 −2
@@ -1138,7 +1138,7 @@ export async function answerFromCell(parent: App, request: Request, named?: stri
11381138 waiters.set(ledger.bodyId, waiting + 1);
11391139 let woke: CellChild | undefined;
11401140 try {
1141 woke = await Promise.race([starting, Bun.sleep(wakeLimits.waitMs).then(() => undefined)]);
1141 woke = await Promise.race([starting, Bun.sleep(patienceOf(request)).then(() => undefined)]);
11421142 } finally {
11431143 const left = (waiters.get(ledger.bodyId) ?? 1) - 1;
11441144 if (left <= 0) waiters.delete(ledger.bodyId);
@@ -1168,7 +1168,18 @@ const waitsToMove = (name: string): string => `${name} is waiting to be moved in
11681168 * How long a request waits for a sleeping cell forge before it is told it is waking, and how many
11691169 * may wait on one cell.
11701170 */
1171 export const wakeLimits = { waitMs: 20_000, waiters: 16 };
1171 export const wakeLimits = { waitMs: 20_000, pageMs: 1_500, waiters: 16 };
1172
1173 /**
1174 * How long this request waits for the wake. A browser navigating (a GET that asks for HTML) is
1175 * held only `pageMs`: a quick wake is never seen, a slow one shows the "waking up" page that
1176 * refreshes itself. Everything else (an API call, a git client, a form's POST, which a refresh
1177 * would lose) is held the whole `waitMs`, never shown HTML.
1178 */
1179 export function patienceOf(request: Request): number {
1180 const page = (request.method === "GET" || request.method === "HEAD") && (request.headers.get("accept") ?? "").includes("text/html");

Next: a GET with no Accept header is held the full waitMs. Webviews and some link previewers send none; they would hang 20 s with no page. Consider treating a missing Accept like a page.

1181 return page ? Math.min(wakeLimits.pageMs, wakeLimits.waitMs) : wakeLimits.waitMs;
1182 }
11721183
11731184 /** Requests held for a waking cell now, by body id. */
11741185 const waiters = new Map<string, number>();
test/front-wake.test.ts added +104
@@ -0,0 +1,104 @@
1 /**
2 * A request to an asleep forge wakes it once, holds API and git clients, and shows a browser
3 * "waking up" (#16854).
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, patienceOf, provideCellsForTest, wakeLimits, closeHostedChildren } from "../src/spawn/host.ts";
12 import { cancelRestarts } from "../src/spawn/stopped.ts";
13 import { quietLogs } from "./helpers/globals.ts";
14
15 quietLogs();
16 const tmp = mkdtempSync(join(tmpdir(), "front-wake-"));
17 const parents: App[] = [];
18 const upstream = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: (r) => new Response(`up ${r.method}`) });
19 afterAll(() => {
20 provideCellsForTest();
21 for (const p of parents) {
22 cancelRestarts(p);
23 closeHostedChildren(p);
24 p.close();
25 }
26 upstream.stop(true);
27 rmSync(tmp, { recursive: true, force: true });
28 });
29
30 /** A parent with one asleep cell forge whose start takes `startMs`; counts its starts. */
31 function asleep(name: string, startMs: number) {
32 provideCellsForTest(() => Promise.resolve({ ok: true }));
33 const dataDir = join(tmp, name);
34 mkdirSync(join(dataDir, "spawn"), { recursive: true });
35 writeFileSync(join(dataDir, "spawn", "kid.json"), JSON.stringify({ name: "kid", bodyId: `cell-${name}`, size: "small", done: true, placement: "cell" }));
36 const parent = createApp({ dataDir, url: "https://f.test" });
37 parents.push(parent);
38 const cells = cellChildren(parent) as unknown as { start: unknown; get: unknown; failure: unknown };
39 let held: CellChild | undefined;
40 let starts = 0;
41 cells.start = async () => {
42 starts++;
43 await Bun.sleep(startMs); // real-timer: the router under test holds a browser on a real 1.5 s timer; the start must take real time
44 held = { bodyId: `cell-${name}`, name: "kid", size: "small", port: upstream.port!, limits: { memoryMiB: 1, cpus: 1, diskMiB: 1 }, pid: 1, exited: new Promise<number>(() => {}) } as CellChild;
45 return held;
46 };
47 cells.get = () => held;
48 cells.failure = () => undefined;
49 return { parent, starts: () => starts, sleepAgain: () => (held = undefined) };
50 }
51 const ask = (method = "GET", accept = "text/html"): Request => new Request("https://kid--f.test/x", { method, headers: { host: "kid--f.test", accept } });
52
53 describe("the front router wakes an asleep forge", () => {
54 test("p95 of the wake, measured over 20 wakes, is under a second", async () => {
55 const f = asleep("p95", 20);
56 const times: number[] = [];
57 for (let i = 0; i < 20; i++) {
58 f.sleepAgain();
59 const t = performance.now();
60 const res = await answerFromCell(f.parent, ask("GET", "application/json"));
61 times.push(performance.now() - t);
62 expect(await res.text()).toBe("up GET");
63 }
64 times.sort((a, b) => a - b);
65 const p95 = times[Math.ceil(times.length * 0.95) - 1]!;
66 expect(p95).toBeLessThan(1000);
67 });
68
69 test("requests that arrive during one wake are all served by one start", async () => {
70 const f = asleep("once", 100);
71 const all = await Promise.all([ask(), ask("GET", "application/json"), ask("POST", "*/*"), ask("GET", "*/*")].map((r) => answerFromCell(f.parent, r)));
72 expect(all.map((r) => r.status)).toEqual([200, 200, 200, 200]);
73 expect(f.starts()).toBe(1);
74 });
75
76 test("a browser is shown a waking page that refreshes itself; an API or git client and a POST are held, never shown HTML", async () => {
77 const was = { ...wakeLimits };
78 wakeLimits.pageMs = 20;
79 wakeLimits.waitMs = 2_000;
80 try {
81 const f = asleep("kinds", 300);
82 const [page, api, git, post] = await Promise.all([
83 answerFromCell(f.parent, ask()),
84 answerFromCell(f.parent, ask("GET", "application/json")),
85 answerFromCell(f.parent, new Request("https://kid--f.test/x.git/info/refs", { headers: { host: "kid--f.test" } })),
86 answerFromCell(f.parent, ask("POST", "text/html")),
87 ]);
88 expect(page.status).toBe(503);
89 expect(page.headers.get("content-type")).toContain("text/html");
90 expect(page.headers.get("refresh")).not.toBeNull();
91 expect(await page.text()).toContain("waking up");
92 for (const held of [api, git, post]) expect(await held.text()).toStartWith("up ");
93 expect(f.starts()).toBe(1);
94 } finally {
95 Object.assign(wakeLimits, was);
96 }
97 });
98
99 test("patience: only a navigating GET is short", () => {
100 expect(patienceOf(ask())).toBe(wakeLimits.pageMs);
101 expect(patienceOf(ask("POST"))).toBe(wakeLimits.waitMs);
102 expect(patienceOf(ask("GET", "application/json"))).toBe(wakeLimits.waitMs);
103 });
104 });

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

Keyboard shortcuts

Docs