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

Machines send heartbeats and new forges go to the emptiest one, from a route table the router reads #17031

Merged opened this

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

Merged

scout/forge:scout/16860-machines-send-heartbeats-and-new-forges → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/16860-machines-send-heartbeats-and-new-forges was merged into main as 0dc8388.

Review

Sign in to review this change.
14 files changed +559 −5
docs/features/machine-load.md added +46
@@ -0,0 +1,46 @@
1 ---
2 topic: Backups and moving
3 row: Machines report load and a new forge goes to the emptiest (#16860)
4 ---
5 # Machines report load, and a new forge goes to the emptiest (#16860)
6
7 Each machine declared with `FORGE_MACHINES` (see `docs/features/move-machine.md`)
8 beats every 15 seconds with what it carries: forges awake, memory in MiB and
9 CPU as busy cores (`Machine.load`, `src/spawn/machine_load.ts`). A machine that
10 has not beaten for 45 seconds, or never, is **silent** and is named. Nothing
11 starts when no machine is declared.
12
13 ## Where it is said
14
15 - **Terminal, Forges screen**: `h` lists each machine, `beating` or `SILENT`,
16 with its load and how many forges the router sends there, and says where a
17 new forge would go (`src/tui/screens/forges.ts`).
18 - **MCP**: `forges` with `{ kind: "machines" }` gives the same lines, the silent
19 machines by name and the emptiest.
20 - **Maintenance**: the `machines-silent` duty (every five minutes) files a
21 finding for each silent machine with the seconds since its last beat
22 (`src/maintain/duties/machines_silent.ts`).
23
24 ## Placement
25
26 The emptiest is picked by forges awake, then memory, then CPU, among this
27 forge's own root (`here`) and the machines that beat lately; a tie stays here.
28 A forge made in its own sandbox (the `forge.spawned` event, heard in
29 `src/spawn/machine_beats.ts`) is then moved there with the move's own steps
30 (`src/spawn/move_machine.ts`), so it has the same budget, receipt and way back;
31 the router reads the one route table (`routes.json`, `src/spawn/routes.ts`)
32 that move writes. When the move fails, or no backup destination is set, the
33 forge stays where it was made and the log says why.
34
35 A machine here reads its forges' process groups; its CPU is this host's
36 one-minute load, and `here` reports the same figure for its own host, so the
37 CPU tiebreak does not favour it. A machine that does not answer within 5 s is
38 silent for that pass without holding up the others, and a pass still running
39 when the next tick comes is not started twice. Another kind of machine is another `Machine` that answers
40 `load`.
41
42 ## Left out
43
44 A remote machine posting its own beat over HTTP: the driver is asked, not
45 listened to. Moving forges off a busy machine by itself: an admin moves one
46 (`move`), and the emptiest other than it is in `forges` `kind: machines`.
src/generated/duties.ts +1
@@ -20,6 +20,7 @@ export const DUTY_MODULES: readonly (readonly [string, () => { duty?: unknown }]
2020 ["efficiency_watcher.ts", () => require("../maintain/duties/efficiency_watcher.ts")],
2121 ["flaky_tests.ts", () => require("../maintain/duties/flaky_tests.ts")],
2222 ["flow_keeper.ts", () => require("../maintain/duties/flow_keeper.ts")],
23 ["machines_silent.ts", () => require("../maintain/duties/machines_silent.ts")],
2324 ["merged_branches.ts", () => require("../maintain/duties/merged_branches.ts")],
2425 ["one_click_drill.ts", () => require("../maintain/duties/one_click_drill.ts")],
2526 ["pinned_lifetimes.ts", () => require("../maintain/duties/pinned_lifetimes.ts")],
src/http/mcp/tools/forges.ts +8 −3
@@ -9,6 +9,7 @@ import { archiveForge, archivedForges, restoreForge } from "../../../spawn/archi
99 import { CHILD_NAME } from "../../../spawn/placement.ts";
1010 import { checkMove } from "../../../spawn/move_check.ts";
1111 import { moveToMachine, planMove, planRecover, recoverForge } from "../../../spawn/move_machine.ts";
12 import { emptiest, machineLines, silentMachines } from "../../../spawn/machine_load.ts";
1213 import { moveToCell } from "../../../spawn/move_cell.ts";
1314 import { resizeForge } from "../../../spawn/manage.ts";
1415 import { previewDoor, reissueDoor } from "../../../spawn/door.ts";
@@ -19,10 +20,10 @@ const sentSays = (n: number) => (n === 0 ? "This forge has sent no forges yet."
1920 export const tool: Tool = {
2021 name: "forges",
2122 listedTo: "admin",
22 doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage with stageAt and resend, last activity, claimed by and when, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link; move + `forge` + `to` a machine (or `here`, the way back): copy, start, switch the router, receipt (unreachable under 60 s); recover + `forge` + `to`: the same from the bucket's last copy, previewed with the copy's time and what is lost",
23 doc: "the forges sent from here, one line each: \"name | state | version | billing\" (unopened links first), with `url` once as a pattern; `name`: that forge's whole row (address, whom for, apps, claimed, stage with stageAt and resend, last activity, claimed by and when, kept, archive reason, reachable, size, use, madeFrom, placement, where); `{ forge, plan?, dryRun? }` reads a forge's plan (small|medium|large); `plan` grants it by hand; `size` workshop raises a forge; `{ forge, sandbox: true }` reads what moving a forge into a sandbox would meet (hooks, command-running keys, size) and with `dryRun: false` moves it, proven, put back on failure (`acknowledge: true` when it was held for what its repositories hold); gift codes: `codes` true lists, `code` {plan, uses?, note?, expires?} makes (shown once), `revoke` id; planned unless `dryRun` is false; `archive` a name or names stops each, writes its data and ledger as one file to the backup destination, then removes it; `restore` a name brings an archived one back; `kind` refused: the last 20 refused first asks; `kind` clients lists each client in the page's words, with runs, pulls, tellAt while working; `action` resend + `forge`: previews, with `dryRun: false` replaces its link; `kind` machines: each machine's heartbeat (awake forges, memory, CPU), the silent ones named, and the emptiest, where a new forge goes; move + `forge` + `to` a machine (or `here`, the way back): copy, start, switch the router, receipt (unreachable under 60 s); recover + `forge` + `to`: the same from the bucket's last copy, previewed with the copy's time and what is lost",
2324 description:
2425 "Forges sent from here (admin).",
25 inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { enum: ["refused", "clients"] }, action: { enum: ["resend", "move", "recover"] }, to: {}, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
26 inputSchema: { type: "object", properties: { name: { type: "string" }, kind: { enum: ["refused", "clients", "machines"] }, action: { enum: ["resend", "move", "recover"] }, to: {}, forge: { type: "string" }, plan: { type: "string" }, codes: { type: "boolean" }, code: { type: "object" }, revoke: { type: "string" }, archive: { type: ["string", "array"], items: { type: "string" } }, restore: { type: "string" }, sandbox: { type: "boolean" }, size: { type: "string" }, acknowledge: { type: "boolean" }, dryRun: { type: "boolean" } } },
2627 writes: true,
2728 tier: "delete",
2829 deletes: (args) => args["archive"] !== undefined,
@@ -61,7 +62,11 @@ export const tool: Tool = {
6162 const lines = clientLines(await clientRows(ctx.app), Date.now());
6263 return good({ says: sentSays(lines.length), clients: lines });
6364 }
64 if (args["kind"] !== "refused") return bad("invalid", "kind is refused or clients");
65 if (args["kind"] === "machines") {
66 const silent = silentMachines(ctx.app).map((m) => m.name);
67 return good({ says: silent.length === 0 ? "Every machine is beating." : `Silent: ${silent.join(", ")}.`, machines: machineLines(ctx.app), silent, emptiest: emptiest(ctx.app) });
68 }
69 if (args["kind"] !== "refused") return bad("invalid", "kind is refused, clients or machines");
6570 if (!mayReadRefusals(user)) return bad("forbidden", "only an admin of this forge sees the refused first asks");
6671 const refused = listRefusals(ctx.app.db, REFUSED_SHOWN, Date.now());
6772 return good({ says: refused.length === 0 ? "No first ask has been refused." : `The last ${refused.length} refused first asks, newest first.`, refused });
src/main.ts +4
@@ -49,6 +49,7 @@ import { firstBoot } from "./spawn/first-boot.ts";
4949 import { previewIdentityKey } from "./spawn/preview-owner.ts";
5050 import { PREVIEW_ADMIN, seedPreview } from "./spawn/preview-seed.ts";
5151 import { startHeartbeat } from "./spawn/heartbeat.ts";
52 import { startMachineBeats } from "./spawn/machine_beats.ts";
5253 import { startUpstreamWatch } from "./spawn/upstream.ts";
5354 import { followTick, watchLandings } from "./spawn/app_follow.ts";
5455 import { startReachWatch } from "./spawn/reach.ts";
@@ -853,6 +854,8 @@ await seedPreview(app)
853854 .catch((error) => app.log.warn("preview not seeded", { error: String(error) }));
854855 // A spawned child reports its standing to its parent (spawn/heartbeat.ts).
855856 const heartbeatTimer = inert ? undefined : startHeartbeat(app);
857 // Each machine beats its load; one that stops is named (spawn/machine_load.ts, #16860).
858 const machineBeatTimer = inert ? undefined : startMachineBeats(app);
856859 // ...and looks upstream once an hour (spawn/upstream.ts).
857860 const upstreamTimer = inert ? undefined : startUpstreamWatch(app);
858861 // ...and this forge asks every child's public addresses what a visitor would get, every few minutes
@@ -1263,6 +1266,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
12631266 clearInterval(nightlyScanTimer);
12641267 if (ledgerGitTimer !== undefined) clearInterval(ledgerGitTimer);
12651268 clearInterval(heartbeatTimer);
1269 clearInterval(machineBeatTimer);
12661270 clearInterval(upstreamTimer);
12671271 clearInterval(reachTimer);
12681272 clearInterval(syncTimer);
src/maintain/duties/machines_silent.ts added +24
@@ -0,0 +1,24 @@
1 /**
2 * Machines that stopped beating (#16860): a declared machine whose load has not been heard for
3 * three beats, or never, is named with the seconds since its last beat. It only reads; moving what
4 * it held is `recover` (docs/features/machine-load.md).
5 */
6
7 import type { Duty } from "../duty.ts";
8
9 export const duty: Duty = {
10 name: "machines-silent",
11 intervalMs: 5 * 60_000,
12 budget: { runsPerDay: 300, dollarsPerDay: 0, reason: "every five minutes is 288 a day; it reads memory and spends nothing" },
13 async run({ now, app }) {
14 if (app === undefined || (process.env["FORGE_MACHINES"] ?? "") === "") return { findings: [], actions: [] };
15 const { silentMachines } = await import("../../spawn/machine_load.ts");
16 return {
17 findings: silentMachines(app, now.getTime()).map((m) => ({
18 summary: m.load === undefined ? `machine ${m.name} has never reported its load` : `machine ${m.name} stopped beating ${Math.round((now.getTime() - m.load.at) / 1000)} s ago`,
19 probe: { kind: "measurement" as const, what: `seconds since machine ${m.name}'s last heartbeat (-1: never)`, number: m.load === undefined ? -1 : Math.round((now.getTime() - m.load.at) / 1000), at: now.toISOString() },
20 })),
21 actions: [],
22 };
23 },
24 };
src/spawn/machine_beats.ts added +35
@@ -0,0 +1,35 @@
1 /**
2 * The machines' heartbeat timer (#16860): every `BEAT_MS` ask each declared machine what it
3 * carries, and place each new forge (`forge.spawned`) on the emptiest. Nothing starts when no
4 * machine is declared; the module that samples loads on the first beat, so a forge without machines
5 * pays nothing at boot.
6 */
7
8 import type { App } from "../app.ts";
9 import { during } from "../perf/jobs.ts";
10
11 const BEAT_MS = 15_000;
12
13 export function startMachineBeats(app: App, env: Record<string, string | undefined> = process.env, everyMs = BEAT_MS): ReturnType<typeof setInterval> | undefined {
14 if ((env["FORGE_MACHINES"] ?? "") === "") return undefined;
15 // A pass still running when the next tick comes is left to finish: passes never pile up.
16 let running = false;
17 const beat = (): void => {
outdated

This subscription is how new forges get placed, and no test covers it. Add one that publishes forge.spawned and expects placeNew to run.

18 if (running) return;
19 running = true;
20 void import("./machine_load.ts")
21 .then((m) => m.sampleBeats(app))
22 .catch((e) => app.log.warn("machine beat failed", { error: String(e).slice(0, 160) }))
23 .finally(() => (running = false));
outdated

The timer starts a new pass every 15 s with no check for one still running, so slow passes overlap. Skip the tick while the previous one is in flight.

24 };
25 // A forge that was just made goes to the emptiest machine, after the answer that made it.
26 app.bus.subscribe((event) => {
27 const name = (event.payload as { name?: unknown } | undefined)?.name;
28 if (event.kind === "forge.spawned" && typeof name === "string")
29 void import("./machine_load.ts").then((m) => m.placeNew(app, name)).then((p) => app.log.info("forge placed", { name, on: p.on }), (e) => app.log.warn("forge not placed", { name, error: String(e).slice(0, 160) }));
30 }, "local");
31 beat();
32 const timer = setInterval(() => during("machine-beats", beat, undefined, app), everyMs);
33 timer.unref();
34 return timer;
35 }
src/spawn/machine_load.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * Machines report their load, and a new forge goes to the emptiest one (#16860). Each machine
3 * beats every `BEAT_MS` with what it carries: forges awake, memory in MiB and CPU as busy cores
4 * (`Machine.load`; a driver that cannot answer is silent, and a silent machine is named). The
5 * latest beat of each lives here in memory and is gone on restart: the next beat refills it. The
6 * route table the router reads is `routes.ts`; this module only chooses what goes into it.
7 *
8 * `emptiest` picks by forges awake, then memory, then CPU, over this forge's own root (`here`) and
9 * the machines that beat lately; a tie stays here. `placeNew` is a finished new forge's one step:
10 * ask the emptiest, and when it is a machine, move the forge there with the move's own steps
11 * (`move_machine.ts`), so it carries the same budget, receipt and way back.
12 */
13
14 import { cpus, loadavg } from "node:os";
15 import type { App } from "../app.ts";
16 import { awakeCount } from "./host.ts";
17 import { machinesOf, type MachineLoad } from "./machines.ts";
18 import { HERE, moveToMachine, type MoveOptions } from "./move_machine.ts";
19 import { routesOf } from "./routes.ts";
20
21 /** A machine that does not answer its load in this long is silent for this pass. */
22 const LOAD_MS = 5_000;
23
24 /** A machine that has not beaten for this long is silent. */
25 export const SILENT_MS = 3 * 15_000;
26
27 interface Beat extends MachineLoad {
28 readonly at: number;
29 }
30
31 type MachineState = "beating" | "silent";
32
33 interface MachineRow {
34 readonly name: string;
35 readonly state: MachineState;
36 readonly load: Beat | undefined;
37 /** How many forges the router sends here (a forge with no route is `here`'s). */
38 readonly forges: number;
39 }
40
41 const beats = new WeakMap<App, Map<string, Beat>>();
42 const beatsOf = (app: App): Map<string, Beat> => {
43 let m = beats.get(app);
44 if (m === undefined) beats.set(app, (m = new Map()));
45 return m;
46 };
47
48 const cleanLoad = (l: MachineLoad): MachineLoad | undefined =>
49 Number.isFinite(l.awake) && l.awake >= 0 && Number.isFinite(l.memMb) && l.memMb >= 0 && Number.isFinite(l.cpu) && l.cpu >= 0
50 ? { awake: Math.floor(l.awake), memMb: l.memMb, cpu: l.cpu }
51 : undefined;
52
53 /** One machine's beat. A reading that is not a number is no beat. */
54 export function recordBeat(app: App, machine: string, load: MachineLoad, now = Date.now()): boolean {
55 const clean = cleanLoad(load);
56 if (clean === undefined) return false;
57 beatsOf(app).set(machine, { ...clean, at: now });
58 return true;
59 }
60
61 /**
outdated

cpu: 0 for here always wins the CPU tiebreak against machines that report the host's load average. Report a real figure or leave CPU out of the comparison, and say which.

62 * This forge's own root, read from this process: the host's one-minute load, as a machine reports
63 * it.
64 */
65 function hereLoad(app: App): MachineLoad {
66 return { awake: awakeCount(app), memMb: Math.round(process.memoryUsage.rss() / 1_048_576), cpu: Math.min(loadavg()[0] ?? 0, cpus().length) };
67 }
68
outdated

No timeout. A machine whose load() hangs blocks this loop forever, so the later machines never beat and are reported silent. Race each call against ~5 s and treat a timeout as silence.

69 /**
70 * Ask every declared machine for its load, and this one; what answers within `loadMs` beats, and a
71 * machine that hangs is silent without holding the rest.
72 */
73 export async function sampleBeats(app: App, now = Date.now(), here: (app: App) => MachineLoad = hereLoad, loadMs = LOAD_MS): Promise<void> {
74 recordBeat(app, HERE, here(app), now);
75 for (const m of machinesOf(app)) {
76 let timer: ReturnType<typeof setTimeout> | undefined;
77 const late = new Promise<undefined>((resolve) => (timer = setTimeout(() => resolve(undefined), loadMs)));
78 const load = await Promise.race([Promise.resolve(m.load?.()).catch(() => undefined), late]);
79 clearTimeout(timer);
80 if (load !== undefined) recordBeat(app, m.name, load, now);
81 }
82 }
83
84 /** Every machine with whether it beats; `here` is first. */
85 export function machineRows(app: App, now = Date.now()): MachineRow[] {
86 const seen = beatsOf(app);
87 const names = [HERE, ...machinesOf(app).map((m) => m.name)];
88 return names.map((name) => {
89 const load = seen.get(name);
90 const routed = name === HERE ? 0 : routesOf(app).filter((r) => r.machine === name).length;
91 return { name, load, state: load !== undefined && now - load.at <= SILENT_MS ? "beating" : "silent", forges: routed };
92 });
93 }
94
95 const loadWords = (l: Beat | undefined): string =>
96 l === undefined ? "has never reported" : `${l.awake} awake, ${l.memMb} MiB, ${l.cpu.toFixed(2)} cores`;
97
98 /** One line each, for the terminal and the MCP tool: the page's words. */
99 export function machineLines(app: App, now = Date.now()): string[] {
100 return machineRows(app, now).map((r) =>
101 r.state === "beating"
102 ? `${r.name} | beating | ${loadWords(r.load)} | ${r.forges} routed`
103 : `${r.name} | SILENT | ${r.load === undefined ? loadWords(undefined) : `last beat ${Math.round((now - r.load.at) / 1000)} s ago, ${loadWords(r.load)}`}`,
104 );
105 }
106
107 /** The machines that stopped beating, named. */
108 export const silentMachines = (app: App, now = Date.now()): MachineRow[] => machineRows(app, now).filter((r) => r.state === "silent" && r.name !== HERE);
109
110 /**
111 * The emptiest place that beats, or `here`; `except` leaves one out (the machine a forge is on).
112 */
113 export function emptiest(app: App, now = Date.now(), except?: string): string {
114 const live = machineRows(app, now).filter((r) => r.state === "beating" && r.load !== undefined && r.name !== except);
115 live.sort((a, b) => a.load!.awake - b.load!.awake || a.load!.memMb - b.load!.memMb || a.load!.cpu - b.load!.cpu || (a.name === HERE ? -1 : b.name === HERE ? 1 : a.name.localeCompare(b.name)));
116 return live[0]?.name ?? HERE;
117 }
118
119 type Placed = { readonly on: string; readonly says: string };
120
121 /**
122 * A new forge goes to the emptiest machine: it stays here when here is the emptiest or the move
123 * fails.
124 */
125 export async function placeNew(app: App, forge: string, options: MoveOptions & { readonly here?: (app: App) => MachineLoad } = {}): Promise<Placed> {
126 if (machinesOf(app).length === 0) return { on: HERE, says: `${forge} stays here: no other machine is declared.` };
127 await sampleBeats(app, Date.now(), options.here);
128 const to = emptiest(app);
129 if (to === HERE) return { on: HERE, says: `${forge} stays here: this is the emptiest machine.` };
130 const moved = await moveToMachine(app, forge, to, options);
131 if (!moved.ok) return { on: HERE, says: `${forge} stays here: ${moved.says}` };
132 return { on: to, says: `${forge} is placed on ${to}, the emptiest machine. ${moved.says}` };
133 }
src/spawn/machines.ts +36 −1
@@ -9,7 +9,8 @@
99 * driver of the same four calls; none is shipped here.
1010 */
1111
12 import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
12 import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
13 import { cpus, loadavg } from "node:os";
1314 import { join } from "node:path";
1415 import type { App } from "../app.ts";
1516 import { cellEnv } from "./cell.ts";
@@ -17,6 +18,13 @@ import { BODY_ID } from "./archive.ts";
1718 import { CHILD_NAME } from "./placement.ts";
1819 import { clearRoute } from "./routes.ts";
1920
21 /** What a machine carries when it beats (#16860): forges awake, memory in MiB, busy cores. */
22 export interface MachineLoad {
23 readonly awake: number;
24 readonly memMb: number;
25 readonly cpu: number;
26 }
27
2028 export interface Machine {
2129 readonly name: string;
2230 /** Where its forges' `spawn/` and `children/` live. */
@@ -30,6 +38,8 @@ export interface Machine {
3038 alive(name: string): boolean;
3139 /** End its process tree. */
3240 stop(name: string): Promise<void>;
41 /** Its heartbeat: what it carries now; undefined when it cannot answer, which is silence. */
42 load?(): MachineLoad | undefined | Promise<MachineLoad | undefined>;
3343 }
3444
3545 export type Launch = (input: { name: string; bodyId: string; root: string; port: number; url: string }) => {
@@ -108,6 +118,31 @@ export function processMachine(
108118 const pid = pidOf(forge);
109119 return pid !== undefined && groupAlive(pid);
110120 },
121 load() {
122 if (!existsSync(root)) return undefined;
123 let awake = 0;
124 let memKb = 0;
125 let names: string[] = [];
126 try {
127 names = readdirSync(join(root, "pids"));
128 } catch {
129 // No forge has run here yet.
130 }
131 for (const f of names) {
132 const forge = f.replace(/\.pid$/, "");
133 const pid = pidOf(forge);
134 if (pid === undefined || !groupAlive(pid)) continue;
135 awake++;
136 // The group leader's resident pages (Linux); elsewhere nothing is counted.
137 try {
138 memKb += (Number(readFileSync(`/proc/${pid}/statm`, "utf8").split(" ")[1]) * 4) || 0;
139 } catch {
140 // Not readable.
141 }
142 }
143 // A machine here shares this host's CPU: the host's one-minute load, as busy cores.
144 return { awake, memMb: Math.round(memKb / 1024), cpu: Math.min(loadavg()[0] ?? 0, cpus().length) };
145 },
111146 async stop(forge) {
112147 const pid = pidOf(forge);
113148 const r = running.get(forge);
src/spawn/routes.ts +3
@@ -45,6 +45,9 @@ function save(app: App, t: Map<string, Route>): void {
4545 renameSync(tmp, file);
4646 }
4747
48 /** Every forge that is on a machine, with its route. */
49 export const routesOf = (app: App): readonly Route[] => [...table(app).values()];
50
4851 export const routeOf = (app: App, name: string): Route | undefined => table(app).get(name);
4952
5053 /** The flip: from now a request for `name` goes to `route`. */
src/tui/screens/forges.ts +11 −1
@@ -24,6 +24,7 @@ import { writeClientsCsv } from "../../spawn/clients_csv.ts";
2424 import { claimedWords, keepWords } from "../../spawn/keep_words.ts";
2525 import { changeLink, revokePreview, ownCode, removeForge, resizeForge, stopForge } from "../../spawn/manage.ts";
2626 import { machinesOf } from "../../spawn/machines.ts";
27 import { emptiest, machineLines, sampleBeats } from "../../spawn/machine_load.ts";
2728 import { moveToCell } from "../../spawn/move_cell.ts";
2829 import { HERE, moveToMachine, planMove, planRecover, recoverForge } from "../../spawn/move_machine.ts";
2930 import { routeOf } from "../../spawn/routes.ts";
@@ -284,6 +285,14 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
284285 }),
285286 );
286287 };
288 // Each machine's heartbeat and the emptiest, where a new forge goes (the MCP `kind: machines`).
289 const machinesSeen = (): void => {

The h screen and its admin gate are untested. Add a test that a non-admin sees nothing and an admin sees the machine lines.

290 if (session?.user?.isAdmin !== true) return;
291 const app = session.app;
292 void sampleBeats(app).then(() =>
293 ctx.push(confirmScreen(ctx, screen, { title: "Machines", body: [...machineLines(app), `A new forge goes to ${emptiest(app)}.`], actions: [{ label: "Close" }], onChoose: () => {} })),
294 );
295 };
287296 // The page's "Raise to xlarge", through the same action (`resizeForge`): an admin's, after
288297 // reading what it would do.
289298 const raiseOne = (): void => {
@@ -324,7 +333,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
324333 };
325334 const screen: Screen = {
326335 title: "Forges you sent",
327 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["g"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")],
336 keys: [binding(["s"], "stop"), binding(["a"], "archive"), binding(["r"], "restore"), binding(["x"], "remove"), binding(["n"], "new link"), binding(["l"], "end a link"), binding(["u"], "undo an ended link"), binding(["o"], "own code or this forge's"), binding(["m"], "move"), binding(["g"], "move to a machine"), binding(["v"], "restore from the newest copy"), binding(["h"], "machines' heartbeats"), binding(["w"], "raise to xlarge"), binding(["f"], "state"), binding(["/"], "search"), binding(["c"], "csv"), binding(["esc"], "close")],
328337 render(area, s) {
329338 const c = ctx.theme.c;
330339 const w = Math.min(100, Math.max(30, area.w - 6));
@@ -390,6 +399,7 @@ export function forgesScreen(ctx: Ctx, rows: readonly ClientRow[], session?: Ses
390399 } else if (e.key === "m") sandboxOne();
391400 else if (e.key === "g") machineOne(false);
392401 else if (e.key === "v") machineOne(true);
402 else if (e.key === "h") machinesSeen();
393403 else if (e.key === "w") raiseOne();
394404 else if (e.key === "x" && session !== undefined)
395405 choose("Remove which forge?", (name) =>
test/job-slices.test.ts +1
@@ -266,6 +266,7 @@ function jobs(): Record<string, () => unknown> {
266266 * on.
267267 */
268268 const UNTIMED: Record<string, string> = {
269 "machine-beats": "a 15 s timer (spawn/machine_beats.ts) whose beat only starts an async import and the machines' asks; its synchronous slice is the call that starts them; machine-load.test.ts drives sampleBeats and placeNew directly",
269270 "config-poll": "a short timer that re-reads one small row per scope and fires listeners only when another process changed it (core/config.ts start/refresh); config-store.test.ts drives a change from a second handle",
270271 "allocation": "one settle pass hourly over repositories with a wallet (core/allocation.ts settleAll): indexed reads and a write only when a week turned; allocation tests drive settleAll directly",
271272 "copies-prune": "two DELETEs on indexed time columns (core/copies.ts pruneCopies), hourly on the outsider prune's own timer; copies-elsewhere.test.ts drives both fades",
test/machine-beats.test.ts added +134
@@ -0,0 +1,134 @@
1 /**
2 * #16860: the heartbeat timer places a new forge when `forge.spawned` is heard, never piles passes
3 * up, and a machine that hangs is silent without holding the rest; the terminal `h` key and the
4 * MCP `kind: machines` are an admin's.
5 */
6 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser, getUserByName } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import { startMachineBeats } from "../src/spawn/machine_beats.ts";
15 import { machineLines, sampleBeats, silentMachines } from "../src/spawn/machine_load.ts";
16 import { forgetMachines, processMachine, registerMachine, type Machine, type MachineLoad } from "../src/spawn/machines.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { pollUntil } from "./helpers/poll.ts";
21 import { settleApp } from "./helpers/tui.ts";
22
23 quietLogs();
24
25 let dir: string, app: App, servers: Servers, admin: string, plain: string;
26 const launch = ({ port }: { root: string; bodyId: string; port: number }) => ({ script: "unused", env: { PORT: String(port) } });
27 const machine = (name: string, load: () => Promise<MachineLoad | undefined> | MachineLoad | undefined): Machine => ({ ...processMachine(name, join(dir, name), launch), load });
28 const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); // real-timer: lets the beat timer under test fire on its real interval; the timer owns its clock
29
30 beforeAll(async () => {
31 dir = await mkdtemp(join(tmpdir(), "machine-beats-"));
32 app = createApp({ dataDir: dir, port: 0 });
33 servers = await serve(app);
34 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
35 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
36 if (!a.ok || !b.ok) throw new Error("users");
37 admin = createToken(app.db, a.value.id, "t", "admin").token;
38 plain = createToken(app.db, b.value.id, "t", "admin").token;
39 });
40 afterAll(async () => {
41 forgetMachines(app);
42 await servers.stop();
43 await rm(dir, { recursive: true, force: true });
44 });
45
46 test("no machine declared starts no timer", () => {
47 expect(startMachineBeats(app, {})).toBeUndefined();
48 expect(startMachineBeats(app, { FORGE_MACHINES: "" })).toBeUndefined();
49 });
50
51 test("a forge.spawned event places the new forge", async () => {
52 const info = spyOn(app.log, "info");
53 const timer = startMachineBeats(app, { FORGE_MACHINES: "x=/x" });
54 try {
55 expect(timer).toBeDefined();
56 app.bus.append({ kind: "forge.spawned", payload: { name: "fresh", org: "o", url: "https://fresh.test", apps: [] } });
57 await pollUntil(() => info.mock.calls.some((c) => c[0] === "forge placed"), "forge placed", 5000);
58 const placed = info.mock.calls.find((c) => c[0] === "forge placed");
59 expect(placed?.[1]).toEqual({ name: "fresh", on: "here" });
60 } finally {
61 clearInterval(timer);
62 info.mockRestore();
63 }
64 });
65
66 test("a machine that never answers is silent, and does not hold the others", async () => {
67 forgetMachines(app);
68 registerMachine(app, machine("hung", () => new Promise(() => {})));
69 registerMachine(app, machine("fine", () => ({ awake: 1, memMb: 10, cpu: 0 })));
70 const started = Date.now();
71 await sampleBeats(app, Date.now(), undefined, 30);
72 expect(Date.now() - started).toBeLessThan(2000);
73 expect(silentMachines(app).map((m) => m.name)).toEqual(["hung"]);
74 expect(machineLines(app).join("\n")).toContain("fine | beating");
75 });
76
77 test("a pass still running is not started again by the next tick", async () => {
78 forgetMachines(app);
79 let asked = 0;
80 registerMachine(app, machine("slow", () => (asked++, new Promise(() => {}))));
81 const timer = startMachineBeats(app, { FORGE_MACHINES: "slow=/x" }, 10);
82 try {
83 await wait(250);
84 expect(asked).toBe(1);
85 } finally {
86 clearInterval(timer);
87 }
88 });
89
90 const call = async (tok: string, args: object) => {
91 const res = await fetch(`${servers.url}/mcp`, {
92 method: "POST",
93 headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${tok}` },
94 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "forges", arguments: args } }),
95 });
96 const j = (await res.json()) as any;
97 return { error: j.result.isError === true, text: String(j.result.content[0].text) };
98 };
99
100 test("the MCP forges tool gives an admin the machine lines and a non-admin nothing", async () => {
101 forgetMachines(app);
102 registerMachine(app, machine("m1", () => ({ awake: 2, memMb: 20, cpu: 0.5 })));
103 await sampleBeats(app);
104 const yes = await call(admin, { kind: "machines" });
105 expect(yes.error).toBe(false);
106 expect(JSON.parse(yes.text).machines.join("\n")).toContain("m1 | beating | 2 awake, 20 MiB, 0.50 cores");
107 const no = await call(plain, { kind: "machines" });
108 expect(no.error).toBe(true);
109 expect(no.text).not.toContain("m1");
110 });
111
112 async function screenAfterH(username: string): Promise<string> {
113 const terminal = headlessTerminal(140, 32);
114 const { app: tui } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(app.db, username)! }, { terminal, exitHooks: false });
115 tui.start();
116 const key = (k: string, ctrl = false) => tui.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
117 key("k", true);
118 for (const ch of "Forges you sent") key(ch);
119 await settleApp(tui);
120 key("enter");
121 await settleApp(tui);
122 key("h");
123 await settleApp(tui);
124 await wait(50);
125 await settleApp(tui);
126 const text = tui.screen.toText();
127 tui.stop();
128 return text;
129 }
130
131 test("the h key of the terminal Forges screen shows an admin the machines and a non-admin nothing", async () => {
132 expect(await screenAfterH("alice")).toContain("m1 | beating");
133 expect(await screenAfterH("bob")).not.toContain("m1 | beating");
134 });
test/machine-load.test.ts added +122
@@ -0,0 +1,122 @@
1 /**
2 * #16860: machines beat their load, a silent one is named, a new forge goes to the emptiest, and a
3 * busy forge moves to the emptier machine through the router's table.
4 */
5 import { afterAll, beforeAll, 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 { dirStore } from "../src/blob/store.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { forgetMachines, processMachine, registerMachine, type Machine, type MachineLoad } from "../src/spawn/machines.ts";
12 import { emptiest, machineLines, placeNew, recordBeat, sampleBeats, silentMachines, SILENT_MS } from "../src/spawn/machine_load.ts";
13 import { moveToMachine } from "../src/spawn/move_machine.ts";
14 import { forgetRoutes, routeOf } from "../src/spawn/routes.ts";
15 import { duty } from "../src/maintain/duties/machines_silent.ts";
16 import { quietLogs } from "./helpers/globals.ts";
17
18 quietLogs();
19
20 const root = mkdtempSync(join(tmpdir(), "machine-load-"));
21 const destination = { source: "dir" as const, store: dirStore(join(root, "bucket")) };
22 let app: App;
23 let a: Machine;
24 let b: Machine;
25 // What each stand-in machine reports; undefined is silence.
26 const busyHere = (): MachineLoad => ({ awake: 5, memMb: 2000, cpu: 2 });
27 const says: Record<string, MachineLoad | undefined> = { a: { awake: 3, memMb: 900, cpu: 1 }, b: { awake: 1, memMb: 400, cpu: 0.2 } };
28
29 const launch = ({ root: r, bodyId, port }: { root: string; bodyId: string; port: number }) => ({
30 script: join(import.meta.dir, "helpers", "machine-forge.ts"),
31 env: { PATH: process.env["PATH"] ?? "", PORT: String(port), FORGE_APP_DATA: join(r, "children", bodyId) },
32 });
33
34 function forge(name: string, body: string): void {
35 const data = join(root, "parent");
36 mkdirSync(join(data, "children", body), { recursive: true });
37 writeFileSync(join(data, "children", body, "note.txt"), `note of ${name}`);
38 writeFileSync(join(data, "spawn", `${name}.json`), JSON.stringify({ name, bodyId: body, done: true, placement: "cell", size: "small", apps: [] }));
39 }
40
41 beforeAll(() => {
42 const data = join(root, "parent");
43 app = createApp({ dataDir: data, url: "https://forge.test", port: 0 });
44 mkdirSync(join(data, "spawn"), { recursive: true });
45 forge("one", "body-one");
46 forge("two", "body-two");
47 const stand = (m: Machine, key: string): Machine => ({ ...m, load: () => says[key] });
48 a = stand(processMachine("a", join(root, "a"), launch), "a");
49 b = stand(processMachine("b", join(root, "b"), launch), "b");
50 forgetMachines(app);
51 registerMachine(app, a);
52 registerMachine(app, b);
53 });
54
55 afterAll(async () => {
56 for (const m of [a, b]) for (const f of ["one", "two"]) await m.stop(f);
57 app.close();
58 forgetMachines(app);
59 forgetRoutes(app);
60 rmSync(root, { recursive: true, force: true });
61 });
62
63 test("a machine that never beat is silent, and every beat that does is read back", async () => {
64 expect(silentMachines(app).map((m) => m.name)).toEqual(["a", "b"]);
65 await sampleBeats(app);
66 expect(silentMachines(app)).toEqual([]);
67 expect(machineLines(app).join("\n")).toContain("b | beating | 1 awake, 400 MiB, 0.20 cores");
68 expect(recordBeat(app, "a", { awake: Number.NaN, memMb: 1, cpu: 0 })).toBe(false);
69 expect(recordBeat(app, "a", { awake: -1, memMb: 1, cpu: 0 })).toBe(false);
70 });
71
72 test("a machine that stops beating is named, by the duty too", async () => {
73 const now = Date.now();
74 says["a"] = undefined;
75 await sampleBeats(app, now + SILENT_MS + 1_000);
76 const gone = silentMachines(app, now + SILENT_MS + 1_000).map((m) => m.name);
77 expect(gone).toEqual(["a"]);
78 process.env["FORGE_MACHINES"] = "a=/x";
79 try {
80 const result = await duty.run({ db: app.db, bus: app.bus, now: new Date(now + SILENT_MS + 1_000), app });
81 expect(result.findings.length).toBe(1);
82 expect(result.findings[0]?.summary).toContain("machine a stopped beating");
83 } finally {
84 delete process.env["FORGE_MACHINES"];
85 }
86 says["a"] = { awake: 3, memMb: 900, cpu: 1 };
87 await sampleBeats(app);
88 expect(silentMachines(app)).toEqual([]);
89 });
90
91 test("a new forge goes to the emptiest machine, the busy one moves to the emptier, and the router follows", async () => {
92 await sampleBeats(app, Date.now(), busyHere);
93 expect(emptiest(app)).toBe("b");
94 const placed = await placeNew(app, "one", { destination, here: busyHere });
95 expect(placed.on).toBe("b");
96 expect(routeOf(app, "one")?.machine).toBe("b");
97
98 // The second forge arrives while b is the busier now: it goes to a.
99 says["a"] = { awake: 0, memMb: 100, cpu: 0 };
100 says["b"] = { awake: 9, memMb: 3000, cpu: 3 };
101 const second = await placeNew(app, "two", { destination, here: busyHere });
102 expect(second.on).toBe("a");
103 expect(routeOf(app, "two")?.machine).toBe("a");
104
105 // b is busy: its forge moves to the emptiest machine other than b.
106 const target = emptiest(app, Date.now(), "b");
107 expect(target).toBe("a");
108 const moved = await moveToMachine(app, "one", target, { destination });
109 expect(moved.ok).toBe(true);
110 expect(routeOf(app, "one")?.machine).toBe("a");
111 const answer = await (await fetch(`http://127.0.0.1:${routeOf(app, "one")!.port}/`)).text();
112 expect(answer).toBe("held: note of one");
113 });
114
115 test("with no machine declared a new forge stays here", async () => {
116 const lone = createApp({ dataDir: join(root, "lone"), url: "https://lone.test", port: 0 });
117 try {
118 expect((await placeNew(lone, "one")).on).toBe("here");
119 } finally {
120 lone.close();
121 }
122 });
test/timers-named.test.ts +1
@@ -111,6 +111,7 @@ const ALLOWED: readonly Allowed[] = [
111111 ...allow("setTimeout", "the next slice of a sliced flow computation: one span per slice would fill the 256-span ring in one refresh", [["src/system/flow_cache.ts", "fn"]]),
112112 ...allow("setTimeout", "the release prover's scheduler seam: its caller passes a callback already inside during(\"release-prove\")", [["src/release/prove.ts", "fn"]]),
113113 ...allow("setTimeout", "track() only holds the round's promise; the round itself runs inside during(\"probes\")", [["src/contract/probes.ts", "() => { void track(during("]]),
114 ...allow("setTimeout", "a machine's load deadline: it only resolves the race when the machine does not answer, no work of its own; the beat itself runs inside during(\"machine-beats\")", [["src/spawn/machine_load.ts", "() => resolve(undefined)"]]),
114115 ...allow("setTimeout", "a failed look's backoff step: its callback only puts the look back on the queue, and the queue's drain does the work", [["src/looks/backoff.ts", "fn"]]),
115116 ...allow("setTimeout", "clears a perf capture after its window: five field writes", [["src/perf/capture.ts", "drop"]]),
116117 ...allow("setTimeout", "clears an image loader's in-flight flag: one comparison and one write", [["src/web/og/raster.ts", "() => loading === mine"]]),

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

Keyboard shortcuts

Docs