Release 0.11.0: benchmark metadata and system info
Release / release (push) Successful in 3m25s

Every run records GPUs (PCIe link under load and maximum, ReBAR, P2P),
runtime image/tag/digest and the engine version the server reports,
model, quant, KV cache, context and concurrency, plus a whitelisted
system summary and a description. Shown on the run page, compare and
sweep views; passed to BetterBench as notes and to the launch80 preview
as sections. Settings -> Hardware for manual values.

Also: scripts/intel-probe.sh (read-only diagnostics for Intel hosts),
and --quick is no longer passed together with --passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-20 19:07:04 +02:00
1 parent 981c4170fc
commit ee6c623e2a
45 files changed
+4627 -60

No files matched your search

+217
View File
@@ -0,0 +1,217 @@
import assert from "node:assert/strict";
import { hostname, userInfo } from "node:os";
import { describe, it } from "node:test";
import { argValue, buildRunMeta, gpuLabel, gpusUsed, imageTag, kvCacheOf, metaNotes, metaRows, modelLabel, quantOf, withLoadLinks } from "./benchmark-meta";
import type { DeploymentOptions, HardwareGpu, HostHardware } from "./db/schema";
import { applyOverrides, formatLinkPair, linkGen, parseLinkText, rebarFrom, systemSummary, systemSummaryText, validateOverrides } from "./hardware";
const intel: HardwareGpu = {
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1",
linkCurrent: { gen: 4, width: 8 },
linkMax: { gen: 5, width: 16 },
barMb: 32768,
rebar: true,
};
const nvidia: HardwareGpu = { ...intel, vendor: "nvidia", pciAddress: "0000:05:00.0", name: "NVIDIA RTX 4090", vramMb: 24564, driver: "nvidia", driverVersion: "580.82.07", barMb: 256, rebar: false };
const hw: HostHardware = {
gpus: [intel, nvidia],
p2p: null,
cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
memoryBytes: 128e9,
kernel: "6.17.1-pve",
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 2e12 },
checkedAt: "2026-10-20T00:00:00.000Z",
};
const opts: DeploymentOptions = { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 8192, extraArgs: [], cacheTypeK: "q8_0", cacheTypeV: "q8_0", parallel: 2 };
describe("PCIe links and ReBAR", () => {
it("maps link speeds to generations and formats current vs maximum", () => {
assert.equal(linkGen("16.0 GT/s PCIe"), 4);
assert.equal(linkGen("2.5 GT/s"), 1);
assert.equal(linkGen("Unknown"), null);
assert.equal(formatLinkPair({ gen: 4, width: 8 }, { gen: 5, width: 16 }), "Gen4 x8 of Gen5 x16");
assert.equal(formatLinkPair({ gen: 5, width: 16 }, { gen: 5, width: 16 }), "Gen5 x16");
assert.equal(formatLinkPair(null, null), null);
});
it("parses typed links", () => {
assert.deepEqual(parseLinkText("Gen4 x8"), { gen: 4, width: 8 });
assert.deepEqual(parseLinkText("gen 5"), { gen: 5, width: null });
assert.deepEqual(parseLinkText("x16"), { gen: null, width: 16 });
assert.equal(parseLinkText("fast"), null);
assert.equal(parseLinkText(""), null);
});
it("calls ReBAR on when a BAR covers the VRAM", () => {
assert.equal(rebarFrom(32768, 32768), true);
assert.equal(rebarFrom(256, 24564), false);
assert.equal(rebarFrom(8192, null), true);
assert.equal(rebarFrom(256, null), null);
assert.equal(rebarFrom(null, 1024), null);
});
});
describe("hardware overrides", () => {
it("replace detected values and are listed", () => {
const e = applyOverrides(hw, { gpus: { "0000:05:00.0": { linkCurrent: "Gen3 x16", rebar: true } }, storage: "Proxmox ZFS mirror", gpuPassthrough: true })!;
assert.deepEqual(e.gpus[1].linkCurrent, { gen: 3, width: 16 });
assert.equal(e.gpus[1].rebar, true);
assert.deepEqual(e.gpus[0], intel);
assert.equal(e.storage?.model, "Proxmox ZFS mirror");
assert.equal(e.gpuPassthrough, true);
assert.deepEqual(e.overridden, ["pcie link", "rebar", "storage", "gpu passthrough"]);
});
it("derive passthrough from a VM with GPUs", () => {
assert.equal(applyOverrides(hw)!.gpuPassthrough, true);
assert.equal(applyOverrides({ ...hw, virtualization: { vm: false, hypervisor: null } })!.gpuPassthrough, false);
});
it("are validated, empty fields dropped", () => {
assert.deepEqual(validateOverrides({ gpus: { "0000:03:00.0": { name: "", linkMax: "Gen5 x16" } }, p2p: "", storage: " " }), { gpus: { "0000:03:00.0": { linkMax: "Gen5 x16" } } });
assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { linkCurrent: "fast" } } }), /isn't a PCIe link/);
assert.throws(() => validateOverrides({ gpus: { "../etc": {} } }), /isn't a PCI address/);
assert.throws(() => validateOverrides({ p2p: "maybe" }), /P2P/);
assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { vramMb: 1.5 } } }), /VRAM/);
assert.throws(() => validateOverrides({ storage: "a\nb" }), /one line/);
});
});
describe("system summary", () => {
it("lists the whitelisted facts", () => {
const text = systemSummaryText(systemSummary(applyOverrides(hw), "Debian GNU/Linux 13 (trixie)", "0.11.0"));
assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor \(16 cores, 32 threads\)/);
assert.match(text, /Models disk: Samsung SSD 990 PRO 2TB, NVMe/);
assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\), kernel 6\.17\.1-pve/);
assert.match(text, /GPU driver: xe kernel 6\.17\.1, nvidia 580\.82\.07/);
assert.match(text, /Virtualization: VM \(KVM\/QEMU\) with GPU passthrough/);
assert.match(text, /Kaname 0\.11\.0/);
});
it("never contains the hostname, user, addresses or paths", () => {
const s = systemSummary(applyOverrides(hw), "Debian GNU/Linux 13", "0.11.0");
const meta = buildRunMeta({
hardware: applyOverrides(hw),
gpus: [intel],
runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: null, extraArgs: [] },
repoId: "unsloth/Qwen3-8B-GGUF",
options: opts,
engineInfo: null,
});
const published = JSON.stringify([s, metaNotes(meta, s, "testing q8 KV")]);
for (const secret of [hostname(), userInfo().username].filter((x) => x.length > 2)) assert.ok(!published.includes(secret), `contains ${secret}`);
assert.doesNotMatch(published, /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
assert.doesNotMatch(published, /\/(models|data|home|srv|mnt|var)\//);
assert.doesNotMatch(published, /0000:0[35]:00\.0/);
// Only these keys exist; a new field must be added here on purpose.
assert.deepEqual(Object.keys(s).sort(), ["cpu", "gpuDrivers", "kaname", "kernel", "memoryBytes", "os", "storage", "virtualization"]);
});
});
describe("run metadata", () => {
it("reads image tags and flags", () => {
assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
assert.equal(imageTag("registry:5000/vllm/vllm-openai@sha256:abc"), null);
assert.equal(imageTag("vllm/vllm-openai:v0.31.0@sha256:abc"), "v0.31.0");
assert.equal(argValue(["--kv-cache-dtype", "fp8", "--x"], "--kv-cache-dtype"), "fp8");
assert.equal(argValue(["--quantization=awq"], "--quantization", "-q"), "awq");
});
it("finds quant and KV cache type per engine", () => {
assert.equal(quantOf("llama.cpp", "Qwen3-8B-Q4_K_M.gguf", "unsloth/Qwen3-8B-GGUF", []), "Q4_K_M");
assert.equal(quantOf("vllm", null, "Qwen/Qwen3.8-27B-FP8", []), "FP8");
assert.equal(quantOf("vllm", null, "org/model", ["--quantization", "awq"]), "awq");
assert.equal(quantOf("vllm", null, "Qwen/Qwen3-8B", []), null);
assert.equal(kvCacheOf("llama.cpp", {}, []), "f16");
assert.equal(kvCacheOf("llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q4_0" }, []), "K q8_0 / V q4_0");
assert.equal(kvCacheOf("vllm", {}, ["--kv-cache-dtype=fp8"]), "fp8");
assert.equal(kvCacheOf("vllm", {}, []), "auto");
});
it("knows which GPUs a deployment gets", () => {
const e = applyOverrides(hw);
const nv = [{ vendor: "nvidia" as const, index: 0, uuid: "GPU-1", name: "x", memoryMb: 1, driver: "d", pciAddress: "0000:05:00.0" }];
assert.deepEqual(gpusUsed(e, "dri", {}, nv).map((g) => g.pciAddress), ["0000:03:00.0"]);
assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-1"] }, nv).map((g) => g.pciAddress), ["0000:05:00.0"]);
assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-other"] }, nv), []);
assert.deepEqual(gpusUsed(e, "cpu", {}, nv), []);
});
it("records what the server reported over the launch options", () => {
const m = buildRunMeta({
hardware: applyOverrides(hw),
gpus: [intel],
runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "", extraArgs: [] },
repoId: "unsloth/Qwen3-8B-GGUF",
options: opts,
engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 8192, at: "" },
});
assert.equal(m.p2p, "n/a");
assert.equal(m.rebar, true);
assert.equal(m.concurrency, 4);
assert.deepEqual(m.runtime, { image: "ghcr.io/ggml-org/llama.cpp:server-intel", tag: "server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b11429-d81235049" });
assert.equal(modelLabel(m), "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache");
assert.equal(gpuLabel(m), "1× Intel Arc Pro B65 (32 GiB)");
const rows = Object.fromEntries(metaRows(m).map((r) => [r.key, r.value]));
assert.equal(rows.pcie, "Gen4 x8 of Gen5 x16 (at idle)");
assert.equal(rows.engine, "llama.cpp b11429-d81235049");
});
it("falls back to the options, and to unknown, when the server didn't say", () => {
const m = buildRunMeta({
hardware: null,
gpus: [nvidia, nvidia],
runtime: { image: "vllm/vllm-openai:v0.31.0", digest: null, engine: "vllm", engineName: "vllm-radiance", extraArgs: ["--kv-cache-dtype", "fp8"] },
repoId: "Qwen/Qwen3.8-27B-FP8",
options: { modelFile: "", contextSize: 32768, extraArgs: [], maxNumSeqs: 8 },
engineInfo: null,
});
assert.equal(m.p2p, null);
assert.equal(m.rebar, false);
assert.equal(m.concurrency, 8);
assert.equal(m.runtime.engineName, "vllm-radiance");
assert.equal(modelLabel(m), "Qwen3.8-27B-FP8 FP8 with fp8 KV cache");
assert.equal(gpuLabel(m), "2× NVIDIA RTX 4090 (24 GiB)");
const notes = metaNotes(m, null, " two\n lines ");
assert.equal(notes.engine, "vllm-radiance");
assert.equal(notes.p2p, "unknown");
assert.equal(notes.description, "two lines");
assert.equal(notes.gpus, "2× NVIDIA RTX 4090 (24 GiB)");
});
});
describe("links under load", () => {
const base = () =>
buildRunMeta({
hardware: applyOverrides(hw),
gpus: [{ ...intel, linkCurrent: { gen: 1, width: 8 } }],
runtime: { image: "x:y", digest: null, engine: "llama.cpp", engineName: null, extraArgs: [] },
repoId: "a/b",
options: opts,
engineInfo: null,
});
it("marks an idle link and uses the fastest one seen under load", () => {
const m = base();
assert.equal(Object.fromEntries(metaRows(m).map((r) => [r.key, r.value])).pcie, "Gen1 x8 of Gen5 x16 (at idle)");
const loaded = withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, false)!;
assert.equal(loaded.linkUnderLoad, true);
assert.equal(Object.fromEntries(metaRows(loaded).map((r) => [r.key, r.value])).pcie, "Gen4 x8 of Gen5 x16");
assert.equal(withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, true), m);
assert.equal(withLoadLinks(m, {}, false), m);
});
it("puts only the maximum link in the notes (known before the run)", () => {
const n = metaNotes(base(), null, null);
assert.equal(n.pcie_max, "Gen5 x16");
assert.equal(n.pcie, undefined);
});
});
+181
View File
@@ -0,0 +1,181 @@
// What a benchmark run records about its setup (RunMeta) and the BetterBench notes made from it.
// Pure; shared by the worker, the web app and tests.
import type { DeploymentOptions, EngineInfo, HardwareGpu, HostGpu, PcieLink, RunMeta, RuntimeAccelerator, RuntimeEngine, SystemSummary } from "@/lib/db/schema";
import { type EffectiveHardware, formatLink, formatLinkPair, onOff, systemSummaryText } from "@/lib/hardware";
import { quantGroup } from "@/lib/selection";
/** "ghcr.io/org/img:tag@sha256:…" → "tag" (null: no tag, i.e. "latest" or digest only). */
export function imageTag(ref: string): string | null {
const noDigest = ref.split("@")[0];
const last = noDigest.slice(noDigest.lastIndexOf("/") + 1);
const i = last.indexOf(":");
return i >= 0 ? last.slice(i + 1) : null;
}
/** Value of `--flag v` or `--flag=v` in an argument list (last one wins). */
export function argValue(args: string[], ...flags: string[]): string | null {
let v: string | null = null;
for (let i = 0; i < args.length; i++) {
for (const f of flags) {
if (args[i] === f && i + 1 < args.length) v = args[i + 1];
else if (args[i].startsWith(`${f}=`)) v = args[i].slice(f.length + 1);
}
}
return v;
}
const REPO_QUANT = /(?:^|[-_.])(nvfp4|mxfp4|fp8(?:[-_]dynamic)?|int8|int4|w8a8|w4a16|awq|gptq|bnb[-_]?4bit|bf16|fp16)(?=$|[-_.])/i;
/** Quant: the GGUF's quant tag, vLLM's --quantization, or one named in the repo (FP8, AWQ, …). */
export function quantOf(engine: RuntimeEngine, file: string | null, repoId: string, args: string[]): string | null {
if (engine === "llama.cpp" && file) return quantGroup(file);
const q = argValue(args, "--quantization", "-q");
if (q) return q;
const m = repoId.split("/").pop()?.match(REPO_QUANT);
return m ? m[1].toUpperCase().replace("_", "-") : null;
}
/** KV cache type: llama.cpp -ctk/-ctv (f16 default), vLLM --kv-cache-dtype ("auto": the model's dtype). */
export function kvCacheOf(engine: RuntimeEngine, o: Pick<DeploymentOptions, "cacheTypeK" | "cacheTypeV">, args: string[]): string {
if (engine === "vllm") return argValue(args, "--kv-cache-dtype") ?? "auto";
const k = argValue(args, "-ctk", "--cache-type-k") ?? o.cacheTypeK ?? "f16";
const v = argValue(args, "-ctv", "--cache-type-v") ?? o.cacheTypeV ?? "f16";
return k === v ? k : `K ${k} / V ${v}`;
}
/** The GPUs a deployment gets: NVIDIA by UUID (all when none picked), /dev/dri ones by vendor. */
export function gpusUsed(hw: EffectiveHardware | null, accelerator: RuntimeAccelerator | undefined, options: Pick<DeploymentOptions, "gpus">, nvidia: HostGpu[]): HardwareGpu[] {
const all = hw?.gpus ?? [];
if (accelerator === "nvidia") {
const picked = options.gpus?.length ? nvidia.filter((g) => options.gpus!.includes(g.uuid)).map((g) => g.pciAddress) : null;
return all.filter((g) => g.vendor === "nvidia" && (!picked || picked.includes(g.pciAddress)));
}
if (accelerator === "dri") return all.filter((g) => g.vendor === "intel" || g.vendor === "amd");
if (accelerator === "rocm") return all.filter((g) => g.vendor === "amd");
return [];
}
export function buildRunMeta(x: {
hardware: EffectiveHardware | null;
gpus: HardwareGpu[];
runtime: { image: string; digest: string | null; engine: RuntimeEngine; engineName: string | null; extraArgs: string[] };
repoId: string;
options: DeploymentOptions;
engineInfo: EngineInfo | null;
}): RunMeta {
const args = [...x.runtime.extraArgs, ...x.options.extraArgs];
const llama = x.runtime.engine === "llama.cpp";
return {
v: 1,
gpus: x.gpus.map((g) => ({ pciAddress: g.pciAddress, name: g.name, vramMb: g.vramMb, linkCurrent: g.linkCurrent, linkMax: g.linkMax, rebar: g.rebar })),
linkUnderLoad: false,
p2p: x.gpus.length < 2 ? "n/a" : (x.hardware?.p2p ?? null),
rebar: x.gpus.length === 0 ? null : x.gpus.every((g) => g.rebar === true) ? true : x.gpus.some((g) => g.rebar === false) ? false : null,
runtime: {
image: x.runtime.image,
tag: imageTag(x.runtime.image),
digest: x.runtime.digest,
engine: x.runtime.engine,
engineName: x.runtime.engineName?.trim() || x.runtime.engine,
engineVersion: x.engineInfo?.version ?? null,
},
model: {
repoId: x.repoId,
file: x.options.modelFile || null,
quant: quantOf(x.runtime.engine, x.options.modelFile || null, x.repoId, args),
kvCache: kvCacheOf(x.runtime.engine, x.options, args),
},
contextSize: x.engineInfo?.contextSize ?? x.options.contextSize ?? null,
concurrency: x.engineInfo?.slots ?? (llama ? x.options.parallel : x.options.maxNumSeqs) ?? null,
overridden: x.hardware?.overridden ?? [],
};
}
/** "2× NVIDIA RTX 4090 (24 GiB)", "1× Intel Arc Pro B65 (32 GiB) + 1× …"; null without GPUs. */
export function gpuLabel(m: RunMeta): string | null {
if (m.gpus.length === 0) return null;
const counts = new Map<string, number>();
for (const g of m.gpus) {
const name = `${g.name ?? "unknown GPU"}${g.vramMb ? ` (${Math.round(g.vramMb / 1024)} GiB)` : ""}`;
counts.set(name, (counts.get(name) ?? 0) + 1);
}
return [...counts].map(([name, n]) => `${n}× ${name}`).join(" + ");
}
/** The PCIe links of the GPUs used, deduplicated; "(idle)" when not measured under load. */
export function pcieLabel(m: RunMeta): string | null {
const links = [...new Set(m.gpus.map((g) => formatLinkPair(g.linkCurrent, g.linkMax) ?? "unknown"))];
if (!links.length) return null;
const idle = !m.linkUnderLoad && m.gpus.some((g) => g.linkCurrent);
return `${links.join(", ")}${idle ? " (at idle)" : ""}`;
}
/** Maximum links only ("Gen5 x16"): known before the run, unlike the link under load. */
export function pcieMaxLabel(m: RunMeta): string | null {
const links = [...new Set(m.gpus.map((g) => formatLink(g.linkMax) ?? "unknown"))];
return links.length ? links.join(", ") : null;
}
/** The run's meta with the fastest links seen during the run as the current links (when sampled). */
export function withLoadLinks(m: RunMeta | null, links: Record<string, PcieLink> | null | undefined, overridden: boolean): RunMeta | null {
if (!m || !links || overridden) return m;
let hit = false;
const gpus = m.gpus.map((g) => {
const l = g.pciAddress ? links[g.pciAddress] : undefined;
if (!l) return g;
hit = true;
return { ...g, linkCurrent: l };
});
return hit ? { ...m, gpus, linkUnderLoad: true } : m;
}
export const engineLabel = (m: RunMeta) => [m.runtime.engineName, m.runtime.engineVersion].filter(Boolean).join(" ");
/** "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache" */
export function modelLabel(m: RunMeta): string {
const name = m.model.repoId.split("/").pop() ?? m.model.repoId;
return `${name}${m.model.quant ? ` ${m.model.quant}` : ""}${m.model.kvCache ? ` with ${m.model.kvCache} KV cache` : ""}`;
}
/** Rows for the run page, compare views and sweeps (label → value, "unknown" where not known). */
export function metaRows(m: RunMeta): { key: string; label: string; value: string }[] {
return [
{ key: "gpus", label: "GPUs", value: gpuLabel(m) ?? "none (CPU)" },
...(m.gpus.length ? [{ key: "pcie", label: "PCIe", value: pcieLabel(m) ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "p2p", label: "P2P", value: m.p2p ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "rebar", label: "ReBAR", value: onOff(m.rebar) }] : []),
{ key: "engine", label: "Engine", value: engineLabel(m) || "unknown" },
{ key: "image", label: "Image", value: m.runtime.image },
{ key: "digest", label: "Digest", value: m.runtime.digest ?? "unknown" },
{ key: "model", label: "Model", value: modelLabel(m) },
{ key: "ctx", label: "Context", value: m.contextSize != null ? m.contextSize.toLocaleString("en-US") : "unknown" },
{ key: "concurrency", label: "Concurrency", value: m.concurrency != null ? String(m.concurrency) : "server default" },
];
}
/**
* BetterBench --note values (recorded in results.json, shown in its report and published to
* launch80). `engine` is the key launch80 uses to name the stack.
*/
export function metaNotes(m: RunMeta, system: SystemSummary | null, description: string | null): Record<string, string> {
const notes: Record<string, string> = {
engine: engineLabel(m) || m.runtime.engine,
image: m.runtime.image,
...(m.runtime.digest ? { digest: m.runtime.digest } : {}),
...(m.model.quant ? { quant: m.model.quant } : {}),
...(m.model.kvCache ? { kv_cache: m.model.kvCache } : {}),
...(m.contextSize != null ? { ctx: String(m.contextSize) } : {}),
...(m.concurrency != null ? { concurrency: String(m.concurrency) } : {}),
gpus: gpuLabel(m) ?? "none",
};
if (m.gpus.length) {
// The link under load is only known after the run (idle GPUs drop to a slower link).
notes.pcie_max = pcieMaxLabel(m) ?? "unknown";
notes.p2p = m.p2p ?? "unknown";
notes.rebar = onOff(m.rebar);
}
if (system) notes.system = systemSummaryText(system);
if (description?.trim()) notes.description = description.trim().replace(/\s+/g, " ").slice(0, 2000);
return notes;
}
+167
View File
@@ -0,0 +1,167 @@
// What a run records about its setup, against a temporary database: detected hardware from the
// worker, Settings → Hardware overrides, the runtime's digest and the server's reported version.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import type { HostHardware } from "./db/schema";
const dir = mkdtempSync(join(tmpdir(), "kaname-setup-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.APP_VERSION = "0.11.0-test";
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
snapshot: typeof import("./benchmark-snapshot");
settings: typeof import("./settings");
benchmarks: typeof import("./benchmarks");
};
let M: Mods;
let deploymentId: string;
const hardware: HostHardware = {
gpus: [
{
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1",
linkCurrent: { gen: 1, width: 1 },
linkMax: { gen: 5, width: 16 },
barMb: 256,
rebar: false,
},
],
p2p: null,
cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
memoryBytes: 128e9,
kernel: "6.17.1",
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: { model: "QEMU HARDDISK", kind: "virtual", sizeBytes: 2e12 },
checkedAt: new Date().toISOString(),
};
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
snapshot: await import("./benchmark-snapshot"),
settings: await import("./settings"),
benchmarks: await import("./benchmarks"),
};
const d = M.db.db();
const s = M.schema;
const now = new Date();
await d.insert(s.workerState).values({
id: "worker",
startedAt: now,
heartbeatAt: now,
docker: {
connected: true,
error: null,
serverVersion: "29.0",
os: "Debian GNU/Linux 13 (trixie)",
architecture: "x86_64",
cpus: 32,
memoryBytes: 128e9,
cpuModel: null,
cpuFeatures: [],
network: "kaname_default",
modelsSource: { type: "bind", source: "/srv/models" },
hardware,
checkedAt: now.toISOString(),
},
});
const [model] = await d.insert(s.models).values({ repoId: "unsloth/Qwen3-8B-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Qwen3-8B-GGUF" }).returning();
const [rt] = await d
.insert(s.runtimes)
.values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageDigest: "sha256:feed" })
.returning();
const [dep] = await d
.insert(s.deployments)
.values({
name: "qwen3 b65",
runtimeId: rt.id,
modelId: model.id,
options: { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 16384, cacheTypeK: "q8_0", cacheTypeV: "q8_0", extraArgs: [] },
state: "running",
engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 16384, at: now.toISOString() },
})
.returning();
deploymentId = dep.id;
});
after(() => {
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment.
}
});
describe("run setup", () => {
it("records GPU, link, ReBAR, engine version, quant, KV cache, context and slots", async () => {
const { metas, system } = await M.snapshot.runSetup([deploymentId, null]);
const m = metas[0]!;
assert.equal(metas[1], null);
assert.equal(m.gpus.length, 1);
assert.equal(m.gpus[0].name, "Intel Arc Pro B65");
assert.deepEqual(m.gpus[0].linkCurrent, { gen: 1, width: 1 });
assert.equal(m.rebar, false);
assert.equal(m.p2p, "n/a");
assert.deepEqual(m.runtime, {
image: "ghcr.io/ggml-org/llama.cpp:server-intel",
tag: "server-intel",
digest: "sha256:feed",
engine: "llama.cpp",
engineName: "llama.cpp",
engineVersion: "b11429-d81235049",
});
assert.deepEqual(m.model, { repoId: "unsloth/Qwen3-8B-GGUF", file: "Qwen3-8B-Q4_K_M.gguf", quant: "Q4_K_M", kvCache: "q8_0" });
assert.equal(m.contextSize, 16384);
assert.equal(m.concurrency, 4);
assert.deepEqual(m.overridden, []);
assert.equal(system.kaname, "0.11.0-test");
assert.equal(system.os, "Debian GNU/Linux 13 (trixie)");
assert.equal(system.virtualization.gpuPassthrough, true);
});
it("applies Settings → Hardware to new runs", async () => {
await M.settings.saveHardwareOverrides({
gpus: { "0000:03:00.0": { linkCurrent: "Gen5 x8", rebar: true } },
storage: "Samsung 990 PRO 2TB (passed through as a virtual disk)",
hypervisor: "Proxmox VE 9 (KVM)",
});
const { metas, system } = await M.snapshot.runSetup([deploymentId]);
assert.deepEqual(metas[0]!.gpus[0].linkCurrent, { gen: 5, width: 8 });
assert.equal(metas[0]!.rebar, true);
assert.deepEqual(metas[0]!.overridden, ["pcie link", "rebar", "storage", "virtualization"]);
assert.equal(system.storage?.model, "Samsung 990 PRO 2TB (passed through as a virtual disk)");
assert.equal(system.virtualization.hypervisor, "Proxmox VE 9 (KVM)");
});
it("rejects invalid overrides and clears them when empty", async () => {
await assert.rejects(M.settings.saveHardwareOverrides({ gpus: { "0000:03:00.0": { linkMax: "Gen9" } } }), (e: Error) => e instanceof M.settings.SettingsError && /PCIe link/.test(e.message));
assert.deepEqual(await M.settings.saveHardwareOverrides({}), {});
assert.deepEqual(await M.settings.getHardwareOverrides(), {});
});
it("keeps a description with the run, editable later", async () => {
const run = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ deploymentId, description: " q8_0 KV to fit 16k " }));
assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
await M.benchmarks.updateBenchmark(run.id, { label: "q8 KV" });
assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
await M.benchmarks.updateBenchmark(run.id, { description: "" });
const row = await M.benchmarks.getBenchmark(run.id);
assert.equal(row?.description, null);
assert.equal(row?.label, "q8 KV");
});
});
+42 -1
View File
@@ -3,7 +3,9 @@
import { and, eq, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
import { buildRunMeta, gpusUsed } from "@/lib/benchmark-meta";
import { type BenchmarkSnapshot, deployments, models, type RunMeta, runtimes, settings, type SystemSummary, workerState } from "@/lib/db/schema";
import { applyOverrides, HARDWARE_OVERRIDES_KEY, parseOverrides, systemSummary } from "@/lib/hardware";
/** Host CPU/RAM and the names of the GPUs a deployment uses (all detected ones when none are picked). */
async function hostFacts(uuids: string[] | null, nvidia: boolean) {
@@ -60,3 +62,42 @@ export async function deploymentSnapshot(deploymentId: string): Promise<{ id: st
},
};
}
/** Kaname's version (the image sets APP_VERSION). */
export const kanameVersion = () => process.env.APP_VERSION ?? "dev";
/** The detected hardware with Settings → Hardware applied, and the host's OS. */
export async function effectiveHardware() {
const [ws, ov] = await Promise.all([
db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
db().query.settings.findFirst({ where: eq(settings.key, HARDWARE_OVERRIDES_KEY) }),
]);
const docker = ws?.docker ?? null;
return { hardware: applyOverrides(docker?.hardware, parseOverrides(ov?.value)), nvidia: docker?.gpus ?? [], os: docker?.os ?? null };
}
/** Hardware, runtime and model facts of a deployment as it runs now, plus the system summary. */
export async function runSetup(deploymentIds: (string | null)[]): Promise<{ metas: (RunMeta | null)[]; system: SystemSummary }> {
const { hardware, nvidia, os } = await effectiveHardware();
const metas = await Promise.all(
deploymentIds.map(async (id) => {
if (!id) return null;
const [d] = await db()
.select({ options: deployments.options, engineInfo: deployments.engineInfo, repoId: models.repoId, runtime: runtimes })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(eq(deployments.id, id));
if (!d) return null;
return buildRunMeta({
hardware,
gpus: gpusUsed(hardware, d.runtime.accelerator, d.options, nvidia),
runtime: { image: d.runtime.image, digest: d.runtime.imageDigest, engine: d.runtime.engine, engineName: d.runtime.engineName, extraArgs: d.runtime.extraArgs },
repoId: d.repoId,
options: d.options,
engineInfo: d.engineInfo,
});
}),
);
return { metas, system: systemSummary(hardware, os, kanameVersion()) };
}
+16 -2
View File
@@ -17,9 +17,13 @@ export class BenchmarkError extends Error {
}
}
export const DESCRIPTION_MAX = 4000;
export const BenchmarkBody = z.object({
deploymentId: z.string().min(1),
label: z.string().trim().max(120).nullable().optional(),
/** Free text: what this run tries out. Passed to BetterBench and launch80 with the system summary. */
description: z.string().trim().max(DESCRIPTION_MAX).nullable().optional(),
quick: z.boolean().default(false),
passes: z.number().int().min(1).max(200).nullable().optional(),
warmup: z.number().int().min(0).max(50).nullable().optional(),
@@ -64,6 +68,7 @@ export async function createBenchmark(input: BenchmarkInput) {
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
description: input.description || null,
settings: {
quick: input.quick,
passes: input.passes ?? null,
@@ -101,6 +106,10 @@ const listColumns = {
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
sweepId: benchmarkRuns.sweepId,
meta: benchmarkRuns.meta,
metaB: benchmarkRuns.metaB,
system: benchmarkRuns.system,
description: benchmarkRuns.description,
createdAt: benchmarkRuns.createdAt,
};
@@ -141,8 +150,13 @@ export async function cancelBenchmark(id: string) {
}
}
export async function updateBenchmarkLabel(id: string, label: string | null) {
const res = await db().update(benchmarkRuns).set({ label: label?.trim() || null }).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
/** Rename a run (label) and/or change its description; fields left out stay as they are. */
export async function updateBenchmark(id: string, patch: { label?: string | null; description?: string | null }) {
const set: Partial<typeof benchmarkRuns.$inferInsert> = {};
if (patch.label !== undefined) set.label = patch.label?.trim() || null;
if (patch.description !== undefined) set.description = patch.description?.trim() || null;
if (Object.keys(set).length === 0) return;
const res = await db().update(benchmarkRuns).set(set).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
}
+109 -1
View File
@@ -377,10 +377,67 @@ export type DockerHostInfo = {
gpus?: HostGpu[];
gpuError?: string | null;
gpuCheckedAt?: string | null;
/** PCIe, ReBAR, system facts from sysfs/procfs (what the worker's container sees of the host). */
hardware?: HostHardware | null;
checkedAt: string;
};
export type HostGpu = { vendor: "nvidia"; index: number; uuid: string; name: string; memoryMb: number; driver: string };
export type HostGpu = {
vendor: "nvidia";
index: number;
uuid: string;
name: string;
memoryMb: number;
driver: string;
pciAddress?: string | null;
/** PCIe link as nvidia-smi reports it (also where sysfs isn't visible, e.g. WSL2). */
linkCurrent?: PcieLink | null;
linkMax?: PcieLink | null;
};
/** A PCIe link: generation (1 = 2.5 GT/s … 6 = 64 GT/s) and lanes. */
export type PcieLink = { gen: number | null; width: number | null };
export type GpuVendor = "nvidia" | "intel" | "amd";
/** A GPU as found on the PCI bus. The link is the card's upstream link (behind on-card switches). */
export type HardwareGpu = {
vendor: GpuVendor;
pciAddress: string;
name: string | null;
vramMb: number | null;
/** Kernel driver (nvidia, xe, i915, amdgpu) and its version (the kernel's for in-tree drivers). */
driver: string | null;
driverVersion: string | null;
linkCurrent: PcieLink | null;
linkMax: PcieLink | null;
/** Largest memory BAR in MiB; Resizable BAR is on when it covers the VRAM. */
barMb: number | null;
rebar: boolean | null;
};
export type HostHardware = {
gpus: HardwareGpu[];
/** Peer-to-peer between GPUs (NVIDIA: nvidia-smi topo); null = unknown or a single GPU. */
p2p: "on" | "off" | "partial" | null;
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
kernel: string | null;
virtualization: { vm: boolean | null; hypervisor: string | null };
/** The disk holding the models folder. */
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
checkedAt: string;
};
/** Settings → Hardware: manual values where detection can't see the truth (VMs, new GPUs). */
export type HardwareOverrides = {
gpus?: Record<string, { name?: string; vramMb?: number; linkCurrent?: string; linkMax?: string; rebar?: boolean }>;
p2p?: "on" | "off" | "partial";
storage?: string;
hypervisor?: string;
gpuPassthrough?: boolean;
gpuDriver?: string;
};
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
@@ -429,6 +486,10 @@ export const runtimes = sqliteTable("runtimes", {
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
pullError: text("pull_error"),
imageCheckedAt: ts("image_checked_at"),
/** Registry digest of the pulled image (sha256:…), from its RepoDigests. */
imageDigest: text("image_digest"),
/** Shown instead of the engine type for forks, e.g. "vllm-radiance". */
engineName: text("engine_name"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
@@ -534,6 +595,8 @@ export const deployments = sqliteTable("deployments", {
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
/** Version, slots and context the server reported once ready. */
engineInfo: text("engine_info", { mode: "json" }).$type<EngineInfo>(),
/** Temporary deployment created by a benchmark sweep (removed when its variant is done). */
sweepId: text("sweep_id"),
createdAt: createdAt(),
@@ -661,6 +724,8 @@ export type ResourceStats = {
memPeakBytes: number | null;
memLimitBytes: number | null;
}[];
/** Fastest PCIe link seen per GPU (PCI address) during the run. */
links?: Record<string, PcieLink>;
/** Whole-GPU figures (nvidia-smi), not per process. */
gpus: { index: number; name: string; vramTotalMb: number; vramPeakMb: number; vramAvgMb: number; utilAvg: number; utilPeak: number; powerAvgW: number | null; powerPeakW: number | null }[];
};
@@ -685,6 +750,43 @@ export type BenchmarkSnapshot = {
command: string;
};
/** What was measured on what, recorded when a run starts (Settings → Hardware overrides applied). */
export type RunMeta = {
v: 1;
gpus: { pciAddress?: string; name: string | null; vramMb: number | null; linkCurrent: PcieLink | null; linkMax: PcieLink | null; rebar: boolean | null }[];
/**
* GPUs lower their link speed when idle: true once linkCurrent is the fastest link seen while the run
* was under load (otherwise it is what detection saw, possibly idle).
*/
linkUnderLoad?: boolean;
/** "n/a" with fewer than two GPUs; null = unknown. */
p2p: "on" | "off" | "partial" | "n/a" | null;
/** On for every GPU used; null = unknown. */
rebar: boolean | null;
runtime: { image: string; tag: string | null; digest: string | null; engine: RuntimeEngine; engineName: string; engineVersion: string | null };
model: { repoId: string; file: string | null; quant: string | null; kvCache: string | null };
contextSize: number | null;
/** Parallel slots (llama.cpp) or max sequences (vLLM); reported by the server where it can. */
concurrency: number | null;
/** Fields taken from Settings → Hardware instead of detection. */
overridden: string[];
};
/** The host, as published: nothing that identifies it (no hostname, IP, user or path). */
export type SystemSummary = {
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
os: string | null;
kernel: string | null;
gpuDrivers: string[];
virtualization: { vm: boolean | null; hypervisor: string | null; gpuPassthrough: boolean | null };
kaname: string;
};
/** What the server reported about itself once ready (llama.cpp /props, vLLM /version and /v1/models). */
export type EngineInfo = { version: string | null; slots: number | null; contextSize: number | null; at: string };
/**
* BetterBench's own report rows for a run (betterbench.report: single_rows, prefill_rows,
* concurrency_rows, combined_score, sample_gate, …), copied as computed. Nothing in Kaname derives
@@ -800,6 +902,12 @@ export const benchmarkRuns = sqliteTable(
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
/** Hardware, runtime and model facts (A, and B of an A/B), recorded at the start. */
meta: text("meta", { mode: "json" }).$type<RunMeta>(),
metaB: text("meta_b", { mode: "json" }).$type<RunMeta>(),
system: text("system", { mode: "json" }).$type<SystemSummary>(),
/** Free text by the user; passed to BetterBench and launch80 with the system summary. */
description: text("description"),
createdAt: createdAt(),
},
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
+210
View File
@@ -0,0 +1,210 @@
// Host hardware as Kaname reports it: PCIe links, ReBAR, the system summary, and the manual
// overrides from Settings → Hardware. Pure; shared by the web app, the worker and tests.
import type { HardwareGpu, HardwareOverrides, HostHardware, PcieLink, SystemSummary } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
const GT_PER_GEN: [number, number][] = [
[2.5, 1],
[5, 2],
[8, 3],
[16, 4],
[32, 5],
[64, 6],
];
/** sysfs "16.0 GT/s PCIe" → 4; unknown speeds → null. */
export function linkGen(speed: string | null | undefined): number | null {
const gt = Number(speed?.match(/([\d.]+)\s*GT\/s/)?.[1]);
return GT_PER_GEN.find(([s]) => Math.abs(s - gt) < 0.01)?.[1] ?? null;
}
export function formatLink(l: PcieLink | null | undefined): string | null {
if (!l || (l.gen == null && l.width == null)) return null;
return [l.gen != null ? `Gen${l.gen}` : null, l.width != null ? `x${l.width}` : null].filter(Boolean).join(" ");
}
/** "Gen4 x8 of Gen5 x16", or just "Gen5 x16" when the link runs at its maximum. */
export function formatLinkPair(current: PcieLink | null | undefined, max: PcieLink | null | undefined): string | null {
const c = formatLink(current);
const m = formatLink(max);
if (!c) return m ? `? of ${m}` : null;
return !m || c === m ? c : `${c} of ${m}`;
}
/** "Gen4 x8", "gen 4 x8", "x16" → a link; null when it isn't one. */
export function parseLinkText(text: string): PcieLink | null {
const t = text.trim();
const m = t.match(/^(?:gen\s*([1-6]))?\s*(?:x\s*(\d{1,2}))?$/i);
if (!t || !m || (!m[1] && !m[2])) return null;
return { gen: m[1] ? Number(m[1]) : null, width: m[2] ? Number(m[2]) : null };
}
/** ReBAR is on when the largest BAR maps (nearly) all of the VRAM; without it BARs are 256 MiB. */
export function rebarFrom(barMb: number | null, vramMb: number | null): boolean | null {
if (barMb == null) return null;
if (vramMb) return barMb >= vramMb * 0.9;
return barMb >= 2048 ? true : null;
}
export const onOff = (v: boolean | null | undefined) => (v == null ? "unknown" : v ? "on" : "off");
export type EffectiveHardware = HostHardware & {
gpuPassthrough: boolean | null;
gpuDriver: string | null;
/** Which values came from Settings → Hardware (e.g. "gpu 0000:03:00.0 link", "storage"). */
overridden: string[];
};
/** Detected hardware with the overrides applied. */
export function applyOverrides(hw: HostHardware | null | undefined, o: HardwareOverrides = {}): EffectiveHardware | null {
if (!hw) return null;
const overridden: string[] = [];
const gpus: HardwareGpu[] = hw.gpus.map((g) => {
const x = o.gpus?.[g.pciAddress];
if (!x) return g;
const cur = x.linkCurrent ? parseLinkText(x.linkCurrent) : null;
const max = x.linkMax ? parseLinkText(x.linkMax) : null;
const set = <K extends keyof HardwareGpu>(key: K, v: HardwareGpu[K] | null | undefined, label: string) => {
if (v == null || v === "") return;
out[key] = v;
overridden.push(label);
};
const out = { ...g };
set("name", x.name, "gpu name");
set("vramMb", x.vramMb, "vram");
set("linkCurrent", cur, "pcie link");
set("linkMax", max, "pcie max link");
set("rebar", x.rebar, "rebar");
if (x.rebar == null && x.vramMb) out.rebar = rebarFrom(g.barMb, x.vramMb);
return out;
});
const passthroughDetected = hw.virtualization.vm ? hw.gpus.length > 0 : hw.virtualization.vm === false ? false : null;
if (o.p2p) overridden.push("p2p");
if (o.storage) overridden.push("storage");
if (o.hypervisor) overridden.push("virtualization");
if (o.gpuPassthrough != null) overridden.push("gpu passthrough");
if (o.gpuDriver) overridden.push("gpu driver");
return {
...hw,
gpus,
p2p: o.p2p ?? hw.p2p,
storage: o.storage ? { model: o.storage, kind: hw.storage?.kind ?? null, sizeBytes: hw.storage?.sizeBytes ?? null } : hw.storage,
virtualization: o.hypervisor ? { vm: true, hypervisor: o.hypervisor } : hw.virtualization,
gpuPassthrough: o.gpuPassthrough ?? passthroughDetected,
gpuDriver: o.gpuDriver ?? null,
overridden: [...new Set(overridden)],
};
}
/** Driver labels, e.g. "nvidia 580.82.07", "xe (kernel 6.17.1)". */
export function driverLabels(gpus: HardwareGpu[]): string[] {
return [...new Set(gpus.filter((g) => g.driver).map((g) => (g.driverVersion ? `${g.driver} ${g.driverVersion}` : g.driver!)))];
}
/**
* The publishable system summary. Only whitelisted facts: CPU, RAM, disk model, OS, kernel, drivers,
* virtualization, Kaname version. Never the hostname, addresses, users or paths.
*/
export function systemSummary(hw: EffectiveHardware | null, os: string | null, kaname: string): SystemSummary {
return {
cpu: hw?.cpu ?? { model: null, cores: null, threads: null },
memoryBytes: hw?.memoryBytes ?? null,
storage: hw?.storage ?? null,
os,
kernel: hw?.kernel ?? null,
gpuDrivers: hw?.gpuDriver ? [hw.gpuDriver] : driverLabels(hw?.gpus ?? []),
virtualization: { vm: hw?.virtualization.vm ?? null, hypervisor: hw?.virtualization.hypervisor ?? null, gpuPassthrough: hw?.gpuPassthrough ?? null },
kaname,
};
}
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
/** One line per fact, for notes, the run page and launch80. */
export function systemSummaryLines(s: SystemSummary): string[] {
const cpu = s.cpu.model
? `${s.cpu.model}${s.cpu.cores || s.cpu.threads ? ` (${[s.cpu.cores && `${s.cpu.cores} cores`, s.cpu.threads && `${s.cpu.threads} threads`].filter(Boolean).join(", ")})` : ""}`
: null;
const disk = s.storage ? [s.storage.model, s.storage.kind && STORAGE_KIND[s.storage.kind], s.storage.sizeBytes && formatBytes(s.storage.sizeBytes)].filter(Boolean).join(", ") : null;
const v = s.virtualization;
const virt = v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}${v.gpuPassthrough ? " with GPU passthrough" : ""}` : "bare metal";
return [
cpu && `CPU: ${cpu}`,
s.memoryBytes && `RAM: ${formatBytes(s.memoryBytes)}`,
disk && `Models disk: ${disk}`,
(s.os || s.kernel) && `OS: ${[s.os, s.kernel && `kernel ${s.kernel}`].filter(Boolean).join(", ")}`,
s.gpuDrivers.length > 0 && `GPU driver: ${s.gpuDrivers.join(", ")}`,
virt && `Virtualization: ${virt}`,
`Kaname ${s.kaname}`,
].filter((x): x is string => !!x);
}
export const systemSummaryText = (s: SystemSummary) => systemSummaryLines(s).join(" · ");
export const HARDWARE_OVERRIDES_KEY = "hardware.overrides";
const TEXT_MAX = 120;
export class HardwareOverrideError extends Error {}
const text = (v: unknown, what: string): string | undefined => {
if (v == null || v === "") return undefined;
if (typeof v !== "string" || v.trim().length > TEXT_MAX || /[\r\n\0]/.test(v)) throw new HardwareOverrideError(`${what}: at most ${TEXT_MAX} characters on one line.`);
return v.trim() || undefined;
};
const bool = (v: unknown, what: string): boolean | undefined => {
if (v == null || v === "") return undefined;
if (typeof v !== "boolean") throw new HardwareOverrideError(`${what} must be on or off.`);
return v;
};
const linkText = (v: unknown, what: string): string | undefined => {
const t = text(v, what);
if (t && !parseLinkText(t)) throw new HardwareOverrideError(`${what}: "${t}" isn't a PCIe link (e.g. "Gen4 x8").`);
return t;
};
/** Validate overrides from the settings form; throws HardwareOverrideError. Empty fields are dropped. */
export function validateOverrides(input: unknown): HardwareOverrides {
const o = (input ?? {}) as Record<string, unknown>;
const out: HardwareOverrides = {};
const gpus: NonNullable<HardwareOverrides["gpus"]> = {};
for (const [addr, raw] of Object.entries((o.gpus ?? {}) as Record<string, Record<string, unknown>>)) {
if (!/^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i.test(addr)) throw new HardwareOverrideError(`"${addr}" isn't a PCI address.`);
const vram = raw?.vramMb;
if (vram != null && vram !== "" && (typeof vram !== "number" || !Number.isInteger(vram) || vram < 256 || vram > 4_194_304)) {
throw new HardwareOverrideError("VRAM must be a whole number of MiB (256 – 4194304).");
}
const g = {
name: text(raw?.name, "GPU name"),
vramMb: typeof vram === "number" ? vram : undefined,
linkCurrent: linkText(raw?.linkCurrent, "Current link"),
linkMax: linkText(raw?.linkMax, "Maximum link"),
rebar: bool(raw?.rebar, "ReBAR"),
};
const set = Object.fromEntries(Object.entries(g).filter(([, v]) => v !== undefined));
if (Object.keys(set).length) gpus[addr.toLowerCase()] = set;
}
if (Object.keys(gpus).length) out.gpus = gpus;
if (o.p2p != null && o.p2p !== "") {
if (o.p2p !== "on" && o.p2p !== "off" && o.p2p !== "partial") throw new HardwareOverrideError("P2P must be on, off or partial.");
out.p2p = o.p2p;
}
const storage = text(o.storage, "Models disk");
const hypervisor = text(o.hypervisor, "Virtualization");
const gpuDriver = text(o.gpuDriver, "GPU driver");
const passthrough = bool(o.gpuPassthrough, "GPU passthrough");
if (storage) out.storage = storage;
if (hypervisor) out.hypervisor = hypervisor;
if (gpuDriver) out.gpuDriver = gpuDriver;
if (passthrough != null) out.gpuPassthrough = passthrough;
return out;
}
/** Stored overrides; anything invalid is ignored rather than breaking a run. */
export function parseOverrides(stored: unknown): HardwareOverrides {
try {
return validateOverrides(stored);
} catch {
return {};
}
}
+4 -1
View File
@@ -89,6 +89,8 @@ export type PayloadPreview = {
summary: string | null;
model: string | null;
notes: Record<string, string>;
/** Page sections: the run's description, hardware/runtime facts and system summary. */
sections: { heading: string; body: string }[];
/** Top-level keys that will be sent, and env keys (endpoint/host must be absent). */
keys: string[];
envKeys: string[];
@@ -105,7 +107,7 @@ export async function readPayloadPreview(runId: string, pubId: string): Promise<
const data = JSON.parse(raw) as Record<string, unknown> & {
$template?: string;
env?: Record<string, unknown>;
l80?: { title?: string; summary?: string };
l80?: { title?: string; summary?: string; sections?: { heading?: string; body?: string }[] };
single_stream?: Record<string, unknown>;
prefill?: unknown[];
concurrency?: unknown[];
@@ -118,6 +120,7 @@ export async function readPayloadPreview(runId: string, pubId: string): Promise<
summary: data.l80?.summary ?? null,
model: typeof env.model === "string" ? env.model : null,
notes: (env.notes as Record<string, string>) ?? {},
sections: (data.l80?.sections ?? []).map((s) => ({ heading: String(s.heading ?? ""), body: String(s.body ?? "") })),
keys: Object.keys(data),
envKeys: Object.keys(env),
hostRemoved: !("endpoint" in env) && !("host" in env),
+5
View File
@@ -18,6 +18,8 @@ export type RuntimeInput = {
accelerator?: RuntimeAccelerator;
image: string;
description?: string | null;
/** Shown instead of the engine type in benchmarks, for forks (e.g. "vllm-radiance"). */
engineName?: string | null;
env?: Record<string, string>;
extraArgs?: string[];
devices?: string[];
@@ -147,6 +149,8 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
if (/[\r\n\0]/.test(v)) throw new RuntimeValidationError(`Value of ${k} must be a single line.`);
env[k] = v;
}
const engineName = input.engineName?.trim() || null;
if (engineName && !/^[\w][\w.+-]{0,59}$/.test(engineName)) throw new RuntimeValidationError("Engine name: letters, digits and . _ + - (up to 60), e.g. vllm-radiance.");
const extraArgs = (input.extraArgs ?? []).map((a) => a.trim()).filter(Boolean);
for (const a of extraArgs) if (/[\r\n\0]/.test(a)) throw new RuntimeValidationError("Arguments must be single lines.");
const devices = (input.devices ?? []).map((d) => d.trim()).filter(Boolean);
@@ -163,6 +167,7 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
accelerator,
image,
description: input.description?.trim() || null,
engineName,
env,
extraArgs,
devices,
+2 -1
View File
@@ -15,6 +15,7 @@ export const RuntimeBody = z.object({
accelerator: z.enum(RUNTIME_ACCELERATORS).optional(),
image: z.string().max(512),
description: z.string().max(2000).nullable().optional(),
engineName: z.string().max(60).nullable().optional(),
env: z.record(z.string(), z.string().max(4000)).optional(),
extraArgs: z.array(z.string().max(4000)).max(200).optional(),
devices: z.array(z.string().max(200)).max(20).optional(),
@@ -70,7 +71,7 @@ export async function updateRuntime(id: string, input: RuntimeInput): Promise<Ru
.set({
...v,
// A different image has to be looked up (and maybe pulled) again.
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, pullError: null } : {}),
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, pullError: null } : {}),
})
.where(eq(runtimes.id, id))
.returning();
+20 -1
View File
@@ -1,9 +1,10 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { type HardwareOverrides, settings } from "@/lib/db/schema";
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
import { isLabelColor } from "@/lib/colors";
import { HARDWARE_OVERRIDES_KEY, HardwareOverrideError, parseOverrides, validateOverrides } from "@/lib/hardware";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
@@ -119,3 +120,21 @@ export async function saveGuardrails(input: Partial<Guardrails>): Promise<Guardr
await write(GUARDRAILS_KEY, parsed);
return parsed;
}
/** Manual hardware values (Settings → Hardware) that replace what detection reports. */
export async function getHardwareOverrides(): Promise<HardwareOverrides> {
return parseOverrides(await read<unknown>(HARDWARE_OVERRIDES_KEY));
}
export async function saveHardwareOverrides(input: unknown): Promise<HardwareOverrides> {
let next: HardwareOverrides;
try {
next = validateOverrides(input);
} catch (err) {
if (err instanceof HardwareOverrideError) throw new SettingsError(err.message);
throw err;
}
if (Object.keys(next).length === 0) await db().delete(settings).where(eq(settings.key, HARDWARE_OVERRIDES_KEY));
else await write(HARDWARE_OVERRIDES_KEY, next);
return next;
}
+1 -1
View File
@@ -89,7 +89,7 @@ export async function getSweep(id: string) {
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runs = runIds.length
? await db()
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error })
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error, meta: benchmarkRuns.meta })
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];