Release 0.15.0: endpoints instead of deployments
Release / release (push) Successful in 12m32s

Kaname keeps two jobs: the model downloader and benchmarks. Benchmarks
now run against endpoints (any OpenAI-compatible server added by URL,
with an optional server-side API key and hand-written hardware notes)
instead of deployments Kaname started itself.

Removed: runtimes, deployments, sweeps, resource telemetry, hardware
detection, the /api/v1 API with tokens and guardrails, and all Docker
access. The quality eval's coding tests run in a network-less sandbox
container that shares only an exchange folder with the worker.

The previous state is kept in branch backup / tag backup-0.14.3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-26 21:43:42 +01:00
1 parent 1d2f908b75
commit 276108932d
199 files changed
+5462 -15961

No files matched your search

+119 -202
View File
@@ -1,55 +1,57 @@
// Runs BetterBench against running deployments, one benchmark at a time (two at once would
// measure each other).
// Runs BetterBench (and the quality eval) against endpoints, one benchmark at a time (two at once
// could measure each other on a shared machine).
import { type ChildProcess, execFile, spawn } from "node:child_process";
import { access, mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq } from "drizzle-orm";
import { overTime } from "@/lib/agent-tuning";
import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchmark-meta";
import { endpointRunMeta, endpointSystem, engineLabel, metaNotes, modelLabel } from "@/lib/benchmark-meta";
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot";
import { kanameVersion, snapshotOf } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import {
apiKeys,
type BenchmarkKind,
benchmarkLogs,
benchmarkRuns,
type BenchmarkSummary,
deployments,
type EndpointSnapshot,
endpoints,
type LogStream,
QUALITY_SECTIONS,
type QualityResult,
type QualitySection,
type RunMeta,
runtimes,
type SystemSummary,
} from "@/lib/db/schema";
import { EVAL_SEED, EVAL_SET_VERSION, SECTION_LABEL } from "@/lib/quality";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { probeEndpoint } from "@/lib/endpoint-probe";
import { coreEnv } from "@/lib/env";
import { EVAL_SEED, EVAL_SET_VERSION, SECTION_LABEL } from "@/lib/quality";
import { abSummary } from "./ab-summary";
import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
import {
AB_DEFAULT_MAX_PAIRS,
AB_DEFAULT_MDE_PCT,
AB_FILE,
AB_KEYS_LAUNCHER,
abArgs,
betterbenchBin,
betterbenchPython,
runArgs,
SUMMARY_SCRIPT,
SUMMARY_VERSION,
} from "./betterbench";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { normalizePciAddress } from "./hardware";
import { errorCauses } from "./log-causes";
import { type GpuTargets, ResourceSampler } from "./resources";
import { runQualityEval } from "./quality";
import { docker, workerImage } from "./runtimes";
import { sandboxDown, sandboxRunner } from "./sandbox-client";
type Current = {
runId: string;
kind: BenchmarkKind;
deploymentIds: string[];
/** BetterBench (runs, A/B); null for a quality eval, which runs in-process and stops via `abort`. */
child: ChildProcess | null;
abort: AbortController | null;
sampler: ResourceSampler | null;
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
meta: RunMeta | null;
metaB: RunMeta | null;
maxPairs: number | null;
cancelled: boolean;
lost: string | null;
@@ -152,48 +154,27 @@ async function summarize(results: string): Promise<BenchmarkSummary> {
return JSON.parse(stdout) as BenchmarkSummary;
}
type Target = { id: string; containerId: string; containerName: string; engine: "llama.cpp" | "vllm"; accelerator: string };
type Target = { id: string; name: string; baseUrl: string; apiKey: string | null; snapshot: EndpointSnapshot };
async function target(deploymentId: string | null): Promise<Target | null> {
if (!deploymentId) return null;
const [d] = await db()
.select({ state: deployments.state, containerId: deployments.containerId, containerName: deployments.containerName, engine: runtimes.engine, accelerator: runtimes.accelerator })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.where(eq(deployments.id, deploymentId));
if (!d || d.state !== "running" || !d.containerName || !d.containerId) return null;
return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator };
}
/**
* What the sampler watches for the GPUs a run uses: NVIDIA via nvidia-smi, Intel/AMD via sysfs (and
* the fdinfo probe for Intel), and every GPU's link where sysfs shows it. Probes run from our own image.
*/
async function gpuTargets(metas: (RunMeta | null)[]): Promise<GpuTargets> {
const addrs = [...new Set(metas.flatMap((m) => m?.gpus.map((g) => g.pciAddress) ?? []).filter((a): a is string => !!a))];
const { hardware, nvidia } = await effectiveHardware();
const image = workerImage();
const used = (hardware?.gpus ?? []).filter((g) => addrs.includes(g.pciAddress));
const pciByIndex: Record<number, string> = {};
for (const g of nvidia) {
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
if (addrs.includes(addr)) pciByIndex[g.index] = addr;
/** The endpoint, asked again now: what it reports goes into the run's snapshot. */
async function target(id: string | null, snap: EndpointSnapshot | null): Promise<Target | string> {
if (!id || !snap) return "The endpoint was deleted.";
const e = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) });
if (!e) return "The endpoint was deleted.";
const probe = await probeEndpoint({ baseUrl: e.baseUrl, apiKey: e.apiKey, engine: e.engine });
await db().update(endpoints).set({ probe }).where(eq(endpoints.id, id));
if (!probe.ok) return `${e.name}: ${probe.error}`;
if (probe.models.length && !probe.models.includes(snap.model)) {
return `${e.name} doesn't serve "${snap.model}" anymore (it has: ${probe.models.slice(0, 5).join(", ")}).`;
}
const others = used.filter((g) => g.vendor !== "nvidia");
return {
nvidia: image && Object.keys(pciByIndex).length ? { image, pciByIndex } : null,
sysfs: others.map((g, i) => ({ index: i, pciAddress: g.pciAddress, name: g.name ?? `${g.vendor} GPU`, vendor: g.vendor, vramTotalMb: g.vramMb })),
intelProbeImage: image,
linkAddresses: addrs.filter((a) => !a.startsWith("nvidia-")),
};
return { id, name: e.name, baseUrl: e.baseUrl, apiKey: e.apiKey, snapshot: snapshotOf(e, snap.model, probe) };
}
/** A/B notes: the shared host facts once, the engine and model per side. */
function abNotes(a: RunMeta | null, b: RunMeta | null, shared: Record<string, string>): Record<string, string> {
function abNotes(a: RunMeta, b: RunMeta, shared: Record<string, string>): Record<string, string> {
const pick = ["gpus", "pcie_max", "p2p", "rebar", "system", "description"];
const out: Record<string, string> = Object.fromEntries(Object.entries(shared).filter(([k]) => pick.includes(k)));
for (const [side, m] of [["a", a], ["b", b]] as const) {
if (!m) continue;
out[`${side}_engine`] = engineLabel(m) || m.runtime.engine;
out[`${side}_model`] = modelLabel(m);
if (m.contextSize != null) out[`${side}_ctx`] = String(m.contextSize);
@@ -202,60 +183,36 @@ function abNotes(a: RunMeta | null, b: RunMeta | null, shared: Record<string, st
return out;
}
const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`;
const endpointUrl = (t: Target) => `${t.baseUrl}/v1`;
async function start(run: typeof benchmarkRuns.$inferSelect) {
const fail = (error: string) => finish(run.id, { state: "failed", error });
const a = await target(run.deploymentId);
if (!a) return fail(run.kind === "ab" ? "Deployment A isn't running anymore." : "The deployment isn't running anymore.");
const b = run.kind === "ab" ? await target(run.deploymentBId) : null;
if (run.kind === "ab" && !b) return fail("Deployment B isn't running anymore.");
if (run.snapshot.type !== "endpoint") return fail("This run is from before endpoints (Kaname 0.15) and can't be started again.");
const a = await target(run.endpointId, run.snapshot);
if (typeof a === "string") return fail(run.kind === "ab" ? `Endpoint A: ${a}` : a);
const snapB = run.snapshotB?.type === "endpoint" ? run.snapshotB : null;
const b = run.kind === "ab" ? await target(run.endpointBId, snapB) : null;
if (typeof b === "string") return fail(`Endpoint B: ${b}`);
const dir = runDir(run.id);
await mkdir(dir, { recursive: true });
const needsKey = run.snapshot.options.requireApiKey || run.snapshotB?.options.requireApiKey;
// One key works for both: BETTERBENCH_API_KEY fills in every missing key flag.
const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
const s = run.snapshot;
const s = a.snapshot;
const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS;
// What runs on what, recorded now (the deployments are up, so the server's version is known).
const setup = await runSetup([a.id, b?.id ?? null]);
const [meta, metaB] = setup.metas;
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
if (run.kind === "eval") return startEval(run, a, keys, meta, setup.system);
const args =
run.kind === "ab" && b
? abArgs({
endpointA: endpoint(a),
endpointB: endpoint(b),
model: s.repoId,
out: join(dir, AB_FILE),
mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT,
maxPairs,
notes: {
a: s.deploymentName,
b: run.snapshotB?.deploymentName ?? "B",
...(run.label ? { label: run.label } : {}),
...abNotes(meta, metaB, metaNotesA),
},
})
: runArgs({
endpoint: endpoint(a),
model: s.repoId,
out: join(dir, RESULTS_FILE),
settings: run.settings,
maxModelLen: s.options.contextSize ?? null,
notes: {
deployment: s.deploymentName,
runtime: s.runtimeName,
image: s.image,
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
ctx: String(s.options.contextSize),
...metaNotesA,
...(run.label ? { label: run.label } : {}),
},
});
// Only what BetterBench needs: no HF_TOKEN or other worker secrets.
// What runs on what, recorded now: the hardware notes plus what the servers just reported.
const meta = endpointRunMeta(s);
const metaB = b ? endpointRunMeta(b.snapshot) : null;
const system = endpointSystem(s.hardware, kanameVersion());
const keys = [a.apiKey, b?.apiKey].filter((k): k is string => !!k);
const notesA = metaNotes(meta, system, run.description ?? s.hardware.description ?? null);
await db()
.update(benchmarkRuns)
.set({ snapshot: s, snapshotB: b?.snapshot ?? null, meta, metaB, system })
.where(eq(benchmarkRuns.id, run.id));
if (run.kind === "eval") return startEval(run, a, meta, system);
// Only what BetterBench needs: no HF_TOKEN or other worker secrets. API keys only through the
// environment, never argv; an A/B with two different keys goes through a launcher that hands
// them to BetterBench inside Python.
const env: Record<string, string | undefined> = {
PATH: process.env.PATH,
HOME: process.env.HOME,
@@ -264,43 +221,51 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
NO_COLOR: "1",
BETTERBENCH_HOME: dir,
BETTERBENCH_NO_UPDATE_CHECK: "1",
...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}),
};
let bin = betterbenchBin();
let args: string[];
if (run.kind === "ab" && b && metaB) {
args = abArgs({
endpointA: endpointUrl(a),
endpointB: endpointUrl(b),
model: s.model,
out: join(dir, AB_FILE),
mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT,
maxPairs,
notes: { ...(run.label ? { label: run.label } : {}), ...abNotes(meta, metaB, notesA) },
});
if (a.apiKey && b.apiKey && a.apiKey !== b.apiKey) {
env.KANAME_API_KEY_A = a.apiKey;
env.KANAME_API_KEY_B = b.apiKey;
bin = betterbenchPython();
args = ["-c", AB_KEYS_LAUNCHER, ...args];
} else if (a.apiKey || b.apiKey) env.BETTERBENCH_API_KEY = (a.apiKey ?? b.apiKey)!;
} else {
args = runArgs({
endpoint: endpointUrl(a),
model: s.model,
out: join(dir, RESULTS_FILE),
settings: run.settings,
maxModelLen: meta.contextSize,
notes: { ...notesA, ...(run.label ? { label: run.label } : {}) },
});
if (a.apiKey) env.BETTERBENCH_API_KEY = a.apiKey;
}
addLog(
run.id,
"system",
run.kind === "ab"
? `Paired A/B: ${s.deploymentName} (A) vs ${run.snapshotB?.deploymentName} (B), ${s.repoId}, with BetterBench`
: `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`,
run.kind === "ab" ? `Paired A/B: ${a.name} (A) vs ${b?.name} (B), ${s.model}, with BetterBench` : `Benchmarking ${a.name} (${s.model}) with BetterBench`,
);
addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys);
await db()
.update(benchmarkRuns)
.set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, metaB, system: setup.system })
.where(eq(benchmarkRuns.id, run.id));
addLog(run.id, "system", `$ betterbench ${(bin === betterbenchBin() ? args : args.slice(2)).join(" ")}`, keys);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
// Resource use of the server(s) under test, and of the GPUs they use.
const c = docker();
const sampler = c
? new ResourceSampler(
c,
[{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])],
await gpuTargets([meta, metaB]),
)
: null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
const child = spawn(bin, args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
const cur: Current = {
runId: run.id,
kind: run.kind,
deploymentIds: [a.id, ...(b ? [b.id] : [])],
child,
abort: null,
sampler,
meta,
metaB,
maxPairs: run.kind === "ab" ? maxPairs : null,
cancelled: false,
lost: null,
@@ -310,63 +275,34 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
child.stdout.on("data", (buf: Buffer) => chunk(run.id, "stdout", buf, keys));
child.stderr.on("data", (buf: Buffer) => chunk(run.id, "stderr", buf, keys));
child.on("error", (err: NodeJS.ErrnoException) => {
addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`);
addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${bin}).` : `Could not start BetterBench: ${err.message}`);
});
child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err)));
log.info(`benchmark ${run.id}: started (${run.kind}) for ${s.deploymentName}`);
log.info(`benchmark ${run.id}: started (${run.kind}) for ${a.name}`);
}
/** Stop the resource sampler; record the PCIe links seen under load in the run's meta. */
async function stopSampling(cur: Current) {
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
if (current === cur) current = null;
if (resources?.links) {
const loaded = (m: RunMeta | null) => withLoadLinks(m, resources.links, !!m?.overridden.includes("pcie link"));
await db()
.update(benchmarkRuns)
.set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) })
.where(eq(benchmarkRuns.id, cur.runId))
.catch((err) => log.warn(`benchmark ${cur.runId}: link update failed: ${message(err)}`));
}
return resources;
}
/** Kaname's quality eval: in-process against the deployment, coding answers in the sandbox. */
async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, keys: string[], meta: RunMeta | null, system: SystemSummary) {
const s = run.snapshot;
/** Kaname's quality eval: in-process against the endpoint, coding answers in the sandbox. */
async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, meta: RunMeta, system: SystemSummary) {
const s = a.snapshot;
const sections = run.settings.evalSections?.length ? run.settings.evalSections : [...QUALITY_SECTIONS];
const dep = await db().query.deployments.findFirst({ columns: { engineInfo: true, options: true }, where: eq(deployments.id, a.id) });
const contextTokens = dep?.engineInfo?.contextSize ?? dep?.options.contextSize ?? s.options.contextSize ?? null;
addLog(run.id, "system", `Quality eval ${EVAL_SET_VERSION} of ${s.deploymentName} (${s.repoId} on ${s.runtimeName}): ${sections.join(", ")}; greedy, seed ${EVAL_SEED}`);
const keys = a.apiKey ? [a.apiKey] : [];
addLog(run.id, "system", `Quality eval ${EVAL_SET_VERSION} of ${a.name} (${s.model}): ${sections.join(", ")}; greedy, seed ${EVAL_SEED}`);
await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, system }).where(eq(benchmarkRuns.id, run.id));
const c = docker();
const sampler = c ? new ResourceSampler(c, [{ side: "a" as const, containerId: a.containerId }], await gpuTargets([meta, null])) : null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
const cur: Current = {
runId: run.id,
kind: "eval",
deploymentIds: [a.id],
child: null,
abort: new AbortController(),
sampler,
meta,
metaB: null,
maxPairs: null,
cancelled: false,
lost: null,
secrets: keys,
};
const sandboxDir = coreEnv().SANDBOX_DIR;
const down = sections.includes("coding") ? await sandboxDown(sandboxDir) : null;
const cur: Current = { runId: run.id, kind: "eval", child: null, abort: new AbortController(), maxPairs: null, cancelled: false, lost: null, secrets: keys };
current = cur;
log.info(`benchmark ${run.id}: quality eval started for ${s.deploymentName}`);
log.info(`benchmark ${run.id}: quality eval started for ${a.name}`);
const onLine = (line: string) => {
addLog(run.id, "stdout", line, keys);
const m = line.match(/^(tools|coding|retrieval): starting$/);
if (m) void db().update(benchmarkRuns).set({ phase: `Quality: ${SECTION_LABEL[m[1] as QualitySection]}` }).where(eq(benchmarkRuns.id, run.id)).then(() => {}, () => {});
};
// Context per request: llama.cpp splits its context across its slots.
const perRequest = s.engine === "llama.cpp" && meta.contextSize && meta.concurrency ? Math.floor(meta.contextSize / meta.concurrency) : meta.contextSize;
runQualityEval(
{ base: `http://${a.containerName}:${ENGINE_PORT[a.engine]}`, model: s.repoId, engine: a.engine, apiKey: keys[0] ?? null, contextTokens },
{ sections, signal: cur.abort!.signal, log: onLine, docker: c, sandboxImage: workerImage() },
{ base: a.baseUrl, model: s.model, engine: s.engine, apiKey: a.apiKey, contextTokens: perRequest },
{ sections, signal: cur.abort!.signal, log: onLine, runCode: down ?? sandboxRunner(sandboxDir!) },
).then(
(q) => doneEval(cur, q, null),
(err) => doneEval(cur, null, err),
@@ -375,18 +311,18 @@ async function startEval(run: typeof benchmarkRuns.$inferSelect, a: Target, keys
async function doneEval(cur: Current, quality: QualityResult | null, err: unknown) {
const id = cur.runId;
const resources = await stopSampling(cur);
if (current === cur) current = null;
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", quality, resources });
await finish(id, { state: "cancelled", quality });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, quality, resources });
await finish(id, { state: "failed", error: cur.lost, quality });
} else if (err || !quality) {
await finish(id, { state: "failed", error: `The quality eval failed: ${message(err)}`, resources });
await finish(id, { state: "failed", error: `The quality eval failed: ${message(err)}` });
} else {
addLog(id, "system", `Done: score ${quality.score ?? "–"} (${quality.sections.map((x) => `${x.section} ${x.unsupported ? "n/a" : `${x.passed}/${x.total}`}`).join(", ")}).`);
await finish(id, { state: "completed", quality, resources });
await finish(id, { state: "completed", quality });
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
@@ -400,32 +336,32 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
partial.delete(`${id}:${stream}`);
}
const resources = await stopSampling(cur);
if (current === cur) current = null;
const dir = runDir(id);
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
if (cur.cancelled) {
addLog(id, "system", "Cancelled.");
await finish(id, { state: "cancelled", hasReport, resources });
await finish(id, { state: "cancelled", hasReport });
} else if (cur.lost) {
addLog(id, "system", cur.lost);
await finish(id, { state: "failed", error: cur.lost, hasReport, resources });
await finish(id, { state: "failed", error: cur.lost, hasReport });
} else if (code === 0 && (await exists(results))) {
try {
if (cur.kind === "ab") {
const ab = abSummary(await readFile(results, "utf8"), cur.maxPairs);
addLog(id, "system", `Done: ${ab.decode_tps.verdict} (${ab.pairs} pairs).`);
await finish(id, { state: ab.pairs > 0 ? "completed" : "failed", ab, resources, error: ab.pairs > 0 ? null : "No pair survived: every pair needs both calls to succeed (see the log)." });
await finish(id, { state: ab.pairs > 0 ? "completed" : "failed", ab, error: ab.pairs > 0 ? null : "No pair survived: every pair needs both calls to succeed (see the log)." });
} else {
const summary = { ...(await summarize(results)), quick: false };
const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
summary.quick = !!run?.settings.quick;
addLog(id, "system", "Done.");
await finish(id, { state: "completed", summary, hasReport, resources });
await finish(id, { state: "completed", summary, hasReport });
}
} catch (err) {
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport, resources });
await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport });
}
} else {
const lines = tails.get(id) ?? [];
@@ -436,12 +372,11 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
state: "failed",
error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"),
hasReport,
resources,
});
}
tails.delete(id);
await flushBenchmarkLogs().catch(() => {});
log.info(`benchmark ${id}: ${cur.cancelled ? "cancelled" : cur.lost ? "failed (deployment gone)" : code === 0 ? "completed" : "failed"}`);
log.info(`benchmark ${id}: ${cur.cancelled ? "cancelled" : cur.lost || code !== 0 ? "failed" : "completed"}`);
}
function stop(cur: Current) {
@@ -452,33 +387,15 @@ function stop(cur: Current) {
setTimeout(() => child.exitCode === null && child.kill("SIGKILL"), 10_000).unref();
}
/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
/** Start the next queued run; stop the current one when it's cancelled. */
export async function tickBenchmarks(): Promise<void> {
if (starting) return;
if (current) {
const cur = current;
const [run] = await db()
.select({ cancel: benchmarkRuns.cancelRequestedAt, startedAt: benchmarkRuns.startedAt, timeLimitS: benchmarkRuns.timeLimitS })
.from(benchmarkRuns)
.where(eq(benchmarkRuns.id, cur.runId));
const [run] = await db().select({ cancel: benchmarkRuns.cancelRequestedAt }).from(benchmarkRuns).where(eq(benchmarkRuns.id, cur.runId));
if (!run || run.cancel) {
cur.cancelled = true;
stop(cur);
return;
}
// Agent runs have a time limit (Settings → API tokens).
if (overTime(run.startedAt, run.timeLimitS)) {
cur.lost = `Stopped: the run exceeded the time limit for agent runs (${Math.round((run.timeLimitS ?? 0) / 60)} min).`;
stop(cur);
return;
}
for (const depId of cur.deploymentIds) {
const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, depId));
if (!d || d.state !== "running") {
cur.lost = cur.deploymentIds.length > 1 ? "A deployment of the A/B stopped during the run." : "The deployment stopped during the run.";
stop(cur);
break;
}
}
return;
}
-20
View File
@@ -48,23 +48,3 @@ describe("betterbench runArgs", () => {
assert.equal(stepOf("model max context: 4096 tokens"), null);
});
});
describe("parseNvidiaSmi", () => {
it("reads nvidia-smi CSV", async () => {
const { parseNvidiaSmi } = await import("./runtimes");
assert.deepEqual(parseNvidiaSmi("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14, 00000000:2B:00.0, 1, 4, 16, 16\n"), [
{
vendor: "nvidia",
index: 0,
uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84",
name: "NVIDIA GeForce RTX 3080",
memoryMb: 10240,
driver: "617.14",
pciAddress: "0000:2b:00.0",
linkCurrent: { gen: 1, width: 16 },
linkMax: { gen: 4, width: 16 },
},
]);
assert.deepEqual(parseNvidiaSmi("NVIDIA-SMI has failed"), []);
});
});
+13 -1
View File
@@ -1,5 +1,5 @@
// BetterBench (https://github.com/GGZ14/BetterBench, Apache-2.0): the benchmark Kaname runs
// against deployments. Flags verified against v0.6.1 (`betterbench run --help`, betterbench/cli.py).
// against endpoints. Flags verified against v0.6.1 (`betterbench run --help`, betterbench/cli.py).
import { dirname, join } from "node:path";
import type { BenchmarkSettings } from "@/lib/db/schema";
@@ -73,6 +73,18 @@ export function abArgs(o: {
];
}
/**
* `betterbench ab` with a different API key per side. Its --api-key-a/-b flags would put the keys on
* the command line (visible in ps), so this launcher (run with BetterBench's Python, the ab argv
* after it) adds them inside the process, from KANAME_API_KEY_A/B in its environment.
*/
export const AB_KEYS_LAUNCHER = [
"import os, sys",
"from betterbench.cli import main",
"keys = ['--api-key-a', os.environ.pop('KANAME_API_KEY_A'), '--api-key-b', os.environ.pop('KANAME_API_KEY_B')]",
"sys.exit(main(sys.argv[1:] + keys))",
].join("\n");
export { AB_FILE } from "@/lib/benchmark-paths";
export const AB_DEFAULT_MDE_PCT = 1;
export const AB_DEFAULT_MAX_PAIRS = 200;
-358
View File
@@ -1,358 +0,0 @@
// Deployments: the worker keeps runtime containers in line with what the web app asked for
// (desiredState), follows their logs, checks health and samples CPU/memory. Containers keep running
// across worker restarts; the worker re-attaches to them.
import { stat } from "node:fs/promises";
import { join } from "node:path";
import { and, asc, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type EngineInfo, type LogStream, models, type RuntimeEngine, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, redactCommand, renderCommand } from "@/lib/deploy-command";
import { ACCELERATOR_DEVICES } from "@/lib/runtimes-shared";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { fetchEngineInfo, versionFromLog } from "./engine-info";
import { errorCauses } from "./log-causes";
import { docker } from "./runtimes";
import type { DockerClient } from "./docker/client";
type Deployment = typeof deployments.$inferSelect;
const LABEL = "kaname.deployment";
const STATS_MS = 5_000;
const LOG_FLUSH_MS = 1_000;
const LOG_KEEP = 5_000;
/** Give up on a container that isn't healthy after this long (big models load slowly on CPU). */
const START_TIMEOUT_MS = 30 * 60_000;
/** Leave this much of the host's memory to the system and other containers. */
const MEMORY_RESERVE_MB = 2048;
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
const slug = (s: string) =>
s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-|-$/g, "")
.slice(0, 40) || "model";
// --- logs ------------------------------------------------------------------------------------
const followers = new Map<string, AbortController>();
const pending: { deploymentId: string; stream: LogStream; line: string; ts: Date }[] = [];
// API key values, refreshed every reconcile pass: hidden in every log line (vLLM prints its
// arguments, including --api-key, at startup).
let apiKeySecrets: string[] = [];
async function loadApiKeys(): Promise<string[]> {
apiKeySecrets = (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
return apiKeySecrets;
}
function addLog(deploymentId: string, stream: LogStream, line: string) {
pending.push({ deploymentId, stream, line: sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...apiKeySecrets]).slice(0, 4000), ts: new Date() });
}
export async function flushDeploymentLogs(): Promise<void> {
if (pending.length === 0) return;
const batch = pending.splice(0, pending.length);
for (let i = 0; i < batch.length; i += 500) await db().insert(deploymentLogs).values(batch.slice(i, i + 500));
// Keep the newest LOG_KEEP lines per deployment.
for (const id of new Set(batch.map((b) => b.deploymentId))) {
const [cut] = await db()
.select({ id: deploymentLogs.id })
.from(deploymentLogs)
.where(eq(deploymentLogs.deploymentId, id))
.orderBy(desc(deploymentLogs.id))
.limit(1)
.offset(LOG_KEEP);
if (cut) await db().delete(deploymentLogs).where(and(eq(deploymentLogs.deploymentId, id), lt(deploymentLogs.id, cut.id)));
}
}
function follow(c: DockerClient, d: { id: string; containerId: string }, tail: number | "all" = 0) {
followers.get(d.id)?.abort();
const ctl = new AbortController();
followers.set(d.id, ctl);
c.followLogs(d.containerId, (stream, line) => addLog(d.id, stream, line), { tail, signal: ctl.signal })
.catch((err) => !ctl.signal.aborted && log.warn(`logs of deployment ${d.id}: ${message(err)}`))
.finally(() => followers.get(d.id) === ctl && followers.delete(d.id));
}
function unfollow(id: string) {
followers.get(id)?.abort();
followers.delete(id);
}
// --- start / stop ------------------------------------------------------------------------------
async function update(id: string, set: Partial<Deployment>) {
await db().update(deployments).set(set).where(eq(deployments.id, id));
}
async function fail(d: Deployment, error: string, exitCode: number | null = null) {
addLog(d.id, "system", `Failed: ${error}`);
log.warn(`deployment ${d.name}: ${error}`);
// desiredState stopped, so the worker doesn't retry in a loop.
await update(d.id, { state: "failed", desiredState: "stopped", error, exitCode, stoppedAt: new Date(), stats: null });
}
async function start(c: DockerClient, d: Deployment) {
const [runtime, model, ws] = await Promise.all([
db().query.runtimes.findFirst({ where: eq(runtimes.id, d.runtimeId) }),
db().query.models.findFirst({ where: eq(models.id, d.modelId) }),
db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
]);
if (!runtime) return fail(d, "The runtime was deleted.");
if (!model) return fail(d, "The model was deleted.");
const host = ws?.docker;
if (!host?.connected) return fail(d, "Docker isn't connected.");
if (!host.network || !host.modelsSource) {
return fail(d, "The Docker network or the models source wasn't detected (see Settings → Runtimes).");
}
const image = await c.inspectImage(runtime.image);
if (!image) return fail(d, `Image ${runtime.image} isn't pulled yet (Settings → Runtimes → Pull).`);
// The files must be there (the worker sees the same models folder the container gets).
for (const f of [d.options.modelFile, d.options.mmproj, d.options.draftFile]) {
if (f == null || (f === "" && runtime.engine !== "vllm")) continue;
const path = join(coreEnv().MODELS_DIR, model.localPath, f);
if (!(await stat(path).catch(() => null))) return fail(d, `File not found: ${model.localPath}/${f}. Is the model downloaded?`);
}
// Memory: what the other running deployments reserve plus this one must fit.
if (d.memoryMb && host.memoryBytes) {
const others = await db()
.select({ memoryMb: deployments.memoryMb })
.from(deployments)
.where(and(inArray(deployments.state, ["starting", "running"])));
const used = others.reduce((s, o) => s + (o.memoryMb ?? 0), 0);
const available = host.memoryBytes / 2 ** 20 - MEMORY_RESERVE_MB - used;
if (d.memoryMb > available) {
return fail(
d,
`Not enough memory: ${formatBytes(d.memoryMb * 2 ** 20)} requested, ${formatBytes(Math.max(0, available) * 2 ** 20)} left for deployments (running ones reserve ${formatBytes(used * 2 ** 20)}).`,
);
}
}
// GPUs: NVIDIA ones are requested from Docker (all, or the selected UUIDs); Intel/AMD come in as /dev nodes.
let deviceRequests: unknown[] = [];
if (runtime.accelerator === "nvidia") {
if (!host.nvidia) return fail(d, "This runtime needs NVIDIA GPUs, but Docker has no NVIDIA runtime (install the NVIDIA Container Toolkit on the Docker host).");
const wanted = d.options.gpus?.length ? d.options.gpus : null;
const missing = wanted?.filter((u) => !(host.gpus ?? []).some((g) => g.uuid === u)) ?? [];
if (missing.length && (host.gpus ?? []).length) return fail(d, `Selected GPU not found: ${missing.join(", ")}. Pick the GPUs again in the deployment.`);
deviceRequests = [{ Driver: "", Count: wanted ? 0 : -1, DeviceIDs: wanted ?? undefined, Capabilities: [["gpu"]] }];
}
const devices = runtime.accelerator === "dri" || runtime.accelerator === "rocm" ? [...new Set([...runtime.devices, ...ACCELERATOR_DEVICES[runtime.accelerator]])] : runtime.devices;
const keys = d.options.requireApiKey ? await loadApiKeys() : [];
if (d.options.requireApiKey && keys.length === 0) return fail(d, "This deployment requires an API key, but there are none. Add one under Settings → API keys.");
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime, apiKeys: keys });
// What Kaname shows and stores: never the key values.
const shown = redactCommand(cmd, keys);
const name = `kaname-${slug(d.name)}-${d.id.slice(-6).toLowerCase()}`;
const portKey = `${cmd.port}/tcp`;
const spec = {
Image: runtime.image,
Cmd: cmd.args,
Env: Object.entries(cmd.env).map(([k, v]) => `${k}=${v}`),
Labels: { [LABEL]: d.id, "kaname.managed": "true" },
ExposedPorts: { [portKey]: {} },
HostConfig: {
Mounts: [{ Type: host.modelsSource.type, Source: host.modelsSource.source, Target: CONTAINER_MODELS_DIR, ReadOnly: true }],
NanoCpus: d.cpus ? Math.round(d.cpus * 1e9) : 0,
Memory: d.memoryMb ? d.memoryMb * 2 ** 20 : 0,
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
Devices: devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
DeviceRequests: deviceRequests,
// Images that don't run as root need the render/video group to open /dev/dri.
GroupAdd: devices.some((p) => p.startsWith("/dev/dri")) ? (host.driGroups ?? []).map(String) : [],
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
Privileged: false,
Init: true,
RestartPolicy: { Name: "no" },
},
NetworkingConfig: { EndpointsConfig: { [host.network]: {} } },
};
addLog(d.id, "system", `Starting ${runtime.name} (${runtime.image})`);
addLog(d.id, "system", `$ ${renderCommand(runtime.image, shown)}`);
try {
await c.removeContainer(name); // leftover from a crash
const created = await c.createContainer(name, spec);
for (const w of created.Warnings ?? []) addLog(d.id, "system", `Docker: ${w}`);
await update(d.id, {
state: "starting",
containerId: created.Id,
containerName: name,
command: shown.args,
imageId: image.Id,
startedAt: new Date(),
readyAt: null,
stoppedAt: null,
error: null,
exitCode: null,
stats: null,
engineInfo: null,
});
await c.startContainer(created.Id);
// A fresh container: everything it printed belongs to this run. (Following before the start
// returns an empty, already-closed stream.)
follow(c, { id: d.id, containerId: created.Id }, "all");
log.info(`deployment ${d.name}: started ${name}`);
} catch (err) {
await c.removeContainer(name).catch(() => {});
await fail(d, `Docker: ${message(err)}`);
}
}
async function stopContainer(c: DockerClient, d: Deployment) {
if (d.containerId) {
await update(d.id, { state: "stopping" });
await c.stopContainer(d.containerId, 15);
await c.removeContainer(d.containerId);
}
unfollow(d.id);
addLog(d.id, "system", "Stopped.");
await update(d.id, { state: "stopped", stoppedAt: new Date(), stats: null, containerId: null });
}
/** Likely causes plus the tail of the log, for error messages. */
async function failureDetails(id: string, tail = 15): Promise<string> {
await flushDeploymentLogs();
const lines = (
await db().select({ line: deploymentLogs.line }).from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(2000)
)
.reverse()
.map((r) => r.line);
const causes = errorCauses(lines);
const last = lines.slice(-tail).join("\n");
return [causes.join("\n"), last && (causes.length ? `Last output:\n${last}` : last)].filter(Boolean).join("\n\n");
}
async function healthy(name: string, port: number): Promise<boolean> {
try {
const res = await fetch(`http://${name}:${port}/health`, { signal: AbortSignal.timeout(2_000) });
return res.ok;
} catch {
return false;
}
}
/** Version, slots and context from the server; the version from its startup log if it doesn't say. */
async function engineInfo(d: Deployment, engine: RuntimeEngine, base: string): Promise<EngineInfo> {
const key = d.options.requireApiKey ? ((await loadApiKeys())[0] ?? null) : null;
const info = await fetchEngineInfo(engine, base, key);
if (!info.version) {
await flushDeploymentLogs();
const lines = await db().select({ line: deploymentLogs.line }).from(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)).orderBy(asc(deploymentLogs.id)).limit(500);
info.version = versionFromLog(engine, lines.map((l) => l.line));
}
if (info.version) addLog(d.id, "system", `Engine: ${engine} ${info.version}${info.slots ? `, ${info.slots} slots` : ""}${info.contextSize ? `, context ${info.contextSize}` : ""}`);
return { ...info, at: new Date().toISOString() };
}
// --- reconcile -----------------------------------------------------------------------------------
const lastStats = new Map<string, number>();
async function reconcileOne(c: DockerClient, d: Deployment) {
if (d.deleteRequestedAt) {
if (d.containerId) {
await c.stopContainer(d.containerId, 15).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
}
unfollow(d.id);
pending.splice(0, pending.length, ...pending.filter((p) => p.deploymentId !== d.id));
await db().batch([db().delete(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)), db().delete(deployments).where(eq(deployments.id, d.id))]);
log.info(`deployment ${d.name} deleted`);
return;
}
if (d.desiredState === "stopped") {
if (d.state === "starting" || d.state === "running" || d.state === "stopping") await stopContainer(c, d);
return;
}
// desired: running
if (d.state === "stopped" || d.state === "failed") return start(c, d);
if (!d.containerId || !d.containerName) return fail(d, "Container is missing.");
const st = await c.containerState(d.containerId);
if (!st || !st.Running) {
const why = st?.OOMKilled ? "out of memory (raise the memory limit)" : `exit code ${st?.ExitCode ?? "?"}`;
unfollow(d.id);
const tail = await failureDetails(d.id);
await c.removeContainer(d.containerId).catch(() => {});
return fail(d, `The container stopped (${why}).${tail ? `\n${tail}` : ""}`, st?.ExitCode ?? null);
}
if (!followers.has(d.id)) follow(c, { id: d.id, containerId: d.containerId });
const runtime = await db().query.runtimes.findFirst({ columns: { engine: true }, where: eq(runtimes.id, d.runtimeId) });
const port = ENGINE_PORT[runtime?.engine ?? "llama.cpp"];
if (d.state === "starting") {
if (await healthy(d.containerName, port)) {
const now = new Date();
const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?";
addLog(d.id, "system", `Ready after ${secs} s.`);
await update(d.id, { state: "running", readyAt: now, engineInfo: await engineInfo(d, runtime?.engine ?? "llama.cpp", `http://${d.containerName}:${port}`) });
} else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) {
await c.stopContainer(d.containerId).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
return fail(d, "Not healthy after 30 minutes.");
}
}
if (Date.now() - (lastStats.get(d.id) ?? 0) >= STATS_MS) {
lastStats.set(d.id, Date.now());
const s = await c.containerStats(d.containerId).catch(() => null);
if (s) await update(d.id, { stats: { ...s, at: new Date().toISOString() } });
}
}
let reconciling = false;
export async function reconcileDeployments(): Promise<void> {
const c = docker();
if (!c || reconciling) return;
reconciling = true;
try {
await loadApiKeys();
for (const d of await db().select().from(deployments)) {
await reconcileOne(c, d).catch((err) => log.error(`deployment ${d.name}`, err));
}
} finally {
reconciling = false;
}
}
/** After a worker restart: re-attach to running containers, remove ones no deployment owns. */
export async function adoptContainers(): Promise<void> {
const c = docker();
if (!c) return;
try {
const rows = await db().select({ id: deployments.id, containerId: deployments.containerId, state: deployments.state }).from(deployments);
const byId = new Map(rows.map((r) => [r.id, r]));
for (const ct of await c.listContainers(LABEL)) {
const owner = byId.get(ct.Labels[LABEL]);
if (!owner || owner.containerId !== ct.Id) {
await c.removeContainer(ct.Id);
log.info(`removed orphaned container ${ct.Names[0] ?? ct.Id}`);
} else if (ct.State === "running") {
follow(c, { id: owner.id, containerId: ct.Id });
}
}
} catch (err) {
log.warn(`adopting deployment containers failed: ${message(err)}`);
}
}
export function stopFollowingLogs() {
for (const id of [...followers.keys()]) unfollow(id);
}
export const LOG_FLUSH_INTERVAL_MS = LOG_FLUSH_MS;
-279
View File
@@ -1,279 +0,0 @@
// Minimal Docker Engine API client (no dependencies): HTTP over TCP (socket proxy) or a unix socket.
// Only the endpoints Kaname needs. Paths are unversioned, so the daemon's own API version is used.
import http from "node:http";
export class DockerError extends Error {
constructor(
message: string,
public status: number | null,
) {
super(message);
this.name = "DockerError";
}
}
type Target = { socketPath: string } | { host: string; port: number };
function parseHost(dockerHost: string): Target {
if (dockerHost.startsWith("unix://")) return { socketPath: dockerHost.slice("unix://".length) };
const url = new URL(dockerHost.replace(/^tcp:/, "http:"));
return { host: url.hostname, port: Number(url.port || 2375) };
}
export class DockerClient {
private target: Target;
constructor(dockerHost: string) {
this.target = parseHost(dockerHost);
}
private raw(method: string, path: string, body?: unknown, timeoutMs = 30_000): Promise<http.IncomingMessage> {
return new Promise((resolve, reject) => {
const payload = body === undefined ? undefined : JSON.stringify(body);
const req = http.request(
{
...this.target,
method,
path,
headers: { Host: "docker", ...(payload ? { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(payload) } : {}) },
timeout: timeoutMs,
},
resolve,
);
req.on("timeout", () => req.destroy(new DockerError(`Docker API ${method} ${path} timed out`, null)));
req.on("error", (err) =>
reject(err instanceof DockerError ? err : new DockerError(`Can't reach Docker (${err.message})`, null)),
);
if (payload) req.write(payload);
req.end();
});
}
private async json<T>(method: string, path: string, body?: unknown): Promise<T> {
const res = await this.raw(method, path, body);
const chunks: Buffer[] = [];
for await (const c of res) chunks.push(c as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
if ((res.statusCode ?? 500) >= 400) {
let message = text;
try {
message = JSON.parse(text).message ?? text;
} catch {}
if (res.statusCode === 403) message = `Docker API refused ${method} ${path} (socket proxy permissions?): ${message}`;
throw new DockerError(message.trim() || `HTTP ${res.statusCode}`, res.statusCode ?? null);
}
return (text ? JSON.parse(text) : null) as T;
}
version() {
return this.json<{ Version: string; ApiVersion: string; Os: string; Arch: string }>("GET", "/version");
}
info() {
return this.json<{
NCPU: number;
MemTotal: number;
OperatingSystem: string;
Architecture: string;
ServerVersion: string;
Runtimes?: Record<string, unknown>;
DiscoveredDevices?: { Source: string; ID: string }[];
}>(
"GET",
"/info",
);
}
/** Inspect a container; null if it doesn't exist. */
async inspectContainer(id: string) {
try {
return await this.json<{
Id: string;
Name: string;
Image: string;
Mounts: { Type: string; Source: string; Destination: string; Name?: string }[];
NetworkSettings: { Networks: Record<string, unknown> };
}>("GET", `/containers/${encodeURIComponent(id)}/json`);
} catch (err) {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
}
}
/** Containers with a label (e.g. "kaname.deployment"), running or not. */
listContainers(label: string) {
const filters = encodeURIComponent(JSON.stringify({ label: [label] }));
return this.json<{ Id: string; Names: string[]; State: string; Labels: Record<string, string> }[]>(
"GET",
`/containers/json?all=1&filters=${filters}`,
);
}
createContainer(name: string, spec: unknown) {
return this.json<{ Id: string; Warnings: string[] }>("POST", `/containers/create?name=${encodeURIComponent(name)}`, spec);
}
async startContainer(id: string) {
await this.json("POST", `/containers/${encodeURIComponent(id)}/start`);
}
/** Stop (SIGTERM, SIGKILL after `timeout` s); ignores "already stopped". */
async stopContainer(id: string, timeout = 10) {
try {
await this.json("POST", `/containers/${encodeURIComponent(id)}/stop?t=${timeout}`);
} catch (err) {
if (!(err instanceof DockerError && (err.status === 304 || err.status === 404))) throw err;
}
}
/** Remove a container (forced); ignores "no such container". */
async removeContainer(id: string) {
try {
await this.json("DELETE", `/containers/${encodeURIComponent(id)}?force=1`);
} catch (err) {
if (!(err instanceof DockerError && err.status === 404)) throw err;
}
}
async containerState(id: string) {
const c = await this.json<{ State: { Status: string; Running: boolean; ExitCode: number; Error: string; OOMKilled: boolean } } | null>(
"GET",
`/containers/${encodeURIComponent(id)}/json`,
).catch((err) => {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
});
return c?.State ?? null;
}
/** One stats sample: CPU % (of one core = 100) and memory. */
async containerStats(id: string): Promise<{ cpuPercent: number; memoryBytes: number; memoryLimitBytes: number }> {
const s = await this.json<{
cpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number; online_cpus: number };
precpu_stats: { cpu_usage: { total_usage: number }; system_cpu_usage: number };
memory_stats: { usage?: number; limit?: number; stats?: { inactive_file?: number; cache?: number } };
}>("GET", `/containers/${encodeURIComponent(id)}/stats?stream=false`);
const cpuDelta = s.cpu_stats.cpu_usage.total_usage - (s.precpu_stats.cpu_usage?.total_usage ?? 0);
const sysDelta = s.cpu_stats.system_cpu_usage - (s.precpu_stats.system_cpu_usage ?? 0);
const cpuPercent = sysDelta > 0 ? (cpuDelta / sysDelta) * (s.cpu_stats.online_cpus || 1) * 100 : 0;
// Like `docker stats`: usage minus page cache.
const cache = s.memory_stats.stats?.inactive_file ?? s.memory_stats.stats?.cache ?? 0;
return {
cpuPercent: Math.round(cpuPercent * 10) / 10,
memoryBytes: Math.max(0, (s.memory_stats.usage ?? 0) - cache),
memoryLimitBytes: s.memory_stats.limit ?? 0,
};
}
/**
* Follow a container's stdout/stderr (from now, plus the last `tail` lines or "all"). The stream uses
* Docker's multiplexed format (8-byte frame headers) for containers without a TTY. Resolves when
* the container stops or `signal` aborts.
*/
async followLogs(
id: string,
onLine: (stream: "stdout" | "stderr", line: string) => void,
options: { tail?: number | "all"; signal?: AbortSignal } = {},
): Promise<void> {
const res = await this.raw(
"GET",
`/containers/${encodeURIComponent(id)}/logs?follow=1&stdout=1&stderr=1&tail=${options.tail ?? 0}`,
undefined,
0,
);
if ((res.statusCode ?? 500) >= 400) throw new DockerError(`logs: HTTP ${res.statusCode}`, res.statusCode ?? null);
options.signal?.addEventListener("abort", () => res.destroy());
let buf = Buffer.alloc(0);
const partial = { stdout: "", stderr: "" };
const emit = (stream: "stdout" | "stderr", text: string) => {
const parts = (partial[stream] + text).split(/\r?\n|\r/);
partial[stream] = parts.pop() ?? "";
for (const p of parts) if (p.trim()) onLine(stream, p);
};
try {
for await (const chunk of res) {
buf = Buffer.concat([buf, chunk as Buffer]);
while (buf.length >= 8) {
const size = buf.readUInt32BE(4);
if (buf.length < 8 + size) break;
emit(buf[0] === 2 ? "stderr" : "stdout", buf.subarray(8, 8 + size).toString("utf8"));
buf = buf.subarray(8 + size);
}
}
} catch (err) {
if (!options.signal?.aborted) throw err;
}
for (const s of ["stdout", "stderr"] as const) if (partial[s].trim()) onLine(s, partial[s]);
}
/** Inspect a local image; null if it isn't pulled. */
async inspectImage(ref: string) {
try {
return await this.json<{ Id: string; Size: number; Created: string; RepoDigests: string[] }>(
"GET",
`/images/${encodeURIComponent(ref)}/json`,
);
} catch (err) {
if (err instanceof DockerError && err.status === 404) return null;
throw err;
}
}
/**
* Pull an image. The daemon streams JSON lines per layer; `onProgress` gets the summed bytes of
* all layers seen so far. Resolves when the pull finished, rejects on an error line.
*/
async pullImage(ref: string, onProgress: (p: { doneBytes: number; totalBytes: number; status: string }) => void): Promise<void> {
const at = ref.lastIndexOf("@") > 0 ? ref.lastIndexOf("@") : -1;
const colon = ref.lastIndexOf(":");
const hasTag = at === -1 && colon > ref.lastIndexOf("/");
const fromImage = at !== -1 ? ref : hasTag ? ref.slice(0, colon) : ref;
const tag = at !== -1 ? "" : hasTag ? ref.slice(colon + 1) : "latest";
const query = new URLSearchParams({ fromImage, ...(tag ? { tag } : {}) });
const res = await this.raw("POST", `/images/create?${query}`, undefined, 60 * 60_000);
if ((res.statusCode ?? 500) >= 400) {
const chunks: Buffer[] = [];
for await (const c of res) chunks.push(c as Buffer);
const text = Buffer.concat(chunks).toString("utf8");
let message = text;
try {
message = JSON.parse(text).message ?? text;
} catch {}
throw new DockerError(message.trim(), res.statusCode ?? null);
}
const layers = new Map<string, { current: number; total: number }>();
let buffer = "";
let status = "Pulling";
for await (const chunk of res) {
buffer += (chunk as Buffer).toString("utf8");
let nl: number;
while ((nl = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (!line) continue;
const msg = JSON.parse(line) as {
id?: string;
status?: string;
error?: string;
progressDetail?: { current?: number; total?: number };
};
if (msg.error) throw new DockerError(msg.error, null);
if (msg.status) status = msg.status;
if (msg.id && msg.status === "Downloading" && msg.progressDetail?.total) {
layers.set(msg.id, { current: msg.progressDetail.current ?? 0, total: msg.progressDetail.total });
} else if (msg.id && (msg.status === "Download complete" || msg.status === "Pull complete" || msg.status === "Already exists")) {
const l = layers.get(msg.id);
if (l) l.current = l.total;
}
let done = 0;
let total = 0;
for (const l of layers.values()) {
done += l.current;
total += l.total;
}
onProgress({ doneBytes: done, totalBytes: total, status });
}
}
}
}
-45
View File
@@ -1,45 +0,0 @@
// What a ready inference server says about itself: version, slots and context. llama.cpp: GET /props
// (build_info "b11429-d81235049", total_slots, default_generation_settings.n_ctx; checked with build
// 11429). vLLM: GET /version and GET /v1/models (max_model_len). Startup log lines as a fallback.
import type { EngineInfo, RuntimeEngine } from "@/lib/db/schema";
type Json = Record<string, unknown>;
const int = (v: unknown) => (typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null);
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim().slice(0, 100) : null);
export function parseLlamaProps(props: Json | null): Omit<EngineInfo, "at"> {
const gen = (props?.default_generation_settings ?? {}) as Json;
return { version: str(props?.build_info), slots: int(props?.total_slots), contextSize: int(gen.n_ctx) };
}
export function parseVllm(version: Json | null, models: Json | null): Omit<EngineInfo, "at"> {
const data = Array.isArray(models?.data) ? (models.data as Json[]) : [];
return { version: str(version?.version), slots: null, contextSize: int(data[0]?.max_model_len) };
}
/** "build: 11429 (d8123504)" (llama.cpp), "vLLM API server version 0.31.0" (vLLM and most forks). */
export function versionFromLog(engine: RuntimeEngine, lines: string[]): string | null {
const re = engine === "llama.cpp" ? /\bbuild[:=]\s*(\d+)\s*\(([0-9a-f]+)\)/ : /\bversion\s+v?(\d+\.\d+[\w.+-]*)/i;
for (const l of lines) {
const m = l.match(re);
if (m) return engine === "llama.cpp" ? `b${m[1]}-${m[2]}` : m[1];
}
return null;
}
async function getJson(url: string, key: string | null): Promise<Json | null> {
try {
const res = await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(3_000) });
return res.ok ? ((await res.json()) as Json) : null;
} catch {
return null;
}
}
/** Ask the server at http://name:port; `key` when the deployment requires an API key. */
export async function fetchEngineInfo(engine: RuntimeEngine, base: string, key: string | null): Promise<Omit<EngineInfo, "at">> {
if (engine === "llama.cpp") return parseLlamaProps(await getJson(`${base}/props`, key));
const [version, models] = await Promise.all([getJson(`${base}/version`, key), getJson(`${base}/v1/models`, key)]);
return parseVllm(version, models);
}
-169
View File
@@ -1,169 +0,0 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { estimateVramMb } from "@/lib/deploy-command";
import { aggregateFdinfo, drmUtilization, parseFdinfo, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs";
import type { SysFs } from "./hardware";
import { parseGpuLine, summarizeSamples } from "./resources";
import { parseDriGroups } from "./runtimes";
/** An in-memory sysfs: files plus directory links. */
function memFs(files: Record<string, string>, links: Record<string, string> = {}): SysFs {
const resolve = (p: string) => {
const hit = Object.keys(links).find((l) => p === l || p.startsWith(`${l}/`));
return hit ? links[hit] + p.slice(hit.length) : p;
};
return {
read: async (p) => files[resolve(p)]?.trim() ?? null,
resolve: async (p) => resolve(p),
list: async (d) => {
const dir = `${resolve(d)}/`;
return [...new Set(Object.keys(files).filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]))];
},
};
}
const xe = (client: number, vramKiB: number, rcs: number, ccs: number, total: number) => `pos:\t0
flags:\t02100002
drm-driver:\txe
drm-client-id:\t${client}
drm-pdev:\t0000:03:00.0
drm-total-system:\t0
drm-resident-system:\t0
drm-total-gtt:\t12 KiB
drm-total-vram0:\t${vramKiB + 1024} KiB
drm-resident-vram0:\t${vramKiB} KiB
drm-cycles-rcs:\t${rcs}
drm-total-cycles-rcs:\t${total}
drm-cycles-ccs:\t${ccs}
drm-total-cycles-ccs:\t${total}
`;
describe("DRM fdinfo", () => {
it("parses xe: resident VRAM, cycles per engine class", () => {
const c = parseFdinfo(xe(42, 9_437_184, 1000, 30_000, 50_000))!;
assert.equal(c.pdev, "0000:03:00.0");
assert.equal(c.clientId, "42");
assert.equal(c.vramBytes, 9_437_184 * 1024);
assert.deepEqual(c.cycles, { rcs: 1000, ccs: 30_000 });
assert.deepEqual(c.totalCycles, { rcs: 50_000, ccs: 50_000 });
});
it("parses i915 (local memory, nanoseconds) and amdgpu's legacy keys", () => {
const i915 = parseFdinfo("drm-driver: i915\ndrm-pdev: 0000:00:02.0\ndrm-client-id: 7\ndrm-engine-render: 1000000 ns\ndrm-engine-capacity-video: 2\ndrm-total-local0: 1024 KiB\ndrm-resident-local0: 512 KiB\n")!;
assert.equal(i915.vramBytes, 512 * 1024);
assert.deepEqual(i915.ns, { render: 1_000_000 });
const amd = parseFdinfo("drm-driver:\tamdgpu\ndrm-pdev:\t0000:0a:00.0\ndrm-client-id:\t3\ndrm-memory-vram:\t2048 KiB\ndrm-memory-gtt:\t16 KiB\ndrm-engine-gfx:\t5000 ns\n")!;
assert.equal(amd.vramBytes, 2048 * 1024);
assert.deepEqual(amd.ns, { gfx: 5000 });
assert.equal(parseFdinfo("pos: 0\nflags: 02\n"), null);
});
it("counts each client once and takes the GPU clock as is", () => {
const s = aggregateFdinfo(1000, [xe(1, 1024, 10, 20, 100), xe(1, 1024, 10, 20, 100), xe(2, 2048, 5, 0, 110), "pos: 0\n"]);
const g = s.gpus["0000:03:00.0"];
assert.equal(g.vramBytes, 3072 * 1024);
assert.deepEqual(g.cycles, { rcs: 15, ccs: 20 });
assert.deepEqual(g.totalCycles, { rcs: 110, ccs: 110 });
});
it("reports the busiest engine class between two snapshots", () => {
const a = aggregateFdinfo(0, [xe(1, 1024, 0, 0, 1000)]).gpus["0000:03:00.0"];
const b = aggregateFdinfo(2000, [xe(1, 1024, 100, 800, 2000)]).gpus["0000:03:00.0"];
assert.equal(drmUtilization(a, b, 2), 80);
assert.equal(drmUtilization(undefined, b, 2), null);
// A client that exited makes the sum drop: idle, not negative.
const c = aggregateFdinfo(4000, [xe(2, 0, 0, 0, 3000)]).gpus["0000:03:00.0"];
assert.equal(drmUtilization(b, c, 2), 0);
// Nanosecond engines: busy time over wall time.
assert.equal(drmUtilization({ vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 0 } }, { vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 1e9 } }, 2), 50);
});
});
describe("hwmon and amdgpu sysfs", () => {
const dev = "/sys/devices/pci0000:00/0000:00:01.0/0000:03:00.0";
const fs = memFs(
{
[`${dev}/hwmon/hwmon3/name`]: "xe",
[`${dev}/hwmon/hwmon3/energy1_input`]: "5000000",
[`${dev}/hwmon/hwmon3/power1_max`]: "200000000",
[`${dev}/hwmon/hwmon3/temp2_input`]: "61000",
[`${dev}/hwmon/hwmon3/temp2_label`]: "pkg",
[`${dev}/hwmon/hwmon3/temp3_input`]: "70000",
[`${dev}/hwmon/hwmon3/temp3_label`]: "vram",
"/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/power1_average": "150000000",
"/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/temp1_input": "55000",
"/sys/devices/pci0000:00/0000:0a:00.0/mem_info_vram_used": String(4 * 2 ** 30),
"/sys/devices/pci0000:00/0000:0a:00.0/gpu_busy_percent": "87",
},
{ "/sys/bus/pci/devices/0000:03:00.0": dev, "/sys/bus/pci/devices/0000:0a:00.0": "/sys/devices/pci0000:00/0000:0a:00.0" },
);
it("reads xe's energy counter and package temperature", async () => {
assert.deepEqual(await readHwmon(fs, "0000:03:00.0"), { energyUj: 5_000_000, powerW: null, tempC: 61 });
});
it("reads amdgpu's power, temperature, VRAM in use and busy percent", async () => {
assert.deepEqual(await readHwmon(fs, "0000:0a:00.0"), { energyUj: null, powerW: 150, tempC: 55 });
assert.deepEqual(await readAmdUsage(fs, "0000:0a:00.0"), { vramUsedMb: 4096, util: 87 });
});
it("turns energy into power between readings", () => {
assert.equal(powerBetween({ energyUj: 1_000_000, powerW: null, tempC: null }, { energyUj: 401_000_000, powerW: null, tempC: null }, 2), 200);
assert.equal(powerBetween(null, { energyUj: 5, powerW: null, tempC: null }, 0), null);
assert.equal(powerBetween(null, { energyUj: null, powerW: 150, tempC: null }, 0), 150);
});
});
describe("GPU summaries", () => {
it("keeps unknown figures unknown and adds temperature", () => {
const s = summarizeSamples(
[],
[
{ index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 120, tempC: 60 },
{ index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 180, tempC: 70 },
],
4,
);
assert.deepEqual(s.gpus[0], {
index: 0,
name: "Intel Arc Pro B65",
pciAddress: "0000:03:00.0",
vramTotalMb: 32768,
vramPeakMb: null,
vramAvgMb: null,
utilAvg: null,
utilPeak: null,
powerAvgW: 150,
powerPeakW: 180,
tempAvgC: 65,
tempPeakC: 70,
});
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16, 47")?.tempC, 47);
});
it("reads /dev/dri group IDs", () => {
assert.deepEqual(parseDriGroups(["/dev/dri/card0 44", "/dev/dri/renderD128 993", "/dev/dri/renderD129 993", "/dev/dri/by-path 0", "stat: error"]), [44, 993]);
});
});
describe("VRAM estimate", () => {
const GiB = 2 ** 30;
it("adds weights, KV cache and buffers for llama.cpp with all layers on the GPU", () => {
const f16 = estimateVramMb(5 * GiB, 32768, "llama.cpp", {}, 32768)!;
const q8 = estimateVramMb(5 * GiB, 32768, "llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q8_0" }, 32768)!;
assert.ok(f16 > 5120 + 1024 && f16 < 5120 + 1024 + 8192, String(f16));
assert.ok(q8 < f16);
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "all" }, null), estimateVramMb(5 * GiB, 4096, "llama.cpp", {}, null));
});
it("can't tell partial offload", () => {
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "20" }, 32768), null);
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { cpuMoe: true }, 32768), null);
});
it("uses vLLM's memory share of the VRAM", () => {
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, 32768), Math.ceil(32768 * 0.9));
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", { gpuMemoryUtilization: 0.5 }, 32768), 16384);
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, null), null);
});
});
-175
View File
@@ -1,175 +0,0 @@
// GPU telemetry without nvidia-smi, for Intel and AMD GPUs.
// - hwmon (sysfs, readable unprivileged): power (energy counter or power reading) and temperature.
// - AMD (amdgpu): VRAM in use and busy percent are plain sysfs files.
// - Intel (xe, i915): the driver has no whole-GPU VRAM/utilization file; both are only reported per
// process in DRM fdinfo (/proc/<pid>/fdinfo, kernel "drm-usage-stats"). A probe container in the
// host's PID namespace dumps those (INTEL_PROBE_SCRIPT); parsing and aggregation happen here.
// Pure parsers for tests; the readers take a SysFs.
import { posix } from "node:path";
import type { SysFs } from "./hardware";
const { join } = posix;
export type HwmonReading = { energyUj: number | null; powerW: number | null; tempC: number | null };
const num = (s: string | null) => (s != null && /^-?\d+$/.test(s.trim()) ? Number(s.trim()) : null);
/**
* Power and temperature from the device's hwmon: an energy counter (µJ, xe: energy1_input) when there
* is one, else a power reading (µW, amdgpu: power1_average); the "pkg"/"edge" temperature, else the
* highest one.
*/
export async function readHwmon(fs: SysFs, pciAddress: string): Promise<HwmonReading> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const dirs = (await fs.list(join(dev, "hwmon"))).filter((d) => d.startsWith("hwmon"));
const out: HwmonReading = { energyUj: null, powerW: null, tempC: null };
for (const d of dirs) {
const h = join(dev, "hwmon", d);
const files = await fs.list(h);
const energy = files.filter((f) => /^energy\d+_input$/.test(f)).sort()[0];
if (energy && out.energyUj == null) out.energyUj = num(await fs.read(join(h, energy)));
for (const f of ["power1_average", "power1_input"]) {
if (out.powerW != null || !files.includes(f)) continue;
const uw = num(await fs.read(join(h, f)));
if (uw != null) out.powerW = uw / 1e6;
}
const temps: { label: string; c: number }[] = [];
for (const f of files.filter((x) => /^temp\d+_input$/.test(x))) {
const v = num(await fs.read(join(h, f)));
if (v == null || v <= 0) continue;
const label = (await fs.read(join(h, f.replace("_input", "_label")))) ?? "";
temps.push({ label: label.toLowerCase(), c: v / 1000 });
}
const main = temps.find((t) => t.label === "pkg" || t.label === "edge") ?? temps.sort((a, b) => b.c - a.c)[0];
if (main && out.tempC == null) out.tempC = main.c;
}
return out;
}
/** amdgpu's own whole-GPU figures. */
export async function readAmdUsage(fs: SysFs, pciAddress: string): Promise<{ vramUsedMb: number | null; util: number | null }> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const used = num(await fs.read(join(dev, "mem_info_vram_used")));
const busy = num(await fs.read(join(dev, "gpu_busy_percent")));
return { vramUsedMb: used != null ? Math.round(used / 2 ** 20) : null, util: busy };
}
/** Power between two readings: from the energy counter if both have one, else the instant reading. */
export function powerBetween(prev: HwmonReading | null, cur: HwmonReading, seconds: number): number | null {
if (prev?.energyUj != null && cur.energyUj != null && cur.energyUj >= prev.energyUj && seconds > 0) return (cur.energyUj - prev.energyUj) / 1e6 / seconds;
return cur.powerW;
}
// --- DRM fdinfo ---------------------------------------------------------------------------------
export type DrmClient = {
pdev: string;
clientId: string;
/** Bytes resident in device memory (regions named vram* / local*). */
vramBytes: number;
/** Per engine class: busy cycles and the GPU's total cycles (xe), or busy nanoseconds (i915, amdgpu). */
cycles: Record<string, number>;
totalCycles: Record<string, number>;
ns: Record<string, number>;
};
const UNIT: Record<string, number> = { "": 1, KiB: 1024, MiB: 2 ** 20, GiB: 2 ** 30 };
/** One /proc/<pid>/fdinfo/<fd> of a DRM client; null for other files. */
export function parseFdinfo(text: string): DrmClient | null {
const kv = new Map<string, string>();
for (const line of text.split("\n")) {
const i = line.indexOf(":");
if (i > 0) kv.set(line.slice(0, i).trim(), line.slice(i + 1).trim());
}
const pdev = kv.get("drm-pdev");
const clientId = kv.get("drm-client-id");
if (!pdev || !clientId) return null;
const c: DrmClient = { pdev: pdev.toLowerCase(), clientId, vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} };
// Resident is what occupies VRAM now; older drivers only report total or the legacy drm-memory-*.
const mem: Record<"resident" | "total" | "memory", number> = { resident: 0, total: 0, memory: 0 };
const seen = { resident: false, total: false, memory: false };
for (const [k, v] of kv) {
let m = k.match(/^drm-(resident|total|memory)-(.+)$/);
if (m && /vram|local/i.test(m[2])) {
const [, n, unit = ""] = v.match(/^(\d+)\s*(KiB|MiB|GiB)?$/) ?? [];
if (n == null) continue;
const kind = m[1] as keyof typeof mem;
mem[kind] += Number(n) * (UNIT[unit] ?? 1);
seen[kind] = true;
continue;
}
if ((m = k.match(/^drm-total-cycles-(.+)$/))) c.totalCycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-cycles-(.+)$/))) c.cycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-engine-(.+)$/)) && !k.startsWith("drm-engine-capacity-")) c.ns[m[1]] = Number(v.replace(/\s*ns$/, "")) || 0;
}
c.vramBytes = seen.resident ? mem.resident : seen.total ? mem.total : mem.memory;
return c;
}
export type DrmSnapshot = { t: number; gpus: Record<string, { vramBytes: number; cycles: Record<string, number>; totalCycles: Record<string, number>; ns: Record<string, number> }> };
/**
* Sum the clients per GPU. One client shows up once per open file descriptor (and process), so
* duplicates by client id are counted once. The GPU's total cycles are a clock, not a sum: max.
*/
export function aggregateFdinfo(t: number, texts: string[]): DrmSnapshot {
const seen = new Set<string>();
const gpus: DrmSnapshot["gpus"] = {};
for (const text of texts) {
const c = parseFdinfo(text);
if (!c || seen.has(`${c.pdev}#${c.clientId}`)) continue;
seen.add(`${c.pdev}#${c.clientId}`);
const g = (gpus[c.pdev] ??= { vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} });
g.vramBytes += c.vramBytes;
for (const [k, v] of Object.entries(c.cycles)) g.cycles[k] = (g.cycles[k] ?? 0) + v;
for (const [k, v] of Object.entries(c.totalCycles)) g.totalCycles[k] = Math.max(g.totalCycles[k] ?? 0, v);
for (const [k, v] of Object.entries(c.ns)) g.ns[k] = (g.ns[k] ?? 0) + v;
}
return { t, gpus };
}
/**
* Busy percent of the busiest engine class between two snapshots (like intel_gpu_top's headline).
* Clients that exit in between make a sum drop; those classes count as idle rather than negative.
*/
export function drmUtilization(prev: DrmSnapshot["gpus"][string] | undefined, cur: DrmSnapshot["gpus"][string], seconds: number): number | null {
if (!prev || seconds <= 0) return null;
const busy: number[] = [];
for (const cls of Object.keys(cur.cycles)) {
const dc = cur.cycles[cls] - (prev.cycles[cls] ?? 0);
const dt = (cur.totalCycles[cls] ?? 0) - (prev.totalCycles[cls] ?? 0);
if (dt > 0) busy.push(Math.max(0, dc) / dt);
}
for (const cls of Object.keys(cur.ns)) busy.push(Math.max(0, cur.ns[cls] - (prev.ns[cls] ?? 0)) / (seconds * 1e9));
if (busy.length === 0) return null;
return Math.min(100, Math.max(...busy) * 100);
}
/**
* Runs inside the probe container (Node from Kaname's own image): every interval, the fdinfo of every
* open DRM file on the host, one JSON line. Reads only; prints nothing else.
*/
export const INTEL_PROBE_SCRIPT = `
const fs = require("fs");
const every = Number(process.argv[1]) || 2000;
function tick() {
const f = [];
let pids = [];
try { pids = fs.readdirSync("/proc").filter((p) => /^\\d+$/.test(p)); } catch {}
for (const p of pids) {
let fds = [];
try { fds = fs.readdirSync("/proc/" + p + "/fdinfo"); } catch { continue; }
for (const d of fds) {
try {
const t = fs.readFileSync("/proc/" + p + "/fdinfo/" + d, "utf8");
if (t.includes("drm-client-id:")) f.push(t);
} catch {}
}
}
process.stdout.write(JSON.stringify({ t: Date.now(), f }) + "\\n");
}
tick();
setInterval(tick, every);
`;
-284
View File
@@ -1,284 +0,0 @@
import assert from "node:assert/strict";
import { before, describe, it } from "node:test";
import { fetchEngineInfo, parseLlamaProps, parseVllm, versionFromLog } from "./engine-info";
import { currentLinks, detectHardware, gpuDisplayName, type SysFs, largestBarMb, mountDevice, normalizePciAddress, parseCpu, parseP2p, pciName } from "./hardware";
import { fastestLinks, parseGpuLine, summarizeSamples } from "./resources";
import { parseNvidiaSmi, repoDigest } from "./runtimes";
const GiB = 2 ** 30;
const hex = (n: number) => `0x${n.toString(16).padStart(16, "0")}`;
/** A `resource` line: start, end, flags (0x0014220c = 64-bit prefetchable memory). */
const bar = (start: number, size: number) => `${hex(start)} ${hex(start + size - 1)} 0x000000000014220c`;
const EMPTY = `${hex(0)} ${hex(0)} 0x0000000000000000`;
const PCI_IDS = `# test pci.ids
10de NVIDIA Corporation
\t2684 AD102 [GeForce RTX 4090]
8086 Intel Corporation
\te211 Battlemage G31 [Arc Pro B65]
\t\t8086 1234 Arc Pro B65 32GB
\te20b Battlemage G21 [Arc B580]
1af4 Red Hat, Inc.
`;
const CPUINFO = [0, 1, 2, 3]
.map((p) => `processor\t: ${p}\nmodel name\t: AMD EPYC 9124 16-Core Processor\nphysical id\t: 0\ncore id\t\t: ${p % 2}\nflags\t\t: fpu avx2 hypervisor\n`)
.join("\n");
const files = new Map<string, string>();
const links = new Map<string, string>();
/** An in-memory sysfs: files plus directory symlinks (sysfs names contain ":", which Windows can't store). */
function memFs(): SysFs {
const resolve = (p: string): string => {
for (let i = 0; i < 10; i++) {
const hit = [...links.keys()].find((l) => p === l || p.startsWith(`${l}/`));
if (!hit) return p;
p = links.get(hit)! + p.slice(hit.length);
}
return p;
};
return {
read: async (p) => files.get(resolve(p))?.trim() ?? null,
resolve: async (p) => resolve(p),
list: async (d) => {
const dir = `${resolve(d)}/`;
const names = [...files.keys(), ...links.keys()].filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]);
return [...new Set(names)];
},
};
}
const file = (path: string, content: string) => files.set(`/${path}`, content);
const link = (path: string, target: string) => links.set(`/${path}`, `/${target}`);
before(() => {
// Intel Arc Pro B65: root port 00:01.0 → on-card switch (01:00.0 up, 02:01.0 down) → GPU 03:00.0.
const rp = "sys/devices/pci0000:00/0000:00:01.0";
const up = `${rp}/0000:01:00.0`;
const down = `${up}/0000:02:01.0`;
const gpu = `${down}/0000:03:00.0`;
file(`${rp}/vendor`, "0x1022");
file(`${up}/vendor`, "0x8086");
file(`${up}/current_link_speed`, "16.0 GT/s PCIe");
file(`${up}/current_link_width`, "8");
file(`${up}/max_link_speed`, "32.0 GT/s PCIe");
file(`${up}/max_link_width`, "16");
file(`${down}/vendor`, "0x8086");
file(`${gpu}/vendor`, "0x8086");
file(`${gpu}/device`, "0xe211");
file(`${gpu}/subsystem_vendor`, "0x8086");
file(`${gpu}/subsystem_device`, "0x1234");
file(`${gpu}/class`, "0x030000");
file(`${gpu}/uevent`, "DRIVER=xe\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:03:00.0");
// What the GPU function itself reports: the switch-internal link.
file(`${gpu}/current_link_speed`, "2.5 GT/s PCIe");
file(`${gpu}/current_link_width`, "1");
file(`${gpu}/resource`, [bar(0xa0000000, 16 * 2 ** 20), EMPTY, bar(0x4000000000, 32 * GiB)].join("\n"));
file(`${gpu}/tile0/physical_vram_size_bytes`, String(32 * GiB));
link("sys/bus/pci/devices/0000:03:00.0", gpu);
// NVIDIA card directly on a root port, 256 MiB BAR (no ReBAR).
const nv = "sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0";
file("sys/devices/pci0000:00/0000:00:03.0/vendor", "0x1022");
file(`${nv}/vendor`, "0x10de");
file(`${nv}/device`, "0x2684");
file(`${nv}/class`, "0x030000");
file(`${nv}/uevent`, "DRIVER=nvidia");
file(`${nv}/current_link_speed`, "16.0 GT/s PCIe");
file(`${nv}/current_link_width`, "16");
file(`${nv}/max_link_speed`, "16.0 GT/s PCIe");
file(`${nv}/max_link_width`, "16");
file(`${nv}/resource`, [bar(0xb0000000, 16 * 2 ** 20), bar(0x6000000000, 256 * 2 ** 20)].join("\n"));
link("sys/bus/pci/devices/0000:05:00.0", nv);
file("sys/module/nvidia/version", "580.82.07");
// A virtio NIC: not a GPU.
file("sys/devices/pci0000:00/0000:00:12.0/vendor", "0x1af4");
file("sys/devices/pci0000:00/0000:00:12.0/class", "0x020000");
link("sys/bus/pci/devices/0000:00:12.0", "sys/devices/pci0000:00/0000:00:12.0");
file("usr/share/misc/pci.ids", PCI_IDS);
file("proc/cpuinfo", CPUINFO);
file("proc/meminfo", "MemTotal: 65536000 kB\nMemFree: 1 kB\n");
file("sys/class/dmi/id/sys_vendor", "QEMU");
file("sys/class/dmi/id/product_name", "Standard PC (Q35 + ICH9, 2009)");
// Models on /dev/nvme0n1p2 (259:2).
file("proc/self/mountinfo", ["22 1 259:1 / / rw - ext4 /dev/nvme0n1p1 rw", "1521 1471 259:2 /srv/models /models rw,relatime - ext4 /dev/nvme0n1p2 rw"].join("\n"));
const disk = "sys/devices/pci0000:00/0000:00:06.0/nvme/nvme0/nvme0n1";
file(`${disk}/device/model`, "Samsung SSD 990 PRO 2TB ");
file(`${disk}/queue/rotational`, "0");
file(`${disk}/size`, String(3_907_029_168));
file(`${disk}/nvme0n1p2/partition`, "2");
link("sys/dev/block/259:2", `${disk}/nvme0n1p2`);
});
describe("hardware detection (sysfs fixture)", () => {
it("finds GPUs, the card's upstream link behind an on-card switch, ReBAR and names", async () => {
const hw = await detectHardware({
fs: memFs(),
modelsDir: "/models",
kernel: "6.17.1-pve",
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 4090", memoryMb: 24564, driver: "580.82.07", pciAddress: "00000000:05:00.0" }],
});
assert.equal(hw.gpus.length, 2);
const [intel, nv] = hw.gpus;
assert.deepEqual(
{ ...intel },
{
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65 32GB",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1-pve",
linkCurrent: { gen: 4, width: 8 },
linkMax: { gen: 5, width: 16 },
barMb: 32768,
rebar: true,
},
);
assert.equal(nv.name, "NVIDIA GeForce RTX 4090");
assert.equal(nv.vramMb, 24564);
assert.equal(nv.driverVersion, "580.82.07");
assert.deepEqual(nv.linkCurrent, { gen: 4, width: 16 });
assert.equal(nv.barMb, 256);
assert.equal(nv.rebar, false);
assert.equal(hw.p2p, null);
});
it("reads CPU, RAM, VM and the models disk", async () => {
const hw = await detectHardware({ fs: memFs(), modelsDir: "/models/", kernel: "6.17.1-pve" });
assert.deepEqual(hw.cpu, { model: "AMD EPYC 9124 16-Core Processor", cores: 2, threads: 4 });
assert.equal(hw.memoryBytes, 65536000 * 1024);
assert.deepEqual(hw.virtualization, { vm: true, hypervisor: "KVM/QEMU" });
assert.deepEqual(hw.storage, { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 3_907_029_168 * 512 });
});
it("doesn't fail on a host without any of it", async () => {
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
const hw = await detectHardware({ fs: empty, modelsDir: "/models", kernel: null });
assert.deepEqual(hw.gpus, []);
assert.equal(hw.storage, null);
assert.deepEqual(hw.cpu, { model: null, cores: null, threads: null });
assert.deepEqual(hw.virtualization, { vm: null, hypervisor: null });
});
});
describe("hardware parsers", () => {
it("normalizes nvidia-smi bus IDs and reads them from the probe CSV", () => {
assert.equal(normalizePciAddress("00000000:0A:00.0"), "0000:0a:00.0");
assert.deepEqual(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07, 00000000:01:00.0")[0].pciAddress, "0000:01:00.0");
assert.equal(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07")[0].pciAddress, null);
});
it("takes the largest memory BAR", () => {
assert.equal(largestBarMb([bar(0x1000, 2 ** 20), bar(0x100000000, 8 * GiB), "0x0000000000001000 0x000000000000107f 0x0000000000040101"].join("\n")), 8192);
assert.equal(largestBarMb(EMPTY), null);
assert.equal(largestBarMb(null), null);
});
it("names GPUs from pci.ids, board name first", () => {
assert.equal(pciName(PCI_IDS, "0x8086", "0xe20b"), "Battlemage G21 [Arc B580]");
assert.equal(pciName(PCI_IDS, "0x8086", "0xe211", "0x8086", "0x1234"), "Arc Pro B65 32GB");
assert.equal(pciName(PCI_IDS, "0x8086", "0xffff"), null);
assert.equal(gpuDisplayName("intel", "Battlemage G21 [Arc B580]"), "Intel Arc B580");
assert.equal(gpuDisplayName("nvidia", "AD102 [GeForce RTX 4090]"), "NVIDIA GeForce RTX 4090");
});
it("reads nvidia-smi's P2P matrix", () => {
const m = (cells: string) => `\tGPU0\tGPU1\n GPU0\tX\t${cells}\n GPU1\t${cells}\tX\n\nLegend:\n X = Self\n OK = Status Ok`;
assert.equal(parseP2p(m("OK")), "on");
assert.equal(parseP2p(m("CNS")), "off");
assert.equal(parseP2p("\tGPU0\tGPU1\tGPU2\n GPU0\tX\tOK\tNS\n GPU1\tOK\tX\tNS\n GPU2\tNS\tNS\tX"), "partial");
assert.equal(parseP2p("garbage"), null);
});
it("counts cores per socket and sees the hypervisor flag", () => {
const c = parseCpu(CPUINFO);
assert.equal(c.cores, 2);
assert.equal(c.threads, 4);
assert.ok(c.hypervisor);
assert.equal(parseCpu(null).model, null);
});
it("finds the mount holding a folder", () => {
const mi = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n2 1 8:16 / /models rw - ext4 /dev/sdb rw\n3 1 8:32 / /models-old rw - ext4 /dev/sdc rw";
assert.equal(mountDevice(mi, "/models"), "8:16");
assert.equal(mountDevice(mi, "/models/unsloth"), "8:16");
assert.equal(mountDevice(mi, "/models-old"), "8:32");
assert.equal(mountDevice(mi, "/data"), "8:1");
});
it("picks the digest of the image's own repository", () => {
assert.equal(repoDigest("ghcr.io/ggml-org/llama.cpp:server", ["ghcr.io/ggml-org/llama.cpp@sha256:aaa", "mirror.local/llama.cpp@sha256:bbb"]), "sha256:aaa");
assert.equal(repoDigest("vllm/vllm-openai:v0.31.0", ["vllm/vllm-openai@sha256:ccc"]), "sha256:ccc");
assert.equal(repoDigest("local:dev", []), null);
});
});
describe("engine info", () => {
it("reads llama-server /props (build 11429)", () => {
assert.deepEqual(parseLlamaProps({ build_info: "b11429-d81235049", total_slots: 4, default_generation_settings: { n_ctx: 4096 } }), {
version: "b11429-d81235049",
slots: 4,
contextSize: 4096,
});
assert.deepEqual(parseLlamaProps(null), { version: null, slots: null, contextSize: null });
});
it("reads vLLM /version and /v1/models", () => {
assert.deepEqual(parseVllm({ version: "0.5.7" }, { data: [{ id: "x", max_model_len: 32768 }] }), { version: "0.5.7", slots: null, contextSize: 32768 });
});
it("falls back to startup log lines", () => {
assert.equal(versionFromLog("llama.cpp", ["main: build: 11429 (d8123504) with gcc"]), "b11429-d8123504");
assert.equal(versionFromLog("vllm", ["INFO 10-20 api_server.py:1 vLLM API server version 0.31.0"]), "0.31.0");
assert.equal(versionFromLog("vllm", ["nothing here"]), null);
});
it("returns nulls when the server can't be reached", async () => {
const info = await fetchEngineInfo("llama.cpp", "http://127.0.0.1:9", null);
assert.deepEqual(info, { version: null, slots: null, contextSize: null });
});
});
describe("PCIe link under load", () => {
it("reads each card's current link from sysfs", async () => {
assert.deepEqual(await currentLinks(memFs(), ["0000:03:00.0", "0000:05:00.0", "0000:09:00.0"]), {
"0000:03:00.0": { gen: 4, width: 8 },
"0000:05:00.0": { gen: 4, width: 16 },
});
});
it("keeps the fastest link seen and reads nvidia-smi's link columns", () => {
const l = (gen: number, width: number) => ({ gen, width });
assert.deepEqual(
fastestLinks([
{ pciAddress: "a", link: l(1, 16) },
{ pciAddress: "a", link: l(4, 16) },
{ pciAddress: "a", link: l(4, 8) },
{ pciAddress: "b", link: l(3, 4) },
]),
{ a: l(4, 16), b: l(3, 4) },
);
assert.deepEqual(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16")?.link, l(4, 16));
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5")?.link, null);
const stats = summarizeSamples([], [], 10, [{ pciAddress: "a", link: l(1, 16) }, { pciAddress: "a", link: l(4, 16) }]);
assert.deepEqual(stats.links, { a: l(4, 16) });
});
it("lists NVIDIA GPUs that aren't on the visible PCI bus (WSL2), with nvidia-smi's link", async () => {
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
const hw = await detectHardware({
fs: empty,
modelsDir: "/models",
kernel: null,
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14", pciAddress: "00000000:01:00.0", linkMax: { gen: 4, width: 16 } }],
});
assert.equal(hw.gpus.length, 1);
assert.equal(hw.gpus[0].pciAddress, "0000:01:00.0");
assert.deepEqual(hw.gpus[0].linkMax, { gen: 4, width: 16 });
assert.equal(hw.gpus[0].rebar, null);
});
});
-316
View File
@@ -1,316 +0,0 @@
// Host hardware from sysfs and procfs, which a container sees unprivileged: GPUs on the PCI bus with
// their PCIe link and BAR size (for Resizable BAR), CPU, RAM, kernel, virtualization and the disk
// holding the models folder. Root-only sources (lspci's extended capabilities, DMI serials) and host
// tools (systemd-detect-virt) aren't available in the worker, so this reads the same facts from files.
// Everything reads through a SysFs, so tests run against an in-memory tree.
import { readdir, readFile, realpath } from "node:fs/promises";
import { release } from "node:os";
import { posix } from "node:path";
import type { GpuVendor, HardwareGpu, HostGpu, HostHardware, PcieLink } from "@/lib/db/schema";
import { linkGen, rebarFrom } from "@/lib/hardware";
const VENDORS: Record<string, GpuVendor> = { "0x10de": "nvidia", "0x8086": "intel", "0x1002": "amd" };
const VENDOR_LABEL: Record<GpuVendor, string> = { nvidia: "NVIDIA", intel: "Intel", amd: "AMD" };
const PCI_ADDR = /^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i;
const PCI_IDS = ["/usr/share/misc/pci.ids", "/usr/share/hwdata/pci.ids"];
/** Where drivers report total VRAM, if they do (amdgpu; xe/i915 vary by kernel). */
const VRAM_FILES = ["mem_info_vram_total", "tile0/physical_vram_size_bytes", "lmem_total_bytes"];
const IORESOURCE_MEM = BigInt(0x200);
const ZERO = BigInt(0);
const MIB = BigInt(2 ** 20);
const { basename, dirname, join } = posix;
/** The few file operations detection needs (absolute POSIX paths). */
export type SysFs = {
/** Trimmed file content, or null when it can't be read. */
read(path: string): Promise<string | null>;
list(dir: string): Promise<string[]>;
/** Symlinks resolved (sysfs device links); the path itself when it isn't one. */
resolve(path: string): Promise<string>;
};
export const nodeFs: SysFs = {
read: (p) => readFile(p, "utf8").then((t) => t.trim(), () => null),
list: (d) => readdir(d).catch(() => []),
resolve: (p) => realpath(p).catch(() => p),
};
const num = (s: string | null) => (s != null && /^\d+$/.test(s) ? Number(s) : null);
/** nvidia-smi's "00000000:01:00.0" → sysfs "0000:01:00.0". */
export function normalizePciAddress(id: string): string {
const [domain, ...rest] = id.trim().toLowerCase().split(":");
return [domain.slice(-4).padStart(4, "0"), ...rest].join(":");
}
/** Largest memory BAR in MiB, from a device's `resource` file ("start end flags" per line). */
export function largestBarMb(resource: string | null): number | null {
if (!resource) return null;
let max = ZERO;
for (const line of resource.split("\n")) {
const [start, end, flags] = line.trim().split(/\s+/).map((x) => {
try {
return BigInt(x);
} catch {
return ZERO;
}
});
if (!end || !(flags & IORESOURCE_MEM)) continue;
const size = end - start + BigInt(1);
if (size > max) max = size;
}
return max > ZERO ? Number(max / MIB) : null;
}
/**
* The card's own upstream link: cards like Intel's Arc B-series sit behind an on-card PCIe switch,
* whose internal link is what the GPU function reports. Walk up while the parent belongs to the same
* vendor and isn't the root port.
*/
async function cardUpstream(fs: SysFs, dev: string, vendor: string): Promise<string> {
let cur = dev;
for (;;) {
const parent = dirname(cur);
if (!PCI_ADDR.test(basename(parent)) || !PCI_ADDR.test(basename(dirname(parent)))) return cur;
if ((await fs.read(join(parent, "vendor"))) !== vendor) return cur;
cur = parent;
}
}
async function link(fs: SysFs, dir: string, kind: "current" | "max") {
const gen = linkGen(await fs.read(join(dir, `${kind}_link_speed`)));
const width = num(await fs.read(join(dir, `${kind}_link_width`)));
return gen == null && width == null ? null : { gen, width };
}
const pciIds = new WeakMap<SysFs, Promise<string | null>>();
async function pciIdsText(fs: SysFs): Promise<string | null> {
if (!pciIds.has(fs)) {
pciIds.set(
fs,
(async () => {
for (const p of PCI_IDS) {
const text = await fs.read(p);
if (text) return text;
}
return null;
})(),
);
}
return pciIds.get(fs)!;
}
/** Name from pci.ids: the subsystem's (board) name if listed, else the chip's; "[Arc B580]" preferred. */
export function pciName(ids: string, vendor: string, device: string, subVendor?: string | null, subDevice?: string | null): string | null {
const v = vendor.replace(/^0x/, "").toLowerCase();
const d = device.replace(/^0x/, "").toLowerCase();
const sub = subVendor && subDevice ? `${subVendor.replace(/^0x/, "")} ${subDevice.replace(/^0x/, "")}`.toLowerCase() : null;
const lines = ids.split("\n");
let i = lines.findIndex((l) => l.startsWith(`${v} `));
if (i < 0) return null;
let chip: string | null = null;
for (i++; i < lines.length && (lines[i].startsWith("\t") || lines[i].startsWith("#") || !lines[i].trim()); i++) {
const l = lines[i];
if (!l.startsWith("\t\t") && l.startsWith("\t")) {
if (chip) break;
if (l.slice(1, 5).toLowerCase() === d) chip = l.slice(7).trim();
} else if (chip && sub && l.startsWith("\t\t") && l.slice(2, 11).toLowerCase() === sub) {
return l.slice(13).trim();
}
}
return chip;
}
/** "AD102 [GeForce RTX 4090]" → "NVIDIA GeForce RTX 4090". */
export function gpuDisplayName(vendor: GpuVendor, pciIdsName: string | null): string | null {
if (!pciIdsName) return null;
const bracket = pciIdsName.match(/\[([^\]]+)\]/)?.[1];
const name = bracket ?? pciIdsName;
const label = VENDOR_LABEL[vendor];
return name.toLowerCase().startsWith(label.toLowerCase()) ? name : `${label} ${name}`;
}
function uevent(text: string | null): Record<string, string> {
return Object.fromEntries((text ?? "").split("\n").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
}
/** Display controllers (class 0x03…) from NVIDIA, Intel and AMD. NVIDIA names/VRAM come from nvidia-smi. */
export async function detectGpus(fs: SysFs, nvidia: HostGpu[], kernel: string | null): Promise<HardwareGpu[]> {
const base = "/sys/bus/pci/devices";
const addrs = (await fs.list(base)).filter((a) => PCI_ADDR.test(a)).sort();
const out: HardwareGpu[] = [];
for (const addr of addrs) {
const dev = await fs.resolve(join(base, addr));
const [cls, vendorId] = await Promise.all([fs.read(join(dev, "class")), fs.read(join(dev, "vendor"))]);
const vendor = vendorId ? VENDORS[vendorId.toLowerCase()] : undefined;
if (!cls?.startsWith("0x03") || !vendor) continue;
const ev = uevent(await fs.read(join(dev, "uevent")));
const driver = ev.DRIVER || null;
const up = await cardUpstream(fs, dev, vendorId!.toLowerCase());
const nv = nvidia.find((g) => g.pciAddress && normalizePciAddress(g.pciAddress) === addr.toLowerCase());
let vramMb: number | null = nv?.memoryMb ?? null;
for (const f of VRAM_FILES) {
if (vramMb) break;
const bytes = num(await fs.read(join(dev, f)));
if (bytes) vramMb = Math.round(bytes / 2 ** 20);
}
const ids = await pciIdsText(fs);
const [device, subVendor, subDevice] = await Promise.all(["device", "subsystem_vendor", "subsystem_device"].map((f) => fs.read(join(dev, f))));
const barMb = largestBarMb(await fs.read(join(dev, "resource")));
const moduleVersion = driver ? await fs.read(join("/sys/module", driver, "version")) : null;
out.push({
vendor,
pciAddress: addr.toLowerCase(),
name: nv?.name ?? (ids && device ? gpuDisplayName(vendor, pciName(ids, vendorId!, device, subVendor, subDevice)) : null),
vramMb,
driver,
driverVersion: nv?.driver ?? moduleVersion ?? (driver && kernel ? `kernel ${kernel}` : null),
linkCurrent: (await link(fs, up, "current")) ?? nv?.linkCurrent ?? null,
linkMax: (await link(fs, up, "max")) ?? nv?.linkMax ?? null,
barMb,
rebar: rebarFrom(barMb, vramMb),
});
}
// NVIDIA GPUs that aren't on the visible PCI bus (WSL2 passes them through its own driver).
for (const g of nvidia) {
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
if (out.some((o) => o.pciAddress === addr)) continue;
out.push({
vendor: "nvidia",
pciAddress: addr,
name: g.name,
vramMb: g.memoryMb || null,
driver: "nvidia",
driverVersion: g.driver || null,
linkCurrent: g.linkCurrent ?? null,
linkMax: g.linkMax ?? null,
barMb: null,
rebar: null,
});
}
return out;
}
/** The current link of each GPU's card (upstream port), for sampling during a run; skips unknown ones. */
export async function currentLinks(fs: SysFs, pciAddresses: string[]): Promise<Record<string, PcieLink>> {
const out: Record<string, PcieLink> = {};
for (const addr of pciAddresses) {
const dev = await fs.resolve(join("/sys/bus/pci/devices", addr));
const vendor = await fs.read(join(dev, "vendor"));
if (!vendor) continue;
const l = await link(fs, await cardUpstream(fs, dev, vendor.toLowerCase()), "current");
if (l) out[addr] = l;
}
return out;
}
/** `nvidia-smi topo -p2p r`: "OK" between every pair → on, none → off. */
export function parseP2p(text: string): "on" | "off" | "partial" | null {
const cells = text
.split("\n")
.filter((l) => /^\s*GPU\d+\s/.test(l))
.flatMap((l) => l.trim().split(/\s+/).slice(1))
.filter((c) => c !== "X" && !/^GPU\d+$/.test(c));
if (cells.length === 0) return null;
const ok = cells.filter((c) => c === "OK").length;
return ok === cells.length ? "on" : ok === 0 ? "off" : "partial";
}
export function parseCpu(cpuinfo: string | null): HostHardware["cpu"] & { hypervisor: boolean } {
if (!cpuinfo) return { model: null, cores: null, threads: null, hypervisor: false };
const blocks = cpuinfo.split(/\n\s*\n/).filter((b) => /^processor\s*:/m.test(b));
const field = (b: string, k: string) => b.match(new RegExp(`^${k}\\s*:\\s*(.*)$`, "m"))?.[1]?.trim() ?? null;
const cores = new Set(blocks.map((b) => `${field(b, "physical id") ?? 0}:${field(b, "core id") ?? field(b, "processor")}`));
return {
model: blocks[0] ? field(blocks[0], "model name") : null,
cores: blocks.length ? cores.size : null,
threads: blocks.length || null,
hypervisor: blocks[0] ? /\bhypervisor\b/.test(field(blocks[0], "flags") ?? "") : false,
};
}
const HYPERVISORS: [RegExp, string][] = [
[/^QEMU|KVM/i, "KVM/QEMU"],
[/Microsoft/i, "Hyper-V"],
[/VMware/i, "VMware"],
[/Xen/i, "Xen"],
[/innotek|VirtualBox/i, "VirtualBox"],
[/Amazon/i, "AWS"],
[/Google/i, "Google Cloud"],
];
/** VM or bare metal, from the CPU's hypervisor flag and the DMI vendor (both readable unprivileged). */
export async function detectVirtualization(fs: SysFs, hypervisorFlag: boolean, kernel: string | null): Promise<HostHardware["virtualization"]> {
const dmi = [await fs.read("/sys/class/dmi/id/sys_vendor"), await fs.read("/sys/class/dmi/id/product_name")].filter(Boolean).join(" ");
if (kernel && /microsoft.*wsl/i.test(kernel)) return { vm: true, hypervisor: "WSL2 (Hyper-V)" };
const known = HYPERVISORS.find(([re]) => re.test(dmi))?.[1] ?? null;
if (hypervisorFlag || known) return { vm: true, hypervisor: known };
return { vm: dmi ? false : null, hypervisor: null };
}
/** The mount holding `dir` (longest mount point that is a prefix), as "major:minor". */
export function mountDevice(mountinfo: string, dir: string): string | null {
const target = posix.normalize(dir.replace(/\\/g, "/")).replace(/(.)\/$/, "$1");
let best: { point: string; dev: string } | null = null;
for (const line of mountinfo.split("\n")) {
const f = line.split(" ");
if (f.length < 5) continue;
const point = f[4].replace(/\\040/g, " ");
const inside = target === point || target.startsWith(point.endsWith("/") ? point : `${point}/`);
if (inside && (!best || point.length > best.point.length)) best = { point, dev: f[2] };
}
return best?.dev ?? null;
}
/** The disk behind a block device: partitions → their disk, device-mapper (LVM, LUKS) → first slave. */
async function diskOf(fs: SysFs, devDir: string, depth = 0): Promise<string | null> {
if (depth > 4) return null;
if (await fs.read(join(devDir, "partition"))) return dirname(devDir);
if (basename(devDir).startsWith("dm-") || basename(devDir).startsWith("md")) {
const slaves = await fs.list(join(devDir, "slaves"));
if (!slaves[0]) return devDir;
return diskOf(fs, await fs.resolve(join("/sys/class/block", slaves[0])), depth + 1);
}
return devDir;
}
export async function detectStorage(fs: SysFs, modelsDir: string): Promise<HostHardware["storage"]> {
const mountinfo = await fs.read("/proc/self/mountinfo");
const dev = mountinfo ? mountDevice(mountinfo, modelsDir) : null;
if (!dev || dev.startsWith("0:")) return null; // ZFS, overlay, network filesystems: no block device
const blockDir = join("/sys/dev/block", dev);
if ((await fs.list(blockDir)).length === 0) return null;
const disk = await diskOf(fs, await fs.resolve(blockDir));
if (!disk) return null;
const name = basename(disk);
const model = (await fs.read(join(disk, "device/model")))?.replace(/\s+/g, " ") || null;
const vendor = (await fs.read(join(disk, "device/vendor")))?.trim() ?? "";
const rotational = await fs.read(join(disk, "queue/rotational"));
const sectors = num(await fs.read(join(disk, "size")));
const virtual = /^vd|^xvd/.test(name) || vendor === "0x1af4" || /QEMU|Virtual Disk|VBOX|VMware/i.test(`${vendor} ${model ?? ""}`);
return {
model: model ?? (virtual ? "virtio disk" : null),
kind: virtual ? "virtual" : name.startsWith("nvme") ? "nvme" : rotational === "1" ? "hdd" : rotational === "0" ? "ssd" : null,
sizeBytes: sectors != null ? sectors * 512 : null,
};
}
export async function detectHardware(o: { fs?: SysFs; modelsDir: string; nvidia?: HostGpu[]; p2p?: HostHardware["p2p"]; kernel?: string | null }): Promise<HostHardware> {
const fs = o.fs ?? nodeFs;
const kernel = o.kernel !== undefined ? o.kernel : release();
const cpu = parseCpu(await fs.read("/proc/cpuinfo"));
const memKb = Number((await fs.read("/proc/meminfo"))?.match(/^MemTotal:\s+(\d+)\s*kB/m)?.[1]);
const gpus = await detectGpus(fs, o.nvidia ?? [], kernel);
return {
gpus,
p2p: gpus.length >= 2 ? (o.p2p ?? null) : null,
cpu: { model: cpu.model, cores: cpu.cores, threads: cpu.threads },
memoryBytes: Number.isFinite(memKb) && memKb > 0 ? memKb * 1024 : null,
kernel,
virtualization: await detectVirtualization(fs, cpu.hypervisor, kernel),
storage: await detectStorage(fs, o.modelsDir).catch(() => null),
checkedAt: new Date().toISOString(),
};
}
+2 -29
View File
@@ -14,12 +14,9 @@ import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks";
import { reportL80Status, tickPublications } from "./publish";
import { tickSweeps } from "./sweeps";
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
import { DownloadRunner } from "./download";
import { log } from "./log";
import type { Runner } from "./runner";
import { docker, handlePullRequests, refreshDockerInfo, resetStalePulls, seedRuntimePresets, syncImageStates } from "./runtimes";
import { scanModelsDir } from "./scan";
import { VerifyRunner } from "./verify";
import { settleModelStatus } from "./model-status";
@@ -33,10 +30,7 @@ const SHUTDOWN_GRACE_MS = 8_000;
const HUB_CHECK_SCAN_MS = 10 * 60_000;
/** How often MODELS_DIR is scanned for folders that could be imported (plus on request). */
const FOLDER_SCAN_MS = 2 * 60_000;
const DOCKER_INFO_MS = 5 * 60_000;
const IMAGE_SYNC_MS = 60_000;
const PULL_CHECK_MS = 3_000;
const DEPLOYMENT_TICK_MS = 2_000;
const LOG_FLUSH_INTERVAL_MS = 1_000;
const BENCHMARK_TICK_MS = 2_000;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
@@ -349,9 +343,6 @@ async function shutdown(reason: string, code = 0) {
stopping = true;
log.info(`shutting down (${reason})`);
timers.forEach(clearInterval);
// Deployment containers keep running; the next worker re-attaches to them.
stopFollowingLogs();
await flushDeploymentLogs().catch(() => {});
await stopBenchmarks().catch(() => {});
await flushBenchmarkLogs().catch(() => {});
if (runners.size > 0) {
@@ -393,29 +384,11 @@ async function main() {
timers.push(setInterval(() => void checkHubDue(), HUB_CHECK_SCAN_MS));
timers.push(setInterval(() => void scanFolders(), FOLDER_SCAN_MS));
// Runtimes (Docker): presets, host facts, image states, pulls.
await resetStalePulls();
await seedRuntimePresets().catch((err) => log.error("seeding runtime presets failed", err));
if (docker()) log.info(`Docker API: ${coreEnv().DOCKER_HOST}`);
else log.info("DOCKER_HOST not set; runtimes are disabled");
const dockerInfo = () => refreshDockerInfo(instanceId).catch((err) => log.error("Docker info failed", err));
const imageSync = () => syncImageStates().catch((err) => log.error("image sync failed", err));
await dockerInfo();
void imageSync();
timers.push(setInterval(() => void dockerInfo(), DOCKER_INFO_MS));
timers.push(setInterval(() => void imageSync(), IMAGE_SYNC_MS));
timers.push(setInterval(() => void handlePullRequests().catch((err) => log.error("pull failed", err)), PULL_CHECK_MS));
// Deployments: re-attach to running containers, then keep them in line with the desired state.
await adoptContainers();
timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS));
timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS));
// Benchmarks: one BetterBench run at a time against a running deployment.
// Benchmarks: one run at a time against an endpoint.
await recoverBenchmarks();
void refreshSummaries();
void reportL80Status();
timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void tickSweeps(), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS));
timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS));
void scanFolders();
+2 -3
View File
@@ -1,5 +1,5 @@
// The quality eval against a fake OpenAI-compatible server: requests, scoring, unsupported sections,
// cancelling. (The code sandbox needs Docker; here coding counts as unsupported.)
// cancelling. (Without a sandbox coding counts as unsupported; a fake runner checks the coding path.)
import assert from "node:assert/strict";
import { createServer, type Server } from "node:http";
@@ -55,8 +55,7 @@ const opts = (o: Partial<Parameters<typeof runQualityEval>[1]> = {}) => ({
sections: ["tools", "coding", "retrieval"] as const as ("tools" | "coding" | "retrieval")[],
signal: new AbortController().signal,
log: () => {},
docker: null,
sandboxImage: null,
runCode: "no code sandbox configured (SANDBOX_DIR)" as Parameters<typeof runQualityEval>[1]["runCode"],
...o,
});
+12 -55
View File
@@ -1,9 +1,9 @@
// Runs the quality eval (src/lib/quality.ts) against a running deployment: greedy decoding with a
// fixed seed, thinking turned off where the chat template supports it, scoring that doesn't depend
// on judgement. Coding answers run with their unit tests in a throwaway container from Kaname's own
// image: no network, read-only, unprivileged user, all capabilities dropped, small limits.
// Runs the quality eval (src/lib/quality.ts) against an endpoint: greedy decoding with a fixed seed,
// thinking turned off where the chat template supports it, scoring that doesn't depend on judgement.
// Coding answers run with their unit tests in the code sandbox (src/sandbox): a separate container
// without network, read-only, no capabilities, small limits.
import type { QualityResult, QualitySection, RuntimeEngine } from "@/lib/db/schema";
import type { EndpointEngine, QualityResult, QualitySection } from "@/lib/db/schema";
import {
buildHaystack,
EVAL_SEED,
@@ -18,13 +18,13 @@ import {
type ToolCall,
toolDefs,
} from "@/lib/quality";
import type { DockerClient } from "./docker/client";
import type { CodeRunner } from "./sandbox-client";
export type EvalTarget = {
/** http://<container>:<port> */
/** The server root, e.g. http://gpu-box:8080 */
base: string;
model: string;
engine: RuntimeEngine;
engine: EndpointEngine | null;
apiKey: string | null;
/** Context per request (llama.cpp: per slot), for the retrieval lengths. */
contextTokens: number | null;
@@ -34,9 +34,8 @@ export type EvalOptions = {
sections: QualitySection[];
signal: AbortSignal;
log: (line: string) => void;
docker: DockerClient | null;
/** Image for the coding sandbox (Kaname's own, it has Python); null: coding can't run. */
sandboxImage: string | null;
/** Runs coding answers; a string says why it can't (then coding doesn't count). */
runCode: CodeRunner | string;
};
const TEMPERATURE = 0;
@@ -107,50 +106,8 @@ async function toolsSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promi
return { section: "tools", passed, total: all.length };
}
/** Run a program in the sandbox; ok when it exits 0 and printed the marker. */
async function runPython(c: DockerClient, image: string, program: string, signal: AbortSignal): Promise<{ ok: boolean; output: string }> {
const runner = "import base64,os;exec(compile(base64.b64decode(os.environ['KANAME_CODE']).decode(),'solution','exec'),{'__name__':'__main__'})";
const created = await c.createContainer(`kaname-eval-sandbox-${Date.now().toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`, {
Image: image,
User: "65534:65534",
Entrypoint: ["python3", "-I", "-c", runner],
Cmd: [],
Env: [`KANAME_CODE=${Buffer.from(program).toString("base64")}`, "PYTHONDONTWRITEBYTECODE=1"],
NetworkDisabled: true,
Labels: { "kaname.managed": "true", "kaname.probe": "eval-sandbox" },
HostConfig: {
NetworkMode: "none",
ReadonlyRootfs: true,
Tmpfs: { "/tmp": "rw,noexec,nosuid,size=16m" },
CapDrop: ["ALL"],
SecurityOpt: ["no-new-privileges"],
Memory: 256 * 2 ** 20,
MemorySwap: 256 * 2 ** 20,
NanoCpus: 1e9,
PidsLimit: 64,
Privileged: false,
AutoRemove: false,
},
});
const lines: string[] = [];
try {
await c.startContainer(created.Id);
await c
.followLogs(created.Id, (_s, line) => lines.length < 200 && lines.push(line), { tail: "all", signal: AbortSignal.any([signal, AbortSignal.timeout(15_000)]) })
.catch(() => {});
const st = await c.containerState(created.Id);
if (st?.Running) {
await c.stopContainer(created.Id, 0).catch(() => {});
return { ok: false, output: "timed out (15 s)" };
}
return { ok: st?.ExitCode === 0 && lines.some((l) => l.includes("KANAME-OK")), output: lines.slice(-6).join("\n") };
} finally {
await c.removeContainer(created.Id).catch(() => {});
}
}
async function codingSection(t: EvalTarget, o: EvalOptions, items: Item[]): Promise<Omit<Section, "score" | "seconds">> {
if (!o.docker || !o.sandboxImage) return { section: "coding", passed: 0, total: 0, unsupported: "no Docker access for the code sandbox" };
if (typeof o.runCode === "string") return { section: "coding", passed: 0, total: 0, unsupported: o.runCode };
let passed = 0;
const all = EVAL_SET.coding.items;
for (const item of all) {
@@ -162,7 +119,7 @@ async function codingSection(t: EvalTarget, o: EvalOptions, items: Item[]): Prom
const code = extractCode(m.content ?? "");
if (!code) detail = "no code block in the answer";
else {
const r = await runPython(o.docker, o.sandboxImage, testProgram(code, item.tests), o.signal);
const r = await o.runCode(testProgram(code, item.tests), o.signal);
pass = r.ok;
detail = r.ok ? "tests pass" : `tests fail: ${r.output.split("\n").slice(-2).join(" ").slice(0, 200)}`;
}
-283
View File
@@ -1,283 +0,0 @@
// Samples resource use while a benchmark runs (every ~2 s):
// - CPU and memory of the deployment containers (Docker stats);
// - NVIDIA GPUs: whole-GPU VRAM/utilization/power/temperature from one long-lived `nvidia-smi -lms`
// probe container;
// - Intel and AMD GPUs: power and temperature from hwmon, AMD VRAM/busy from sysfs, Intel VRAM and
// utilization from DRM fdinfo via a probe container in the host's PID namespace (gpu-sysfs.ts);
// - the GPUs' PCIe link (it drops to a slower speed when idle, so the fastest one seen under load is
// the one worth recording).
// Aggregation is pure (summarizeSamples) for tests.
import type { GpuVendor, PcieLink, ResourceStats } from "@/lib/db/schema";
import type { DockerClient } from "./docker/client";
import { aggregateFdinfo, type DrmSnapshot, drmUtilization, type HwmonReading, INTEL_PROBE_SCRIPT, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs";
import { currentLinks, nodeFs } from "./hardware";
import { log } from "./log";
const INTERVAL_MS = 2_000;
export type ContainerSample = { side: "a" | "b"; cpuPercent: number; memoryBytes: number; memoryLimitBytes: number };
export type GpuSample = {
index: number;
name: string;
pciAddress?: string;
vramTotalMb: number | null;
vramUsedMb: number | null;
util: number | null;
powerW: number | null;
tempC?: number | null;
link?: PcieLink | null;
};
export type LinkSample = { pciAddress: string; link: PcieLink };
const avg = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null);
const peak = (xs: number[]) => (xs.length ? Math.max(...xs) : null);
const known = (xs: (number | null | undefined)[]) => xs.filter((x): x is number => x != null);
const GPU_QUERY = "index,name,memory.total,memory.used,utilization.gpu,power.draw,pcie.link.gen.current,pcie.link.width.current,temperature.gpu";
/** One CSV line of `nvidia-smi --query-gpu=${GPU_QUERY}` (columns after power are optional). */
export function parseGpuLine(line: string): GpuSample | null {
const p = line.split(",").map((x) => x.trim());
if (p.length < 6 || !/^\d+$/.test(p[0])) return null;
const n = (s: string | undefined) => (s != null && s !== "" && Number.isFinite(Number(s)) ? Number(s) : null);
const gen = n(p[6]);
const width = n(p[7]);
return {
index: Number(p[0]),
name: p[1],
vramTotalMb: n(p[2]),
vramUsedMb: n(p[3]),
util: n(p[4]),
powerW: n(p[5]),
tempC: n(p[8]),
link: gen != null || width != null ? { gen, width } : null,
};
}
/** Faster link: higher generation first, then more lanes. */
const faster = (a: PcieLink | undefined, b: PcieLink) => !a || (b.gen ?? 0) > (a.gen ?? 0) || ((b.gen ?? 0) === (a.gen ?? 0) && (b.width ?? 0) > (a.width ?? 0));
/** Fastest link per GPU over the run. */
export function fastestLinks(samples: LinkSample[]): Record<string, PcieLink> {
const out: Record<string, PcieLink> = {};
for (const s of samples) if (faster(out[s.pciAddress], s.link)) out[s.pciAddress] = s.link;
return out;
}
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number, links: LinkSample[] = []): ResourceStats {
const sides = [...new Set(containers.map((c) => c.side))].sort();
const fastest = fastestLinks(links);
return {
samples: containers.length,
seconds: Math.round(seconds),
...(Object.keys(fastest).length ? { links: fastest } : {}),
containers: sides.map((side) => {
const xs = containers.filter((c) => c.side === side);
// Docker reports CPU in percent of one core; keep cores.
const cpu = xs.map((x) => x.cpuPercent / 100);
const mem = xs.map((x) => x.memoryBytes);
const limit = xs.find((x) => x.memoryLimitBytes > 0)?.memoryLimitBytes ?? null;
return {
side,
cpuAvg: avg(cpu),
cpuPeak: peak(cpu),
memAvgBytes: avg(mem),
memPeakBytes: peak(mem),
// Without a limit Docker reports the host's memory; that isn't a limit.
memLimitBytes: limit,
};
}),
gpus: [...new Set(gpus.map((g) => g.index))]
.sort((a, b) => a - b)
.map((index) => {
const xs = gpus.filter((g) => g.index === index);
const vram = known(xs.map((x) => x.vramUsedMb));
const util = known(xs.map((x) => x.util));
const power = known(xs.map((x) => x.powerW));
const temp = known(xs.map((x) => x.tempC));
return {
index,
name: xs[0].name,
...(xs[0].pciAddress ? { pciAddress: xs[0].pciAddress } : {}),
vramTotalMb: xs.find((x) => x.vramTotalMb != null)?.vramTotalMb ?? null,
vramPeakMb: peak(vram),
vramAvgMb: avg(vram),
utilAvg: avg(util),
utilPeak: peak(util),
powerAvgW: avg(power),
powerPeakW: peak(power),
tempAvgC: avg(temp),
tempPeakC: peak(temp),
};
}),
};
}
/** A GPU sampled from sysfs (Intel, AMD); `index` is its position among the GPUs of the run. */
export type SysfsGpu = { index: number; pciAddress: string; name: string; vendor: GpuVendor; vramTotalMb: number | null };
export type GpuTargets = {
/** NVIDIA GPUs via nvidia-smi (our own image as the probe); index → PCI address for the link. */
nvidia: { image: string; pciByIndex: Record<number, string> } | null;
sysfs: SysfsGpu[];
/** Image for the Intel fdinfo probe; null: Intel VRAM/utilization aren't sampled. */
intelProbeImage: string | null;
/** PCI addresses whose link is read from sysfs. */
linkAddresses: string[];
};
export const NO_GPUS: GpuTargets = { nvidia: null, sysfs: [], intelProbeImage: null, linkAddresses: [] };
export class ResourceSampler {
private containerSamples: ContainerSample[] = [];
private gpuSamples: GpuSample[] = [];
private linkSamples: LinkSample[] = [];
private timer?: NodeJS.Timeout;
private busy = false;
private probeIds: string[] = [];
private abort = new AbortController();
private started = Date.now();
private lastHwmon = new Map<string, { at: number; r: HwmonReading }>();
private lastDrm: DrmSnapshot | null = null;
private intelNow = new Map<string, { vramMb: number; util: number | null }>();
constructor(
private c: DockerClient,
private targets: { side: "a" | "b"; containerId: string }[],
private gpus: GpuTargets = NO_GPUS,
) {}
async start(): Promise<void> {
this.started = Date.now();
this.timer = setInterval(() => void this.sample(), INTERVAL_MS);
void this.sample();
const warn = (what: string) => (err: unknown) => log.warn(`${what} sampling unavailable: ${err instanceof Error ? err.message : err}`);
if (this.gpus.nvidia) await this.startNvidiaProbe(this.gpus.nvidia.image).catch(warn("NVIDIA GPU"));
if (this.gpus.intelProbeImage && this.gpus.sysfs.some((g) => g.vendor === "intel")) await this.startIntelProbe(this.gpus.intelProbeImage).catch(warn("Intel GPU"));
}
private async sample() {
if (this.busy) return;
this.busy = true;
try {
for (const t of this.targets) {
const s = await this.c.containerStats(t.containerId).catch(() => null);
if (s) this.containerSamples.push({ side: t.side, ...s });
}
if (this.gpus.linkAddresses.length) {
const links = await currentLinks(nodeFs, this.gpus.linkAddresses).catch(() => ({}));
for (const [pciAddress, link] of Object.entries(links)) this.linkSamples.push({ pciAddress, link });
}
for (const g of this.gpus.sysfs) await this.sampleSysfs(g).catch(() => {});
} finally {
this.busy = false;
}
}
private async sampleSysfs(g: SysfsGpu) {
const now = Date.now();
const r = await readHwmon(nodeFs, g.pciAddress);
const prev = this.lastHwmon.get(g.pciAddress);
this.lastHwmon.set(g.pciAddress, { at: now, r });
const powerW = powerBetween(prev?.r ?? null, r, prev ? (now - prev.at) / 1000 : 0);
let vramUsedMb: number | null = null;
let util: number | null = null;
if (g.vendor === "amd") ({ vramUsedMb, util } = await readAmdUsage(nodeFs, g.pciAddress));
if (g.vendor === "intel") {
const x = this.intelNow.get(g.pciAddress);
vramUsedMb = x?.vramMb ?? null;
util = x?.util ?? null;
}
// The first energy reading has nothing to compare with; skip it rather than record no power.
if (prev || r.energyUj == null) {
this.gpuSamples.push({ index: g.index, name: g.name, pciAddress: g.pciAddress, vramTotalMb: g.vramTotalMb, vramUsedMb, util, powerW, tempC: r.tempC });
}
}
private async startProbe(name: string, spec: Record<string, unknown>, onLine: (line: string) => void) {
const created = await this.c.createContainer(`kaname-${name}-${Date.now().toString(36)}`, spec);
this.probeIds.push(created.Id);
await this.c.startContainer(created.Id);
void this.c.followLogs(created.Id, (_s, line) => onLine(line), { tail: "all", signal: this.abort.signal }).catch(() => {});
}
private startNvidiaProbe(image: string) {
return this.startProbe(
"gpu-sampler",
{
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: [`--query-gpu=${GPU_QUERY}`, "--format=csv,noheader,nounits", `-lms`, String(INTERVAL_MS)],
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
Labels: { "kaname.managed": "true", "kaname.probe": "gpu-sampler" },
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false, AutoRemove: false },
},
(line) => {
const g = parseGpuLine(line);
if (!g) return;
const addr = this.gpus.nvidia?.pciByIndex[g.index];
this.gpuSamples.push(addr ? { ...g, pciAddress: addr } : g);
if (addr && g.link) this.linkSamples.push({ pciAddress: addr, link: g.link });
},
);
}
/**
* Intel GPUs report VRAM and engine time only per process (DRM fdinfo). The probe runs Node from
* Kaname's image in the host's PID namespace, reads /proc/<pid>/fdinfo and prints it: no network,
* read-only, all capabilities dropped except reading other processes' fdinfo.
*/
private startIntelProbe(image: string) {
return this.startProbe(
"intel-sampler",
{
Image: image,
User: "0:0",
Entrypoint: ["node", "-e", INTEL_PROBE_SCRIPT],
Cmd: [String(INTERVAL_MS)],
Labels: { "kaname.managed": "true", "kaname.probe": "intel-sampler" },
HostConfig: {
PidMode: "host",
NetworkMode: "none",
ReadonlyRootfs: true,
CapDrop: ["ALL"],
CapAdd: ["SYS_PTRACE", "DAC_READ_SEARCH"],
SecurityOpt: ["no-new-privileges"],
Memory: 256 * 2 ** 20,
PidsLimit: 32,
Privileged: false,
AutoRemove: false,
},
},
(line) => {
let msg: { t?: number; f?: string[] };
try {
msg = JSON.parse(line);
} catch {
return;
}
if (typeof msg.t !== "number" || !Array.isArray(msg.f)) return;
const snap = aggregateFdinfo(msg.t, msg.f);
const prev = this.lastDrm;
this.lastDrm = snap;
for (const g of this.gpus.sysfs.filter((x) => x.vendor === "intel")) {
const cur = snap.gpus[g.pciAddress];
const util = cur ? drmUtilization(prev?.gpus[g.pciAddress], cur, prev ? (snap.t - prev.t) / 1000 : 0) : prev ? 0 : null;
this.intelNow.set(g.pciAddress, { vramMb: Math.round((cur?.vramBytes ?? 0) / 2 ** 20), util });
}
},
);
}
/** Stop sampling and return the aggregate (never throws). */
async stop(): Promise<ResourceStats> {
clearInterval(this.timer);
this.abort.abort();
for (const id of this.probeIds) {
await this.c.stopContainer(id, 1).catch(() => {});
await this.c.removeContainer(id).catch(() => {});
}
return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000, this.linkSamples);
}
}
-401
View File
@@ -1,401 +0,0 @@
// Worker side of runtimes: Docker host facts, image state per runtime, pulling images.
// The web app never talks to Docker; it reads what the worker reports in the DB.
import { readFile } from "node:fs/promises";
import { hostname } from "node:os";
import { resolve } from "node:path";
import { and, eq, isNotNull, ne } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type DockerHostInfo, type HostGpu, type HostHardware, type PcieLink, runtimes, settings, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { RUNTIME_PRESETS } from "@/lib/runtimes-shared";
import { DockerClient, DockerError } from "./docker/client";
import { detectHardware, normalizePciAddress, parseP2p } from "./hardware";
import { log } from "./log";
const PROGRESS_MS = 1_000;
/** CPU flags that matter for inference engines. */
const CPU_FEATURES = ["avx2", "avx512f", "avx512_bf16", "avx512_vnni", "avx512bw", "amx_bf16", "amx_int8", "f16c", "fma"];
let client: DockerClient | null | undefined;
export function docker(): DockerClient | null {
if (client === undefined) {
const host = coreEnv().DOCKER_HOST;
client = host ? new DockerClient(host) : null;
}
return client;
}
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
/** CPU model and features from /proc/cpuinfo (the host's, also inside a container). */
async function cpuFacts(): Promise<{ model: string | null; features: string[] }> {
try {
const text = await readFile("/proc/cpuinfo", "utf8");
const model = text.match(/^model name\s*:\s*(.+)$/m)?.[1]?.trim() ?? null;
const flags = new Set(text.match(/^flags\s*:\s*(.+)$/m)?.[1]?.split(/\s+/) ?? []);
return { model, features: CPU_FEATURES.filter((f) => flags.has(f)) };
} catch {
return { model: null, features: [] }; // not Linux (dev on Windows/macOS)
}
}
/** Find our own container to learn the network and where MODELS_DIR comes from on the host. */
async function selfDetect(c: DockerClient): Promise<Pick<DockerHostInfo, "network" | "modelsSource"> & { image: string | null }> {
const env = coreEnv();
let network: string | null = env.KANAME_DOCKER_NETWORK ?? null;
let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE
? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE }
: null;
// Always inspected: the worker's own image also serves as the GPU probe image.
const self = await c.inspectContainer(hostname()).catch(() => null);
if (self) {
network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null;
const mount = self.Mounts.find((m) => resolve(m.Destination) === resolve(env.MODELS_DIR));
if (!modelsSource && mount) {
modelsSource = mount.Type === "volume" ? { type: "volume", source: mount.Name ?? mount.Source } : { type: "bind", source: mount.Source };
}
}
return { network, modelsSource, image: self?.Image ?? null };
}
// --- GPUs ---------------------------------------------------------------------
const GPU_PROBE_MS = 60 * 60_000;
let ownImage: string | null = null;
/** The worker's own image (from the last host check); probe containers run from it. */
export const workerImage = () => ownImage;
let gpuCache: { at: number; gpus: HostGpu[]; p2p: HostHardware["p2p"]; error: string | null } | null = null;
/** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */
export function parseNvidiaSmi(csv: string): HostGpu[] {
return csv
.split(/\r?\n/)
.map((l) => l.split(",").map((p) => p.trim()))
.filter((p) => p.length >= 5 && /^\d+$/.test(p[0]))
.map(([index, uuid, name, mem, driver, bus, genCur, genMax, widthCur, widthMax]) => ({
vendor: "nvidia" as const,
index: Number(index),
uuid,
name,
memoryMb: Number(mem) || 0,
driver,
pciAddress: bus ? normalizePciAddress(bus) : null,
linkCurrent: nvLink(genCur, widthCur),
linkMax: nvLink(genMax, widthMax),
}));
}
const nvNum = (s: string | undefined) => (s && /^\d+$/.test(s) ? Number(s) : null);
function nvLink(gen: string | undefined, width: string | undefined): PcieLink | null {
const l = { gen: nvNum(gen), width: nvNum(width) };
return l.gen == null && l.width == null ? null : l;
}
/**
* Lists the GPUs containers get from Docker (nvidia-smi, which the NVIDIA Container Toolkit injects)
* and, with two or more, whether they can talk peer-to-peer.
*/
async function probeNvidia(c: DockerClient, image: string): Promise<{ gpus: HostGpu[]; p2p: HostHardware["p2p"] }> {
const gpus = parseNvidiaSmi((await nvidiaSmi(c, image, ["--query-gpu=index,uuid,name,memory.total,driver_version,pci.bus_id,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,pcie.link.width.max", "--format=csv,noheader,nounits"])).join("\n"));
let p2p: HostHardware["p2p"] = null;
if (gpus.length >= 2) p2p = parseP2p((await nvidiaSmi(c, image, ["topo", "-p2p", "r"]).catch(() => [])).join("\n"));
return { gpus, p2p };
}
/** Runs `nvidia-smi <args>` in a short-lived container (our own image) that gets every GPU; its output lines. */
function nvidiaSmi(c: DockerClient, image: string, args: string[]): Promise<string[]> {
return runProbe(c, {
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: args,
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false },
});
}
/**
* Group IDs of the host's /dev/dri nodes (render, video), as a short-lived container with /dev/dri
* sees them (Docker copies the host's owner and mode). Runtime containers get them as extra groups,
* so images that don't run as root can open the GPU.
*/
async function probeDriGroups(c: DockerClient, image: string): Promise<number[]> {
const lines = await runProbe(c, {
Image: image,
Entrypoint: ["sh", "-c", "stat -c '%n %g' /dev/dri/*"],
Cmd: [],
HostConfig: { Devices: [{ PathOnHost: "/dev/dri", PathInContainer: "/dev/dri", CgroupPermissions: "r" }], NetworkMode: "none", Privileged: false, ReadonlyRootfs: true },
});
return parseDriGroups(lines);
}
/** "`/dev/dri/renderD128 993`" lines → the distinct non-root group IDs. */
export function parseDriGroups(lines: string[]): number[] {
const gids = lines.map((l) => l.trim().match(/^\/dev\/dri\/\S+\s+(\d+)$/)?.[1]).filter((g): g is string => !!g).map(Number);
return [...new Set(gids.filter((g) => g > 0))].sort((a, b) => a - b);
}
/** Runs a short-lived probe container from our own image and returns its output lines. */
async function runProbe(c: DockerClient, spec: { Image: string; Entrypoint: string[]; Cmd: string[]; Env?: string[]; HostConfig: Record<string, unknown> }): Promise<string[]> {
const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, { ...spec, Labels: { "kaname.managed": "true", "kaname.probe": "gpu" } });
try {
const lines: string[] = [];
await c.startContainer(created.Id);
await c.followLogs(created.Id, (_s, line) => lines.push(line), { tail: "all", signal: AbortSignal.timeout(30_000) });
const st = await c.containerState(created.Id);
if (st && st.ExitCode !== 0) throw new Error(`${spec.Entrypoint[0]} exited with ${st.ExitCode}: ${lines.slice(-3).join(" ")}`);
return lines;
} finally {
await c.removeContainer(created.Id).catch(() => {});
}
}
async function gpuFacts(c: DockerClient, info: Awaited<ReturnType<DockerClient["info"]>>, selfImage: string | null) {
const nvidia = !!info.Runtimes?.nvidia || !!info.DiscoveredDevices?.some((d) => d.ID.startsWith("nvidia.com/gpu"));
if (!nvidia) return { nvidia, gpus: [], p2p: null, gpuError: null, gpuCheckedAt: null };
if (!gpuCache || Date.now() - gpuCache.at > GPU_PROBE_MS) {
try {
if (!selfImage) throw new Error("Kaname's own image is unknown (the worker isn't running in a container), so GPUs can't be probed.");
const { gpus, p2p } = await probeNvidia(c, selfImage);
gpuCache = { at: Date.now(), gpus, p2p, error: null };
if (gpus.length) {
log.info(`GPUs: ${gpus.map((g) => `${g.index}: ${g.name} (${Math.round(g.memoryMb / 1024)} GiB)`).join(", ")}`);
await seedGpuPresets();
}
} catch (err) {
gpuCache = { at: Date.now(), gpus: [], p2p: null, error: message(err) };
log.warn(`GPU probe failed: ${message(err)}`);
}
}
return { nvidia, gpus: gpuCache.gpus, p2p: gpuCache.p2p, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
}
const CUDA_SEEDED_KEY = "runtimes.cudaPresetSeeded";
/** The first time NVIDIA GPUs show up, add the llama.cpp CUDA runtime (once). */
async function seedGpuPresets() {
const d = db();
if (await d.query.settings.findFirst({ where: eq(settings.key, CUDA_SEEDED_KEY) })) return;
const p = RUNTIME_PRESETS.find((x) => x.id === "llama.cpp-cuda");
if (p) {
await d.insert(runtimes).values({ name: p.name, engine: p.engine, accelerator: "nvidia", image: p.image, description: p.description ?? null, preset: p.id });
log.info(`NVIDIA GPU found: added the "${p.name}" runtime`);
}
await d.insert(settings).values({ key: CUDA_SEEDED_KEY, value: true }).onConflictDoNothing();
}
const INTEL_SEEDED_KEY = "runtimes.intelPresetSeeded";
/** The first time an Intel GPU shows up, add the llama.cpp runtimes for it (SYCL and Vulkan, once). */
async function seedIntelPresets() {
const d = db();
if (await d.query.settings.findFirst({ where: eq(settings.key, INTEL_SEEDED_KEY) })) return;
for (const p of RUNTIME_PRESETS.filter((x) => x.id === "llama.cpp-intel" || x.id === "llama.cpp-vulkan")) {
await d.insert(runtimes).values({
name: p.name,
engine: p.engine,
accelerator: p.accelerator ?? "dri",
image: p.image,
description: p.description ?? null,
env: p.env ?? {},
devices: p.devices ?? [],
preset: p.id,
});
log.info(`Intel GPU found: added the "${p.name}" runtime`);
}
await d.insert(settings).values({ key: INTEL_SEEDED_KEY, value: true }).onConflictDoNothing();
}
let driCache: { at: number; gids: number[] } | null = null;
/** Render/video group IDs of /dev/dri, re-checked hourly while there are Intel or AMD GPUs. */
async function driGroups(c: DockerClient, image: string | null, hardware: HostHardware | null): Promise<number[] | undefined> {
if (!image || !hardware?.gpus.some((g) => g.vendor !== "nvidia")) return undefined;
if (!driCache || Date.now() - driCache.at > GPU_PROBE_MS) {
try {
driCache = { at: Date.now(), gids: await probeDriGroups(c, image) };
log.info(`/dev/dri groups: ${driCache.gids.join(", ") || "none besides root"}`);
} catch (err) {
driCache = { at: Date.now(), gids: [] };
log.warn(`/dev/dri group check failed: ${message(err)}`);
}
}
return driCache.gids;
}
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
export async function refreshDockerInfo(instanceId: string): Promise<void> {
const c = docker();
let info: DockerHostInfo | null = null;
if (c) {
const cpu = await cpuFacts();
const base = {
cpuModel: cpu.model,
cpuFeatures: cpu.features,
checkedAt: new Date().toISOString(),
};
try {
const [v, i] = await Promise.all([c.version(), c.info()]);
const self = await selfDetect(c);
ownImage = self.image;
const { p2p, ...gpu } = await gpuFacts(c, i, self.image);
const hardware = await detectHardware({ modelsDir: coreEnv().MODELS_DIR, nvidia: gpu.gpus, p2p }).catch((err) => {
log.warn(`hardware detection failed: ${message(err)}`);
return null;
});
if (hardware?.gpus.some((g) => g.vendor === "intel")) await seedIntelPresets();
const driGids = await driGroups(c, self.image, hardware);
info = {
connected: true,
error: null,
serverVersion: v.Version,
os: i.OperatingSystem,
architecture: i.Architecture,
cpus: i.NCPU,
memoryBytes: i.MemTotal,
...base,
network: self.network,
modelsSource: self.modelsSource,
...gpu,
hardware,
...(driGids ? { driGroups: driGids } : {}),
};
} catch (err) {
info = {
connected: false,
error: message(err),
serverVersion: null,
os: null,
architecture: null,
cpus: null,
memoryBytes: null,
network: null,
modelsSource: null,
...base,
};
}
}
await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
}
/** The registry digest ("sha256:…") of an image reference, from Docker's RepoDigests ("repo@sha256:…"). */
export function repoDigest(ref: string, repoDigests: string[] | null | undefined): string | null {
const repo = ref.split("@")[0].replace(/:[^/:]+$/, "");
const all = repoDigests ?? [];
const hit = all.find((d) => d.split("@")[0] === repo) ?? all[0];
return hit?.split("@")[1] ?? null;
}
const SEEDED_KEY = "runtimes.presetsSeeded";
/** Create the preset runtimes once (deleted presets don't come back). */
export async function seedRuntimePresets(): Promise<void> {
const d = db();
const seeded = await d.query.settings.findFirst({ where: eq(settings.key, SEEDED_KEY) });
if (seeded) return;
const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1);
if (existing.length === 0) {
// CPU presets only; GPU ones are added from Settings (or automatically when an NVIDIA GPU shows up).
const presets = RUNTIME_PRESETS.filter((p) => (p.accelerator ?? "cpu") === "cpu");
await d.insert(runtimes).values(
presets.map((p) => ({
name: p.name,
engine: p.engine,
accelerator: p.accelerator ?? "cpu",
image: p.image,
description: p.description ?? null,
env: p.env ?? {},
extraArgs: p.extraArgs ?? [],
devices: p.devices ?? [],
shmSizeMb: p.shmSizeMb ?? null,
numaTuning: p.numaTuning ?? false,
preset: p.id,
})),
);
log.info(`created ${presets.length} preset runtime(s)`);
}
await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing();
}
/** Look up every runtime's image locally (present / missing), except ones being pulled. */
export async function syncImageStates(): Promise<void> {
const c = docker();
if (!c) return;
const rows = await db().select().from(runtimes).where(ne(runtimes.imageState, "pulling"));
for (const r of rows) {
try {
const img = await c.inspectImage(r.image);
await db()
.update(runtimes)
.set(
img
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageDigest: repoDigest(r.image, img.RepoDigests), imageCheckedAt: new Date() }
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, imageCheckedAt: new Date() },
)
.where(eq(runtimes.id, r.id));
} catch (err) {
log.warn(`image check for ${r.image} failed: ${message(err)}`);
}
}
}
/** Pulls interrupted by a worker restart can't still be running. */
export async function resetStalePulls(): Promise<void> {
await db().update(runtimes).set({ imageState: "unknown", pullProgress: null }).where(eq(runtimes.imageState, "pulling"));
}
let pulling = false;
/** Pull images whose "Pull" was requested after the last pull started. One at a time. */
export async function handlePullRequests(): Promise<void> {
const c = docker();
if (!c || pulling) return;
const rows = await db().select().from(runtimes).where(isNotNull(runtimes.pullRequestedAt));
const next = rows.find((r) => r.imageState !== "pulling" && (!r.pullStartedAt || r.pullRequestedAt! > r.pullStartedAt));
if (!next) return;
pulling = true;
const d = db();
await d
.update(runtimes)
.set({ imageState: "pulling", pullStartedAt: new Date(), pullError: null, pullProgress: { doneBytes: 0, totalBytes: 0, status: "Starting" } })
.where(eq(runtimes.id, next.id));
log.info(`pulling ${next.image}`);
let lastWrite = 0;
try {
await c.pullImage(next.image, (p) => {
if (Date.now() - lastWrite < PROGRESS_MS) return;
lastWrite = Date.now();
// Drizzle queries only run when awaited/then'd; `void query` would never execute.
d.update(runtimes)
.set({ pullProgress: p })
.where(eq(runtimes.id, next.id))
.then(
() => {},
(err) => log.warn(`pull progress update failed: ${message(err)}`),
);
});
const img = await c.inspectImage(next.image);
await d
.update(runtimes)
.set({
imageState: img ? "present" : "failed",
imageId: img?.Id ?? null,
imageSize: img?.Size ?? null,
imageCreated: img?.Created ?? null,
imageDigest: img ? repoDigest(next.image, img.RepoDigests) : null,
pullProgress: null,
pullError: img ? null : "Pull finished but the image isn't there.",
imageCheckedAt: new Date(),
})
.where(eq(runtimes.id, next.id));
log.info(`pulled ${next.image}`);
} catch (err) {
const msg = err instanceof DockerError ? err.message : message(err);
await d.update(runtimes).set({ imageState: "failed", pullProgress: null, pullError: msg }).where(eq(runtimes.id, next.id));
log.warn(`pulling ${next.image} failed: ${msg}`);
} finally {
pulling = false;
}
}
+59
View File
@@ -0,0 +1,59 @@
import assert from "node:assert/strict";
import { mkdtemp, readdir, readFile, rename, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import { ALIVE_FILE, type SandboxResult } from "@/sandbox/protocol";
import { sandboxDown, sandboxRunner } from "./sandbox-client";
let dir = "";
let stop = false;
/** A stand-in for the sandbox container: "runs" programs by looking at them. */
async function fakeSandbox() {
while (!stop) {
for (const name of await readdir(dir)) {
if (!name.endsWith(".py")) continue;
const id = name.slice(0, -3);
const program = await readFile(join(dir, name), "utf8");
await rm(join(dir, name));
const result: SandboxResult = program.includes("sleep")
? { exitCode: null, timedOut: true, output: "" }
: { exitCode: program.includes("fail") ? 1 : 0, timedOut: false, output: program.includes("fail") ? "AssertionError" : "KANAME-OK" };
await writeFile(join(dir, `${id}.tmp`), JSON.stringify(result));
await rename(join(dir, `${id}.tmp`), join(dir, `${id}.json`));
}
await new Promise((r) => setTimeout(r, 20));
}
}
before(async () => {
dir = await mkdtemp(join(tmpdir(), "kaname-sandbox-"));
});
after(async () => {
stop = true;
await rm(dir, { recursive: true, force: true });
});
describe("code sandbox exchange", () => {
it("says why the sandbox can't be used", async () => {
assert.match((await sandboxDown(undefined))!, /SANDBOX_DIR/);
assert.match((await sandboxDown(dir))!, /isn't running/);
await writeFile(join(dir, ALIVE_FILE), "x");
assert.equal(await sandboxDown(dir), null);
const old = new Date(Date.now() - 60_000);
await utimes(join(dir, ALIVE_FILE), old, old);
assert.match((await sandboxDown(dir))!, /stopped answering/);
});
it("hands programs over and reads the result, leaving nothing behind", async () => {
void fakeSandbox();
const run = sandboxRunner(dir);
const signal = new AbortController().signal;
assert.deepEqual(await run("print('KANAME-OK')", signal), { ok: true, output: "KANAME-OK" });
assert.equal((await run("fail()", signal)).ok, false);
assert.deepEqual(await run("sleep()", signal), { ok: false, output: "timed out (15 s)" });
const left = (await readdir(dir)).filter((n) => n !== ALIVE_FILE);
assert.deepEqual(left, []);
});
});
+44
View File
@@ -0,0 +1,44 @@
// The worker's side of the code sandbox (src/sandbox): hand a program over, wait for its result.
import { randomBytes } from "node:crypto";
import { readFile, rename, rm, stat, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { ALIVE_FILE, ALIVE_STALE_MS, programFile, resultFile, RUN_TIMEOUT_S, type SandboxResult } from "@/sandbox/protocol";
export type CodeRunner = (program: string, signal: AbortSignal) => Promise<{ ok: boolean; output: string }>;
/** Why the sandbox can't be used right now, or null when it's up. */
export async function sandboxDown(dir: string | undefined): Promise<string | null> {
if (!dir) return "no code sandbox configured (SANDBOX_DIR)";
const s = await stat(join(dir, ALIVE_FILE)).catch(() => null);
if (!s) return "the code sandbox isn't running (start the sandbox service)";
if (Date.now() - s.mtimeMs > ALIVE_STALE_MS) return "the code sandbox stopped answering";
return null;
}
/** Runs programs in the sandbox; ok when the program exits 0 and printed the marker. */
export function sandboxRunner(dir: string, marker = "KANAME-OK"): CodeRunner {
return async (program, signal) => {
const id = randomBytes(10).toString("hex");
const tmp = join(dir, `${id}.tmp`);
await writeFile(tmp, program);
await rename(tmp, join(dir, programFile(id)));
const deadline = Date.now() + (RUN_TIMEOUT_S + 30) * 1000;
const out = join(dir, resultFile(id));
try {
while (Date.now() < deadline && !signal.aborted) {
const text = await readFile(out, "utf8").catch(() => null);
if (text != null) {
const r = JSON.parse(text) as SandboxResult;
if (r.timedOut) return { ok: false, output: `timed out (${RUN_TIMEOUT_S} s)` };
return { ok: r.exitCode === 0 && r.output.includes(marker), output: r.output.split("\n").slice(-6).join("\n") };
}
await new Promise((res) => setTimeout(res, 150));
}
return { ok: false, output: signal.aborted ? "cancelled" : "the sandbox didn't answer" };
} finally {
await rm(out, { force: true });
await rm(join(dir, programFile(id)), { force: true });
}
};
}
-185
View File
@@ -1,185 +0,0 @@
// Runs benchmark sweeps one variant at a time: a temporary deployment with the variant's settings,
// a benchmark run against it once it is healthy, then the deployment is removed again. State lives in
// the sweep row, so a worker restart picks up where it was (an interrupted run fails its variant).
import { and, asc, eq, inArray } from "drizzle-orm";
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema";
import { estimateMemoryMb } from "@/lib/deploy-command";
import { overTime } from "@/lib/agent-tuning";
import { applyOverrides } from "@/lib/sweep";
import { log } from "./log";
let busy = false;
const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
type Sweep = typeof benchmarkSweeps.$inferSelect;
async function save(id: string, set: Partial<typeof benchmarkSweeps.$inferInsert>) {
await db().update(benchmarkSweeps).set(set).where(eq(benchmarkSweeps.id, id));
}
/** Stop and remove a sweep's temporary deployment (the deployments reconciler does the work). */
async function removeDeployment(id: string | null | undefined) {
if (!id) return;
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
}
/** The variant's memory limit: the base limit, raised to the estimate when the variant needs more. */
async function memoryFor(sweep: Sweep, options: Sweep["base"]["options"], accelerator: string, engine: "llama.cpp" | "vllm"): Promise<number | null> {
if (!sweep.base.memoryMb) return null;
const files = await db()
.select({ path: modelFiles.path, size: modelFiles.size })
.from(modelFiles)
.where(and(eq(modelFiles.modelId, sweep.base.modelId), eq(modelFiles.selected, true)));
const bytes =
engine === "llama.cpp"
? files.filter((f) => [options.modelFile, options.mmproj, options.draftFile].includes(f.path)).reduce((s, f) => s + f.size, 0)
: files.reduce((s, f) => s + f.size, 0);
const est = estimateMemoryMb(bytes, options.contextSize, engine, { ...options, accelerator: accelerator as never });
return Math.max(sweep.base.memoryMb, est);
}
async function advance(sweep: Sweep): Promise<void> {
const variants = [...sweep.variants];
const put = async (i: number, patch: Partial<SweepVariant>) => {
variants[i] = { ...variants[i], ...patch };
await save(sweep.id, { variants });
};
const timedOut = overTime(sweep.startedAt, sweep.timeLimitS);
if (sweep.cancelRequestedAt || timedOut) {
for (const v of variants) {
const open = v.state === "evaluating" ? v.evalRunId : v.state === "benchmarking" ? v.runId : null;
if (open) await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, open));
if (v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating") await removeDeployment(v.deploymentId);
}
await save(sweep.id, {
state: timedOut ? "failed" : "cancelled",
...(timedOut ? { error: `Stopped: the sweep exceeded the time limit for agent sweeps (${Math.round((sweep.timeLimitS ?? 0) / 60)} min).` } : {}),
finishedAt: new Date(),
variants: variants.map((v) => (v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating" ? { ...v, state: "skipped" as const } : v)),
});
log.info(`sweep ${sweep.id}: ${timedOut ? "stopped at its time limit" : "cancelled"}`);
return;
}
const i = variants.findIndex((v) => v.state === "pending" || v.state === "deploying" || v.state === "benchmarking" || v.state === "evaluating");
if (i < 0) {
const ok = variants.filter((v) => v.state === "done").length;
await save(sweep.id, { state: ok > 0 ? "completed" : "failed", finishedAt: new Date(), error: ok > 0 ? null : "No variant could be benchmarked." });
log.info(`sweep ${sweep.id}: ${ok}/${variants.length} variants done`);
return;
}
const v = variants[i];
if (v.state === "pending") {
const rt = await db().query.runtimes.findFirst({ columns: { engine: true, accelerator: true }, where: eq(runtimes.id, sweep.base.runtimeId) });
if (!rt) return void (await put(i, { state: "failed", error: "The runtime was deleted." }));
const { options, cpus } = applyOverrides(sweep.base, v.overrides);
const memoryMb = await memoryFor(sweep, options, rt.accelerator, rt.engine);
const [row] = await db()
.insert(deployments)
.values({
name: `${sweep.base.name} · ${v.label}`.slice(0, 80),
runtimeId: sweep.base.runtimeId,
modelId: sweep.base.modelId,
options,
cpus,
memoryMb,
hostPort: null,
desiredState: "running",
sweepId: sweep.id,
})
.returning({ id: deployments.id });
await put(i, { state: "deploying", deploymentId: row.id });
log.info(`sweep ${sweep.id}: variant ${i + 1}/${variants.length} (${v.label}) deploying`);
return;
}
if (v.state === "deploying") {
const d = v.deploymentId ? await db().query.deployments.findFirst({ columns: { state: true, error: true }, where: eq(deployments.id, v.deploymentId) }) : null;
if (!d) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." }));
if (d.state === "failed") {
await put(i, { state: "failed", error: d.error ?? "The deployment failed to start." });
return removeDeployment(v.deploymentId);
}
if (d.state !== "running") return; // still starting
const snap = await deploymentSnapshot(v.deploymentId!);
if (!snap) return void (await put(i, { state: "failed", error: "The variant's deployment disappeared." }));
const [run] = await db()
.insert(benchmarkRuns)
.values({
kind: "run",
deploymentId: snap.id,
modelId: snap.modelId,
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label}`.slice(0, 120),
settings: sweep.settings,
snapshot: snap.snapshot,
sweepId: sweep.id,
// Runs of an agent's sweep carry its token and the per-run time limit.
requestedByTokenId: sweep.requestedByTokenId,
requestedBy: sweep.requestedBy,
timeLimitS: sweep.runTimeLimitS,
})
.returning({ id: benchmarkRuns.id });
await put(i, { state: "benchmarking", runId: run.id });
return;
}
// benchmarking, then (sweeps with quality) evaluating
const runId = v.state === "evaluating" ? v.evalRunId : v.runId;
const run = runId ? await db().query.benchmarkRuns.findFirst({ columns: { state: true, error: true }, where: eq(benchmarkRuns.id, runId) }) : null;
if (!run) {
await put(i, { state: "failed", error: "The variant's run disappeared." });
return removeDeployment(v.deploymentId);
}
if (run.state === "queued" || run.state === "running") return;
if (run.state === "completed" && v.state === "benchmarking" && sweep.settings.quality) {
const snap = await deploymentSnapshot(v.deploymentId!);
if (snap) {
const [ev] = await db()
.insert(benchmarkRuns)
.values({
kind: "eval",
deploymentId: snap.id,
modelId: snap.modelId,
label: `${sweep.label ? `${sweep.label}: ` : ""}${v.label} · quality`.slice(0, 120),
settings: { quick: false, passes: null, warmup: null, phases: [], evalSections: [] },
snapshot: snap.snapshot,
sweepId: sweep.id,
requestedByTokenId: sweep.requestedByTokenId,
requestedBy: sweep.requestedBy,
timeLimitS: sweep.runTimeLimitS,
})
.returning({ id: benchmarkRuns.id });
return void (await put(i, { state: "evaluating", evalRunId: ev.id }));
}
}
const ok = run.state === "completed" || (v.state === "evaluating" && !!v.runId);
// A failed eval doesn't undo the speed result; it shows on the eval run.
await put(i, ok ? { state: "done" } : { state: "failed", error: run.error ?? `The run was ${run.state}.` });
await removeDeployment(v.deploymentId);
}
/** Drive the running sweep (or start the oldest queued one). */
export async function tickSweeps(): Promise<void> {
if (busy) return;
busy = true;
try {
let sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.state, "running"), orderBy: asc(benchmarkSweeps.createdAt) });
if (!sweep) {
const next = await db().query.benchmarkSweeps.findFirst({ where: inArray(benchmarkSweeps.state, ["queued"]), orderBy: asc(benchmarkSweeps.createdAt) });
if (!next) return;
await save(next.id, { state: "running", startedAt: new Date() });
sweep = { ...next, state: "running" };
log.info(`sweep ${next.id}: started (${next.variants.length} variants)`);
}
await advance(sweep).catch((err) => log.error(`sweep ${sweep!.id}`, err));
} catch (err) {
log.error("sweeps", message(err));
} finally {
busy = false;
}
}