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

Crew: after an agent.sh release, watch the box (check-in, idle CPU between syncs, no rollback) and post it on the release #18276

opened this

Merged 5h 59m ago, live in production

torque/forge:torque/18272-crew-after-an-agent-sh-release-watch-the → main 0 commits fork

  • Merged. torque/18272-crew-after-an-agent-sh-release-watch-the was merged into main as 707f092.

Review

Sign in to review this change.
13 files changed +474 −5
docs/features/games.md +2
@@ -197,4 +197,6 @@ A game's own refusal is a failure: `op` with a name that does not exist ("That p
197197
198198 `/games/<box>` opens on **How to join** (the box's machine name with Copy, and who is on, server by server), then one row a server: its name, its state in words, players, TPS, then memory, CPU and how long it has been up in the cloud tree's words (`containersIn` in `src/cloud/containers.ts`: "not known" for what the box did not say or once it is silent, nothing for a server that is not running) and the 24 h sparklines, and a quiet button (Start while it is not running, else Restart); Stop, Restart and Remove are behind **More**. A server's page leads with its state, the same memory, CPU and uptime line under it, which says so when the server is not running (the terminal's people part too), its main button (the page's one accent), who is on and **Why someone could not join** (each cause with who, how often and "Tell them": what to say). Console, Numbers, Sleep, World, Environment, Settings and Mods follow, each folded and one tap away; nothing was removed (the numbers stayed in the row). A start, stop or restart that was asked shows on the server ("Starting: asked 10 s ago", then "Started" or why not) until the server answers, and the page updates itself. The player form has no default: choose what to do, in the plain word with the game's own beside it in the choice only (Let in (whitelist), Make operator (op), Ban, Lift a ban (pardon)); headings and notes use the plain word. The terminal says the same: the state line, the address, the "Tell them" fixes and the plain words (`src/games/gist.ts`). No address shows when the box has no machine name.
199199
200 **After an agent release** (`src/games/agent_watch.ts`, #18272): when this forge starts answering a game agent script it has not answered before, it watches the boxes that exist at that moment (one made later, or deleted, is not waited for) and posts one comment on the newest release's pull at that moment. That is the release that changed `agent.sh` unless another release landed before a box first synced with the new script; the forge does not work out which commit changed the script, so then the comment goes on the later release's pull. It says: whether each box checked in with the new script, whether the agent stayed near idle between syncs (the median of its first three readings at most 15% of one core; the agent reports `diag.agent.cpuPct`, its own and its children's CPU since the last full sync), and whether the rollback fired (`diag.agent.rolledBackSha` is the new sha). It posts when every judged box has a verdict, or after 30 minutes naming the boxes that did not check in; the forge's one-minute timer settles it, so a release whose boxes are all silent still gets its comment. The first sync a forge ever sees only records a baseline. Nobody asks for it and there is no screen: it is a comment, on every door a pull is.
201
200202 **Held** (`src/games/hold.ts`): a box whose agent starts nothing until a person has looked at its volume (docs/features/game-box.md) says so first, on `/games/<box>`, on each of its servers' pages, at the top of the terminal's Games and box screens, on its machine in the cloud tree and as `held` in the `games` tool. Its owner reads why, when the agent last looked and the next step; anyone else only that its owner has to look. The agent sends a code (`diag.hold`), never a sentence, and one the forge does not know is said as held without a reason. Held is not stopped: containers that already run are left alone. Start, Restart and Recreate (`src/games/power.ts`), and a world's import, restore and snapshot (`src/games/worlds.ts`: each ends by starting the server), say "held" and are refused at every door, also when an old page or screen asks; Stop and Pull go through, as at the agent. A box that has gone silent is asked, and its agent answers. An older agent sends nothing, and nothing is said.
src/core/migration-pins/20261204200000-game-agent-watch.pin added +1
@@ -0,0 +1,1 @@
1 d63fde9809bea6acc421bba3a7bb3a477c2710fe0c8065d32197cfdf37b7d052
src/core/migrations/20261204200000-game-agent-watch.ts added +19
@@ -0,0 +1,19 @@
1 // After a release that changes the game agent, the forge watches each box (#18272): which boxes
2 // checked in with the new script, how much CPU it used between syncs, and whether it was rolled
3 // back; then it posts the result once on the release's pull. Additive.
4 export default `
5 CREATE TABLE IF NOT EXISTS game_agent_watch (
6 sha TEXT PRIMARY KEY,
7 pull_number INTEGER,
8 started_at TEXT NOT NULL,
9 posted_at TEXT NOT NULL DEFAULT '',
10 box_ids TEXT NOT NULL DEFAULT '[]'
11 ) WITHOUT ROWID;
12 CREATE TABLE IF NOT EXISTS game_agent_seen (
13 sha TEXT NOT NULL,
14 box_id TEXT NOT NULL,
15 cpu_json TEXT NOT NULL DEFAULT '[]',
16 rolled_back TEXT NOT NULL DEFAULT '',
17 PRIMARY KEY (sha, box_id)
18 ) WITHOUT ROWID;
19 `;
src/games/agent.sh +28 −1
@@ -1627,6 +1627,32 @@ rename_strays() {
16271627 return 0
16281628 }
16291629
1630 # What the forge watches after a release that changes this script (#18272): which script this is
1631 # (its sha256, taken once), the share of one CPU this agent and what it ran used since the last full
1632 # sync (utime+stime+cutime+cstime of /proc/$$/stat over the wall time; 100 is one whole core), and the
1633 # sha whose update was rolled back, if any. Never fails: a missing /proc says nothing.
1634 OWN_SHA="$(sha256sum "$SELF" 2>/dev/null | cut -d' ' -f1)"
1635 OWN_TICKS=""
1636 OWN_AT=""
1637 OWN_JSON='{}'
1638 own_report() {
1639 local stat rest f now ticks hz pct=""
1640 stat="$(cat "/proc/$$/stat" 2>/dev/null)" || stat=""
1641 if [ -n "$stat" ]; then
1642 rest="${stat##*) }"
1643 read -ra f <<<"$rest"
1644 ticks=$((${f[11]:-0} + ${f[12]:-0} + ${f[13]:-0} + ${f[14]:-0}))
1645 now="$(date +%s)"
1646 hz="$(getconf CLK_TCK 2>/dev/null || echo 100)"
1647 if [ -n "$OWN_AT" ] && [ "$now" -gt "$OWN_AT" ]; then pct=$((100 * (ticks - OWN_TICKS) / (hz * (now - OWN_AT)))); fi
1648 OWN_TICKS="$ticks"
1649 OWN_AT="$now"
1650 fi
1651 OWN_JSON="$(jq -cn --arg sha "$OWN_SHA" --arg pct "$pct" --arg back "$(sed -n 1p "$ROLLED" 2>/dev/null)" \
1652 '{sha: $sha} + (if $pct == "" then {} else {cpuPct: ($pct | tonumber)} end) + (if $back == "" then {} else {rolledBackSha: $back} end)' 2>/dev/null)" || OWN_JSON='{}'
1653 [ -n "$OWN_JSON" ] || OWN_JSON='{}'
1654 }
1655
16301656 sync() {
16311657 local next answer code
16321658 next="$(now)"
@@ -1638,7 +1664,8 @@ sync() {
16381664 logs "$since" | json_or '{}' >"$DIR/.sync.logs"
16391665 between
16401666 host | json_or '{}' >"$DIR/.sync.host"
1641 bounded_diag | jq -c --argjson plugins "$(plugins_report)" --argjson hold "$(held)" --argjson waits "$([ -f "$DIR/.jars.waits" ] && echo true || echo false)" --arg back "$(sed -n 2p "$ROLLED" 2>/dev/null)" '. + {hold: $hold} + (if $plugins == {} then {} else {plugins: $plugins} end) + (if $waits then {jarsWait: true} else {} end) + (if $back == "" then {} else {rolledBack: $back} end)' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
1667 own_report
1668 bounded_diag | jq -c --argjson plugins "$(plugins_report)" --argjson hold "$(held)" --argjson waits "$([ -f "$DIR/.jars.waits" ] && echo true || echo false)" --arg back "$(sed -n 2p "$ROLLED" 2>/dev/null)" --argjson own "$OWN_JSON" '. + {hold: $hold, agent: $own} + (if $plugins == {} then {} else {plugins: $plugins} end) + (if $waits then {jarsWait: true} else {} end) + (if $back == "" then {} else {rolledBack: $back} end)' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
16421669 between
16431670 people | json_or '{}' >"$DIR/.sync.people"
16441671 between
src/games/agent_watch.ts added +151
@@ -0,0 +1,151 @@
1 /**
2 * After a release that changes the game agent (`agent.sh`), watch the boxes and say what happened
3 * on the release's pull (#18272, part 3 of #18250): did each box check in with the new script, did
4 * the agent stay near idle between syncs, and did the rollback (#18019) fire. The agent reports its
5 * own sha, its CPU since the last full sync and the sha it rolled back in its diag (`diag.agent`);
6 * this keeps the readings per release and posts one comment, once, when every box has a verdict or
7 * `WATCH_MS` has passed.
8 *
9 * A new script is told apart by its sha: the first sync a forge answers with a sha it has not
10 * watched opens a watch, tied to the newest release of the forge's own repository. The very first
11 * sync ever only records a baseline, so turning this on does not post about a release nobody
12 * watched.
13 *
14 * Limits, said plainly: the pull is the newest release at the moment the watch opens, which is the
15 * release that changed `agent.sh` unless another release landed between that one and the first
16 * sync answered with the new sha (then the comment goes on that later release's pull). Only the
17 * boxes that existed when the watch opened are judged: one made afterwards, or deleted since, is
18 * not waited for. A watch is also settled by `settleWatches` on the forge's timer, so a release
19 * whose boxes all stay silent still gets its comment after `WATCH_MS`.
20 */
21
22 import type { App } from "../app.ts";
23 import { engineActor } from "../core/engine.ts";
24 import { getIssueById } from "../core/issues.ts";
25 import { getPull } from "../core/pulls.ts";
26 import { getRepo } from "../core/repos.ts";
27 import { median } from "../efficiency/baseline.ts";
28 import { addComment } from "../actions/issues.ts";
29 import { latestReleaseOf } from "../release/record.ts";
30 import type { Diag } from "./diag.ts";
31 import { listBoxes, type GameBox } from "./store.ts";
32
33 /** How long the boxes are given to settle before the comment says who did not. */
34 export const WATCH_MS = 30 * 60_000;
35 /** Readings of the agent's CPU a box needs before it is judged. */
36 export const READINGS = 3;
37 /**
38 * The most the agent's median CPU may be between syncs and still count as near idle, in percent of
39 * one core.
40 */
41 export const IDLE_PCT = 15;
42 const KEPT = 12;
43
44 export type Verdict = "ok" | "busy" | "rolled-back" | "waiting";
45
46 export interface Seen {
47 readonly box: string;
48 readonly cpu: readonly number[];
49 readonly rolledBack: string;
50 }
51
52 /** The median of readings; 0 for none (`efficiency/baseline.ts` has the median). */
53 export const medianOf = (xs: readonly number[]): number => median(xs) ?? 0;
54
55 /** One box's verdict: a rollback is final; else judged by the median of its first readings. */
56 export function verdictOf(s: Seen): Verdict {
57 if (s.rolledBack !== "") return "rolled-back";
58 if (s.cpu.length < READINGS) return "waiting";
59 return medianOf(s.cpu) <= IDLE_PCT ? "ok" : "busy";
60 }
61
62 /** The comment: one line a box, then the answer to the three questions. */
63 export function watchText(sha: string, boxes: readonly Seen[], expired: boolean): string {
64 const lines = boxes.map((s) => {
65 const v = verdictOf(s);
66 const cpu = `${String(Math.round(medianOf(s.cpu)))}% of a core between syncs (median of ${String(s.cpu.length)})`;
67 if (v === "rolled-back") return `- ${s.box}: rolled back — ${s.rolledBack}`;
68 if (v === "ok") return `- ${s.box}: checked in with the new agent; ${cpu}; no rollback`;
69 if (v === "busy") return `- ${s.box}: checked in with the new agent but it is not idle: ${cpu}, more than ${String(IDLE_PCT)}%`;
70 return s.cpu.length > 0
71 ? `- ${s.box}: checked in, but only ${String(s.cpu.length)} of ${String(READINGS)} readings in ${String(WATCH_MS / 60_000)} min`
72 : `- ${s.box}: did not check in with the new agent within ${String(WATCH_MS / 60_000)} min`;
73 });
74 const good = boxes.length > 0 && boxes.every((s) => verdictOf(s) === "ok");
75 const head = good
76 ? `Game agent ${sha.slice(0, 12)}: every box checked in, stayed near idle (at most ${String(IDLE_PCT)}% of a core) and none rolled back.`
77 : `Game agent ${sha.slice(0, 12)}: needs a look${expired ? ` (${String(WATCH_MS / 60_000)} min passed)` : ""}.`;
78 return [head, "", ...(lines.length > 0 ? lines : ["- no game box exists"])].join("\n");
79 }
80
81 interface WatchRow {
82 sha: string;
83 pull_number: number | null;
84 started_at: string;
85 posted_at: string;
86 box_ids: string;
87 }
88
89 /**
90 * Take one box's full sync: open a watch for `sha` if this forge has not watched it, record the
91 * box's reading, and post the result when it is complete. Never throws into the sync.
92 */
93 export function watchAgent(app: App, box: Pick<GameBox, "id">, diag: Diag, sha: string, now = Date.now()): void {
94 const db = app.db;
95 const at = new Date(now).toISOString();
96 const any = db.query<{ n: number }, []>("SELECT count(*) AS n FROM game_agent_watch").get()!.n;
97 let row = db.query<WatchRow, [string]>("SELECT * FROM game_agent_watch WHERE sha = ?1").get(sha) ?? undefined;
98 if (row === undefined) {
99 const repo = app.config.forgeRepo === undefined ? undefined : getRepo(db, ...(app.config.forgeRepo.split("/") as [string, string]));
100 const pull = any === 0 || repo === undefined ? null : (latestReleaseOf(db, repo.id)?.pullNumber ?? null);
101 // The first answer ever is a baseline: posted already, so nothing is said about it.
102 const ids = JSON.stringify(listBoxes(db).map((b) => b.id));
103 db.query("INSERT OR IGNORE INTO game_agent_watch (sha, pull_number, started_at, posted_at, box_ids) VALUES (?1, ?2, ?3, ?4, ?5)").run(sha, pull, at, any === 0 ? at : "", ids);
104 row = db.query<WatchRow, [string]>("SELECT * FROM game_agent_watch WHERE sha = ?1").get(sha)!;
105 }
106 if (row.posted_at !== "") return;
107 const own = diag.agent;
108 const rolled = own?.rolledBackSha === sha && typeof diag.rolledBack === "string" ? diag.rolledBack.slice(0, 300) : "";
109 const had = db.query<{ cpu_json: string }, [string, string]>("SELECT cpu_json FROM game_agent_seen WHERE sha = ?1 AND box_id = ?2").get(sha, box.id);
110 let cpu: number[] = had === null ? [] : (JSON.parse(had.cpu_json) as number[]);
111 if (own?.sha === sha && typeof own.cpuPct === "number" && Number.isFinite(own.cpuPct) && own.cpuPct >= 0) cpu = [...cpu, Math.min(own.cpuPct, 10_000)].slice(-KEPT);
112 if (cpu.length > 0 || rolled !== "") {
113 db.query(
114 `INSERT INTO game_agent_seen (sha, box_id, cpu_json, rolled_back) VALUES (?1, ?2, ?3, ?4)
115 ON CONFLICT (sha, box_id) DO UPDATE SET cpu_json = excluded.cpu_json, rolled_back = CASE WHEN excluded.rolled_back <> '' THEN excluded.rolled_back ELSE rolled_back END`,
116 ).run(sha, box.id, JSON.stringify(cpu), rolled);
117 }
118 settle(app, row, now);
119 }
120
121 /**
122 * Settle every open watch whose boxes are all judged or whose time is up; run on the forge's timer.
123 */
124 export function settleWatches(app: App, now = Date.now()): void {
125 const open = app.db.query<WatchRow, []>("SELECT * FROM game_agent_watch WHERE posted_at = ''").all();
126 for (const row of open) settle(app, row, now);
127 }
128
129 function settle(app: App, row: WatchRow, now: number): void {
130 const db = app.db;
131 const judged = new Set(JSON.parse(row.box_ids) as string[]);
132 const boxes = listBoxes(db).filter((b) => judged.has(b.id));
133 const seen = boxes.map((b): Seen => {
134 const r = db.query<{ cpu_json: string; rolled_back: string }, [string, string]>("SELECT cpu_json, rolled_back FROM game_agent_seen WHERE sha = ?1 AND box_id = ?2").get(row.sha, b.id);
135 return { box: b.name, cpu: r === null ? [] : (JSON.parse(r.cpu_json) as number[]), rolledBack: r?.rolled_back ?? "" };
136 });
137 const expired = now - Date.parse(row.started_at) >= WATCH_MS;
138 if (!expired && seen.some((s) => verdictOf(s) === "waiting")) return;
139 // Marked first: a second sync in this tick cannot post it twice.
140 if (db.query("UPDATE game_agent_watch SET posted_at = ?2 WHERE sha = ?1 AND posted_at = ''").run(row.sha, new Date(now).toISOString()).changes === 0) return;
141 const text = watchText(row.sha, seen, expired);
142 const parts = app.config.forgeRepo?.split("/");
143 const repo = parts?.length === 2 ? getRepo(db, parts[0]!, parts[1]!) : undefined;
144 const pull = repo === undefined || row.pull_number === null ? undefined : getPull(db, repo.id, row.pull_number);
145 if (repo === undefined || pull === undefined) {
146 app.log.info("game agent watch: no release pull to post on", { sha: row.sha.slice(0, 12) });
147 return;
148 }
149 const said = addComment(app, engineActor(db), repo, getIssueById(db, pull.id) ?? pull, text);
150 if (!said.ok) app.log.warn("game agent watch: the comment was refused", { sha: row.sha.slice(0, 12), why: said.error });
151 }
src/games/diag.ts +6
@@ -42,6 +42,12 @@ export interface Diag {
4242 readonly removed?: readonly string[];
4343 readonly stray?: readonly string[];
4444 };
45 /**
46 * The agent's own report (#18272): the sha256 of the script it runs, the share of one CPU it and
47 * what it ran used since the last full sync (100 is a whole core), and the sha whose update it
48 * rolled back. An older agent does not say.
49 */
50 readonly agent?: { readonly sha?: string; readonly cpuPct?: number; readonly rolledBackSha?: string };
4551 /** The agent put the previous script back after an update that did not check in, and says why (#18019). */
4652 readonly rolledBack?: string;
4753 }
src/http/games_routes.ts +7
@@ -5,7 +5,9 @@
55
66 import { applyWhenQuiet } from "../games/when_quiet.ts";
77 import { composeServices, readCompose } from "../games/compose.ts";
8 import { watchAgent } from "../games/agent_watch.ts";
89 import { AGENT_SH, AGENT_SHA } from "../games/boot.ts";
10 import { readDiag } from "../games/diag.ts";
911 import { heal } from "../games/heal.ts";
1012 import { synced } from "../games/notify.ts";
1113 import { auditShellResults } from "../games/shell.ts";
@@ -92,6 +94,11 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
9294 // Every shell command the box answered, its output with it, into the audit.
9395 auditShellResults(ctx.app, box, (body.results ?? []).map((r) => r.id));
9496 recordMetrics(ctx.app.db, box, body);
97 try {
98 watchAgent(ctx.app, box, readDiag(JSON.stringify(body.diag ?? {})), AGENT_SHA);
99 } catch (e) {
100 ctx.app.log.warn("game agent watch failed", { error: String(e) });
101 }
95102 recordPeople(ctx.app.db, box, body.people);
96103 // A pack server's files against its lockfile: the answers judged, a check asked where one is due.
97104 if (body.boot === undefined) await packChecks(ctx.app, box, body);
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 } from "./spawn/preview-looks.ts";
5151 import { isPreviewEnv } from "./spawn/preview_who.ts";
52 import { settleWatches } from "./games/agent_watch.ts";
5253 import { startHeartbeat } from "./spawn/heartbeat.ts";
5354 import { startMachineBeats } from "./spawn/machine_beats.ts";
5455 import { startUpstreamWatch } from "./spawn/upstream.ts";
@@ -1067,6 +1068,8 @@ void followTick(app, true).catch((error) => app.log.error("could not link the ap
10671068 // A pinned forge still waiting for its address or answer is watched again
10681069 // (`actions/pinned_watch.ts`, #16372).
10691070 resumePinnedWatches(app);
1071 // An agent release is judged and said after its 30 minutes even when no box syncs (#18272).
1072 const agentWatchTimer = setInterval(() => background("agent-watch", () => settleWatches(app), undefined, app), 60_000);
10701073 const staleTimer = setInterval(() => background("asks", tickAsks, undefined, app), 120_000);
10711074 // A desk note whose time is up goes off the home line at once, over the stream.
10721075 const deskTimer = setInterval(() => background("desk", () => sweepDesk(app), undefined, app), 30_000);
@@ -1354,6 +1357,7 @@ function drain(signal: NodeJS.Signals): Promise<unknown> {
13541357 clearInterval(stateTimer);
13551358 clearInterval(syncTimer);
13561359 clearInterval(staleTimer);
1360 clearInterval(agentWatchTimer);
13571361 clearInterval(deskTimer);
13581362 clearInterval(entitlementTimer);
13591363 if (allocationTimer !== undefined) clearInterval(allocationTimer);
test/game-agent-rollback.test.ts +58
@@ -79,6 +79,7 @@ describe("an agent update on trial", () => {
7979 expect(existsSync(`${b.self}.prev`)).toBe(false);
8080 expect(existsSync(join(b.root, "game", ".trial"))).toBe(false);
8181 expect(b.diags.at(-1)?.["rolledBack"]).toBeUndefined();
82 expect(b.diags.at(-1)?.["agent"]).toEqual({ sha: sha(good) });
8283 } finally {
8384 await b.done();
8485 }
@@ -101,6 +102,8 @@ describe("an agent update on trial", () => {
101102 expect(b.asked.filter((p) => p.endsWith("/agent/script")).length).toBe(fetched);
102103 expect(b.text()).toBe(OLD);
103104 expect(b.diags.at(-1)?.["rolledBack"]).toContain("agent update rolled back");
105 // The diag names the script it runs and the sha it put aside, for the forge's watch (#18272).
106 expect(b.diags.at(-1)?.["agent"]).toMatchObject({ sha: sha(OLD), rolledBackSha: sha(bad) });
104107
105108 // A different agentSha ends the refusal and is tried.
106109 b.state.want = sha(good);
@@ -133,3 +136,58 @@ describe("the box's page", () => {
133136 expect(boxStatus({})).toEqual([]);
134137 });
135138 });
139
140 describe("the agent's own CPU", () => {
141 test.skipIf(lacks.length > 0)("the first full sync reports no cpuPct; the next, a number from ticks over wall time", async () => {
142 const root = mkdtempSync(join(tmpdir(), "forge-game-cpu-"));
143 mkdirSync(join(root, "game"));
144 const self = join(root, "agent.sh");
145 copyFileSync(AGENT, self);
146 const agents: Record<string, unknown>[] = [];
147 let second: () => void = () => {};
148 const heard = new Promise<void>((resolve) => {
149 second = resolve;
150 });
151 const forge = Bun.serve({
152 port: 0,
153 hostname: "127.0.0.1",
154 async fetch(req) {
155 const body = (await req.json().catch(() => ({}))) as { light?: boolean; diag?: { agent?: Record<string, unknown> } };
156 if (body.light !== true && body.diag?.agent !== undefined) {
157 agents.push(body.diag.agent);
158 if (agents.length === 2) second();
159 }
160 return Response.json({ composeSha: "", commands: [], agentSha: sha(OLD) });
161 },
162 });
163 const p = Bun.spawn(["bash", self], {
164 env: {
165 PATH: process.env["PATH"] ?? "",
166 HOME: root,
167 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
168 FORGE_GAME_TOKEN: TOKEN,
169 FORGE_GAME_DIR: join(root, "game"),
170 FORGE_GAME_DOCKER: "true",
171 FORGE_GAME_DIAG_S: "0",
172 FORGE_GAME_VOLUME_CHECK: "0",
173 FORGE_GAME_EVERY: "1",
174 },
175 stdout: "pipe",
176 stderr: "pipe",
177 });
178 try {
179 await heard; // the test's own timeout ends it if the second sync never comes
180 expect(agents.length).toBeGreaterThanOrEqual(2);
181 expect(agents[0]).toEqual({ sha: sha(OLD) });
182 const pct = agents[1]?.["cpuPct"];
183 expect(typeof pct).toBe("number");
184 // An agent asleep between syncs uses a sliver of one core, never a multiple of it.
185 expect(pct as number).toBeGreaterThanOrEqual(0);
186 expect(pct as number).toBeLessThan(100);
187 } finally {
188 p.kill();
189 forge.stop(true);
190 await rm(root, { recursive: true, force: true });
191 }
192 }, 40_000);
193 });
test/game-agent-watch.test.ts added +193
@@ -0,0 +1,193 @@
1 /**
2 * After a release that changes the game agent (#18272): each box's check-in with the new script,
3 * its CPU between syncs and any rollback are kept per release and said once on the release's pull.
4 * Numbers are built by hand: readings 2, 4, 6 have the median 4 (idle); 30, 40, 50 have 40 (not
5 * idle).
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { listComments } from "../src/core/issues.ts";
14 import type { Pull } from "../src/core/pulls.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { IDLE_PCT, medianOf, READINGS, settleWatches, verdictOf, watchAgent, watchText, WATCH_MS } from "../src/games/agent_watch.ts";
18 import type { Diag } from "../src/games/diag.ts";
19 import { AGENT_SHA } from "../src/games/boot.ts";
20 import { forgeHttp } from "../src/http/server.ts";
21 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
22 import { recordRelease } from "../src/release/record.ts";
23 import { quietLogs } from "./helpers/globals.ts";
24 import { openTopicPull } from "./helpers/open-pull.ts";
25
26 quietLogs();
27
28 const OLD = "a".repeat(64);
29 const NEW = "b".repeat(64);
30 const T0 = Date.parse("2026-12-04T12:00:00Z");
31
32 let dir: string;
33 let app: App;
34 let alice: User;
35 let repo: Repo;
36 let pull: Pull;
37 let one: GameBox;
38 let two: GameBox;
39
40 beforeAll(async () => {
41 dir = await mkdtemp(join(tmpdir(), "forge-agent-watch-"));
42 app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge" });
43 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
44 if (!made.ok) throw new Error(String(made.error));
45 alice = made.value;
46 const created = await createRepo(app, alice, { name: "forge", visibility: "public" });
47 if (!created.ok) throw new Error(String(created.error));
48 repo = created.value;
49 const seeded = await commitToBranch(app, alice, repo, { message: "start", files: [{ path: "README.md", content: "r\n" }] });
50 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
51 pull = await openTopicPull(app, alice, repo, 1, true);
52 createGameBox(app.db, { name: "one" });
53 createGameBox(app.db, { name: "two" });
54 one = boxNamed(app.db, "one")!;
55 two = boxNamed(app.db, "two")!;
56 });
57 afterAll(async () => {
58 app.close();
59 await rm(dir, { recursive: true, force: true });
60 });
61
62 const says = (): string[] => listComments(app.db, pull.id).map((c) => c.body).filter((b) => b.startsWith("Game agent"));
63 const diag = (sha: string, cpuPct?: number, more: Partial<Diag> = {}): Diag => ({ agent: { sha, ...(cpuPct === undefined ? {} : { cpuPct }) }, ...more });
64
65 describe("the pure parts", () => {
66 test("median of readings", () => {
67 expect(medianOf([6, 2, 4])).toBe(4);
68 expect(medianOf([2, 4])).toBe(3);
69 expect(medianOf([])).toBe(0);
70 });
71 test("a verdict: waiting, then idle or busy by the median; a rollback is final", () => {
72 expect(verdictOf({ box: "b", cpu: [1, 1], rolledBack: "" })).toBe("waiting");
73 expect(verdictOf({ box: "b", cpu: [2, 4, 6], rolledBack: "" })).toBe("ok");
74 expect(verdictOf({ box: "b", cpu: [30, 40, 50], rolledBack: "" })).toBe("busy");
75 expect(verdictOf({ box: "b", cpu: [IDLE_PCT, IDLE_PCT, IDLE_PCT], rolledBack: "" })).toBe("ok");
76 expect(verdictOf({ box: "b", cpu: [], rolledBack: "agent update rolled back: x" })).toBe("rolled-back");
77 expect(READINGS).toBe(3);
78 });
79 test("the text names each box and the three questions", () => {
80 const t = watchText(NEW, [{ box: "one", cpu: [2, 4, 6], rolledBack: "" }, { box: "two", cpu: [], rolledBack: "" }], true);
81 expect(t).toContain("needs a look");
82 expect(t).toContain("- one: checked in with the new agent; 4% of a core between syncs (median of 3); no rollback");
83 expect(t).toContain("- two: did not check in with the new agent within 30 min");
84 });
85 });
86
87 describe("watching a release", () => {
88 test("the first sync ever is a baseline: nothing is said", () => {
89 watchAgent(app, one, diag(OLD, 1), OLD, T0);
90 expect(says()).toEqual([]);
91 });
92
93 test("a new sha opens a watch on the newest release's pull; it posts once, when every box is judged", () => {
94 recordRelease(app.db, { sha: "c".repeat(40), repoId: repo.id, pullNumber: pull.number, ok: true, line: "ok" });
95 // The new agent's first report has no reading yet (it has no earlier sync to measure against).
96 watchAgent(app, one, diag(NEW), NEW, T0 + 1_000);
97 for (const [i, v] of [2, 4, 6].entries()) watchAgent(app, one, diag(NEW, v), NEW, T0 + 10_000 * (i + 2));
98 expect(says()).toEqual([]); // box two has not been heard
99 // An old agent's report does not count for the new one.
100 watchAgent(app, two, diag(OLD, 1), NEW, T0 + 60_000);
101 expect(says()).toEqual([]);
102 for (const [i, v] of [30, 40, 50].entries()) watchAgent(app, two, diag(NEW, v), NEW, T0 + 70_000 + 10_000 * i);
103 const posted = says();
104 expect(posted).toHaveLength(1);
105 expect(posted[0]).toContain("needs a look");
106 expect(posted[0]).toContain("- one: checked in with the new agent; 4% of a core");
107 expect(posted[0]).toContain("- two: checked in with the new agent but it is not idle: 40%");
108 // Later syncs say nothing more.
109 watchAgent(app, one, diag(NEW, 3), NEW, T0 + 200_000);
110 expect(says()).toHaveLength(1);
111 });
112
113 test("a rollback is said, and a box that never checks in is named once the time is up", () => {
114 const sha = "d".repeat(64);
115 recordRelease(app.db, { sha: "e".repeat(40), repoId: repo.id, pullNumber: pull.number, ok: true, line: "ok" });
116 watchAgent(app, one, diag(OLD, 1, { rolledBack: "agent update rolled back: the new agent exited 3 times within 600 s" }), sha, T0 + 300_000);
117 watchAgent(app, one, { agent: { sha: OLD, rolledBackSha: sha }, rolledBack: "agent update rolled back: the new agent exited 3 times within 600 s" }, sha, T0 + 310_000);
118 expect(says()).toHaveLength(1); // box two is still waiting
119 watchAgent(app, two, diag(OLD, 1), sha, T0 + 300_000 + WATCH_MS);
120 const posted = says();
121 expect(posted).toHaveLength(2);
122 expect(posted[1]).toContain("- one: rolled back — agent update rolled back: the new agent exited 3 times");
123 expect(posted[1]).toContain("- two: did not check in with the new agent");
124 });
125
126 test("a stale rollback of another sha is not this release's", () => {
127 const sha = "f".repeat(64);
128 watchAgent(app, one, { agent: { sha: OLD, rolledBackSha: "d".repeat(64) }, rolledBack: "old news" }, sha, T0 + 5_000_000);
129 expect(says()).toHaveLength(2);
130 expect(app.db.query("SELECT rolled_back FROM game_agent_seen WHERE sha = ?1").all(sha)).toEqual([]);
131 });
132 });
133
134 describe("when nobody syncs, and who is judged", () => {
135 test("a watch is settled by the timer after WATCH_MS and names every box", () => {
136 const sha = "1".repeat(64);
137 recordRelease(app.db, { sha: "2".repeat(40), repoId: repo.id, pullNumber: pull.number, ok: true, line: "ok" });
138 settleWatches(app, T0 + 6_000_000 + WATCH_MS); // the earlier test's silent watch is said first
139 const before = says().length;
140 watchAgent(app, one, diag(OLD, 1), sha, T0 + 10_000_000); // opens the watch; no reading
141 settleWatches(app, T0 + 10_000_000 + WATCH_MS - 1); // the 30 minutes are not up
142 expect(says()).toHaveLength(before);
143 settleWatches(app, T0 + 10_000_000 + WATCH_MS);
144 const posted = says();
145 expect(posted).toHaveLength(before + 1);
146 expect(posted.at(-1)).toContain("- one: did not check in");
147 expect(posted.at(-1)).toContain("- two: did not check in");
148 settleWatches(app, T0 + 20_000_000);
149 expect(says()).toHaveLength(before + 1);
150 });
151
152 test("a box made after the watch opened, or deleted since, is not waited for", () => {
153 const sha = "3".repeat(64);
154 const before = says().length;
155 const at = T0 + 30_000_000;
156 watchAgent(app, one, diag(OLD, 1), sha, at);
157 createGameBox(app.db, { name: "late" });
158 for (const [i, v] of [1, 2, 3].entries()) watchAgent(app, one, diag(sha, v), sha, at + 1_000 * (i + 1));
159 expect(says()).toHaveLength(before); // box two is judged, and has not been heard
160 for (const [i, v] of [1, 2, 3].entries()) watchAgent(app, two, diag(sha, v), sha, at + 10_000 + 1_000 * i);
161 const posted = says();
162 expect(posted).toHaveLength(before + 1); // not held for "late"
163 expect(posted.at(-1)).not.toContain("late");
164 expect(posted.at(-1)).toContain("every box checked in");
165 });
166 });
167
168 describe("the sync route feeds the watch", () => {
169 test("a box's full sync that says the forge's own agent sha is a reading, and the comment is posted", async () => {
170 const http = forgeHttp(app);
171 const fresh = createGameBox(app.db, { name: "route" });
172 const sha = AGENT_SHA;
173 const before = says().length;
174 // A watch for this forge's agent sha, judged by this one box only.
175 app.db.query("INSERT INTO game_agent_watch (sha, pull_number, started_at, posted_at, box_ids) VALUES (?1, ?2, ?3, '', ?4)").run(sha, pull.number, new Date().toISOString(), JSON.stringify([fresh.id]));
176 const send = (cpuPct: number) =>
177 http.handle(
178 new Request("http://forge.test/api/v1/games/agent/sync", {
179 method: "POST",
180 headers: { authorization: `Bearer ${fresh.token}`, "content-type": "application/json" },
181 body: JSON.stringify({ agent: 1, services: [], diag: { agent: { sha, cpuPct } } }),
182 }),
183 );
184 for (const v of [2, 4]) expect((await send(v)).status).toBe(200);
185 expect(says()).toHaveLength(before);
186 expect(app.db.query<{ cpu_json: string }, [string]>("SELECT cpu_json FROM game_agent_seen WHERE sha = ?1").get(sha)?.cpu_json).toBe("[2,4]");
187 expect((await send(6)).status).toBe(200);
188 const posted = says();
189 expect(posted).toHaveLength(before + 1);
190 expect(posted.at(-1)).toContain(`Game agent ${sha.slice(0, 12)}: every box checked in`);
191 expect(posted.at(-1)).toContain("- route: checked in with the new agent; 4% of a core");
192 });
193 });
test/game-diag.test.ts +1 −1
@@ -210,7 +210,7 @@ esac
210210 try {
211211 expect(await agent.exited).toBe(0);
212212 expect(box.bodies).toHaveLength(1);
213 expect(box.bodies[0]!["diag"]).toEqual({ note: "diag ran over 1 s", hold: null });
213 expect(box.bodies[0]!["diag"]).toMatchObject({ note: "diag ran over 1 s", hold: null });
214214 // The hung probe was stopped at the deadline: the sync went out in seconds.
215215 expect(Date.now() - started).toBeLessThan(4_500);
216216 } finally {
test/game-volume.test.ts +3 −3
@@ -400,7 +400,7 @@ describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", ()
400400 ]);
401401 expect(bodies.at(-1)!["composeSha"]).toBe("");
402402 // The forge reads the code, not the sentence.
403 expect(bodies.at(-1)!["diag"]).toEqual({ hold: { why: "other-worlds", since: expect.stringMatching(/^\d{4}-\d\d-\d\dT[\d:]+Z$/) } });
403 expect(bodies.at(-1)!["diag"]).toMatchObject({ hold: { why: "other-worlds", since: expect.stringMatching(/^\d{4}-\d\d-\d\dT[\d:]+Z$/) } });
404404 // A person moved the volume's worlds aside, on the volume: this disk's data moves there, and the games come up.
405405 const aside = join(b.root, "st", "volume", "forge-aside");
406406 mkdirSync(aside);
@@ -409,7 +409,7 @@ describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", ()
409409 expect(await waitFor(() => started().length > 0, { within: 10_000, what: "the up" })).toBe(true);
410410 expect(b.file("level.dat")).toBe("new and empty");
411411 expect(readFileSync(join(aside, "level.dat"), "utf8")).toBe("the worlds");
412 expect(bodies.at(-1)!["diag"]).toEqual({ hold: null });
412 expect(bodies.at(-1)!["diag"]).toMatchObject({ hold: null });
413413 } finally {
414414 server.stop(true);
415415 }
@@ -478,7 +478,7 @@ describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", ()
478478 const { bodies, sync, server } = synced(b, () => ({ commands: [], composeSha: "abc" }));
479479 try {
480480 await sync();
481 expect(bodies.at(-1)!["diag"]).toEqual({ hold: { why: "unknown", since } });
481 expect(bodies.at(-1)!["diag"]).toMatchObject({ hold: { why: "unknown", since } });
482482 } finally {
483483 server.stop(true);
484484 }
test/job-slices.test.ts +1
@@ -308,6 +308,7 @@ const UNTIMED: Record<string, string> = {
308308 "kept-log-flush": "every 2 s: one append of the buffered stall and minute lines to perf/loop.log, rotated past its size (perf/kept_log.ts); perf-kept-log.test.ts drives flush directly",
309309 "snapshot-cut-timeout": "a one-shot timer per file a snapshot cuts (snapshot/cut.ts), fired only when the cutter's worker has not answered within CUT_TIMEOUT_MS: it ends the worker and refuses the jobs it held; snapshot-cut.test.ts drives a silent worker to it",
310310 "advisory-feed": "hourly (and once 30 s after boot): one read of each repository's lockfile and two network fetches, KEV and OSV (core/advisory_feed.ts); the network is not timed here and advisory-feed.test.ts drives listenOnce with a fake fetch",
311 "agent-watch": "every 60 s: one read of the unposted agent watches (a table of at most a few rows), a handful of indexed reads each and at most one comment (games/agent_watch.ts); game-agent-watch.test.ts drives settleWatches with a clock",
311312 "series-sampler": "every 30 s: one /metrics render and one batched insert (series/store.ts record), bounded by the rows it keeps; series-explore.test.ts drives tick directly",
312313 "dev-reload": "a one-shot timer, 250 ms after a change in a dev cell's tree, that asks the dev server's root until it answers: a loopback fetch, off the loop, for one cell of one person (apps/dev_hot.ts); dev-hot.test.ts drives a change and the fault it ends in",
313314 "dev-line-told": "a one-shot timer, under a second, that tells a starting dev cell's pane of the last line of a burst (apps/dev_cell.ts): one in-memory read and one dev.state event, for one cell of one person; talk-pane-bar.test.ts drives a burst",

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

Keyboard shortcuts

Docs