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

A lent job on a game box keeps the server's tps and mspt from before it and during it #17957

opened this

Merged 19h 12m ago, live in production

scout/forge:scout/17949-a-lent-job-on-a-game-box-keeps-the-serve → main 0 commits fork 3 threads · 3 unresolved

  • Merged. scout/17949-a-lent-job-on-a-game-box-keeps-the-serve was merged into main as a357207.

Review

Sign in to review this change.
15 files changed +407 −4
docs/features/lent-runners.md +5 −1
@@ -41,7 +41,11 @@ trust:
4141 never from the box: only a job whose declared `limits.memoryMiB` fits it is claimed, one that
4242 declares none is not, and nothing is claimed while any of the box's servers is waking
4343 (`src/games/lend_fit.ts`). Its authors are limited to the repository's writers, so an outside
44 contributor's pull is never sent to it.
44 contributor's pull is never sent to it. What the box's server did meanwhile is kept with the job
45 (#17949, `src/games/lent_proof.ts`): the last tps and mspt from before the claim, and the lowest
46 tps and highest mspt each sync shows while it is held, as `tps 20.0 → 19.6 · mspt 11 → 15 while
47 lent`: in the check's facts (`Server`, page and terminal), on the box's row in Settings → Runners
48 and the terminal's runners screen, and as `lent` in the `games` tool's `list`. No setting.
4549
4650 A runner A owns has no scope and claims as before. A `lent-` runner enrolled before scopes takes
4751 the defaults from the day it was enrolled.
src/checks/runner_jobs.ts +3
@@ -21,6 +21,7 @@ import type { Database } from "bun:sqlite";
2121 import type { App } from "../app.ts";
2222 import { sha256 } from "../kernel/hash.ts";
2323 import { boxAuthors, boxSpareMiB } from "../games/lend_fit.ts";
24 import { startProof } from "../games/lent_proof.ts";
2425 import { id, secret } from "../kernel/id.ts";
2526 import { background } from "../perf/jobs.ts";
2627 import { DONE_ENV, keepDone } from "./shard_event.ts";
@@ -501,6 +502,8 @@ export function claimJob(
501502 )
502503 .run(row.id, runner.id, sha256(token), now + leaseMs, now).changes > 0;
503504 if (taken) {
505 // A game box's runner: keep the server's numbers from before the job (`games/lent_proof.ts`).
506 if (me.box_id !== "") startProof(db, me.box_id, row.id, runner.id, now);
504507 const got = db
505508 .query<{ spec: string; canary_for: string | null }, [string]>("SELECT spec, canary_for FROM check_job WHERE id = ?1")
506509 .get(row.id)!;
src/core/migration-pins/20261203080000-lent-proof.pin added +1
@@ -0,0 +1,1 @@
1 64f2f5cf6c75219ff94717202a7bfbef9fd40c9e3ea27a63f9c9686b2f15267e
src/core/migrations/20261203080000-lent-proof.ts added +22
@@ -0,0 +1,22 @@
1 // What a game box's server did while it was lent (#17949). `game_box.last_tps` and `last_mspt` are
2 // its newest sync's readings (null: none yet). `lent_proof` is one row a lent check job: the
3 // readings from before the claim and the worst seen while it ran, kept after the job is gone.
4 // Additive.
5 export default `
6 ALTER TABLE game_box ADD COLUMN last_tps REAL;
7 ALTER TABLE game_box ADD COLUMN last_mspt REAL;
8 CREATE TABLE lent_proof (
9 job_id TEXT PRIMARY KEY,
10 run_id TEXT NOT NULL,
11 box_id TEXT NOT NULL,
12 runner_id TEXT NOT NULL,
13 at INTEGER NOT NULL,
14 before_tps REAL,
15 before_mspt REAL,
16 low_tps REAL,
17 high_mspt REAL
18 );
19 CREATE INDEX lent_proof_run ON lent_proof (run_id);
20 CREATE INDEX lent_proof_runner ON lent_proof (runner_id, at);
21 CREATE INDEX lent_proof_box ON lent_proof (box_id);
22 `;
src/games/lent_proof.ts added +86
@@ -0,0 +1,86 @@
1 /**
2 * What a game box's server did while a check job ran on it (#17949). The agent already sends RCON
3 * `tps` and `mspt` with each sync; the forge keeps the newest pair on the box, copies it to the job
4 * when the box's runner claims one (the numbers from before), and while that job is held keeps the
5 * lowest tps and highest mspt each sync shows. The line is one sentence every door prints.
6 */
7
8 import type { Database } from "bun:sqlite";
9
10 export interface LentProof {
11 readonly beforeTps: number | null;
outdated

New 30-day retention cap that nothing asked for (box 4: no new cap). Remove it, or say why it is needed.

12 readonly beforeMspt: number | null;
13 readonly lowTps: number | null;
14 readonly highMspt: number | null;
15 }
16
17 /** One sync's worst reading over the box's servers: the lowest tps, the highest mspt. */
18 export interface Reading {
19 readonly tps: number | undefined;
20 readonly mspt: number | undefined;
21 }
22
23 /** A sync's readings: noted on every open proof of the box, and kept as the box's newest. */
24 export function noteReading(db: Database, boxId: string, reading: Reading): void {
25 const { tps, mspt } = reading;
26 if (tps === undefined && mspt === undefined) return;
27 db.query(
28 `UPDATE lent_proof SET
29 low_tps = CASE WHEN ?2 IS NULL THEN low_tps WHEN low_tps IS NULL THEN ?2 ELSE MIN(low_tps, ?2) END,
30 high_mspt = CASE WHEN ?3 IS NULL THEN high_mspt WHEN high_mspt IS NULL THEN ?3 ELSE MAX(high_mspt, ?3) END
31 WHERE box_id = ?1 AND job_id IN (SELECT id FROM check_job WHERE state = 'claimed')`,
32 ).run(boxId, tps ?? null, mspt ?? null);
33 db.query("UPDATE game_box SET last_tps = COALESCE(?2, last_tps), last_mspt = COALESCE(?3, last_mspt) WHERE id = ?1").run(boxId, tps ?? null, mspt ?? null);
34 }
35
36 /**
37 * The box's runner claimed a job: keep the numbers from before it. A job claimed again after a
38 * lapse keeps the worst it already saw, and takes the before numbers only where it has none.
39 */
40 export function startProof(db: Database, boxId: string, jobId: string, runnerId: string, now: number): void {
41 db.query(
42 `INSERT INTO lent_proof (job_id, run_id, box_id, runner_id, at, before_tps, before_mspt, low_tps, high_mspt)
outdated

INSERT OR REPLACE resets low_tps and high_mspt when the job is re-claimed after a lapse, so the worst readings already seen are lost. Keep them (INSERT ... ON CONFLICT DO NOTHING, or carry the old values).

43 SELECT j.id, j.run_id, b.id, ?3, ?4, b.last_tps, b.last_mspt, NULL, NULL FROM check_job j, game_box b WHERE j.id = ?1 AND b.id = ?2 AND true
44 ON CONFLICT (job_id) DO UPDATE SET box_id = excluded.box_id, runner_id = excluded.runner_id, at = excluded.at,
45 before_tps = COALESCE(before_tps, excluded.before_tps), before_mspt = COALESCE(before_mspt, excluded.before_mspt)`,
46 ).run(jobId, boxId, runnerId, now);
47 }
48
49 type Row = { before_tps: number | null; before_mspt: number | null; low_tps: number | null; high_mspt: number | null };
50 const toProof = (r: Row): LentProof => ({ beforeTps: r.before_tps, beforeMspt: r.before_mspt, lowTps: r.low_tps, highMspt: r.high_mspt });
51 const COLUMNS = "before_tps, before_mspt, low_tps, high_mspt";
52
53 /** The newest proof of a check run (it may have been claimed again after a lapse) or of a box. */
54 export function newestProof(db: Database, by: "run_id" | "box_id", id: string): LentProof | undefined {
55 const r = db.query<Row, [string]>(`SELECT ${COLUMNS} FROM lent_proof WHERE ${by} = ?1 ORDER BY at DESC LIMIT 1`).get(id);
56 return r === null ? undefined : toProof(r);
57 }
58
59 /** The line for a check run that a game box held; undefined when none did. */
60 export function lentLineOf(db: Database, runId: string): string | undefined {
61 const p = newestProof(db, "run_id", runId);
62 const line = p === undefined ? "" : proofLine(p);
63 return line === "" ? undefined : line;
64 }
65
66 /** The newest proof of each runner, by runner id: what the runners' rows say of their box. */
67 export function proofByRunner(db: Database): Map<string, LentProof> {
68 const rows = db.query<Row & { runner_id: string }, []>(
69 `SELECT runner_id, ${COLUMNS} FROM lent_proof p WHERE at = (SELECT MAX(at) FROM lent_proof WHERE runner_id = p.runner_id)`,
70 ).all();
71 return new Map(rows.map((r) => [r.runner_id, toProof(r)]));
72 }
73
74 /** `proofLine` of a proof that may be absent; "" then. */
75 export const proofWords = (p: LentProof | undefined): string => (p === undefined ? "" : proofLine(p));
76
77 const tpsWord = (n: number): string => n.toFixed(1);
78 const msptWord = (n: number): string => String(Math.round(n));
79
80 /** `tps 20.0 → 19.6 · mspt 11 → 15 while lent`; "" when nothing was read. */
81 export function proofLine(p: LentProof): string {
82 const pair = (name: string, before: number | null, worst: number | null, word: (n: number) => string): string =>
83 before === null && worst === null ? "" : `${name} ${before === null ? "?" : word(before)} → ${worst === null ? "?" : word(worst)}`;
84 const parts = [pair("tps", p.beforeTps, p.lowTps, tpsWord), pair("mspt", p.beforeMspt, p.highMspt, msptWord)].filter((s) => s !== "");
85 return parts.length === 0 ? "" : `${parts.join(" · ")} while lent`;
86 }
src/games/metrics.ts +5
@@ -11,6 +11,7 @@
1111 */
1212
1313 import type { Database } from "bun:sqlite";
14 import { noteReading } from "./lent_proof.ts";
1415 import { SERVICE_NAME, type GameBox } from "./store.ts";
1516 import type { SpareSample, SpareService } from "./spare.ts";
1617
@@ -188,6 +189,8 @@ export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: Metr
188189 r.tps = parseTps(text(m["tps"]));
189190 r.mspt = parseMspt(text(m["mspt"]));
190191 }
192 const tpsRead = [...rows.values()].flatMap((r) => (r.tps === undefined ? [] : [r.tps]));
193 const msptRead = [...rows.values()].flatMap((r) => (r.mspt === undefined ? [] : [r.mspt]));
191194 const events: { service: string; player: string; kind: PlayerEventKind; text: string }[] = [];
192195 for (const [service, lines] of Object.entries(body.logs ?? {}).slice(0, 64)) {
193196 if (!SERVICE_NAME.test(service) || !Array.isArray(lines)) continue;
@@ -207,6 +210,8 @@ export function recordMetrics(db: Database, box: Pick<GameBox, "id">, body: Metr
207210 }
208211 }
209212 db.transaction(() => {
213 // The lowest tps and highest mspt of the servers, for a check job the box holds (#17949).
214 noteReading(db, box.id, { tps: tpsRead.length === 0 ? undefined : Math.min(...tpsRead), mspt: msptRead.length === 0 ? undefined : Math.max(...msptRead) });
210215 const upsert = db.query(
211216 `INSERT INTO game_metric (box_id, service, minute, n, players_max, players_last, players_n, tps_sum, tps_min, tps_n, mspt_sum, mspt_max, mspt_n, cpu_sum, mem_sum, errors, warns, joins, leaves)
212217 VALUES (?1, ?2, ?3, 1, ?4, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17)
src/http/mcp/tools/games.ts +5
@@ -21,6 +21,7 @@ import { eventsOf, networkOf, PEOPLE_OPS, peopleOf, peopleWords, queuePeople } f
2121 import { findingsOf } from "../../../games/player_events.ts";
2222 import { linkShown } from "../../../games/snapshots.ts";
2323 import { takeBack } from "../../../games/take_back.ts";
24 import { newestProof, proofWords } from "../../../games/lent_proof.ts";
2425 import { queueWorld } from "../../../games/worlds.ts";
2526
2627 export const tool: Tool = {
@@ -76,6 +77,7 @@ export const tool: Tool = {
7677 }),
7778 );
7879 const held = boxes.map((b) => heldLines(heldOn(db, user, b)));
80 const lent = boxes.map((b) => (mayDo(roleOn(db, user, b.id), "owner") ? proofWords(newestProof(db, "box_id", b.id)) : ""));
7981 return good({
8082 items: boxes.map((b, i) => ({
8183 name: b.name,
@@ -89,6 +91,9 @@ export const tool: Tool = {
8991 ...(held[i]!.length === 0 ? {} : { held: held[i] }),
9092 status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3),
9193 packFiles: packCheckLines(ctx.app, b.id),
94 // What the server did while a check job ran on the box (`games/lent_proof.ts`), the
95 // owner's to read.
outdated

lent has no test. Add one that calls list as the box owner and as a non-owner. Also compute proofWords(newestProof(...)) once instead of twice.

96 ...(lent[i] === "" ? {} : { lent: lent[i] }),
9297 // What the forge mended alone and could not (`games/heal.ts`), the owner's to read.
9398 ...(mayDo(roleOn(db, user, b.id), "owner") ? { healed: healWords(db, b) } : {}),
9499 ...(cloud[i] === undefined ? {} : { cloud: cloud[i] }),
src/runs/run_facts.ts +5
@@ -45,6 +45,10 @@ export interface RunFactsInput {
4545 * log.
4646 */
4747 readonly account?: string | undefined;
48 /**
49 * What a game box's server did while it held the check (`proofLine`); none when it was not one.
50 */
51 readonly lent?: string | undefined;
4852 }
4953
5054 /**
@@ -126,6 +130,7 @@ export function runFacts(i: RunFactsInput): RunFact[] {
126130 : `a cluster job on ${node}`;
127131 facts.push({ label: "Ran on", text: where, ...(run.placement === "runner" && i.admin ? { href: "/settings/runners" } : {}) });
128132 }
133 if (i.lent !== undefined && i.lent !== "") facts.push({ label: "Server", text: i.lent });
129134 if (i.account !== undefined) facts.push({ label: "Account", text: i.account });
130135 if (run.feed !== null) facts.push({ label: "Fed", text: feedLine(run.feed) });
131136 if (run.startedAt !== null) facts.push({ label: "Started", text: run.startedAt, at: run.startedAt });
src/tui/screens/runlog.ts +2
@@ -30,6 +30,7 @@ import { costText, envLabel, runTone } from "./runwords.ts";
3030 import { priceWords } from "../../core/run_price.ts";
3131 import { getUsage } from "../../core/usage.ts";
3232 import { jobSandboxWords, startWords } from "../../checks/placement.ts";
33 import { lentLineOf } from "../../games/lent_proof.ts";
3334 import { runFacts, tookText } from "../../runs/run_facts.ts";
3435 import { tookParts } from "../../checks/took_line.ts";
3536 import { choiceOf } from "../../crew/account_choice.ts";
@@ -121,6 +122,7 @@ export function runLogScreen(
121122 writer: canSeeOwnerFacts(f.app.db, repo, f.user),
122123 took: tookText(run, log),
123124 account: choiceOf(log),
125 lent: canSeeOwnerFacts(f.app.db, repo, f.user) ? lentLineOf(f.app.db, run.id) : undefined,
124126 }).map((x) => `${x.label}: ${x.text}${x.href === undefined ? "" : ` ${x.href}`}`);
125127 const took = run.kind === "check" ? tookParts(log) : [];
126128 const stepsTook = took.length === 0 ? [] : [`Steps took: ${took.map((p) => `${p.name} ${p.seconds.toFixed(1)}s`).join(" · ")}`];
src/tui/screens/runners.ts +4
@@ -9,6 +9,7 @@
99 import { list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1010 import { isLocal } from "../../checks/runner_pool.ts";
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
12 import { proofByRunner, proofWords } from "../../games/lent_proof.ts";
1213 import { cannotByRunner } from "../../games/lend_why.ts";
1314 import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts";
1415 import { lentLine, scopeLine } from "../../checks/lent_scope.ts";
@@ -60,6 +61,7 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
6061 const held = heldByRunner(f.db);
6162 const cannot = cannotByRunner(f.db);
6263 const work = workByRunner(f.db);
64 const proofs = proofByRunner(f.db);
6365 return entries().map((e) => {
6466 if (e.kind === "offer") {
6567 const o = e.o;
@@ -77,6 +79,8 @@ export function runnersScreen(f: Session, ctx: Ctx): Screen {
7779 return {
7880 title: `${r.name} ${stateWords(r, now)}${isLocal(r) ? " (the forge's own)" : ""}`,
7981 meta: `${asked}${machine === "" ? "" : ` · ${machine}`} · runs ${w.jobs} at once · holding ${n} · ${w.ran} job${w.ran === 1 ? "" : "s"} run${scopeLine(r, now)}${cannot.has(r.id) ? ` · ${cannot.get(r.id)}` : ""}`,
82 // Under the row, where a narrow screen never gives it up as it does the meta's pieces.
83 ...(proofs.has(r.id) ? { note: proofWords(proofs.get(r.id)) } : {}),
8084 };
8185 });
8286 };
src/web/pages/runners.ts +5 −3
@@ -11,6 +11,7 @@
1111 import { listLending, offerLending, resumeLending, stopLending, type LendView } from "../../actions/lending.ts";
1212 import { list, removeHandMade, resume, revoke, runnerState } from "../../actions/runners.ts";
1313 import { isLocal } from "../../checks/runner_pool.ts";
14 import { proofByRunner, proofWords } from "../../games/lent_proof.ts";
1415 import { cannotByRunner } from "../../games/lend_why.ts";
1516 import { lendRoomLine, lookHere } from "../../checks/lend_pool.ts";
1617 import { lentLine, scopeFacts } from "../../checks/lent_scope.ts";
@@ -48,7 +49,7 @@ function runnerTrail(r: Enrolled) {
4849 return html`${r.paused === "" ? "" : form("resume", "Resume")}${form("revoke", "Revoke")}`;
4950 }
5051
51 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string) {
52 function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, cannot: string, proof: string) {
5253 const state = runnerState(r.seenAt, now);
5354 const machine = runnerMachineWords(r);
5455 return row({
@@ -66,7 +67,7 @@ function runnerRow(r: Enrolled, held: number, work: RunnerWork, now: number, can
6667 : badge("Never asked", { variant: "outline", icon: "ban" })}`,
6768 meta: html`${r.seenAt === 0 ? "Has not asked for work" : html`Last asked for work ${time(new Date(r.seenAt).toISOString())}`}
6869 · runs ${work.jobs} at once · holding ${held} now · ${work.ran} job${work.ran === 1 ? "" : "s"} run · enrolled ${time(r.createdAt, { date: true })}`,
69 facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...scopeFacts(r, now)],
70 facts: [...(cannot === "" ? [] : [{ label: "Lending", value: cannot }]), ...(proof === "" ? [] : [{ label: "Server", value: proof }]), ...(machine === "" ? [] : [{ label: "Machine", value: machine }]), ...scopeFacts(r, now)],
7071 trail: runnerTrail(r),
7172 });
7273 }
@@ -198,6 +199,7 @@ export function runnersPage(ctx: Ctx): Response {
198199 const held = heldByRunner(ctx.app.db);
199200 const cannot = cannotByRunner(ctx.app.db);
200201 const work = workByRunner(ctx.app.db);
202 const proofs = proofByRunner(ctx.app.db);
201203 const waiting = yieldNote(yieldState(process.env["FORGE_LEND_YIELD_LOAD"]));
202204 const lent = lentLine(lentIn(ctx.app.db, now));
203205 const body = html`<section class="settings-block">
@@ -207,7 +209,7 @@ export function runnersPage(ctx: Ctx): Response {
207209 ${seen.value.length === 0
208210 ? emptyList("runners")
209211 : html`<ul class="list setting-list" id="runner-list">
210 ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? ""))}
212 ${seen.value.map((r) => runnerRow(r, held.get(r.id) ?? 0, work.get(r.id) ?? { jobs: 1, ran: 0 }, now, cannot.get(r.id) ?? "", proofWords(proofs.get(r.id))))}
211213 </ul>`}
212214 </section>${lendingBlock(ctx)}`;
213215 notePhase(ctx.request, "render", performance.now() - rendering);
src/web/studio/run.ts +2
@@ -40,6 +40,7 @@ import { html, raw, when, type Html } from "../html.ts";
4040 import { runLine } from "../describe.ts";
4141 import { page } from "../layout.ts";
4242 import { badge, btn, card, disclosure, listCard, row as stepRow, runStateBadge, type Tone } from "../ui.ts";
43 import { lentLineOf } from "../../games/lent_proof.ts";
4344 import { runFacts, summaryParts, tookText, type RunFact } from "../../runs/run_facts.ts";
4445 import { STEP_PART, tookParts } from "../../checks/took_line.ts";
4546 import { RUN_NEXT_WORDS, runNext, type RunNext } from "../../runs/run_next.ts";
@@ -253,6 +254,7 @@ export async function runView(
253254 writer,
254255 took: duration,
255256 account: logHidden ? undefined : choiceOf(lines),
257 lent: writer ? lentLineOf(db, run.id) : undefined,
256258 });
257259 const elapsed =
258260 duration === undefined
test/game-lent-proof.test.ts added +140
@@ -0,0 +1,140 @@
1 /**
2 * #17949: a game box's server numbers around a lent check job. Made-up syncs from before and during
3 * the job: the box's claim keeps the last tps and mspt it had, the syncs while the job is held keep
4 * the lowest tps and highest mspt, one line says so on the runners page, the check's facts and the
5 * games tool, and a sync after the job is done changes nothing.
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 { createRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { setLoadSource } from "../src/checks/lent_yield.ts";
14 import { claimJob, offerJob, type RunnerJob } from "../src/checks/runner_jobs.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import type { Run } from "../src/core/runs.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, getUserByName } from "../src/core/users.ts";
19 import { lentRunnerOf, setLend } from "../src/games/lend.ts";
20 import { startProof, lentLineOf, proofLine, newestProof } from "../src/games/lent_proof.ts";
21 import { recordMetrics } from "../src/games/metrics.ts";
22 import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts";
23 import { forgeHttp, type ForgeHttp } from "../src/http/server.ts";
24 import { runFacts } from "../src/runs/run_facts.ts";
25 import { quietLogs } from "./helpers/globals.ts";
26 import { noCanary } from "./helpers/lent.ts";
27
28 quietLogs();
29
30 const NOW = Date.parse("2026-12-02T12:00:00Z");
31 const tps = (n: number): string => `TPS from last 1m, 5m, 15m: *${n.toFixed(1)}, 19.8, 19.9`;
32 const mspt = (n: number): string => `Server tick times (avg/min/max) from last 5s, 10s, 1m: ◴ ${n.toFixed(1)}/4.0/30.0, 9.0/3.0/40.0, 8.0/3.0/50.0`;
33
34 describe("a lent job keeps the server's tps and mspt", () => {
35 let dataDir = "";
36 let app: App;
37 let http: ForgeHttp;
38 let repo: Repo;
39 let box: GameBox;
40 let tok = "";
41 let at = NOW;
42
43 /** One sync, `at` a minute after the last. */
44 const sync = (t: number, m: number) => {
45 at += 60_000;
46 recordMetrics(app.db, box, { metrics: { hub: { tps: tps(t), mspt: mspt(m) } } }, new Date(at));
47 };
48 const offer = (name: string): RunnerJob =>
49 offerJob(app.db, {
50 runId: name,
51 repoId: repo.id,
52 dir: "/nowhere",
53 author: "alice",
54 job: {
55 run: name,
56 repo: "alice/mc-network",
57 commit: "a".repeat(40),
58 depth: 1,
59 steps: [{ name: "check", command: "bun test" }],
60 env: { CI: "1" },
61 limits: { memoryMiB: 256 },
62 timeoutS: 60,
63 egress: [],
64 egressMode: "enforce",
65 cell: "preferred",
66 cache: { repo: "r", tree: "", base: "" },
67 },
68 });
69
70 beforeAll(async () => {
71 dataDir = await mkdtemp(join(tmpdir(), "forge-lent-proof-"));
72 app = createApp({ dataDir, port: 0, modrinthFetch: async () => Response.json([]) });
73 http = forgeHttp(app);
74 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
75 if (!made.ok) throw new Error(made.error);
76 const alice = getUserByName(app.db, "alice")!;
77 tok = createToken(app.db, alice.id, "rw", "rw").token;
78 const repoMade = await createRepo(app, alice, { name: "mc-network", visibility: "public" });
79 if (!repoMade.ok) throw new Error(String(repoMade.error));
80 repo = repoMade.value;
81 createGameBox(app.db, { name: "net", repo: "alice/mc-network", place: "do:nyc3:s-4vcpu-8gb" });
82 box = boxNamed(app.db, "net")!;
83 app.db.query("UPDATE game_box SET host_json = ?2 WHERE id = ?1").run(box.id, JSON.stringify({ memMiB: 8000 }));
84 // Samples that leave spare memory, the hub asleep.
85 const start = NOW - 1500 * 60_000;
86 for (let i = 0; i <= 1500; i++) {
87 const awake = i < 100;
88 recordMetrics(app.db, box, { services: [{ name: "proxy", cpuPct: 5, memMiB: 500 }, { name: "hub", cpuPct: awake ? 80 : 0, memMiB: awake ? 3000 : 0 }] }, new Date(start + i * 60_000));
89 }
90 at = NOW;
91 for (const [name, state, mem] of [["proxy", "running", 500], ["hub", "exited", 0]] as const)
92 app.db.query("INSERT INTO game_service (box_id, name, state, mem_mib) VALUES (?1, ?2, ?3, ?4)").run(box.id, name, state, mem);
93 setLend(app.db, box, true, alice.id, NOW);
94 setLoadSource(() => 0);
95 }, 30_000);
96
97 afterAll(async () => {
98 setLoadSource();
99 app.close();
100 await rm(dataDir, { recursive: true, force: true });
101 });
102
103 test("before, during and after a job", async () => {
104 const runner = lentRunnerOf(app.db, box.id)!;
105 noCanary(app.db, runner);
106 sync(20, 10);
107 sync(19.9, 11); // the last reading before the claim
108 const job = offer("run-a");
109 expect(claimJob(app.db, { id: runner, cells: true }, at)?.job.id).toBe(job.id);
110 expect(newestProof(app.db, "box_id", box.id)).toEqual({ beforeTps: 19.9, beforeMspt: 11, lowTps: null, highMspt: null });
111 sync(19.6, 15);
112 sync(19.8, 12);
113 sync(19.7, 14);
114 expect(proofLine(newestProof(app.db, "box_id", box.id)!)).toBe("tps 19.9 → 19.6 · mspt 11 → 15 while lent");
115 expect(lentLineOf(app.db, "run-a")).toBe("tps 19.9 → 19.6 · mspt 11 → 15 while lent");
116
117 // Every door says it: the runners page, the check's facts, the games tool's list.
118 const runners = await (await http.handle(new Request("http://forge.test/settings/runners", { headers: { authorization: `Bearer ${tok}` } }))).text();
119 expect(runners).toContain("tps 19.9 → 19.6 · mspt 11 → 15 while lent");
120 const facts = runFacts({
121 run: { id: "run-a", kind: "check", env: "pull-7", commitOid: "", branch: "", state: "ok", summary: "", placement: "runner", node: "", startedAt: null, finishedAt: null, attempt: 0, feed: null } as Run,
122 base: "/alice/mc-network",
123 defaultBranch: "main",
124 admin: true,
125 writer: true,
126 lent: lentLineOf(app.db, "run-a"),
127 });
128 expect(facts.find((f) => f.label === "Server")?.text).toBe("tps 19.9 → 19.6 · mspt 11 → 15 while lent");
129
130 // The same job claimed again after a lapse keeps the worst it saw and the numbers from before.
131 startProof(app.db, box.id, job.id, runner, at);
132 expect(lentLineOf(app.db, "run-a")).toBe("tps 19.9 → 19.6 · mspt 11 → 15 while lent");
133
134 // Done: later syncs are not counted against it.
135 app.db.query("UPDATE check_job SET state = 'done' WHERE id = ?1").run(job.id);
136 sync(5, 90);
137 expect(lentLineOf(app.db, "run-a")).toBe("tps 19.9 → 19.6 · mspt 11 → 15 while lent");
138 expect(lentLineOf(app.db, "no-such-run")).toBeUndefined();
139 });
140 });
test/game-metrics.test.ts +2
@@ -96,6 +96,8 @@ describe("the rollup", () => {
9696 db.exec("CREATE TABLE user (id TEXT PRIMARY KEY, username TEXT)");
9797 db.exec(m.default);
9898 db.exec(n.default);
99 db.exec((await import("../src/core/migrations/20261203080000-lent-proof.ts")).default);
100 db.exec((await import("../src/core/migrations/20261116005600-check-runner.ts")).default);
99101 db.exec((await import("../src/core/migrations/20261202000000-game-people.ts")).default.replace(/^.*game_box.*$/m, ""));
100102 db.query("INSERT INTO game_service (box_id, name) VALUES ('b', 'hub')").run();
101103 });
test/lent-proof-doors.test.ts added +120
@@ -0,0 +1,120 @@
1 /**
2 * #17949, every door: the proof line of a lent job (`games/lent_proof.ts`) is read in the games
3 * tool's `list` (the box's owner's alone), on the runners screen, in the run log's facts and on the
4 * run's page, and a guest or a reader who does not write the repository sees none of the run's.
5 */
6 import { afterAll, beforeAll, expect, 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 { createRepo } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { enrolRunner } from "../src/checks/runner_jobs.ts";
13 import { createSession } from "../src/core/sessions.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { startProof } from "../src/games/lent_proof.ts";
18 import { boxNamed, createGameBox, grant } from "../src/games/store.ts";
19 import { serve, type Servers } from "../src/http/server.ts";
20 import type { Repo } from "../src/core/repos.ts";
21 import type { Ctx, Screen } from "../src/tui/app/app.ts";
22 import type { Session } from "../src/tui/session.ts";
23 import { createForgeApp } from "../src/tui/forge.ts";
24 import { runLogScreen } from "../src/tui/screens/runlog.ts";
25 import { runnersScreen } from "../src/tui/screens/runners.ts";
26 import { headlessTerminal } from "../src/tui/term/terminal.ts";
27 import { quietLogs } from "./helpers/globals.ts";
28 import { mcpTool } from "./helpers/mcp.ts";
29 import { settleApp } from "./helpers/tui.ts";
30
31 quietLogs();
32
33 const LINE = "tps 19.9 → 19.6 · mspt 11 → 15 while lent";
34
35 let dir = "";
36 let app: App;
37 let servers: Servers;
38 let alice: User;
39 let bob: User;
40 let runId = "";
41 let lamp: Repo;
42
43 const user = async (username: string, adminIfFirst = false): Promise<User> => {
44 const made = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@f.test`, password: "a-good-passphrase", adminIfFirst });
45 if (!made.ok) throw new Error(made.error);
46 return made.value;
47 };
48
49 const tui = async (who: User, screen: (f: Session, c: Ctx) => Screen, keys: readonly string[] = []) => {
50 const terminal = headlessTerminal(120, 30);
51 const { app: t, session } = createForgeApp(app, { sshUsername: who.username, remoteAddress: "127.0.0.1", user: who }, { terminal, exitHooks: false });
52 t.start();
53 await settleApp(t);
54 t.push(screen(session, t.ctx));
55 await settleApp(t);
56 for (const key of keys) {
57 terminal.feed(key);
58 await settleApp(t);
59 }
60 const text = t.screen.toText();
61 t.stop?.();
62 return text;
63 };
64
65 beforeAll(async () => {
66 dir = await mkdtemp(join(tmpdir(), "forge-lent-proof-doors-"));
67 app = createApp({ dataDir: dir, port: 0, modrinthFetch: async () => Response.json([]) });
68 servers = await serve(app);
69 alice = await user("alice", true);
70 bob = await user("bob");
71 const repo = await createRepo(app, alice, { name: "lamp", visibility: "public" });
72 if (!repo.ok) throw new Error(String(repo.error));
73 createGameBox(app.db, { name: "mc", repo: "alice/lamp", place: "do:nyc3:s-4vcpu-8gb" });
74 const box = boxNamed(app.db, "mc")!;
75 grant(app.db, box.id, bob.id, "operator");
76 const { runner } = enrolRunner(app.db, "lent-box-mc", alice.id);
77 app.db.query("UPDATE check_runner SET box_id = ?2 WHERE id = ?1").run(runner.id, box.id);
78 lamp = repo.value;
79 const run = createRun(app.db, { repoId: repo.value.id, kind: "check" });
80 runId = run.id;
81 // A job of that run, claimed by the box's runner, then its numbers as the syncs left them.
82 app.db.query("INSERT INTO check_job (id, run_id, repo_id, dir, spec) VALUES ('job-1', ?1, ?2, '/x', '{}')").run(run.id, repo.value.id);
83 app.db.query("UPDATE game_box SET last_tps = 19.9, last_mspt = 11 WHERE id = ?1").run(box.id);
84 startProof(app.db, box.id, "job-1", runner.id, Date.now());
85 app.db.query("UPDATE lent_proof SET low_tps = 19.6, high_mspt = 15 WHERE job_id = 'job-1'").run();
86 }, 30_000);
87
88 afterAll(async () => {
89 servers.stop();
90 app.close();
91 await rm(dir, { recursive: true, force: true });
92 });
93
94 test("the games tool's list gives the owner the line, and a non-owner none", async () => {
95 const owner = await mcpTool(servers.url, createToken(app.db, alice.id, "admin", "admin").token, "games", { action: "list" });
96 expect(owner.value.items[0].lent).toBe(LINE);
97 const other = await mcpTool(servers.url, createToken(app.db, bob.id, "rw", "rw").token, "games", { action: "list" });
98 expect(other.value.items).toHaveLength(1);
99 expect("lent" in other.value.items[0]).toBe(false);
100 });
101
102 test("the runners screen shows the line under the box's runner", async () => {
103 expect(await tui(alice, runnersScreen)).toContain(LINE);
104 });
105
106 test("the run log's Server fact is a writer's: the owner reads it, a reader who does not write does not", async () => {
107 const asRepo = (f: Session, c: Ctx) => runLogScreen(f, c, lamp, runId);
108 expect(await tui(alice, asRepo)).toContain(`Server: ${LINE}`);
109 expect(await tui(bob, asRepo)).not.toContain("Server:");
110 });
111
112 test("the run's page: a writer reads it, a guest and a non-writer do not", async () => {
113 const url = `${servers.url}/alice/lamp/runs/${runId}`;
114 const cookie = (who: User) => ({ cookie: `forge_session=${createSession(app.db, who.id).token}` });
115 expect(await (await fetch(url, { headers: cookie(alice) })).text()).toContain(LINE);
116 const guest = await fetch(url);
117 expect(guest.status).toBe(200);
118 expect(await guest.text()).not.toContain("while lent");
119 expect(await (await fetch(url, { headers: cookie(bob) })).text()).not.toContain("while lent");
120 });

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

Keyboard shortcuts

Docs