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

Spawn sizes: small, medium, large in the plan, the ledger and parent.json, with a quota #2947

Parked opened this
Closed without merging

scout/forge:scout/2925-spawn-sizes-small-medium-large-in-the-pl → main 2 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +348 −9
README.md +8
@@ -140,6 +140,14 @@ data under `$FORGE_DATA/children/`. Browsers send `*.localhost` to this
140140 machine; curl needs `--resolve kid--localhost:3000:127.0.0.1`. The rest is in
141141 `docs/SPAWN.md`.
142142
143 A child has a `size`: `small` (default), `medium` or `large`, presets of CPU,
144 memory and disk in `src/spawn/sizes.ts`, recorded in the ledger, `parent.json`

Say where a person chooses the size: the "How much it holds" field on the page, the terminal's new-forge screen once it has the field, size on POST /api/v1/forges and the MCP spawn tool.

145 and `GET /api/v1/forges`. What the host hands out to all its children is
146 `FORGE_CHILD_CPUS`, `FORGE_CHILD_MEMORY_MIB` and `FORGE_CHILD_DISK_MIB` (default:
147 the machine's); a spawn past it is a 409 `refused`. The size is chosen under "How much it
148 holds" on `/forges/new`, in the size field of the terminal's new-forge screen,
149 as `size` in `POST /api/v1/forges` and in the MCP `spawn` tool.
150
143151 The commits the forge writes for you — merges, squashes, reverts, web edits —
144152 carry `[email protected].<forge host>`, never your account email. Choosing your
145153 real address is an opt-in under **Commit email** in `/settings` (or
src/actions/spawn.ts +10
@@ -55,6 +55,7 @@ import { claimLink, hasAdmin, mintClaim, spawnedOrg } from "../spawn/claim.ts";
5555 import { childPublicUrl, parentOrigin, type Placement } from "../spawn/placement.ts";
5656 import { planSpawn, type SpawnInput, type SpawnPlan, type SpawnSource } from "../spawn/plan.ts";
5757 import { chainForChild, DEFAULT_MODE, forgeLinkOf, type FollowMode, type Hop } from "../spawn/chain.ts";
58 import { DEFAULT_SIZE, resourcesOf, type Resources, type Size } from "../spawn/sizes.ts";
5859 import { requireUser } from "./access.ts";
5960
6061 export interface Spawned {
@@ -106,6 +107,8 @@ interface Ledger {
106107 readonly forWhom?: string;
107108 readonly apps?: readonly string[];
108109 readonly createdAt?: string;
110 /** What the child is declared to hold; absent means small. */
111 readonly size?: Size;
109112 /**
110113 * What the parent shows the child to learn its private facts (when anything
111114 * last happened); the child keeps only its hash. Never in an answer.
@@ -244,6 +247,7 @@ async function make(
244247 ...(plan.forWhom === undefined ? {} : { forWhom: plan.forWhom }),
245248 apps: plan.apps.map((a) => a.ref),
246249 createdAt: new Date().toISOString(),
250 ...(plan.size === undefined ? {} : { size: plan.size }),
247251 statusToken: secret(),
248252 beatKey: secret(),
249253 };
@@ -437,6 +441,8 @@ async function copyInto(
437441 // The child's own address: <name>--<parent's host>.
438442 url: liveChildUrl(app, plan.name),
439443 keepAccess: plan.keepAccess,
444 size: plan.size ?? DEFAULT_SIZE,
445 resources: resourcesOf(plan.size),
440446 // Each app is a fork: where it came from, so the child can follow it.
441447 apps: plan.apps.map((a) => ({ repo: `${plan.org}/${a.ref.split("/")[1]}`, upstream: a.ref })),
442448 ...(plan.fresh === undefined ? {} : { fresh: `${plan.org}/${plan.fresh.name}` }),
@@ -645,6 +651,8 @@ export interface Child {
645651 readonly apps: readonly string[];
646652 /** When it was begun; null on a ledger older than the client list. */
647653 readonly createdAt: string | null;
654 readonly size: Size;
655 readonly resources: Resources;
648656 }
649657
650658 /** The children this forge has made or begun, from its ledger, by name. */
@@ -663,6 +671,8 @@ export async function listChildren(app: App): Promise<Child[]> {
663671 for: ledger.forWhom ?? null,
664672 apps: ledger.apps ?? [],
665673 createdAt: ledger.createdAt ?? null,
674 size: ledger.size ?? DEFAULT_SIZE,
675 resources: resourcesOf(ledger.size),
666676 });
667677 }
668678 return out;
src/http/mcp.ts +6
@@ -1488,6 +1488,12 @@ const TOOLS: readonly Tool[] = [
14881488 description:
14891489 "How the child follows this forge's code: tell-me (default) says when the parent has moved; take-updates takes them.",
14901490 },
1491 size: {
1492 type: "string",
1493 enum: ["small", "medium", "large"],
1494 description:
1495 "What the child is declared to hold (CPU, memory, disk): small (default), medium or large. Refused when the host's quota for children is spent.",
1496 },
14911497 keepAccess: {
14921498 type: "boolean",
14931499 description:
src/spawn/door.ts +27 −4
@@ -24,9 +24,11 @@ import {
2424 type Placement,
2525 } from "./placement.ts";
2626 import { dryRun, planSpawn, KEY_BUDGET_NOTE, MAX_APPS, type CatalogApp, type CrewBrief, type SpawnSource } from "./plan.ts";
27 import { isSize, quotaFrom, type Quota, type Size } from "./sizes.ts";
2728 import { bootHostedChild } from "./host.ts";
2829 import { ANON_SPAWNS_PER_DAY, checkAnonSpawn, noteAnonSpawn } from "./rate.ts";
29 import { readdirSync, readFileSync } from "node:fs";
30 import { readdirSync, readFileSync, statfsSync } from "node:fs";
31 import { availableParallelism, totalmem } from "node:os";
3032 import { readdir, stat } from "node:fs/promises";
3133 import { join } from "node:path";
3234
@@ -71,6 +73,7 @@ function seedBodies(app: App, store: BodyStore): void {
7173 name?: unknown;
7274 bodyId?: unknown;
7375 url?: unknown;
76 size?: unknown;
7477 };
7578 if (typeof ledger.name !== "string" || typeof ledger.bodyId !== "string") continue;
7679 if (store.list().some((b) => b.bodyId === ledger.bodyId || b.name === ledger.name)) continue;
@@ -79,6 +82,7 @@ function seedBodies(app: App, store: BodyStore): void {
7982 name: ledger.name,
8083 url: childPublicUrl(ledger.name, origin),
8184 depth: 1,
85 ...(isSize(ledger.size) ? { size: ledger.size } : {}),
8286 agents: 1,
8387 ssh: false,
8488 });
@@ -88,20 +92,38 @@ function seedBodies(app: App, store: BodyStore): void {
8892 }
8993 }
9094
95 /** What the host hands out to children: `FORGE_CHILD_*`, else the machine's. */
96 function hostQuota(app: App): Quota {
97 let diskMiB = 1_048_576;
98 try {
99 const fs = statfsSync(app.config.dataDir);
100 diskMiB = Math.floor((fs.blocks * fs.bsize) / 1_048_576);
101 } catch {
102 // An unreadable disk leaves the quota to the declared value.
103 }
104 return quotaFrom(process.env, {
105 cpu: availableParallelism(),
106 memoryMiB: Math.floor(totalmem() / 1_048_576),
107 diskMiB,
108 });
109 }
110
91111 function placementFor(app: App): Placement {
92112 let p = placements.get(app);
93113 if (!p) {
94114 const store = memoryBodies();
95115 seedBodies(app, store);
96 p = hostedPlacement({ host: parentOrigin(app.config), store, maxChildren: () => maxChildren(app.db) });
116 p = hostedPlacement({ host: parentOrigin(app.config), store, maxChildren: () => maxChildren(app.db),
117 quota: () => hostQuota(app),
118 });
97119 placements.set(app, p);
98120 }
99121 return p;
100122 }
101123
102124 /** Why this forge can hold no child right now, or undefined when it can. */
103 export function noRoom(app: App): string | undefined {
104 return placementFor(app).room?.()?.message;
125 export function noRoom(app: App, size?: Size): string | undefined {
126 return placementFor(app).room?.(size)?.message;
105127 }
106128
107129 /** One status and one sentence per kind of failure. */
@@ -236,6 +258,7 @@ export async function spawnDoor(
236258 budgetUsd: raw["budgetUsd"],
237259 fresh: raw["fresh"],
238260 followMode: raw["followMode"],
261 size: raw["size"],
239262 ...(anon ? {} : { for: raw["for"] }),
240263 };
241264
src/spawn/placement.ts +21 −5
@@ -11,20 +11,21 @@
1111
1212 import { err, ok, type Result } from "../kernel/result.ts";
1313 import type { SpawnPlan } from "./plan.ts";
14 import { DEFAULT_SIZE, overQuota, type Quota, type Size } from "./sizes.ts";
1415
1516 export interface Placed {
1617 readonly url: string;
1718 readonly bodyId: string;
1819 }
1920
20 export type PlacementRefusal = { readonly reason: "children" | "depth" | "exists" | "unknown"; readonly message: string };
21 export type PlacementRefusal = { readonly reason: "children" | "depth" | "exists" | "quota" | "unknown"; readonly message: string };
2122
2223 export interface Placement {
2324 place(plan: SpawnPlan): Promise<Result<Placed, PlacementRefusal>>;
2425 /** Idempotent: retiring a body that is gone is a success. */
2526 retire(bodyId: string): Promise<Result<void, PlacementRefusal>>;
2627 /** Why no child fits here now (the depth or the count), before anyone fills in a form. */
27 room?(): PlacementRefusal | undefined;
28 room?(size?: Size): PlacementRefusal | undefined;
2829 }
2930
3031 /** What the hosted placement remembers about each child it holds. */
@@ -33,6 +34,8 @@ export interface Body {
3334 readonly name: string;
3435 readonly url: string;
3536 readonly depth: number;
37 /** What it was declared to hold; absent on a body older than sizes. */
38 readonly size?: Size;
3639 /** A hosted child runs one agent at a time and offers no SSH. */
3740 readonly agents: 1;
3841 readonly ssh: false;
@@ -140,6 +143,8 @@ export interface HostedOptions {
140143 /** A number, or a function read on every check so a setting applies live. */
141144 readonly maxChildren?: number | (() => number);
142145 readonly maxDepth?: number;
146 /** What all children together may hold; read on every check. Unlimited when absent. */
147 readonly quota?: () => Quota;
143148 readonly store?: BodyStore;
144149 /** Injectable so tests need no randomness. */
145150 readonly newId?: () => string;
@@ -156,7 +161,7 @@ export function hostedPlacement(opts: HostedOptions): Placement {
156161 const maxDepth = opts.maxDepth ?? MAX_DEPTH;
157162 const newId = opts.newId ?? (() => `hosted-${crypto.randomUUID()}`);
158163
159 const full = (): PlacementRefusal | undefined => {
164 const full = (size: Size = DEFAULT_SIZE): PlacementRefusal | undefined => {
160165 // A child lives one level below this forge; it may not exceed the limit.
161166 if (depth + 1 > maxDepth)
162167 return { reason: "depth", message: `forges nest at most ${maxDepth} deep; this one is already at ${depth}` };
@@ -167,13 +172,16 @@ export function hostedPlacement(opts: HostedOptions): Placement {
167172 reason: "children",
168173 message: `${held} of ${max} forges sent on this node — retire one, or raise the room in settings`,
169174 };
175 const quota = opts.quota?.();
176 const over = quota && overQuota(size, store.list().map((b) => b.size), quota);
177 if (over) return { reason: "quota", message: over };
170178 return undefined;
171179 };
172180
173181 return {
174182 room: full,
175183 async place(plan) {
176 const no = full();
184 const no = full(plan.size);
177185 if (no) return err(no);
178186 const held = store.list();
179187 if (held.some((b) => b.name === plan.name)) {
@@ -181,7 +189,15 @@ export function hostedPlacement(opts: HostedOptions): Placement {
181189 }
182190 const url = childPublicUrl(plan.name, opts.host);
183191 const bodyId = newId();
184 store.add({ bodyId, name: plan.name, url, depth: depth + 1, agents: 1, ssh: false });
192 store.add({
193 bodyId,
194 name: plan.name,
195 url,
196 depth: depth + 1,
197 ...(plan.size === undefined ? {} : { size: plan.size }),
198 agents: 1,
199 ssh: false,
200 });
185201 return ok({ url, bodyId });
186202 },
187203 async retire(bodyId) {
src/spawn/plan.ts +13
@@ -9,6 +9,7 @@
99
1010 import { err, ok, type Result } from "../kernel/result.ts";
1111 import { DEFAULT_MODE, type FollowMode } from "./chain.ts";
12 import { DEFAULT_SIZE, isSize, type Size } from "./sizes.ts";
1213
1314 export const MAX_APPS = 50;
1415 export const MAX_BRIEFS = 100;
@@ -69,6 +70,8 @@ export interface SpawnInput {
6970 readonly fresh?: unknown;
7071 /** How the child follows the forge's code: `tell-me` (default) or `take-updates`. */
7172 readonly followMode?: unknown;
73 /** How much the child is declared to hold: `small` (default), `medium` or `large`. */
74 readonly size?: unknown;
7275 }
7376
7477 /** What the parent has to offer. Extra fields are ignored, never copied. */
@@ -109,6 +112,8 @@ export interface SpawnPlan {
109112 readonly fresh?: PlannedFresh;
110113 /** How the child follows its parent's forge code; absent means `tell-me`. */
111114 readonly followMode?: FollowMode;
115 /** What the child is declared to hold; absent means `small`. */
116 readonly size?: Size;
112117 }
113118
114119 export interface DryRun {
@@ -250,6 +255,13 @@ export function planSpawn(
250255 if (input.followMode !== DEFAULT_MODE) followMode = input.followMode;
251256 }
252257
258 let size: Size | undefined;
259 if (input.size !== undefined && input.size !== null && input.size !== "") {
260 if (!isSize(input.size)) return refuse("size", "must be small, medium or large");
261 // Only a chosen size is named, so a plan without one hashes as it always did.
262 if (input.size !== DEFAULT_SIZE) size = input.size;
263 }
264
253265 // `forWhom` only when said, so a plan without it hashes as it always did.
254266 return ok({
255267 name,
@@ -263,6 +275,7 @@ export function planSpawn(
263275 ...(forWhom === "" ? {} : { forWhom }),
264276 ...(fresh === undefined ? {} : { fresh }),
265277 ...(followMode === undefined ? {} : { followMode }),
278 ...(size === undefined ? {} : { size }),
266279 });
267280 }
268281
src/spawn/sizes.ts added +65
@@ -0,0 +1,65 @@
1 /**
2 * Sizes: what a child forge is declared to hold, as presets in one table,
3 * and the quota the host hands out across all its children. Pure — the
4 * environment and the machine come in as arguments.
5 */
6
7 export const SIZES = ["small", "medium", "large"] as const;
8 export type Size = (typeof SIZES)[number];
9 export const DEFAULT_SIZE: Size = "small";
10
11 export interface Resources {
12 readonly cpu: number;
13 readonly memoryMiB: number;
14 readonly diskMiB: number;
15 }
16
17 export const PRESETS: Readonly<Record<Size, Resources>> = {
18 small: { cpu: 1, memoryMiB: 512, diskMiB: 2048 },
19 medium: { cpu: 2, memoryMiB: 2048, diskMiB: 8192 },
20 large: { cpu: 4, memoryMiB: 8192, diskMiB: 32768 },
21 };
22
23 export const isSize = (v: unknown): v is Size =>
24 typeof v === "string" && (SIZES as readonly string[]).includes(v);
25
26 /** The resources a child holds; a ledger older than sizes held a small one. */
27 export const resourcesOf = (size: Size | undefined): Resources => PRESETS[size ?? DEFAULT_SIZE];
28
29 /** What the host may hand out in total to its children. */
30 export type Quota = Resources;
31
32 const positive = (v: string | undefined): number | undefined => {
33 const n = v === undefined || !/^\d{1,9}$/.test(v.trim()) ? Number.NaN : Number(v);
34 return Number.isInteger(n) && n > 0 ? n : undefined;
35 };
36
37 /** The declared quota: `FORGE_CHILD_*` where set and valid, else the machine's. */
38 export function quotaFrom(env: Record<string, string | undefined>, machine: Quota): Quota {
39 return {
40 cpu: positive(env["FORGE_CHILD_CPUS"]) ?? machine.cpu,
41 memoryMiB: positive(env["FORGE_CHILD_MEMORY_MIB"]) ?? machine.memoryMiB,
42 diskMiB: positive(env["FORGE_CHILD_DISK_MIB"]) ?? machine.diskMiB,
43 };
44 }
45
46 /** One sentence when a child of `size` would push `held` past `quota`; undefined when it fits. */
47 export function overQuota(size: Size, held: readonly (Size | undefined)[], quota: Quota): string | undefined {
48 const used = { cpu: 0, memoryMiB: 0, diskMiB: 0 };
49 for (const s of held) {
50 const r = resourcesOf(s);
51 used.cpu += r.cpu;
52 used.memoryMiB += r.memoryMiB;
53 used.diskMiB += r.diskMiB;
54 }
55 const want = PRESETS[size];
56 const rows = [
57 ["CPUs", "cpu", ""],
58 ["MiB of memory", "memoryMiB", ""],
59 ["MiB of disk", "diskMiB", ""],
60 ] as const;
61 for (const [label, key] of rows)
62 if (used[key] + want[key] > quota[key])
63 return `a ${size} forge needs ${want[key]} ${label}; this host has ${Math.max(0, quota[key] - used[key])} of ${quota[key]} left for children`;
64 return undefined;
65 }
src/tui/screens/newforge.ts +7
@@ -9,6 +9,7 @@
99
1010 import { childUrlOf, spawnDoor } from "../../spawn/door.ts";
1111 import { MAX_BUDGET_USD, MIN_BUDGET_USD } from "../../spawn/plan.ts";
12 import { PRESETS, SIZES } from "../../spawn/sizes.ts";
1213 import type { Ctx, Screen } from "../app/app.ts";
1314 import { binding } from "../app/keys.ts";
1415 import { style } from "../term/style.ts";
@@ -34,6 +35,11 @@ const SPECS: readonly Spec[] = [
3435 { key: "modelEndpoint", label: "API base URL", hint: "A gateway for the key; empty for Anthropic. Optional." },
3536 { key: "budgetUsd", label: "Budget in dollars", hint: `${MIN_BUDGET_USD}–${MAX_BUDGET_USD}, for the key's whole life. Needed with a key.` },
3637 { key: "followMode", label: "Follows this forge's code", hint: "tell-me (default) or take-updates. Recorded for now: nothing tells you or takes updates yet." },
38 {
39 key: "size",
40 label: "How much it holds",
41 hint: `small (default), medium or large: ${SIZES.map((z) => `${z} ${PRESETS[z].cpu} CPU, ${PRESETS[z].memoryMiB} MiB, ${PRESETS[z].diskMiB} MiB disk`).join("; ")}.`,
42 },
3743 ];
3844
3945 /** The door's "field: reason" refusal, as the field it names and the reason. */
@@ -60,6 +66,7 @@ export function newForgeScreen(f: Session, ctx: Ctx): Screen {
6066 apps,
6167 ...(val("fresh") === "" ? {} : { fresh: val("fresh") }),
6268 followMode: val("followMode") === "" ? "tell-me" : val("followMode"),
69 ...(val("size") === "" ? {} : { size: val("size") }),
6370 ...(val("for") === "" ? {} : { for: val("for") }),
6471 ...(val("direction") === "" ? {} : { direction: val("direction") }),
6572 ...(val("modelKey") === "" ? {} : { modelKey: val("modelKey") }),
src/web/pages/new-forge.ts +20
@@ -13,6 +13,7 @@ import { listAgents } from "../../core/agents.ts";
1313 import { listReposVisibleTo } from "../../core/repos.ts";
1414 import type { User } from "../../core/users.ts";
1515 import type { Ctx } from "../../http/context.ts";
16 import { DEFAULT_SIZE, PRESETS, SIZES } from "../../spawn/sizes.ts";
1617 import { childHost, childUrlOf, noRoom, spawnDoor, type Door } from "../../spawn/door.ts";
1718 import {
1819 LEFT_BEHIND,
@@ -35,6 +36,7 @@ interface Values {
3536 readonly crew: readonly string[];
3637 readonly fresh: string;
3738 readonly followMode: string;
39 readonly size: string;
3840 readonly keepAccess: boolean;
3941 readonly budgetUsd: string;
4042 readonly modelEndpoint: string;
@@ -50,6 +52,7 @@ const EMPTY: Values = {
5052 crew: [],
5153 fresh: "",
5254 followMode: "tell-me",
55 size: DEFAULT_SIZE,
5356 keepAccess: false,
5457 budgetUsd: "",
5558 modelEndpoint: "",
@@ -206,6 +209,21 @@ function formView(
206209 ? html`<span class="error" id="f-followMode-err">${errors["followMode"]}</span>`
207210 : null}
208211 </fieldset>
212 <fieldset class="field" ${errors["size"] ? html`data-invalid` : null}>

The page gets the size choice here. src/tui/screens/newforge.ts needs the same field, passed through spawnDoor in the same way, so both doors offer it.

213 <legend>How much it holds</legend>
214 ${SIZES.map(
215 (s) => html`<label class="check">
216 <input type="radio" name="size" value="${s}" ${values.size === s ? html`checked` : null} />
217 <span
218 >${s}
219 <span class="muted small"
220 >${PRESETS[s].cpu} CPU, ${PRESETS[s].memoryMiB} MiB memory, ${PRESETS[s].diskMiB} MiB disk</span
221 ></span
222 >
223 </label>`,
224 )}
225 ${errors["size"] ? html`<span class="error" id="f-size-err">${errors["size"]}</span>` : null}
226 </fieldset>
209227 ${crew.length === 0
210228 ? null
211229 : html`<fieldset class="field">
@@ -391,6 +409,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
391409 crew: all(form, "crew"),
392410 fresh: field(form, "fresh").trim(),
393411 followMode: field(form, "followMode").trim() || "tell-me",
412 size: field(form, "size").trim() || DEFAULT_SIZE,
394413 keepAccess: asBool(form, "keepAccess"),
395414 budgetUsd: field(form, "budgetUsd").trim(),
396415 modelEndpoint: field(form, "modelEndpoint").trim(),
@@ -405,6 +424,7 @@ export async function newForgeSubmit(ctx: Ctx): Promise<Response> {
405424 keepAccess: values.keepAccess,
406425 ...(values.fresh === "" ? {} : { fresh: values.fresh }),
407426 followMode: values.followMode,
427 size: values.size,
408428 ...(values.forWhom === "" ? {} : { for: values.forWhom }),
409429 ...(values.direction.trim() === "" ? {} : { direction: values.direction }),
410430 ...(key === "" ? {} : { modelKey: key }),
test/spawn-api.test.ts +2
@@ -149,6 +149,8 @@ describe("spawn over the API and MCP", () => {
149149 for: null,
150150 apps: expect.any(Array),
151151 createdAt: expect.any(String),
152 size: "small",
153 resources: { cpu: 1, memoryMiB: 512, diskMiB: 2048 },
152154 },
153155 ]);
154156 // The same request again is answered, not made twice.
test/spawn-keys.test.ts +2
@@ -364,6 +364,8 @@ describe("a spawned child's own keys and domain", () => {
364364 "keepAccess",
365365 "name",
366366 "org",
367 "resources",
368 "size",
367369 // The hash of the parent's status secret (#776): the child keeps only
368370 // the hash, so this names nothing in the parent and reveals no secret.
369371 "statusHash",
test/spawn-sizes.test.ts added +131
@@ -0,0 +1,131 @@
1 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { mkdtemp, readFile, rm } from "node:fs/promises";
3 import { tmpdir } from "node:os";
4 import { join } from "node:path";
5 import { createApp, type App } from "../src/app.ts";
6 import { createUser } from "../src/core/users.ts";
7 import { createToken } from "../src/core/tokens.ts";
8 import { serve, type Servers } from "../src/http/server.ts";
9 import { usePlacement } from "../src/spawn/door.ts";
10 import { hostedPlacement } from "../src/spawn/placement.ts";
11 import { planSpawn } from "../src/spawn/plan.ts";
12 import { PRESETS, SIZES, overQuota, quotaFrom } from "../src/spawn/sizes.ts";
13 import { sha256 } from "../src/kernel/hash.ts";
14
15 const base = { name: "kid", org: "kids", apps: [], carryBriefs: false, carrySubscriptions: false };
16 const src = { catalog: [], briefs: [], subscriptions: [] };
17
18 describe("sizes", () => {
19 test("the preset table grows with the size", () => {
20 expect(PRESETS).toEqual({
21 small: { cpu: 1, memoryMiB: 512, diskMiB: 2048 },
22 medium: { cpu: 2, memoryMiB: 2048, diskMiB: 8192 },
23 large: { cpu: 4, memoryMiB: 8192, diskMiB: 32768 },
24 });
25 expect(SIZES).toEqual(["small", "medium", "large"]);
26 });
27
28 test("a plan without a size, or with small, hashes as before; others are named", () => {
29 const plain = planSpawn(base, src);
30 const small = planSpawn({ ...base, size: "small" }, src);
31 const large = planSpawn({ ...base, size: "large" }, src);
32 if (!plain.ok || !small.ok || !large.ok) throw new Error();
33 expect("size" in plain.value).toBe(false);
34 expect(sha256(JSON.stringify(small.value))).toBe(sha256(JSON.stringify(plain.value)));
35 expect(large.value.size).toBe("large");
36 });
37
38 test("an unknown size is refused", () => {
39 for (const size of ["huge", 3, {}]) {
40 const r = planSpawn({ ...base, size }, src);
41 expect(!r.ok && r.error.field).toBe("size");
42 }
43 });
44
45 test("the quota comes from FORGE_CHILD_*, else the machine", () => {
46 const machine = { cpu: 8, memoryMiB: 16000, diskMiB: 100000 };
47 expect(quotaFrom({}, machine)).toEqual(machine);
48 expect(quotaFrom({ FORGE_CHILD_CPUS: "3", FORGE_CHILD_MEMORY_MIB: "x", FORGE_CHILD_DISK_MIB: "-1" }, machine)).toEqual({
49 ...machine,
50 cpu: 3,
51 });
52 });
53
54 test("a size that would pass the total is refused in one sentence", () => {
55 const quota = { cpu: 4, memoryMiB: 100000, diskMiB: 100000 };
56 expect(overQuota("large", [], quota)).toBeUndefined();
57 expect(overQuota("medium", ["large"], quota)).toContain("a medium forge needs 2 CPUs; this host has 0 of 4 left");
58 expect(overQuota("small", ["medium", undefined], quota)).toBeUndefined();
59 });
60
61 test("room() and place() enforce the quota against the children held", async () => {
62 const placement = hostedPlacement({ host: "forge.test", quota: () => ({ cpu: 5, memoryMiB: 99999, diskMiB: 99999 }) });
63 const plan = (name: string, size?: "medium" | "large") => ({ ...planOf(name), ...(size ? { size } : {}) });
64 expect((await placement.place(plan("a", "large"))).ok).toBe(true);
65 expect(placement.room?.()).toBeUndefined(); // one small still fits
66 expect(placement.room?.("medium")?.reason).toBe("quota");
67 const no = await placement.place(plan("b", "medium"));
68 expect(!no.ok && no.error.reason).toBe("quota");
69 expect((await placement.place(plan("c"))).ok).toBe(true);
70 expect(placement.room?.()?.reason).toBe("quota");
71 });
72 });
73
74 function planOf(name: string) {
75 const r = planSpawn({ ...base, name, org: name }, src);
76 if (!r.ok) throw new Error();
77 return r.value;
78 }
79
80 describe("size in the ledger, parent.json and the API", () => {
81 let dataDir: string;
82 let app: App;
83 let servers: Servers;
84 let token: string;
85 let n = 0;
86 beforeAll(async () => {
87 dataDir = await mkdtemp(join(tmpdir(), "forge-spawn-sizes-"));
88 app = createApp({ dataDir, port: 0 });
89 servers = await serve(app);
90 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
91 if (!a.ok) throw new Error("user");
92 token = createToken(app.db, a.value.id, "rw", "rw").token;
93 usePlacement(
94 app,
95 hostedPlacement({ host: "forge.test", quota: () => ({ cpu: 4, memoryMiB: 99999, diskMiB: 99999 }), newId: () => `body-${++n}` }),
96 );
97 }, 30_000);
98 afterAll(async () => {
99 servers.stop();
100 app.close();
101 await rm(dataDir, { recursive: true, force: true });
102 });
103 const post = (payload: unknown) =>
104 fetch(`${servers.url}/api/v1/forges`, {
105 method: "POST",
106 headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
107 body: JSON.stringify(payload),
108 });
109
110 test("a medium child's size is in the ledger, parent.json and the list; a refused one is 409", async () => {
111 const made = await post({ name: "mid", size: "medium", dryRun: false });
112 expect(made.status).toBe(201);
113 const ledger = JSON.parse(await readFile(join(dataDir, "spawn", "mid.json"), "utf8"));
114 expect(ledger.size).toBe("medium");
115 const parent = JSON.parse(await readFile(join(dataDir, "children", "body-1", "parent.json"), "utf8"));
116 expect(parent.size).toBe("medium");
117 expect(parent.resources).toEqual(PRESETS.medium);
118
119 const list = (await (await fetch(`${servers.url}/api/v1/forges`, { headers: { authorization: `Bearer ${token}` } })).json()) as any;
120 expect(list.items[0]).toMatchObject({ name: "mid", size: "medium", resources: PRESETS.medium });
121
122 const refused = await post({ name: "big", size: "large", dryRun: false });
123 expect(refused.status).toBe(409);
124 expect(((await refused.json()) as any).error).toBe("refused");
125
126 const dflt = await post({ name: "tiny", dryRun: false });
127 expect(dflt.status).toBe(201);
128 const tiny = JSON.parse(await readFile(join(dataDir, "children", "body-2", "parent.json"), "utf8"));
129 expect(tiny.size).toBe("small");
130 });
131 });
test/spawn.test.ts +2
@@ -85,6 +85,8 @@ describe("spawnForge", () => {
8585 org: "kids",
8686 url: "https://kid--forge.test",
8787 keepAccess: false,
88 size: "small",
89 resources: { cpu: 1, memoryMiB: 512, diskMiB: 2048 },
8890 // A hash only: what the parent answers to stays in its own ledger.
8991 statusHash: expect.stringMatching(/^[0-9a-f]{64}$/),
9092 // The child signs heartbeats to its parent with it (#425).
test/tui-newforge.test.ts +34
@@ -190,4 +190,38 @@ describe("the new forge screen", () => {
190190 delete (app.config as { forgeRepo?: string }).forgeRepo;
191191 }
192192 }));
193
194 test("the size is a field: medium reaches the ledger", () =>
195 withScreen(admin, async ({ tui, terminal }) => {
196 terminal.feed("tuisize" + "\t".repeat(9) + "medium\x10");
197 await settleApp(tui);
198 expect(tui.screen.toText()).toContain("The plan");
199 terminal.feed("\r");
200 await settleApp(tui);
201 const ledger = await Bun.file(join(dir, "spawn", "tuisize.json")).json();
202 expect(ledger.size).toBe("medium");
203 }));
204
205 test("a bad size is refused on its field; an over-quota size shows the refusal", async () => {
206 await withScreen(admin, async ({ tui, terminal }) => {
207 terminal.feed("tuihuge" + "\t".repeat(9) + "huge\x10");
208 await settleApp(tui);
209 expect(tui.screen.toText()).not.toContain("The plan");
210 expect(tui.screen.toText()).toContain("must be small, medium or large");
211 });
212 usePlacement(app, hostedPlacement({ host: "forge.test", quota: () => ({ cpu: 1, memoryMiB: 99999, diskMiB: 99999 }) }));
213 try {
214 await withScreen(admin, async ({ tui, terminal }) => {
215 terminal.feed("tuiover" + "\t".repeat(9) + "medium\x10");
216 await settleApp(tui);
217 terminal.feed("\r");
218 await settleApp(tui);
219 const text = tui.screen.toText();
220 expect(text).toContain("a medium forge needs 2 CPUs");
221 expect(await Bun.file(join(dir, "spawn", "tuiover.json")).exists()).toBe(false);
222 });
223 } finally {
224 usePlacement(app, hostedPlacement({ host: "forge.test" }));
225 }
226 });
193227 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs