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

Game box: refuse a wake or a mod install the box has no memory for #18057

opened this

Merged 9h 28m ago, live in production

sold/memory-check → main 0 commits 3 threads · 3 unresolved

  • Merged. sold/memory-check was merged into main as 7fe508f.

Review

Sign in to review this change.
10 files changed +141 −21
src/games/box_memory.ts added +45
@@ -0,0 +1,45 @@
1 import { agoWords } from "../kernel/ago.ts";
2
3 /**
4 * Room on a game box (#18025): a server that starts, or a mod that is added, on a box whose host
5 * memory (as its agent last said it) leaves less than the server's own heap plus a margin for the
6 * system, gets the box killed by the kernel's memory killer instead of a refusal. Said in words, here.
7 */
8
9 /** Kept free beyond the server's heap: the box's own processes and the page cache. */
10 export const MARGIN_MIB = 512;
11
12 /** A heap in MiB from itzg's MEMORY ("1G", "1536M", "512m"); 1 GiB when it says nothing. */
13 export function heapMiB(memory: string | undefined): number {
14 const m = /^(\d+(?:\.\d+)?)\s*([gGmM])?$/.exec((memory ?? "").trim());
15 if (m === null) return 1024;
16 return Math.round(Number(m[1]) * (m[2]?.toLowerCase() === "m" ? 1 : 1024));
17 }
18
19 /** A reading older than this is not acted on: the box may have changed since. */
20 export const STALE_MS = 10 * 60_000;
21
22 /** What a refusal needs of a box: its last host numbers, and when it said them. */
23 export interface BoxRoom {
24 readonly host: Readonly<Record<string, number>>;
25 readonly seenAt: string;
26 }
27
28 /**
29 * Why `what` should not go ahead, or undefined when the box has room, has not said its memory, or
30 * said it too long ago to trust. `memory` is the server's MEMORY setting. `running`: the server is
31 * up, so its heap is already in what the box uses and only the margin is asked for.
32 */
33 export function memoryRefusal(box: BoxRoom, memory: string | undefined, what: string, running: boolean, now = Date.now()): string | undefined {
34 const total = box.host["memMiB"];
35 const used = box.host["memUsedMiB"];
36 if (typeof total !== "number" || typeof used !== "number" || total <= 0) return undefined;
37 const age = now - Date.parse(box.seenAt);
38 if (!Number.isFinite(age) || age > STALE_MS) return undefined;
39 const free = Math.max(0, total - used);
40 const heap = running ? 0 : heapMiB(memory);
41 const need = heap + MARGIN_MIB;
42 if (free >= need) return undefined;
43 const asked = running ? `${MARGIN_MIB} MiB for the box` : `the server's memory ${heap} MiB plus ${MARGIN_MIB} MiB for the box`;
44 return `${what} needs ${need} MiB free (${asked}), and the box said ${agoWords(box.seenAt, now)} that it has ${free} MiB free of ${total} MiB. Stop a server you are not using, or move to a bigger box, then try again.`;
45 }
src/games/mods.ts +7 −1
@@ -20,8 +20,9 @@ import type { App } from "../app.ts";
2020 import type { User } from "../core/users.ts";
2121 import { commitCompose, composeDir, pluginUrls, readCompose, readRepoFile, serviceEnv, setServiceEnv } from "./compose.ts";
2222 import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, targetOf, updates, type Locked, type LockedPack, type Result, type Target, type Version } from "./modrinth.ts";
23 import { memoryRefusal, type BoxRoom } from "./box_memory.ts";
2324 import { AUTOSTOPPER } from "./sleep.ts";
24 import type { GameBox } from "./store.ts";
25 import { servicesOf, type GameBox } from "./store.ts";
2526
2627 /** What a service has, as its repository says at the compose file's commit. */
2728 export interface Mods {
@@ -38,6 +39,8 @@ export interface Mods {
3839 readonly env: Readonly<Record<string, string>>;
3940 /** The modpack the server runs (TYPE=MODRINTH), every file of it locked. */
4041 readonly pack: LockedPack | undefined;
42 /** The box's last host numbers and when it said them, and whether the server is up: for the memory check. */
43 readonly room?: BoxRoom & { readonly running: boolean };
4144 }
4245
4346 /** A change, previewed: its lines in words, and what the commit writes. */
@@ -134,6 +137,7 @@ export async function modsOf(app: App, box: GameBox, service: string): Promise<R
134137 sha: compose.sha,
135138 env,
136139 pack: target.value.pack ? pack : undefined,
140 room: { host: box.host, seenAt: box.seenAt, running: servicesOf(app.db, box.id).some((x) => x.name === service && x.state === "running") },
137141 },
138142 };
139143 }
@@ -197,6 +201,8 @@ export async function planInstall(app: App, m: Mods, service: string, ref: strin
197201 return { ok: false, error: "Name a Modrinth project by its slug or id, like luckperms." };
198202 const had = find(m.lock, wantedRef);
199203 if (had?.top) return { ok: false, error: `${had.title} ${had.version} is installed.` };
204 const crowded = m.room === undefined ? undefined : memoryRefusal(m.room, m.env["MEMORY"], `Adding ${wantedRef} restarts ${service}, and that`, m.room.running);
outdated

A running server's heap is already in memUsedMiB, and the restart frees it. This refuses installs on tight boxes that would fit. Count the heap only for a stopped server, or leave the install unchecked when it is running.

205 if (crowded !== undefined) return { ok: false, error: crowded };
200206 // A bare slug already in MODRINTH_PROJECTS is taken into the lock, pinned, with this change.
201207 const adopt = m.loose.filter(bareSlug);
202208 const kept = m.loose.filter((e) => !bareSlug(e));
src/games/power.ts +15 −5
@@ -5,8 +5,10 @@
55 * and pull go through, as they do at the agent. Whether a person may ask is the door's own check.
66 */
77
8 import type { Database } from "bun:sqlite";
8 import type { App } from "../app.ts";
99 import type { User } from "../core/users.ts";
10 import { memoryRefusal } from "./box_memory.ts";
11 import { readCompose, serviceEnv } from "./compose.ts";
1012 import { heldRefusal, startsNothing } from "./hold.ts";
1113 import { queueCommand, type GameBox } from "./store.ts";
1214
@@ -18,9 +20,17 @@ const starts = (kind: Power): boolean => kind !== "stop" && kind !== "pull";
1820 /** Whether the box would refuse it now, as it last said. */
1921 export const refusesNow = (box: GameBox, kind: Power): boolean => starts(kind) && startsNothing(box, Date.now());
2022
21 /** Ask the box for it, or say why it was not asked. */
22 export function askPower(db: Database, by: User | undefined, box: GameBox, service: string, kind: Power): { readonly ok: true; readonly id: string } | { readonly ok: false; readonly error: string } {
23 const error = starts(kind) ? heldRefusal(db, by, box, `${kind[0]!.toUpperCase()}${kind.slice(1)} ${service}`) : undefined;
23 /**
24 * Ask the box for it, or say why it was not asked: held, or (for a start, the wake of a stopped
25 * server) too little free memory on the box, as it last said, for the server's heap and a margin.
26 */
27 export async function askPower(app: App, by: User | undefined, box: GameBox, service: string, kind: Power): Promise<{ readonly ok: true; readonly id: string } | { readonly ok: false; readonly error: string }> {
28 const error = starts(kind) ? heldRefusal(app.db, by, box, `${kind[0]!.toUpperCase()}${kind.slice(1)} ${service}`) : undefined;
2429 if (error !== undefined) return { ok: false, error };
25 return { ok: true, id: queueCommand(db, box.id, service, kind, "", by?.id ?? "") };
30 if (kind === "start") {
31 const compose = await readCompose(app, box);
32 const crowded = compose === undefined ? undefined : memoryRefusal(box, serviceEnv(compose.text, service)["MEMORY"], `Starting ${service}`, false);
outdated

box.host is whatever the agent last said, however old. Bound its age or say how old it is in the refusal, or a stale reading blocks a wake that would fit.

33 if (crowded !== undefined) return { ok: false, error: crowded };
34 }
35 return { ok: true, id: queueCommand(app.db, box.id, service, kind, "", by?.id ?? "") };
2636 }
src/games/presets.ts +1 −6
@@ -12,6 +12,7 @@
1212 import type { App } from "../app.ts";
1313 import type { User } from "../core/users.ts";
1414 import { commitCompose, composeServices, readCompose, serviceEnv, setTopEntry } from "./compose.ts";
15 import { heapMiB } from "./box_memory.ts";
1516 import { lockPath, lockText, planInstall, type Mods } from "./mods.ts";
1617 import { targetOf, type Locked, type Result } from "./modrinth.ts";
1718 import { isGameServer, policyOf, proxyOf, setPolicy } from "./sleep.ts";
@@ -75,12 +76,6 @@ export async function wishOn(app: App, box: GameBox, words: string): Promise<Wis
7576 return parseWish(words, [...servicesOf(app.db, box.id).map((s) => s.name), ...(compose === undefined ? [] : composeServices(compose.text))]);
7677 }
7778
78 /** A heap in MiB from itzg's MEMORY ("1G", "1536M", "512m"); 1 GiB when it says nothing. */
79 export function heapMiB(memory: string | undefined): number {
80 const m = /^(\d+(?:\.\d+)?)\s*([gGmM])?$/.exec((memory ?? "").trim());
81 if (m === null) return 1024;
82 return Math.round(Number(m[1]) * (m[2]?.toLowerCase() === "m" ? 1 : 1024));
83 }
8479 const gb = (mib: number): string => (mib % 1024 === 0 ? `${mib / 1024}G` : `${(mib / 1024).toFixed(1)}G`);
8580
8681 /**
src/http/mcp/tools/games.ts +1 −1
@@ -170,7 +170,7 @@ export const tool: Tool = {
170170 if (action === "power") {
171171 const kind = str(args["kind"]);
172172 if (!isPower(kind)) return bad("invalid", "kind is start, stop, restart, recreate or pull");
173 const asked = askPower(db, user, box, service, kind);
173 const asked = await askPower(ctx.app, user, box, service, kind);
174174 return asked.ok ? good({ says: `${kind} ${service}: asked.`, id: asked.id }) : bad("refused", asked.error);
175175 }
176176 if (action === "env") {
src/tui/screens/games.ts +11 −4
@@ -35,7 +35,7 @@ import { spareRow } from "../../games/spare_row.ts";
3535 import { healWords } from "../../games/heal.ts";
3636 import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts";
3737 import { heldLines, heldOn } from "../../games/hold.ts";
38 import { askPower, type Power } from "../../games/power.ts";
38 import { askPower, refusesNow, type Power } from "../../games/power.ts";
3939 import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts";
4040 import { getUserByName } from "../../core/users.ts";
4141 import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts";
@@ -279,9 +279,16 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen {
279279 if (kind === undefined || at === undefined || e.ctrl || e.alt) return false;
280280 if (!mayDo(roleOn(f.app.db, f.user, at.box.id, at.service.name), "operator")) note = `You are not an operator of ${at.service.name}.`;
281281 else {
282 const asked = askPower(f.app.db, f.user, at.box, at.service.name, kind);
283 // Why is above the list, on every draw.
284 note = !asked.ok ? `${kind} ${at.box.name}/${at.service.name}: not asked, ${at.box.name} is held.` : `${kind} ${at.box.name}/${at.service.name}: asked. It shows on the server until the server answers.`;
282 const { box, service } = at;
283 void askPower(f.app, f.user, box, service.name, kind)
outdated

The async block is unawaited and has no catch. A throw from readCompose is an unhandled rejection and the note never changes. Catch it and set the note, and test the TUI path.

284 .then((asked) => {
285 // Why is above the list, on every draw.
286 note = !asked.ok ? `${kind} ${box.name}/${service.name}: not asked, ${refusesNow(box, kind) ? `${box.name} is held.` : asked.error}` : `${kind} ${box.name}/${service.name}: asked. It shows on the server until the server answers.`;
287 })
288 .catch(() => {
289 note = `${kind} ${box.name}/${service.name}: not asked, the forge could not check the box. Try again.`;
290 })
291 .finally(() => ctx.invalidate());
285292 }
286293 ctx.invalidate();
287294 return true;
src/web/pages/games.ts +1 −1
@@ -1074,7 +1074,7 @@ export async function gamePowerSubmit(ctx: Ctx): Promise<Response> {
10741074 if (got instanceof Response) return got;
10751075 const kind = field(got.form, "kind");
10761076 if (!isPower(kind)) return notFoundPage(ctx);
1077 const asked = askPower(ctx.app.db, ctx.auth.user, got.box, got.service, kind);
1077 const asked = await askPower(ctx.app, ctx.auth.user, got.box, got.service, kind);
10781078 return flashTo(ctx, `/games/${got.box.name}/${got.service}`, !asked.ok ? { tone: "danger", message: asked.error } : { message: `${kind[0]!.toUpperCase()}${kind.slice(1)} ${got.service}: asked. It shows on the server until the server answers.` });
10791079 }
10801080
test/game-hold.test.ts +15 −1
@@ -2,7 +2,7 @@
22 * A held game box says so first, at every door (#17532): why, and the next step, to its owner; that
33 * its owner has to look, to anyone else. The words come from a code, so no log line is read.
44 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
5 import { afterAll, beforeAll, expect, spyOn, test } from "bun:test";
66 import { mkdtempSync } from "node:fs";
77 import { rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
@@ -16,6 +16,7 @@ import { createToken } from "../src/core/tokens.ts";
1616 import { createUser, type User } from "../src/core/users.ts";
1717 import { boxStatus, DIAG_MOST, holdOf, keptDiag, readDiag } from "../src/games/diag.ts";
1818 import { heldOn } from "../src/games/hold.ts";
19 import * as power from "../src/games/power.ts";
1920 import { POWER, type Power } from "../src/games/power.ts";
2021 import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts";
2122 import { serve, type Servers } from "../src/http/server.ts";
@@ -297,3 +298,16 @@ test("a world's import, restore and snapshot end by starting the server, so a he
297298 expect(asked()).toEqual(Array(6).fill("world"));
298299 expect(await get(alice, "/games/mc/hub")).not.toContain("snapshot: held");
299300 });
301
302 test("the terminal says why a start was refused, and says so when the check itself throws", async () => {
303 sync(null);
304 const spy = spyOn(power, "askPower");
305 try {
306 spy.mockResolvedValueOnce({ ok: false, error: "Starting hub needs 1536 MiB free." });
307 expect(await keys("s")).toContain("start mc/hub: not asked, Starting hub needs 1536 MiB free.");
308 spy.mockRejectedValueOnce(new Error("repo unreadable"));
309 expect(await keys("s")).toContain("start mc/hub: not asked, the forge could not check the box. Try again.");
310 } finally {
311 spy.mockRestore();
312 }
313 });
test/game-mods.test.ts +43 −1
@@ -16,9 +16,10 @@ import { createUser, getUserByName, type User } from "../src/core/users.ts";
1616 import { readCompose, readRepoFile, serviceEnv } from "../src/games/compose.ts";
1717 import { search, searchPacks, targetOf } from "../src/games/modrinth.ts";
1818 import { commitPlan, lockPath, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../src/games/mods.ts";
19 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
19 import { boxNamed, createGameBox, recordSync, type GameBox } from "../src/games/store.ts";
2020 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
2121 import { packVerdict } from "../src/games/pack_check.ts";
22 import { askPower } from "../src/games/power.ts";
2223 import { AUTOSTOPPER, commitPolicy } from "../src/games/sleep.ts";
2324 import { quietLogs } from "./helpers/globals.ts";
2425
@@ -691,3 +692,44 @@ describe("the page and the MCP tool", () => {
691692 expect((listed.value["installed"] as { project: string }[]).map((p) => p.project)).toContain("chunkylib");
692693 });
693694 });
695
696 describe("room on the box (#18025)", () => {
697 // The hub sets no MEMORY: its heap is 1 GiB, so a stopped one needs 1536 MiB free.
698 const said = (free: number, ago = 60_000): GameBox => ({ ...box, seenAt: new Date(Date.now() - ago).toISOString(), host: { memMiB: 8000, memUsedMiB: 8000 - free } });
699 const planFor = async (b: GameBox) => {
700 const m = await modsOf(app, b, "hub");
701 if (!m.ok) throw new Error(m.error);
702 return planInstall(app, m.value, "hub", "worldedit");
703 };
704 const refusal = (r: { ok: boolean; error?: string }): string => (r.ok ? "" : (r.error ?? ""));
705
706 test("a mod install on a stopped server is refused in words, with how old the reading is", async () => {
707 const no = refusal(await planFor(said(1535)));
708 expect(no).toContain("needs 1536 MiB free");
709 expect(no).toContain("the box said 1 minute ago that it has 1535 MiB free of 8000 MiB");
710 // Anything else it says (this mod may need more than the stand-in has) is not about memory.
711 expect(refusal(await planFor(said(1536)))).not.toContain("MiB free");
712 expect(refusal(await planFor(box))).not.toContain("MiB free");
713 });
714
715 test("a reading older than ten minutes is not acted on", async () => {
716 expect(refusal(await planFor(said(0, 11 * 60_000)))).not.toContain("MiB free");
717 expect(refusal(await planFor(said(0, 9 * 60_000)))).toContain("needs 1536 MiB free");
718 });
719
720 test("a wake (start) is refused the same way, and queues nothing; a stop is not", async () => {
721 const no = await askPower(app, alice, said(1535), "hub", "start");
722 expect(no.ok).toBe(false);
723 if (!no.ok) expect(no.error).toContain("Starting hub needs 1536 MiB free");
724 expect((await askPower(app, alice, said(1536), "hub", "start")).ok).toBe(true);
725 expect((await askPower(app, alice, said(0), "hub", "stop")).ok).toBe(true);
726 expect((await askPower(app, alice, said(0, 11 * 60_000), "hub", "start")).ok).toBe(true);
727 });
728
729 test("a running server's heap is already in what the box uses: only the 512 MiB margin is asked", async () => {
730 recordSync(app.db, box, { services: [{ name: "hub", state: "running" }] });
731 const no = refusal(await planFor(said(511)));
732 expect(no).toContain("needs 512 MiB free (512 MiB for the box)");
733 expect(refusal(await planFor(said(512)))).not.toContain("MiB free");
734 });
735 });
test/game-presets.test.ts +2 −1
@@ -18,7 +18,8 @@ import { createToken } from "../src/core/tokens.ts";
1818 import { createUser, type User } from "../src/core/users.ts";
1919 import { readCompose, readRepoFile, serviceEnv, serviceLabels } from "../src/games/compose.ts";
2020 import { lockPath } from "../src/games/mods.ts";
21 import { commitServer, heapMiB, memoryMath, parseWish, planRemoveServer, planServer, wishOn, proxyLines } from "../src/games/presets.ts";
21 import { heapMiB } from "../src/games/box_memory.ts";
22 import { commitServer, memoryMath, parseWish, planRemoveServer, planServer, wishOn, proxyLines } from "../src/games/presets.ts";
2223 import { policyOf, WAKER } from "../src/games/sleep.ts";
2324 import { boxNamed, createGameBox, recordSync } from "../src/games/store.ts";
2425 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";

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

Keyboard shortcuts

Docs