diff --git a/README.md b/README.md index 0a52c1c..e07fa1e 100644 --- a/README.md +++ b/README.md @@ -166,9 +166,17 @@ it has no CPU fallback, and hits never touch it. Each hashes) and the worker identity. `GET /health` shows the identity and the stored count. -GPU tenancy. The daemon holds one GPU slot; a `POST /motion/generate` while another job holds it -is refused with HTTP 503, `retry-after: 60` and `{ ok: false, code: "gpu-busy", source: "slot" }`. -A job already running finishes; the gate never stops work. `npm test` runs the gate's tests. +GPU permission. Raven's GPU is the household's first. A tray icon in the household's session +(`scripts/vili-gpu-tray.ps1`, logon task `GameCult\ViliTray`, installed by +`scripts/install-vili-tray-task.ps1`) shows whether Vili may use the GPU and flips it with one click. +The daemon owns the yes or no in `vili.service.cc` (`gamecult.vili.gpu_permission.v1`): off on a +fresh install, set only from loopback (`POST /gpu-permission { allowed }`, read at +`GET /gpu-permission`). A `POST /motion/generate` is refused with HTTP 503, `retry-after: 60` and +`{ ok: false, code: "gpu-busy", source }` where `source` is `household` (the permission is off), +`slot` (another job holds the one GPU slot) or `vram` (host `nvidia-smi.exe` free VRAM is below +`VILI_GPU_MIN_FREE_MIB`, default 10240, or unreadable); nothing queues, and the consumer owns the +retry. A job already running finishes; the gate never stops work. `operator_state.gpu` is +`{ allowed, changedAt, jobRunning, lastRefusal }`. `npm test` runs the gate's tests. Measured on Raven on `2026-10-22`, for a 2 second clip at 20 diffusion steps: the worker is healthy 29 seconds after `docker rm` (was 179) and rests at 2.3 GiB diff --git a/docs/verse-service-contract.md b/docs/verse-service-contract.md index f53a54c..ad2cbb1 100644 --- a/docs/verse-service-contract.md +++ b/docs/verse-service-contract.md @@ -46,15 +46,19 @@ promoted from JSON once that request/receipt shape stabilizes. supported Kimodo generation controls to the resident worker. Vili owns job identity, request persistence, worker lifecycle, timeout handling, and the artifact stem. Kimodo owns synthesis and model-specific export. Vili also owns GPU -tenancy admission: the daemon holds one GPU slot, and `POST /motion/generate` is judged -when it reaches the slot. It answers HTTP 503 with `retry-after: 60` and one of three bodies, by -`source`: `{ "ok": false, "code": "gpu-busy", "source": "admission", "gpu": { inUse, since, -checkedAt, probeOk } }` while the household is using the GPU; `{ "ok": false, "code": -"gpu-busy", "source": "slot" }` while another job holds the slot (nothing queues); and `{ -"ok": false, "code": "gpu-busy", "source": "placement", "jobId" }` when the encoder child -refused its own placement, where the job file was written and no household status is -claimed. The `code` field is the only carrier; a consumer retries after `retry-after` and -never matches error text. A job already running finishes. +admission from the household's permission: the daemon holds one GPU slot, and `POST /motion/generate` is judged +when it reaches the slot. It answers HTTP 503 with `retry-after: 60` and one of four bodies, by +`source`: `{ "ok": false, "code": "gpu-busy", "source": "household", "gpu": { allowed: false, +changedAt } }` while the household's permission is off; `{ "ok": false, "code": "gpu-busy", +"source": "slot" }` while another job holds the slot (nothing queues); `{ "ok": false, "code": +"gpu-busy", "source": "vram", freeMiB, minFreeMiB }` when host free VRAM is below the minimum or +unreadable (`freeMiB` null); and `{ "ok": false, "code": "gpu-busy", "source": "placement", +"jobId" }` when the encoder child refused its own placement, where the job file was written and no +household status is claimed. `GET /gpu-permission` answers `{ allowed, changedAt, jobRunning, +lastRefusal }` to anyone; `POST /gpu-permission { "allowed": boolean }` is the household's switch and +answers 403 `{ "ok": false, "code": "household-only" }` to any caller that is not on the host's +loopback. The `code` field is the only carrier; a consumer retries after `retry-after`, never sets +the permission, and never matches error text. A job already running finishes. ```json { diff --git a/scripts/gpu-tenancy.mjs b/scripts/gpu-tenancy.mjs index b6156ff..e26f9b6 100644 --- a/scripts/gpu-tenancy.mjs +++ b/scripts/gpu-tenancy.mjs @@ -1,28 +1,68 @@ -// GPU tenancy gate. The detection of the household's use is deleted; this file holds the one GPU -// slot only, until the household's permission lands. It refuses new work and never stops work. +// GPU tenancy gate: the one owner of "may heavy GPU work start now". The household decides, through +// the permission it sets at the tray; the daemon owns that yes or no, the one GPU slot, and one host +// free-VRAM read per admission. The gate refuses new work; it never stops work. +// +// acquire() judges in a fixed order and nothing waits: the permission, then the slot, then host free +// VRAM. The slot is taken before the VRAM read so concurrent requests are refused at once. export const RETRY_AFTER_SECONDS = 60; -export function createGpuTenancy({ minFreeMiB = 10240 } = {}) { +export function createGpuTenancy({ now, permission, savePermission, readFreeMiB, minFreeMiB = 10240 }) { + let allowed = permission?.allowed === true; + let changedAt = permission?.changedAt ?? null; let held = false; - return { - status: () => ({ jobRunning: held, minFreeMiB }), - acquire() { - if (held) return { refusal: { ok: false, code: "gpu-busy", source: "slot" } }; - held = true; - return { - release() { - held = false; - }, - }; - }, - }; + let lastRefusal = null; + + const status = () => ({ allowed, changedAt, jobRunning: held, lastRefusal }); + + function refuse(source, extra = {}) { + lastRefusal = { at: new Date(now()).toISOString(), source }; + return { refusal: { ok: false, code: "gpu-busy", source, ...extra } }; + } + const household = () => refuse("household", { gpu: { allowed: false, changedAt } }); + + async function setAllowed(next) { + if (typeof next !== "boolean") throw new TypeError("allowed must be a boolean"); + if (next === allowed) return status(); + const value = { allowed: next, changedAt: new Date(now()).toISOString() }; + await savePermission(value); + allowed = value.allowed; + changedAt = value.changedAt; + return status(); + } + + async function acquire() { + if (!allowed) return household(); + if (held) return refuse("slot"); + held = true; + let freeMiB; + try { + freeMiB = await readFreeMiB(); + } catch { + freeMiB = null; + } + if (!allowed) { + held = false; + return household(); + } + if (!Number.isFinite(freeMiB) || freeMiB < minFreeMiB) { + held = false; + return refuse("vram", { freeMiB: Number.isFinite(freeMiB) ? freeMiB : null, minFreeMiB }); + } + return { + release() { + held = false; + }, + }; + } + + return { status, setAllowed, acquire }; } // Takes the slot, runs the job to its end and returns its result, or returns the typed refusal // without calling the job. The gate never holds, pauses or cancels a job. export async function admitThen(gate, job) { - const slot = gate.acquire(); + const slot = await gate.acquire(); if (slot.refusal) return slot.refusal; try { return await job(); @@ -31,6 +71,12 @@ export async function admitThen(gate, job) { } } +// nvidia-smi's first line is the free MiB as a base-10 integer; anything else is null. +export function parseFreeMiB(stdout) { + const line = String(stdout ?? "").split("\n")[0].trim(); + return /^\d+$/.test(line) ? Number(line) : null; +} + // The encoder child's placement refusal reaches the daemon as a typed code on the worker's error body; // it is never read out of error text. Placement is the child's own view of free VRAM, not the // household gate, so the body carries no gate status. Returns the typed 503 body, or null for any diff --git a/scripts/test-gpu-gate-http.mjs b/scripts/test-gpu-gate-http.mjs index 4d1b3b0..9fe62a2 100644 --- a/scripts/test-gpu-gate-http.mjs +++ b/scripts/test-gpu-gate-http.mjs @@ -1,19 +1,152 @@ // Boots the real daemon and observes the gate where it is decided: the HTTP edge. Needs the -// daemon's own dependencies (ws, cultcache-ts), so it runs on a machine that has them. +// daemon's own dependencies (ws, cultcache-ts), so it runs on a machine that has them. Every boot +// sets VILI_GPU_MIN_FREE_MIB=999999 so an allowed request ends in a VRAM refusal and never starts +// the worker: no test here may start a GPU job. import assert from "node:assert/strict"; import { spawn } from "node:child_process"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdtemp, readdir, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; const daemonPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "vili-daemon.mjs"); -const port = 18000 + Math.floor(Math.random() * 1000); +let nextPort = 18000 + Math.floor(Math.random() * 1000); -test("a malformed GPU override refuses to start and names the variable, not its value", async () => { +async function bootDaemon(stateRoot, { host = "127.0.0.1", env = { VILI_GPU_MIN_FREE_MIB: "999999" } } = {}) { + const port = nextPort++; + const child = spawn(process.execPath, [daemonPath, "--host", host, "--port", String(port), "--state-root", stateRoot], { + env: { ...process.env, ...env }, + stdio: ["ignore", "pipe", "pipe"], + windowsHide: true, + }); + let output = ""; + child.stdout.on("data", (chunk) => { output += chunk; }); + child.stderr.on("data", (chunk) => { output += chunk; }); + const deadline = Date.now() + 30000; + while (!output.includes("Vili listening")) { + if (child.exitCode !== null || Date.now() > deadline) throw new Error(`daemon did not start: ${output.slice(-500)}`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + const stop = () => new Promise((resolve) => { + if (child.exitCode !== null) resolve(); + else { child.once("exit", resolve); child.kill(); } + }); + return { child, port, stop }; +} + +const url = (d, route, host = "127.0.0.1") => `http://${host}:${d.port}${route}`; +const generate = (d, body) => fetch(url(d, "/motion/generate"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), +}); +const setPermission = (d, body, host = "127.0.0.1") => fetch(url(d, "/gpu-permission", host), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), +}); +const readPermission = async (d) => (await fetch(url(d, "/gpu-permission"))).json(); + +test("http: refusal at the daemon edge", async () => { + const stateRoot = await mkdtemp(path.join(os.tmpdir(), "vili-gate-")); + const d = await bootDaemon(stateRoot); + try { + assert.deepEqual(await readPermission(d), { allowed: false, changedAt: null, jobRunning: false, lastRefusal: null }); + assert.equal((await generate(d, {})).status, 400, "request-shape errors come ahead of the gate"); + + const refused = await generate(d, { prompt: "a person waves hello, never seen before" }); + assert.equal(refused.status, 503); + assert.equal(refused.headers.get("retry-after"), "60"); + assert.deepEqual(await refused.json(), { ok: false, code: "gpu-busy", source: "household", gpu: { allowed: false, changedAt: null } }); + + assert.deepEqual(await readdir(path.join(stateRoot, "jobs")), [], "no job file"); + assert.equal((await readdir(stateRoot)).includes("artifacts"), false, "no artifact directory"); + + const state = await (await fetch(url(d, "/operator-state"))).json(); + assert.equal(state.gpu.lastRefusal.source, "household"); + assert.equal(state.gpu.allowed, false); + } finally { + await d.stop(); + await rm(stateRoot, { recursive: true, force: true }); + } +}); + +test("http: the permission persists across a daemon restart", async () => { + const stateRoot = await mkdtemp(path.join(os.tmpdir(), "vili-gate-persist-")); + let d = await bootDaemon(stateRoot); + try { + const on = await setPermission(d, { allowed: true }); + assert.equal(on.status, 200); + const onBody = await on.json(); + assert.equal(onBody.ok, true); + assert.equal(onBody.gpu.allowed, true); + const before = await readPermission(d); + assert.equal(before.allowed, true); + assert.ok(before.changedAt); + + assert.equal((await setPermission(d, { allowed: "yes" })).status, 400); + assert.equal((await setPermission(d, {})).status, 400); + assert.deepEqual(await readPermission(d), before, "a refused write changes nothing"); + + await d.stop(); + d = await bootDaemon(stateRoot); + const after = await readPermission(d); + assert.equal(after.allowed, true); + assert.equal(after.changedAt, before.changedAt); + + await setPermission(d, { allowed: false }); + await d.stop(); + d = await bootDaemon(stateRoot); + assert.equal((await readPermission(d)).allowed, false, "off persists too"); + } finally { + await d.stop(); + await rm(stateRoot, { recursive: true, force: true }); + } +}); + +test("http: an allowed request reaches the slot and the VRAM read", async () => { + const stateRoot = await mkdtemp(path.join(os.tmpdir(), "vili-gate-slot-")); + const d = await bootDaemon(stateRoot); + try { + await setPermission(d, { allowed: true }); + const refused = await generate(d, { prompt: "a person waves hello, never seen before" }); + assert.equal(refused.status, 503); + const body = await refused.json(); + assert.equal(body.source, "vram", "admitted through acquire(), then refused for VRAM"); + assert.equal(body.minFreeMiB, 999999); + assert.deepEqual(await readdir(path.join(stateRoot, "jobs")), [], "no job file"); + assert.equal((await readdir(stateRoot)).includes("artifacts"), false); + const state = await readPermission(d); + assert.equal(state.lastRefusal.source, "vram"); + assert.equal(state.jobRunning, false); + } finally { + await d.stop(); + await rm(stateRoot, { recursive: true, force: true }); + } +}); + +test("http: the switch is the household's", async () => { + const stateRoot = await mkdtemp(path.join(os.tmpdir(), "vili-gate-lan-")); + const d = await bootDaemon(stateRoot, { host: "0.0.0.0" }); + try { + const lan = Object.values(os.networkInterfaces()).flat().find((i) => i.family === "IPv4" && !i.internal)?.address; + assert.ok(lan, "the host has a non-loopback IPv4 address"); + const before = await readPermission(d); + const refused = await setPermission(d, { allowed: true }, lan); + assert.equal(refused.status, 403); + assert.deepEqual(await refused.json(), { ok: false, code: "household-only" }); + assert.deepEqual(await readPermission(d), before, "GET still reads the previous value"); + assert.equal((await setPermission(d, { allowed: true })).status, 200, "loopback still sets it"); + } finally { + await d.stop(); + await rm(stateRoot, { recursive: true, force: true }); + } +}); + +test("http: a malformed override refuses to start and names the variable, not its value", async () => { const stateRoot = await mkdtemp(path.join(os.tmpdir(), "vili-gate-env-")); - const child = spawn(process.execPath, [daemonPath, "--host", "127.0.0.1", "--port", String(port + 1), "--state-root", stateRoot], { + const child = spawn(process.execPath, [daemonPath, "--host", "127.0.0.1", "--port", String(nextPort++), "--state-root", stateRoot], { env: { ...process.env, VILI_GPU_MIN_FREE_MIB: "10240MiB-secret" }, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, diff --git a/scripts/test-gpu-tenancy.mjs b/scripts/test-gpu-tenancy.mjs index dbb3dab..2d192c7 100644 --- a/scripts/test-gpu-tenancy.mjs +++ b/scripts/test-gpu-tenancy.mjs @@ -1,24 +1,173 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { admitThen, createGpuTenancy, gpuTenancyOptionsFromEnv, placementRefusal } from "./gpu-tenancy.mjs"; +import { admitThen, createGpuTenancy, gpuTenancyOptionsFromEnv, parseFreeMiB, placementRefusal } from "./gpu-tenancy.mjs"; -test("slot: a second request while a job runs is refused as a slot refusal and never waits", async () => { - const gate = createGpuTenancy(); - let release; - const running = admitThen(gate, () => new Promise((resolve) => { release = () => resolve("done"); })); +function deferred() { + let resolve; + const promise = new Promise((r) => { resolve = r; }); + return { promise, resolve }; +} + +// Fake ports: a clock, a store spy and a free-VRAM source. No GPU, no daemon, no cache. +function rig({ permission, free = 12000, minFreeMiB } = {}) { + const r = { t: Date.parse("2026-10-23T10:00:00Z"), saved: [], reads: 0, free, failSave: false }; + r.gate = createGpuTenancy({ + now: () => r.t, + permission, + minFreeMiB, + savePermission: async (value) => { + if (r.failSave) throw new Error("disk full"); + r.saved.push(value); + }, + readFreeMiB: async () => { + r.reads += 1; + if (typeof r.free === "function") return r.free(); + return r.free; + }, + }); + return r; +} +const ON = { allowed: true, changedAt: "2026-10-23T09:00:00.000Z" }; + +test("gate: toggle off refuses and creates no job", async () => { + const r = rig(); let calls = 0; - const refused = await admitThen(gate, async () => { calls += 1; }); - assert.deepEqual(refused, { ok: false, code: "gpu-busy", source: "slot" }); + const refused = await admitThen(r.gate, async () => { calls += 1; }); + assert.deepEqual(refused, { ok: false, code: "gpu-busy", source: "household", gpu: { allowed: false, changedAt: null } }); assert.equal(calls, 0); - release(); - assert.equal(await running, "done"); - assert.equal(await admitThen(gate, async () => "next"), "next", "the slot frees when the job ends"); + assert.equal(r.reads, 0, "the VRAM is never read for a household refusal"); + assert.deepEqual(r.gate.status(), { + allowed: false, + changedAt: null, + jobRunning: false, + lastRefusal: { at: "2026-10-23T10:00:00.000Z", source: "household" }, + }); }); -test("slot: a failing job still frees the slot", async () => { - const gate = createGpuTenancy(); - await assert.rejects(admitThen(gate, async () => { throw new Error("boom"); }), /boom/); - assert.equal(await admitThen(gate, async () => "after"), "after"); +test("gate: toggle on admits", async () => { + const r = rig({ permission: ON }); + let calls = 0; + const result = await admitThen(r.gate, async () => { + calls += 1; + assert.equal(r.gate.status().jobRunning, true); + return { ok: true, value: "finished" }; + }); + assert.deepEqual(result, { ok: true, value: "finished" }); + assert.equal(calls, 1); + assert.equal(r.gate.status().jobRunning, false); + assert.equal(r.gate.status().lastRefusal, null); +}); + +test("gate: toggle off mid-job lets the job finish and refuses the next", async () => { + const r = rig({ permission: ON }); + const end = deferred(); + const running = admitThen(r.gate, async () => { await end.promise; return { ok: true, value: "finished" }; }); + while (!r.gate.status().jobRunning) await new Promise((resolve) => setImmediate(resolve)); + const off = await r.gate.setAllowed(false); + assert.equal(off.allowed, false); + assert.equal(off.jobRunning, true, "the job is still running"); + let calls = 0; + const next = await admitThen(r.gate, async () => { calls += 1; }); + assert.equal(next.source, "household"); + assert.equal(calls, 0); + end.resolve(); + assert.deepEqual(await running, { ok: true, value: "finished" }); + assert.equal(r.gate.status().jobRunning, false); +}); + +test("gate: the concurrent slot behaves as h2's did", async () => { + const vram = deferred(); + const r = rig({ permission: ON, free: () => vram.promise }); + const end = deferred(); + let calls = 0; + const job = async () => { calls += 1; await end.promise; return "done"; }; + const all = [admitThen(r.gate, job), admitThen(r.gate, job), admitThen(r.gate, job)]; + // the two losers are decided before the VRAM read resolves + const losers = await Promise.all([all[1], all[2]]); + assert.deepEqual(losers, [{ ok: false, code: "gpu-busy", source: "slot" }, { ok: false, code: "gpu-busy", source: "slot" }]); + assert.equal(r.reads, 1, "only the slot holder reads VRAM"); + vram.resolve(12000); + end.resolve(); + assert.equal(await all[0], "done"); + assert.equal(calls, 1); + assert.equal(r.gate.status().jobRunning, false); + + await assert.rejects(admitThen(r.gate, async () => { throw new Error("boom"); }), /boom/); + assert.equal(r.gate.status().jobRunning, false, "a throwing job frees the slot"); + r.free = 100; + assert.equal((await admitThen(r.gate, async () => "x")).source, "vram"); + const readsBefore = r.reads; + r.free = 12000; + assert.equal(await admitThen(r.gate, async () => "again"), "again", "a vram refusal frees the slot"); + assert.equal(r.reads, readsBefore + 1, "the next admission reads VRAM again"); +}); + +test("gate: VRAM read fails closed", async () => { + const cases = [[9000, 9000], [10239, 10239], [null, null], [Number.NaN, null], [() => { throw new Error("smi"); }, null]]; + for (const [free, expected] of cases) { + const r = rig({ permission: ON, free }); + let calls = 0; + const refused = await admitThen(r.gate, async () => { calls += 1; }); + assert.deepEqual(refused, { ok: false, code: "gpu-busy", source: "vram", freeMiB: expected, minFreeMiB: 10240 }); + assert.equal(calls, 0); + assert.equal(r.gate.status().jobRunning, false); + assert.equal(r.gate.status().lastRefusal.source, "vram"); + } + const edge = rig({ permission: ON, free: 10240 }); + assert.equal(await admitThen(edge.gate, async () => "in"), "in", "exactly the minimum admits"); + const custom = rig({ permission: ON, free: 5000, minFreeMiB: 4096 }); + assert.equal(await admitThen(custom.gate, async () => "in"), "in", "the minimum is the configured one"); +}); + +test("gate: a toggle during the VRAM read wins", async () => { + const vram = deferred(); + const r = rig({ permission: ON, free: () => vram.promise }); + let calls = 0; + const pending = admitThen(r.gate, async () => { calls += 1; }); + await r.gate.setAllowed(false); + vram.resolve(12000); + const refused = await pending; + assert.equal(refused.source, "household"); + assert.equal(calls, 0); + assert.equal(r.gate.status().jobRunning, false); +}); + +test("gate: setAllowed saves before it answers", async () => { + const r = rig(); + r.failSave = true; + await assert.rejects(r.gate.setAllowed(true), /disk full/); + assert.equal(r.gate.status().allowed, false, "a failed save leaves the state unchanged"); + assert.equal(r.gate.status().changedAt, null); + r.failSave = false; + + await assert.rejects(r.gate.setAllowed("yes"), TypeError); + await assert.rejects(r.gate.setAllowed(undefined), TypeError); + assert.deepEqual(r.saved, [], "a non-boolean saves nothing"); + + r.t += 1000; + const on = await r.gate.setAllowed(true); + assert.deepEqual(r.saved, [{ allowed: true, changedAt: "2026-10-23T10:00:01.000Z" }]); + assert.equal(on.allowed, true); + assert.equal(on.changedAt, "2026-10-23T10:00:01.000Z"); + + r.t += 5000; + const same = await r.gate.setAllowed(true); + assert.equal(r.saved.length, 1, "a same-value call saves nothing"); + assert.equal(same.changedAt, "2026-10-23T10:00:01.000Z", "and keeps changedAt"); +}); + +test("gate: a stored permission is the starting state", () => { + assert.deepEqual(rig({ permission: ON }).gate.status(), { allowed: true, changedAt: ON.changedAt, jobRunning: false, lastRefusal: null }); + assert.equal(rig({ permission: { allowed: "yes", changedAt: "x" } }).gate.status().allowed, false, "only a true boolean allows"); +}); + +test("parseFreeMiB reads the first line as a base-10 integer", () => { + assert.equal(parseFreeMiB("5001\r\n"), 5001); + assert.equal(parseFreeMiB("0"), 0); + assert.equal(parseFreeMiB(" 12 \n7\n"), 12); + for (const bad of ["", "[N/A]", "abc", "-5", "1e3", "12.5", "12 MiB", "\n5", null, undefined]) { + assert.equal(parseFreeMiB(bad), null, JSON.stringify(bad)); + } }); test("placement refusal is keyed on the typed code, never on text, and carries no gate status", () => { diff --git a/scripts/vili-daemon.mjs b/scripts/vili-daemon.mjs index a2ef9b5..51282a7 100644 --- a/scripts/vili-daemon.mjs +++ b/scripts/vili-daemon.mjs @@ -6,7 +6,7 @@ import { fileURLToPath } from "node:url"; import { createRequire } from "node:module"; import { execFile } from "node:child_process"; import { WebSocketServer } from "ws"; -import { RETRY_AFTER_SECONDS, admitThen, createGpuTenancy, gpuTenancyOptionsFromEnv, placementRefusal } from "./gpu-tenancy.mjs"; +import { RETRY_AFTER_SECONDS, admitThen, createGpuTenancy, gpuTenancyOptionsFromEnv, parseFreeMiB, placementRefusal } from "./gpu-tenancy.mjs"; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const require = createRequire(import.meta.url); @@ -63,6 +63,19 @@ const operatorStateDefinition = defineDocumentType({ { slot: 4, memberName: "gpu", typeName: "object" }, ], }); +const gpuPermissionDefinition = defineDocumentType({ + type: "gamecult.vili.gpu_permission", + schemaName: "gamecult.vili.gpu_permission", + schemaId: "gamecult.vili.gpu_permission.v1", + schemaVersion: "gamecult.vili.gpu_permission.v1", + name: (value) => value?.host || "raven", + schema: objectSchema, + members: [ + { slot: 0, memberName: "host", typeName: "string", isName: true }, + { slot: 1, memberName: "allowed", typeName: "boolean" }, + { slot: 2, memberName: "changedAt", typeName: "string" }, + ], +}); const eveSurfaceDefinition = defineDocumentType({ type: "gamecult.eve.surface_state", schemaName: "gamecult.eve.surface_state", @@ -110,6 +123,7 @@ const transportProfileDefinition = defineDocumentType({ const viliDocumentRegistry = defineDocumentRegistry( providerAdvertisementDefinition, operatorStateDefinition, + gpuPermissionDefinition, eveSurfaceDefinition, commandBoundaryDefinition, transportProfileDefinition, @@ -138,7 +152,23 @@ function parseArgs(argv) { const args = parseArgs(process.argv.slice(2)); const startedAt = new Date().toISOString(); const gpuOptions = gpuTenancyOptionsFromEnv(process.env); -const gpuTenancy = createGpuTenancy(gpuOptions); +// The daemon's one cache and store instance: every write to vili.service.cc goes through one queue. +const viliCache = CultCache.builder() + .withRegistry(viliDocumentRegistry) + .withGenericStore(new SingleFileMessagePackBackingStore(path.join(args.stateRoot, viliStoreFileName))) + .build(); +let storedPermission; +if (!args.health && !args.printProviderAdvertisement) { + await viliCache.pullAllBackingStores(); + storedPermission = viliCache.get(gpuPermissionDefinition, "raven"); +} +const gpuTenancy = createGpuTenancy({ + now: Date.now, + ...gpuOptions, + permission: storedPermission, + savePermission: (value) => viliCache.put(gpuPermissionDefinition, "raven", { host: "raven", ...value }), + readFreeMiB: hostFreeMiB, +}); let backendStatus = { checkedAt: null, dockerImage: "unknown", @@ -175,6 +205,11 @@ function wsl(script, options = {}) { return run("wsl.exe", ["-d", "Ubuntu-24.04", "-u", "root", "--", "bash", "-lc", script], options); } +async function hostFreeMiB() { + const r = await run("nvidia-smi.exe", ["--query-gpu=memory.free", "--format=csv,noheader,nounits"], { timeout: 5000 }); + return r.ok ? parseFreeMiB(r.stdout) : null; +} + function shQuote(value) { return `'${String(value).replaceAll("'", "'\\''")}'`; } @@ -281,6 +316,7 @@ function operatorState() { deckProviders: "/eve/deck/providers", smoke: "/smoke", generate: "/motion/generate", + gpuPermission: "/gpu-permission", }, }; } @@ -304,6 +340,11 @@ function commandBoundary() { "motion artifact references", ], }, + gpuPermission: { + method: "POST", + path: "/gpu-permission", + owns: ["the household GPU permission for this host, from loopback only"], + }, smoke: { method: "GET", path: "/smoke", @@ -383,15 +424,11 @@ async function persistSurfaces() { } async function persistCultCacheSurfaces() { - const cache = CultCache.builder() - .withRegistry(viliDocumentRegistry) - .withGenericStore(new SingleFileMessagePackBackingStore(path.join(args.stateRoot, viliStoreFileName))) - .build(); - await cache.put(providerAdvertisementDefinition, providerId, providerAdvertisement()); - await cache.put(operatorStateDefinition, "vili", operatorState()); - await cache.put(eveSurfaceDefinition, providerId, eveSurface()); - await cache.put(commandBoundaryDefinition, "vili", commandBoundary()); - await cache.put(transportProfileDefinition, "vili", transportProfile()); + await viliCache.put(providerAdvertisementDefinition, providerId, providerAdvertisement()); + await viliCache.put(operatorStateDefinition, "vili", operatorState()); + await viliCache.put(eveSurfaceDefinition, providerId, eveSurface()); + await viliCache.put(commandBoundaryDefinition, "vili", commandBoundary()); + await viliCache.put(transportProfileDefinition, "vili", transportProfile()); } async function refreshBackendStatus({ includeKimodoHelp = false } = {}) { @@ -508,6 +545,28 @@ async function readRequestBody(request) { return raw ? JSON.parse(raw) : {}; } +const loopbackAddresses = new Set(["127.0.0.1", "::1", "::ffff:127.0.0.1"]); + +// The household's switch: only a caller on this machine (the tray, in the household's session) sets it. +async function setGpuPermission(request, response) { + if (!loopbackAddresses.has(request.socket.remoteAddress)) { + json(response, 403, { ok: false, code: "household-only" }); + return; + } + let body; + try { + body = await readRequestBody(request); + } catch (error) { + json(response, 400, { ok: false, error: `Invalid JSON: ${error.message}` }); + return; + } + if (typeof body?.allowed !== "boolean") { + json(response, 400, { ok: false, error: "allowed must be a boolean." }); + return; + } + json(response, 200, { ok: true, gpu: await gpuTenancy.setAllowed(body.allowed) }); +} + async function generateMotion(request, response) { let body; try { @@ -704,6 +763,10 @@ async function handleRequest(request, response) { await refreshBackendStatus({ includeKimodoHelp: false }); const ok = result.backendStatus.kimodoHelp === "ok" && worker.ok && worker.body?.ok; json(response, ok ? 200 : 502, { ok, ...result, worker: worker.body || worker }); + } else if (url.pathname === "/gpu-permission" && request.method === "GET") { + json(response, 200, gpuTenancy.status()); + } else if (url.pathname === "/gpu-permission" && request.method === "POST") { + await setGpuPermission(request, response); } else if (url.pathname === "/motion/generate" && request.method === "POST") { await generateMotion(request, response); } else {