From 54e680f284fa95f6bb55d01b692bba932fddad6c Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 22 Oct 2026 23:13:49 +0200 Subject: [PATCH] GPU tenancy gate: hysteresis gate, probe child and tests One owner for "may heavy GPU work start": numbers-only samples (full-screen state, sustained 3D use, host free VRAM) in, { inUse, since, checkedAt, probeOk } out; fail closed at start and when the probe goes stale. Co-Authored-By: Claude Opus 5.5 --- package.json | 2 + scripts/gpu-tenancy-probe.ps1 | 20 +++ scripts/gpu-tenancy.mjs | 143 +++++++++++++++++ scripts/test-gpu-gate-http.mjs | 65 ++++++++ scripts/test-gpu-tenancy.mjs | 271 +++++++++++++++++++++++++++++++++ 5 files changed, 501 insertions(+) create mode 100644 scripts/gpu-tenancy-probe.ps1 create mode 100644 scripts/gpu-tenancy.mjs create mode 100644 scripts/test-gpu-gate-http.mjs create mode 100644 scripts/test-gpu-tenancy.mjs diff --git a/package.json b/package.json index 25f6a94..4164e53 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,8 @@ "scripts": { "start": "node scripts/vili-daemon.mjs", "health": "node scripts/vili-daemon.mjs --health", + "test": "node --test scripts/test-gpu-tenancy.mjs", + "test:http": "node --test scripts/test-gpu-gate-http.mjs", "smoke": "node scripts/smoke-vili.mjs", "provider": "node scripts/vili-daemon.mjs --print-provider-advertisement" }, diff --git a/scripts/gpu-tenancy-probe.ps1 b/scripts/gpu-tenancy-probe.ps1 new file mode 100644 index 0000000..c80bf2b --- /dev/null +++ b/scripts/gpu-tenancy-probe.ps1 @@ -0,0 +1,20 @@ +# One sample line per interval: {"quns":n,"freeMiB":n,"util3d":n}. Numbers only; no process identity is read. +param([int]$ParentPid, [int]$IntervalMs = 15000) +$ErrorActionPreference = 'Stop' +Add-Type -Namespace Vili -Name Shell -MemberDefinition '[DllImport("shell32.dll")] public static extern int SHQueryUserNotificationState(out int state);' +while ($true) { + $clock = [Diagnostics.Stopwatch]::StartNew() + if (-not (Get-Process -Id $ParentPid -ErrorAction SilentlyContinue)) { exit } + try { + $quns = 0 + if ([Vili.Shell]::SHQueryUserNotificationState([ref]$quns) -ne 0) { throw 'quns' } + $free = nvidia-smi.exe --query-gpu=memory.free --format=csv,noheader,nounits | Select-Object -First 1 + if ($LASTEXITCODE -ne 0) { throw 'smi' } + $sum = (Get-Counter '\GPU Engine(*engtype_3D)\Utilization Percentage' -SampleInterval 1 -MaxSamples 1).CounterSamples | Measure-Object -Property CookedValue -Sum + $line = [ordered]@{ quns = [int]$quns; freeMiB = [int]$free; util3d = [math]::Min(100, [math]::Round([double]$sum.Sum, 1)) } | ConvertTo-Json -Compress + [Console]::Out.WriteLine($line) + [Console]::Out.Flush() + } catch { } + $rest = $IntervalMs - $clock.ElapsedMilliseconds + if ($rest -gt 0) { Start-Sleep -Milliseconds $rest } +} diff --git a/scripts/gpu-tenancy.mjs b/scripts/gpu-tenancy.mjs new file mode 100644 index 0000000..1009a66 --- /dev/null +++ b/scripts/gpu-tenancy.mjs @@ -0,0 +1,143 @@ +// GPU tenancy gate: the one owner of "may heavy GPU work start now", from the host's view. +// It reads numbers only (full-screen state, 3D-engine use, host free VRAM), keeps a yes/no and a +// timestamp, and never learns which program is running. It refuses new work; it never stops work. + +export const RETRY_AFTER_SECONDS = 60; +const QUNS_BUSY = 2; +const QUNS_RUNNING_D3D_FULL_SCREEN = 3; + +export function createGpuTenancy({ + now, + sampleIntervalMs = 15000, + clearHoldMs = 180000, + minFreeMiB = 10240, + util3dBusyPct = 20, + staleAfterMs = 3 * sampleIntervalMs, +}) { + const startedAt = now(); + let inUse = true; + let since = startedAt; + let checkedAt = null; + let lastSeenAt = startedAt; + let clearSince = null; + let previousUtil3d = null; + + const staleSince = () => (now() - lastSeenAt > staleAfterMs ? lastSeenAt + staleAfterMs : null); + + function observe(sample) { + const t = now(); + const staleAt = staleSince(); + if (staleAt !== null) { + if (!inUse) { + inUse = true; + since = staleAt; + } + clearSince = null; + previousUtil3d = null; + } + const sustained3d = sample.util3d > util3dBusyPct && previousUtil3d !== null && previousUtil3d > util3dBusyPct; + const busy = sample.quns === QUNS_BUSY + || sample.quns === QUNS_RUNNING_D3D_FULL_SCREEN + || sample.freeMiB < minFreeMiB + || sustained3d; + previousUtil3d = sample.util3d; + lastSeenAt = t; + checkedAt = t; + if (busy) { + clearSince = null; + if (!inUse) { + inUse = true; + since = t; + } + return; + } + if (clearSince === null) clearSince = t; + if (inUse && t - clearSince >= clearHoldMs) { + inUse = false; + since = t; + } + } + + function status() { + const staleAt = staleSince(); + if (staleAt !== null) { + return { inUse: true, since: inUse ? since : staleAt, checkedAt, probeOk: false }; + } + return { inUse, since, checkedAt, probeOk: true }; + } + + return { observe, status }; +} + +// A probe line is JSON; only the three finite numbers survive, so nothing else can reach the gate. +export function parseSample(line) { + let value; + try { + value = JSON.parse(line); + } catch { + return null; + } + if (value === null || typeof value !== "object") return null; + const { quns, freeMiB, util3d } = value; + for (const field of [quns, freeMiB, util3d]) { + if (typeof field !== "number" || !Number.isFinite(field)) return null; + } + return { quns, freeMiB, util3d }; +} + +// Checks the gate once. A busy gate refuses without calling the job; a free gate runs the job to +// its end and returns its result: the gate never holds, pauses or cancels a job. +export async function admitThen(gate, job) { + const gpu = gate.status(); + if (gpu.inUse) return { ok: false, code: "gpu-busy", source: "admission", gpu }; + return job(); +} + +// 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. Returns the typed 503 body, or null for any other outcome. +export function placementRefusal(workerBody, gpu, jobId) { + if (workerBody?.code !== "gpu-busy") return null; + return { ok: false, code: "gpu-busy", source: "placement", gpu, jobId }; +} + +// One long-lived hidden PowerShell child feeds samples. It exits with the daemon (the script watches +// the parent pid); if it exits on its own it is respawned at most once per interval. +export function startProbe({ spawn, scriptPath, intervalMs, onSample, parentPid = process.pid }) { + let stopped = false; + let lastSpawnAt = 0; + + function launch() { + if (stopped) return; + lastSpawnAt = Date.now(); + const child = spawn("powershell.exe", [ + "-NoProfile", + "-NonInteractive", + "-ExecutionPolicy", "Bypass", + "-File", scriptPath, + "-ParentPid", String(parentPid), + "-IntervalMs", String(intervalMs), + ], { windowsHide: true, stdio: ["ignore", "pipe", "ignore"] }); + let pending = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk) => { + pending += chunk; + const lines = pending.split("\n"); + pending = lines.pop(); + for (const line of lines) { + const sample = parseSample(line.trim()); + if (sample) onSample(sample); + } + }); + let respawned = false; + const respawn = () => { + if (respawned) return; + respawned = true; + setTimeout(launch, Math.max(0, lastSpawnAt + intervalMs - Date.now())).unref(); + }; + child.on("exit", respawn); + child.on("error", respawn); + } + + launch(); + return { stop: () => { stopped = true; } }; +} diff --git a/scripts/test-gpu-gate-http.mjs b/scripts/test-gpu-gate-http.mjs new file mode 100644 index 0000000..325b1f5 --- /dev/null +++ b/scripts/test-gpu-gate-http.mjs @@ -0,0 +1,65 @@ +// Boots the real daemon and observes the gate where it is decided: the HTTP edge. A fresh daemon is +// in use until a clear hold passes, so a new job is refused whatever the host is doing. Needs the +// daemon's own dependencies (ws, cultcache-ts), so it runs on a machine that has them. +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +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); + +async function bootDaemon(stateRoot) { + const child = spawn(process.execPath, [daemonPath, "--host", "127.0.0.1", "--port", String(port), "--state-root", stateRoot], { + 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)); + } + return child; +} + +const post = (body) => fetch(`http://127.0.0.1:${port}/motion/generate`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(body), +}); + +test("a new job is refused 503 gpu-busy with retry-after, creating nothing; validation stays 400", async () => { + const stateRoot = await mkdtemp(path.join(os.tmpdir(), "vili-gate-")); + const daemon = await bootDaemon(stateRoot); + try { + const invalid = await post({}); + assert.equal(invalid.status, 400, "request-shape errors come ahead of the gate"); + + const refused = await post({ prompt: "a person waves hello, never seen before" }); + assert.equal(refused.status, 503); + assert.equal(refused.headers.get("retry-after"), "60"); + const body = await refused.json(); + assert.equal(body.ok, false); + assert.equal(body.code, "gpu-busy"); + assert.equal(body.source, "admission"); + assert.equal(body.gpu.inUse, true); + assert.deepEqual(Object.keys(body.gpu).sort(), ["checkedAt", "inUse", "probeOk", "since"]); + assert.equal(body.jobId, undefined); + + 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(`http://127.0.0.1:${port}/operator-state`)).json(); + assert.deepEqual(Object.keys(state.gpu).sort(), ["checkedAt", "inUse", "probeOk", "since"]); + assert.equal(state.gpu.inUse, true); + } finally { + daemon.kill(); + await rm(stateRoot, { recursive: true, force: true }); + } +}); diff --git a/scripts/test-gpu-tenancy.mjs b/scripts/test-gpu-tenancy.mjs new file mode 100644 index 0000000..6e56f83 --- /dev/null +++ b/scripts/test-gpu-tenancy.mjs @@ -0,0 +1,271 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import test from "node:test"; +import { admitThen, createGpuTenancy, parseSample, placementRefusal, startProbe } from "./gpu-tenancy.mjs"; + +const SEC = 1000; +const CLEAR = { quns: 1, freeMiB: 14000, util3d: 1 }; + +function rig(options = {}) { + let t = 1_000_000; + const gate = createGpuTenancy({ now: () => t, ...options }); + return { + gate, + t0: t, + at: () => t, + advance: (ms) => { t += ms; }, + feed(sample, afterMs = 15 * SEC) { + t += afterMs; + gate.observe(sample); + }, + }; +} + +function freeRig(options) { + const r = rig(options); + r.feed(CLEAR); + r.advance(180 * SEC); + r.feed(CLEAR); + assert.equal(r.gate.status().inUse, false, "precondition: gate is free"); + return r; +} + +test("hysteresis: busy holds for the clear window", () => { + const r = rig(); + r.feed(CLEAR); + r.feed({ ...CLEAR, quns: 3 }); + const busyAt = r.at(); + assert.deepEqual(r.gate.status(), { inUse: true, since: busyAt, checkedAt: busyAt, probeOk: true }); + for (let elapsed = 15; elapsed < 180; elapsed += 15) { + r.feed(CLEAR); + assert.equal(r.gate.status().inUse, true, `still held ${elapsed} s into the hold`); + assert.equal(r.gate.status().since, busyAt); + } + // a busy sample late in the hold restarts it + r.feed({ ...CLEAR, quns: 2 }); + const restartAt = r.at(); + for (let elapsed = 15; elapsed < 180; elapsed += 15) { + r.feed(CLEAR); + assert.equal(r.gate.status().inUse, true, `restarted hold, ${elapsed} s`); + } + r.feed(CLEAR); + assert.equal(r.at() - restartAt, 180 * SEC); + const freedAt = r.at(); + assert.deepEqual(r.gate.status(), { inUse: false, since: freedAt, checkedAt: freedAt, probeOk: true }); + r.feed(CLEAR); + assert.equal(r.gate.status().since, freedAt, "since moves only when the state turns"); + r.feed({ ...CLEAR, freeMiB: 100 }); + assert.deepEqual(r.gate.status(), { inUse: true, since: r.at(), checkedAt: r.at(), probeOk: true }); +}); + +test("hysteresis: a busy sample just before the window ends restarts it", () => { + const r = rig(); + r.feed(CLEAR); + for (let i = 0; i < 11; i += 1) r.feed(CLEAR); + assert.equal(r.gate.status().inUse, true, "165 s clear is not enough"); + r.feed({ ...CLEAR, quns: 3 }); + r.feed(CLEAR); + r.feed(CLEAR); + assert.equal(r.gate.status().inUse, true); +}); + +test("sustained 3D, immediate full-screen and VRAM", () => { + const spike = freeRig(); + spike.feed({ ...CLEAR, util3d: 80 }); + spike.feed(CLEAR); + assert.equal(spike.gate.status().inUse, false, "one 3D spike between clear samples"); + + const sustained = freeRig(); + sustained.feed({ ...CLEAR, util3d: 80 }); + assert.equal(sustained.gate.status().inUse, false, "first high sample alone"); + sustained.feed({ ...CLEAR, util3d: 80 }); + assert.equal(sustained.gate.status().inUse, true, "two consecutive high samples"); + + const edge = freeRig(); + edge.feed({ ...CLEAR, util3d: 20 }); + edge.feed({ ...CLEAR, util3d: 20 }); + assert.equal(edge.gate.status().inUse, false, "exactly the threshold is not above it"); + + for (const [name, sample] of [ + ["QUNS_BUSY", { ...CLEAR, quns: 2 }], + ["QUNS_RUNNING_D3D_FULL_SCREEN", { ...CLEAR, quns: 3 }], + ["low free VRAM", { ...CLEAR, freeMiB: 10239 }], + ]) { + const r = freeRig(); + r.feed(sample); + assert.equal(r.gate.status().inUse, true, name); + } + + const enough = freeRig(); + enough.feed({ ...CLEAR, freeMiB: 10240 }); + assert.equal(enough.gate.status().inUse, false, "free VRAM equal to the minimum is enough"); + + const otherStates = freeRig(); + for (const quns of [1, 4, 5, 6, 7]) otherStates.feed({ ...CLEAR, quns }); + assert.equal(otherStates.gate.status().inUse, false, "other notification states are not household use"); +}); + +test("thresholds from the options are honored", () => { + const r = rig({ minFreeMiB: 500, util3dBusyPct: 90, clearHoldMs: 30 * SEC }); + r.feed({ ...CLEAR, freeMiB: 600, util3d: 85 }); + r.feed({ ...CLEAR, freeMiB: 600, util3d: 85 }); + r.feed({ ...CLEAR, freeMiB: 600, util3d: 85 }); + assert.equal(r.gate.status().inUse, false); + r.feed({ ...CLEAR, freeMiB: 400 }); + assert.equal(r.gate.status().inUse, true); +}); + +test("start and stale fail closed", () => { + const r = rig(); + assert.deepEqual(r.gate.status(), { inUse: true, since: r.t0, checkedAt: null, probeOk: true }); + r.feed(CLEAR); + r.advance(180 * SEC); + r.feed(CLEAR); + assert.equal(r.gate.status().inUse, false); + const lastSample = r.at(); + + r.advance(45 * SEC); + assert.equal(r.gate.status().probeOk, true, "exactly 3 intervals is not stale yet"); + r.advance(1); + const stale = r.gate.status(); + assert.equal(stale.inUse, true); + assert.equal(stale.probeOk, false); + assert.equal(stale.since, lastSample + 45 * SEC); + assert.equal(stale.checkedAt, lastSample); + + r.feed(CLEAR, 0); + assert.equal(r.gate.status().inUse, true, "samples resumed but the hold has not passed"); + assert.equal(r.gate.status().probeOk, true); + for (let i = 0; i < 11; i += 1) r.feed(CLEAR); + assert.equal(r.gate.status().inUse, true); + r.feed(CLEAR); + assert.equal(r.gate.status().inUse, false); +}); + +test("a gate that never hears from its probe stays in use and not ok", () => { + const r = rig(); + r.advance(46 * SEC); + assert.deepEqual(r.gate.status(), { inUse: true, since: r.t0, checkedAt: null, probeOk: false }); +}); + +test("defer, not kill", async () => { + const r = freeRig(); + let release; + let started = 0; + const running = admitThen(r.gate, () => { + started += 1; + return new Promise((resolve) => { release = () => resolve({ ok: true, value: "finished" }); }); + }); + assert.equal(started, 1); + r.feed({ ...CLEAR, quns: 3 }); + assert.equal(r.gate.status().inUse, true, "the gate went busy while the job runs"); + + let secondCalls = 0; + const second = await admitThen(r.gate, async () => { secondCalls += 1; }); + assert.equal(secondCalls, 0, "a second job is refused without being called"); + assert.equal(second.code, "gpu-busy"); + + release(); + assert.deepEqual(await running, { ok: true, value: "finished" }); +}); + +test("a job that fails is not swallowed by the gate", async () => { + const r = freeRig(); + await assert.rejects(admitThen(r.gate, async () => { throw new Error("job failed"); }), /job failed/); +}); + +test("typed busy result", async () => { + const r = rig(); + r.feed({ ...CLEAR, quns: 3 }); + const since = r.gate.status().since; + r.feed({ ...CLEAR, quns: 3 }); + r.feed({ ...CLEAR, quns: 3 }); + let calls = 0; + const refusal = await admitThen(r.gate, async () => { calls += 1; }); + assert.deepEqual(refusal, { + ok: false, + code: "gpu-busy", + source: "admission", + gpu: { inUse: true, since, checkedAt: r.at(), probeOk: true }, + }); + assert.equal(calls, 0); +}); + +test("placement refusal is keyed on the typed code, never on text", () => { + const gpu = { inUse: false, since: 1, checkedAt: 2, probeOk: true }; + assert.deepEqual(placementRefusal({ ok: false, code: "gpu-busy", error: "x" }, gpu, "vili-1"), { + ok: false, code: "gpu-busy", source: "placement", gpu, jobId: "vili-1", + }); + assert.equal(placementRefusal({ ok: false, error: "gpu-busy: 0.50 GiB of VRAM free" }, gpu, "vili-1"), null); + assert.equal(placementRefusal({ ok: false, code: null }, gpu, "vili-1"), null); + assert.equal(placementRefusal(null, gpu, "vili-1"), null); +}); + +test("no program name canary", () => { + const canary = "canary-vili-7f3a"; + const line = JSON.stringify({ quns: 3, freeMiB: 2048, util3d: 55.5, name: canary, process: canary, instance: canary }); + const sample = parseSample(line); + assert.deepEqual(sample, { quns: 3, freeMiB: 2048, util3d: 55.5 }); + assert.deepEqual(Object.keys(sample).sort(), ["freeMiB", "quns", "util3d"]); + const r = rig(); + r.gate.observe(sample); + assert.equal(JSON.stringify(r.gate.status()).includes(canary), false); +}); + +test("parseSample drops anything that is not three finite numbers", () => { + assert.equal(parseSample("not json"), null); + assert.equal(parseSample("null"), null); + assert.equal(parseSample("[1,2,3]"), null); + assert.equal(parseSample(JSON.stringify({ quns: 1, freeMiB: 1 })), null); + assert.equal(parseSample(JSON.stringify({ quns: "1", freeMiB: 1, util3d: 1 })), null); + assert.equal(parseSample('{"quns":1,"freeMiB":1,"util3d":1e999}'), null); + assert.equal(parseSample(""), null); +}); + +function fakeSpawn() { + const spawned = []; + const spawn = (command, args, options) => { + const child = new EventEmitter(); + child.stdout = new EventEmitter(); + child.stdout.setEncoding = () => {}; + spawned.push({ command, args, options, child }); + return child; + }; + return { spawn, spawned }; +} + +test("probe: one hidden child, lines become samples, junk is dropped", () => { + const { spawn, spawned } = fakeSpawn(); + const samples = []; + const probe = startProbe({ spawn, scriptPath: "gpu-tenancy-probe.ps1", intervalMs: 15000, onSample: (s) => samples.push(s), parentPid: 4242 }); + assert.equal(spawned.length, 1); + const { command, args, options, child } = spawned[0]; + assert.equal(command, "powershell.exe"); + assert.equal(options.windowsHide, true); + assert.deepEqual(options.stdio, ["ignore", "pipe", "ignore"]); + assert.deepEqual(args.slice(args.indexOf("-ParentPid")), ["-ParentPid", "4242", "-IntervalMs", "15000"]); + assert.ok(args.includes("-File") && args.includes("gpu-tenancy-probe.ps1")); + + child.stdout.emit("data", '{"quns":1,"freeMiB":14000,"util3d":2}\n{"quns":2,"free'); + child.stdout.emit("data", 'MiB":9000,"util3d":3}\r\ngarbage\n'); + assert.deepEqual(samples, [ + { quns: 1, freeMiB: 14000, util3d: 2 }, + { quns: 2, freeMiB: 9000, util3d: 3 }, + ]); + probe.stop(); +}); + +test("probe: respawns at most once per interval after the child exits", async () => { + const { spawn, spawned } = fakeSpawn(); + const probe = startProbe({ spawn, scriptPath: "p.ps1", intervalMs: 80, onSample: () => {} }); + spawned[0].child.emit("exit", 1); + spawned[0].child.emit("error", new Error("again")); + spawned[0].child.emit("exit", 1); + assert.equal(spawned.length, 1, "no immediate respawn"); + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.equal(spawned.length, 2, "one respawn for one death, however many events"); + probe.stop(); + spawned[1].child.emit("exit", 1); + await new Promise((resolve) => setTimeout(resolve, 200)); + assert.equal(spawned.length, 2, "a stopped probe does not respawn"); +});