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:
1 parent
1d2f908b75
commit
276108932d
199 files changed
+5462
-15961
No files matched your search
@@ -1,66 +0,0 @@
|
||||
import "server-only";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
import type { TokenIdentity } from "@/lib/api-tokens";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { agentActivity } from "@/lib/db/schema";
|
||||
|
||||
export type ActivityOutcome = "ok" | "pending_approval" | "refused";
|
||||
|
||||
/** Record what a token did (or was refused); never fails the request it belongs to. */
|
||||
export async function logActivity(
|
||||
token: TokenIdentity,
|
||||
action: string,
|
||||
x: { targetType?: string; targetId?: string | null; outcome: ActivityOutcome; code?: string | null; message?: string | null },
|
||||
): Promise<void> {
|
||||
try {
|
||||
await db()
|
||||
.insert(agentActivity)
|
||||
.values({
|
||||
tokenId: token.id,
|
||||
tokenName: token.name,
|
||||
action,
|
||||
targetType: x.targetType ?? null,
|
||||
targetId: x.targetId ?? null,
|
||||
outcome: x.outcome,
|
||||
code: x.code ?? null,
|
||||
message: x.message?.slice(0, 500) ?? null,
|
||||
});
|
||||
} catch (err) {
|
||||
console.error("[agent-activity]", err);
|
||||
}
|
||||
}
|
||||
|
||||
export type ActivityRow = typeof agentActivity.$inferSelect;
|
||||
|
||||
export async function listActivity(tokenId: string, limit = 100): Promise<ActivityRow[]> {
|
||||
return db().select().from(agentActivity).where(eq(agentActivity.tokenId, tokenId)).orderBy(desc(agentActivity.createdAt)).limit(limit);
|
||||
}
|
||||
|
||||
/** An error with a code and an HTTP status below 500: a refusal the agent caused, worth logging. */
|
||||
function refusal(err: unknown): { code: string; message: string } | null {
|
||||
const e = err as { code?: unknown; status?: unknown; message?: unknown };
|
||||
if (typeof e?.code === "string" && typeof e.status === "number" && e.status < 500) return { code: e.code, message: String(e.message ?? "") };
|
||||
if (err instanceof Error && err.name === "ZodError") return { code: "invalid_request", message: err.message.slice(0, 300) };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run an agent action and record it: ok, pending approval (when the result's state says so) or
|
||||
* refused with the error code. The error is rethrown for the route to answer.
|
||||
*/
|
||||
export async function act<T extends object>(token: TokenIdentity, action: string, target: { type: string; id?: string | null }, fn: () => Promise<T>): Promise<T> {
|
||||
try {
|
||||
const r = await fn();
|
||||
const { id, state } = r as { id?: unknown; state?: unknown };
|
||||
await logActivity(token, action, {
|
||||
targetType: target.type,
|
||||
targetId: target.id ?? (typeof id === "string" ? id : null),
|
||||
outcome: state === "pending_approval" ? "pending_approval" : "ok",
|
||||
});
|
||||
return r;
|
||||
} catch (err) {
|
||||
const why = refusal(err);
|
||||
if (why) await logActivity(token, action, { targetType: target.type, targetId: target.id ?? null, outcome: "refused", code: why.code, message: why.message });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
@@ -1,293 +0,0 @@
|
||||
import "server-only";
|
||||
import { and, eq, inArray, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { checkArgs, checkHostPort, checkLimits, checkStart, checkVram, type GpuLoad, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
import type { TokenIdentity } from "@/lib/api-tokens";
|
||||
import { effectiveHardware } from "@/lib/benchmark-snapshot";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { benchmarkRuns, benchmarkSweeps, type DeploymentOptions, deployments, models, type RuntimeAccelerator, runtimes } from "@/lib/db/schema";
|
||||
import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, estimateVramMb, renderCommand } from "@/lib/deploy-command";
|
||||
import {
|
||||
createDeployment,
|
||||
DeploymentBody,
|
||||
DeploymentError,
|
||||
type DeploymentInput,
|
||||
type DeploymentRow,
|
||||
deploymentFileBytes,
|
||||
getDeployment,
|
||||
requestDelete,
|
||||
setDesiredState,
|
||||
updateDeployment,
|
||||
validateDeployment,
|
||||
} from "@/lib/deployments";
|
||||
import { getDockerInfo } from "@/lib/runtimes";
|
||||
import { getTuning } from "@/lib/settings";
|
||||
|
||||
// Deployments through the API: the same validation, estimates and command as the UI, plus the agent
|
||||
// guardrails (runtime allowlist, argument allowlist, ports, caps, one GPU job at a time, protected
|
||||
// deployments, approval). Agents only change deployments their own token created.
|
||||
|
||||
const RUN_OPEN = ["pending_approval", "queued", "running"] as const;
|
||||
|
||||
/** Stored (already validated) options as request input; they're validated again on the way in. */
|
||||
const asInput = (o: DeploymentOptions) => o as DeploymentInput["options"];
|
||||
|
||||
export const AgentDeploymentBody = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(80).optional(),
|
||||
runtimeId: z.string().min(1),
|
||||
modelId: z.string().min(1),
|
||||
options: DeploymentBody.shape.options.strict(),
|
||||
cpus: z.number().min(0.1).max(1024).nullable().optional(),
|
||||
memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
|
||||
hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
|
||||
/** Start right away (default); with approval mode "approve" the start waits for the user. */
|
||||
start: z.boolean().default(true),
|
||||
/** Only validate and return the command and estimates; nothing is created. */
|
||||
dryRun: z.boolean().default(false),
|
||||
})
|
||||
.strict();
|
||||
export type AgentDeploymentInput = z.infer<typeof AgentDeploymentBody>;
|
||||
|
||||
export const AgentDeploymentPatch = z
|
||||
.object({
|
||||
name: z.string().trim().min(1).max(80).optional(),
|
||||
options: DeploymentBody.shape.options.partial().strict().optional(),
|
||||
cpus: z.number().min(0.1).max(1024).nullable().optional(),
|
||||
memoryMb: z.number().int().min(256).max(4_194_304).nullable().optional(),
|
||||
hostPort: z.number().int().min(1024).max(65_535).nullable().optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** Agent deployments, runs and sweeps that keep the GPU busy right now (all tokens). */
|
||||
export async function gpuLoad(selfId?: string): Promise<GpuLoad> {
|
||||
const notSelf = selfId ? ne(deployments.id, selfId) : undefined;
|
||||
const agentDep = and(isNotNull(deployments.requestedByTokenId), isNull(deployments.deleteRequestedAt), notSelf);
|
||||
const [[dep], [starting], [runs], [sweeps]] = await Promise.all([
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(deployments)
|
||||
.where(and(agentDep, or(eq(deployments.desiredState, "running"), isNotNull(deployments.startRequestedAt), inArray(deployments.state, ["starting", "running"])))),
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(deployments)
|
||||
.where(and(agentDep, eq(deployments.state, "starting"))),
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(benchmarkRuns)
|
||||
.where(and(isNotNull(benchmarkRuns.requestedByTokenId), inArray(benchmarkRuns.state, [...RUN_OPEN]))),
|
||||
db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(benchmarkSweeps)
|
||||
.where(and(isNotNull(benchmarkSweeps.requestedByTokenId), inArray(benchmarkSweeps.state, [...RUN_OPEN]))),
|
||||
]);
|
||||
return { agentDeployments: Number(dep.n), agentStarting: Number(starting.n), agentRuns: Number(runs.n) + Number(sweeps.n) };
|
||||
}
|
||||
|
||||
type Pool = { accelerator: RuntimeAccelerator; gpus: string[] | null };
|
||||
const sharesGpus = (a: Pool, b: Pool) =>
|
||||
a.accelerator !== "cpu" &&
|
||||
b.accelerator !== "cpu" &&
|
||||
(a.accelerator === "nvidia") === (b.accelerator === "nvidia") &&
|
||||
(a.accelerator !== "nvidia" || !a.gpus?.length || !b.gpus?.length || a.gpus.some((g) => b.gpus!.includes(g)));
|
||||
|
||||
/** VRAM of the GPUs a deployment gets (NVIDIA: the picked ones or all; /dev/dri: Intel and AMD). */
|
||||
async function poolVramMb(pool: Pool): Promise<number | null> {
|
||||
const { hardware, nvidia } = await effectiveHardware();
|
||||
if (pool.accelerator === "nvidia") {
|
||||
const gs = pool.gpus?.length ? nvidia.filter((g) => pool.gpus!.includes(g.uuid)) : nvidia;
|
||||
return gs.length ? gs.reduce((s, g) => s + g.memoryMb, 0) : null;
|
||||
}
|
||||
const gs = (hardware?.gpus ?? []).filter((g) => (pool.accelerator === "rocm" ? g.vendor === "amd" : g.vendor !== "nvidia"));
|
||||
return gs.length && gs.every((g) => g.vramMb) ? gs.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
|
||||
}
|
||||
|
||||
/** Estimated VRAM (null: can't tell) of a deployment's options. */
|
||||
async function vramOf(modelId: string, engine: "llama.cpp" | "vllm", options: DeploymentOptions, totalMb: number | null) {
|
||||
return estimateVramMb(await deploymentFileBytes(modelId, options, engine), options.contextSize, engine, options, totalMb);
|
||||
}
|
||||
|
||||
/** Refuse a start that would crowd a running protected deployment on the same GPUs out of VRAM. */
|
||||
async function checkProtectedVram(self: { id?: string; modelId: string; engine: "llama.cpp" | "vllm"; accelerator: RuntimeAccelerator; options: DeploymentOptions }) {
|
||||
if (self.accelerator === "cpu") return;
|
||||
const pool: Pool = { accelerator: self.accelerator, gpus: self.options.gpus ?? null };
|
||||
const running = (
|
||||
await db()
|
||||
.select({ id: deployments.id, name: deployments.name, protected: deployments.protected, modelId: deployments.modelId, options: deployments.options, engine: runtimes.engine, accelerator: runtimes.accelerator })
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(and(isNull(deployments.deleteRequestedAt), inArray(deployments.state, ["starting", "running"]), self.id ? ne(deployments.id, self.id) : undefined))
|
||||
).filter((d) => sharesGpus(pool, { accelerator: d.accelerator, gpus: d.options.gpus ?? null }));
|
||||
const protectedNames = running.filter((d) => d.protected).map((d) => d.name);
|
||||
if (protectedNames.length === 0) return;
|
||||
const totalMb = await poolVramMb(pool);
|
||||
checkVram({
|
||||
protectedNames,
|
||||
newMb: await vramOf(self.modelId, self.engine, self.options, totalMb),
|
||||
runningMb: await Promise.all(running.map(async (d) => (await vramOf(d.modelId, d.engine, d.options, totalMb)) ?? -1)),
|
||||
totalMb,
|
||||
});
|
||||
}
|
||||
|
||||
async function runtimeFor(g: TuningGuardrails, runtimeId: string) {
|
||||
const rt = await db().query.runtimes.findFirst({ where: eq(runtimes.id, runtimeId) });
|
||||
if (!rt) throw new DeploymentError("not_found", "Runtime not found. List them with GET /api/v1/runtimes.", 404);
|
||||
if (g.allowedRuntimeIds.length && !g.allowedRuntimeIds.includes(rt.id)) {
|
||||
throw new TuningError("runtime_not_allowed", `runtime "${rt.name}" isn't on the agents' allowlist. Pick one from GET /api/v1/runtimes with "allowed": true.`, 403);
|
||||
}
|
||||
if (rt.imageState !== "present") throw new TuningError("runtime_not_pulled", `runtime "${rt.name}" has no pulled image; ask the user to pull it in Settings → Runtimes.`, 409);
|
||||
return rt;
|
||||
}
|
||||
|
||||
/** The checked deployment: validated options, memory limit, estimates and the command it would run. */
|
||||
async function prepare(g: TuningGuardrails, input: { name: string; runtimeId: string; modelId: string; options: z.infer<typeof DeploymentBody>["options"]; cpus?: number | null; memoryMb?: number | null; hostPort?: number | null }, selfId?: string) {
|
||||
const rt = await runtimeFor(g, input.runtimeId);
|
||||
checkArgs(g, rt.engine, input.options.extraArgs);
|
||||
checkHostPort(g, input.hostPort);
|
||||
const options = await validateDeployment({ ...input, cpus: input.cpus ?? null, memoryMb: input.memoryMb ?? null, hostPort: input.hostPort ?? null }, selfId);
|
||||
const model = await db().query.models.findFirst({ columns: { repoId: true, localPath: true }, where: eq(models.id, input.modelId) });
|
||||
const fileBytes = await deploymentFileBytes(input.modelId, options, rt.engine);
|
||||
const docker = await getDockerInfo();
|
||||
const estimateMb = estimateMemoryMb(fileBytes, options.contextSize, rt.engine, { ...options, accelerator: rt.accelerator });
|
||||
const { memoryMb, cpus } = checkLimits(g, { memoryMb: input.memoryMb, cpus: input.cpus, estimateMb, hostMemoryMb: docker?.memoryBytes ? docker.memoryBytes / 2 ** 20 : null, hostCpus: docker?.cpus ?? null });
|
||||
const totalVram = rt.accelerator === "cpu" ? null : await poolVramMb({ accelerator: rt.accelerator, gpus: options.gpus ?? null });
|
||||
const vramMb = rt.accelerator === "cpu" ? null : estimateVramMb(fileBytes, options.contextSize, rt.engine, options, totalVram);
|
||||
const cmd = buildCommand({
|
||||
engine: rt.engine,
|
||||
options,
|
||||
model: { repoId: model?.repoId ?? "", localPath: model?.localPath ?? "" },
|
||||
runtime: rt,
|
||||
apiKeys: options.requireApiKey ? [API_KEY_PLACEHOLDER] : [],
|
||||
});
|
||||
return {
|
||||
rt,
|
||||
options,
|
||||
memoryMb,
|
||||
cpus,
|
||||
preview: {
|
||||
command: renderCommand(rt.image, cmd),
|
||||
estimates: { memoryMb: estimateMb, vramMb, gpuVramMb: totalVram },
|
||||
limits: { memoryMb, cpus },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Create (and by default start) a deployment for a token. */
|
||||
export async function createAgentDeployment(token: TokenIdentity, body: AgentDeploymentInput, g?: TuningGuardrails) {
|
||||
const guard = g ?? (await getTuning());
|
||||
const name = body.name ?? `${token.name} ${new Date().toISOString().slice(0, 16).replace("T", " ")}`;
|
||||
const p = await prepare(guard, { ...body, name });
|
||||
if (body.start) {
|
||||
checkStart(guard, await gpuLoad());
|
||||
await checkProtectedVram({ modelId: body.modelId, engine: p.rt.engine, accelerator: p.rt.accelerator, options: p.options });
|
||||
}
|
||||
if (body.dryRun) return { dryRun: true as const, created: false, id: null, state: "dry_run", ...p.preview };
|
||||
const pending = body.start && guard.approvalMode === "approve";
|
||||
const { id } = await createDeployment(
|
||||
{ name, runtimeId: body.runtimeId, modelId: body.modelId, options: asInput(p.options), cpus: p.cpus, memoryMb: p.memoryMb, hostPort: body.hostPort ?? null },
|
||||
body.start,
|
||||
{ requestedBy: { tokenId: token.id, name: token.name }, startPendingApproval: pending },
|
||||
);
|
||||
return { dryRun: false as const, created: true, id, state: pending ? "pending_approval" : body.start ? "starting" : "stopped", ...p.preview };
|
||||
}
|
||||
|
||||
/** A deployment this token may change: its own, and not protected. */
|
||||
async function ownDeployment(token: TokenIdentity, id: string): Promise<DeploymentRow> {
|
||||
const d = await getDeployment(id);
|
||||
if (!d) throw new DeploymentError("not_found", "No deployment with this id.", 404);
|
||||
if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't change, stop, delete or benchmark it.`, 403);
|
||||
if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only change their own deployments.`, 403);
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Change an own, stopped deployment's launch options (fields left out stay). */
|
||||
export async function updateAgentDeployment(token: TokenIdentity, id: string, patch: z.infer<typeof AgentDeploymentPatch>) {
|
||||
const guard = await getTuning();
|
||||
const d = await ownDeployment(token, id);
|
||||
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment first (POST …/stop), then change it.", 409);
|
||||
const input = {
|
||||
name: patch.name ?? d.name,
|
||||
runtimeId: d.runtimeId,
|
||||
modelId: d.modelId,
|
||||
options: asInput({ ...d.options, ...patch.options }),
|
||||
cpus: patch.cpus !== undefined ? patch.cpus : d.cpus,
|
||||
memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : d.memoryMb,
|
||||
hostPort: patch.hostPort !== undefined ? patch.hostPort : d.hostPort,
|
||||
};
|
||||
// The memory limit follows the options unless the agent sets one: re-estimate when it was implicit.
|
||||
const p = await prepare(guard, { ...input, memoryMb: patch.memoryMb !== undefined ? patch.memoryMb : patch.options ? null : d.memoryMb }, id);
|
||||
await updateDeployment(id, { ...input, options: asInput(p.options), memoryMb: p.memoryMb, cpus: p.cpus });
|
||||
return p.preview;
|
||||
}
|
||||
|
||||
/** Start an own deployment (waits for approval in mode "approve"). */
|
||||
export async function startAgentDeployment(token: TokenIdentity, id: string): Promise<{ state: string }> {
|
||||
const guard = await getTuning();
|
||||
const d = await ownDeployment(token, id);
|
||||
if (d.desiredState === "running") return { state: d.state };
|
||||
if (d.startRequestedAt) return { state: "pending_approval" };
|
||||
await runtimeFor(guard, d.runtimeId);
|
||||
checkStart(guard, await gpuLoad(id));
|
||||
await checkProtectedVram({ id, modelId: d.modelId, engine: d.engine, accelerator: d.accelerator, options: d.options });
|
||||
if (guard.approvalMode === "approve") {
|
||||
await db().update(deployments).set({ startRequestedAt: new Date() }).where(eq(deployments.id, id));
|
||||
return { state: "pending_approval" };
|
||||
}
|
||||
await setDesiredState(id, "running");
|
||||
return { state: "starting" };
|
||||
}
|
||||
|
||||
export async function stopAgentDeployment(token: TokenIdentity, id: string): Promise<void> {
|
||||
await ownDeployment(token, id);
|
||||
await setDesiredState(id, "stopped");
|
||||
}
|
||||
|
||||
export async function deleteAgentDeployment(token: TokenIdentity, id: string): Promise<void> {
|
||||
await ownDeployment(token, id);
|
||||
await requestDelete(id);
|
||||
}
|
||||
|
||||
/** Compact deployment state for agents; the log only on request. */
|
||||
export function deploymentView(d: DeploymentRow, token: TokenIdentity) {
|
||||
const port = ENGINE_PORT[d.engine];
|
||||
const pending = !!d.startRequestedAt;
|
||||
const state = pending ? "pending_approval" : d.state;
|
||||
return {
|
||||
id: d.id,
|
||||
name: d.name,
|
||||
state,
|
||||
desiredState: d.desiredState,
|
||||
protected: d.protected,
|
||||
requestedBy: d.requestedBy,
|
||||
mine: d.requestedByTokenId === token.id,
|
||||
runtime: { id: d.runtimeId, name: d.runtimeName, engine: d.engine, accelerator: d.accelerator, image: d.runtimeImage },
|
||||
model: { id: d.modelId, repoId: d.repoId },
|
||||
options: d.options,
|
||||
limits: { cpus: d.cpus, memoryMb: d.memoryMb },
|
||||
hostPort: d.hostPort,
|
||||
endpoint: d.state === "running" && d.containerName ? `http://${d.containerName}:${port}/v1` : null,
|
||||
engine: d.engineInfo ? { version: d.engineInfo.version, slots: d.engineInfo.slots, contextSize: d.engineInfo.contextSize } : null,
|
||||
usage: d.stats ? { cpuPercent: Math.round(d.stats.cpuPercent), memoryBytes: d.stats.memoryBytes, memoryLimitBytes: d.stats.memoryLimitBytes, at: d.stats.at } : null,
|
||||
error: d.error,
|
||||
startedAt: d.startedAt?.toISOString() ?? null,
|
||||
readyAt: d.readyAt?.toISOString() ?? null,
|
||||
next: deploymentNext(state, d.desiredState),
|
||||
};
|
||||
}
|
||||
|
||||
function deploymentNext(state: string, desired: string): string {
|
||||
if (state === "pending_approval") return "The start waits for the user's approval in Kaname. Don't retry or poll; tell the user and stop.";
|
||||
if (state === "starting" || (desired === "running" && state === "stopped")) return "Starting (loading the model); GET this deployment with ?wait=600 instead of polling.";
|
||||
if (state === "running") return "Ready: benchmark it with POST /api/v1/benchmarks.";
|
||||
if (state === "failed") return "Failed to start; see error (and ?log=50). Change the options (PATCH) and start again, or tell the user.";
|
||||
if (state === "stopping") return "Stopping.";
|
||||
return "Stopped.";
|
||||
}
|
||||
|
||||
/** Settled for ?wait=: not on the way between states. */
|
||||
export function deploymentSettled(v: { state: string; desiredState: string }): boolean {
|
||||
if (v.state === "starting" || v.state === "stopping") return false;
|
||||
if (v.desiredState === "running" && v.state === "stopped") return false;
|
||||
if (v.desiredState === "stopped" && v.state === "running") return false;
|
||||
return true;
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
import "server-only";
|
||||
import { and, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
|
||||
import { checkAuthor, checkGuardrails, type Guardrails } from "@/lib/agent-guardrails";
|
||||
import { newPaths, resolveRequestPaths } from "@/lib/agent-selection";
|
||||
import type { TokenIdentity } from "@/lib/api-tokens";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { jobs, modelFiles, models } from "@/lib/db/schema";
|
||||
import { lookupRepo } from "@/lib/hub/lookup";
|
||||
import { JobError, OPEN_STATES, queueDownload } from "@/lib/jobs";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { addFilesToModel, addModel, ModelError, restoreSelection } from "@/lib/models";
|
||||
import { escapeGlob } from "@/lib/selection";
|
||||
import { getGuardrails, getRecommendedRoles } from "@/lib/settings";
|
||||
import { addTag, normalizeTagName } from "@/lib/tags";
|
||||
import { getWorkerStatus } from "@/lib/worker-status";
|
||||
|
||||
export type DownloadRequest = {
|
||||
repoId: string;
|
||||
sha: string;
|
||||
/** Branch to track for update checks (default "main"). */
|
||||
revision?: string;
|
||||
quant?: string;
|
||||
include?: string[];
|
||||
tags?: string[];
|
||||
};
|
||||
|
||||
export type DownloadOutcome = {
|
||||
/** false: the same repo + commit + files was requested before; nothing new was queued. */
|
||||
created: boolean;
|
||||
modelId: string;
|
||||
jobId: string | null;
|
||||
state: string;
|
||||
requestedBytes: number;
|
||||
files: string[];
|
||||
message: string;
|
||||
};
|
||||
|
||||
/** Bytes that open download jobs still have to fetch (pending approval included). */
|
||||
export async function reservedBytes(): Promise<number> {
|
||||
const [r] = await db()
|
||||
.select({ n: sql<number>`coalesce(sum(${jobs.totalBytes} - ${jobs.doneBytes}), 0)` })
|
||||
.from(jobs)
|
||||
.where(and(eq(jobs.kind, "download"), inArray(jobs.state, [...OPEN_STATES])));
|
||||
return Number(r.n);
|
||||
}
|
||||
|
||||
/** API-requested jobs that are pending approval, queued or running (all tokens). */
|
||||
export async function openAgentJobs(): Promise<number> {
|
||||
const [r] = await db()
|
||||
.select({ n: sql<number>`count(*)` })
|
||||
.from(jobs)
|
||||
.where(and(isNotNull(jobs.requestedByTokenId), inArray(jobs.state, [...OPEN_STATES])));
|
||||
return Number(r.n);
|
||||
}
|
||||
|
||||
function stateMessage(state: string, created: boolean): string {
|
||||
if (state === "pending_approval") {
|
||||
return `${created ? "Requested" : "Already requested"}; waiting for the user to approve it in Kaname. Do not retry or poll; tell the user and stop.`;
|
||||
}
|
||||
if (state === "queued" || state === "downloading" || state === "verifying") return `${created ? "Queued" : "Already queued"}; GET /api/v1/jobs/{jobId}?wait=900 until it is done.`;
|
||||
if (state === "completed") return "Already downloaded.";
|
||||
return `The last download ended as "${state}"; ask the user to retry it in Kaname.`;
|
||||
}
|
||||
|
||||
/** Latest job of a model, for answers to repeated requests. */
|
||||
async function latestJob(modelId: string) {
|
||||
return db().query.jobs.findFirst({ columns: { id: true, state: true }, where: eq(jobs.modelId, modelId), orderBy: (j, { desc }) => desc(j.createdAt) });
|
||||
}
|
||||
|
||||
/**
|
||||
* A download requested through the API. Checks the author allowlist, resolves the files at the
|
||||
* pinned commit, applies the guardrails, then uses the same addModel / addFilesToModel / queue path
|
||||
* as the UI. Repeating a request returns what exists instead of queueing a duplicate.
|
||||
*/
|
||||
export async function requestDownload(token: TokenIdentity, req: DownloadRequest, guardrails?: Guardrails): Promise<DownloadOutcome> {
|
||||
const g = guardrails ?? (await getGuardrails());
|
||||
// The allowlist first, before anything goes to the Hub.
|
||||
checkAuthor(g, req.repoId);
|
||||
(req.tags ?? []).forEach(normalizeTagName); // validate before anything is written
|
||||
|
||||
const hub = await lookupRepo(req.repoId, req.sha);
|
||||
const paths = resolveRequestPaths(hub.files, req, await getRecommendedRoles());
|
||||
const size = new Map(hub.files.map((f) => [f.path, f.size]));
|
||||
const requestedBy = { tokenId: token.id, name: token.name };
|
||||
const pendingApproval = g.approvalMode === "approve";
|
||||
|
||||
const existing = await db().query.models.findFirst({ where: sql`lower(${models.repoId}) = lower(${hub.repoId})` });
|
||||
if (existing && existing.pinnedSha !== hub.sha) {
|
||||
throw new ModelError(
|
||||
"already_exists",
|
||||
`${existing.repoId} is already in the library, pinned to commit ${existing.pinnedSha}; you asked for ${hub.sha}. Updating a model is done by the user in Kaname, not through the API.`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
|
||||
let add = paths;
|
||||
if (existing) {
|
||||
const selected = await db().select({ path: modelFiles.path }).from(modelFiles).where(and(eq(modelFiles.modelId, existing.id), eq(modelFiles.selected, true)));
|
||||
add = newPaths(paths, selected.map((f) => f.path));
|
||||
if (add.length === 0) {
|
||||
const job = await latestJob(existing.id);
|
||||
const state = job?.state ?? existing.status;
|
||||
return { created: false, modelId: existing.id, jobId: job?.id ?? null, state, requestedBytes: 0, files: paths, message: stateMessage(state, false) };
|
||||
}
|
||||
const open = await db().query.jobs.findFirst({ columns: { id: true, state: true }, where: and(eq(jobs.modelId, existing.id), inArray(jobs.state, [...OPEN_STATES])) });
|
||||
if (open) {
|
||||
throw new JobError("busy", `${existing.repoId} has a download that is still ${open.state.replace("_", " ")} (job ${open.id}). Request the other files once it has finished.`, 409);
|
||||
}
|
||||
}
|
||||
|
||||
const requestBytes = add.reduce((s, p) => s + (size.get(p) ?? 0), 0);
|
||||
const worker = await getWorkerStatus();
|
||||
checkGuardrails(g, {
|
||||
repoId: hub.repoId,
|
||||
requestBytes,
|
||||
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
|
||||
reservedBytes: await reservedBytes(),
|
||||
openAgentJobs: await openAgentJobs(),
|
||||
});
|
||||
|
||||
let modelId: string;
|
||||
let jobId: string;
|
||||
if (existing) {
|
||||
modelId = existing.id;
|
||||
({ jobId } = await addFilesToModel(existing.id, add, { pendingApproval, requestedBy }));
|
||||
} else {
|
||||
({ id: modelId } = await addModel({
|
||||
repoId: hub.repoId,
|
||||
revision: req.revision?.trim() || "main",
|
||||
sha: hub.sha,
|
||||
rule: { include: paths.map(escapeGlob), exclude: [] },
|
||||
requestedBy,
|
||||
}));
|
||||
({ jobId } = await queueDownload(modelId, "initial", { pendingApproval, requestedBy }));
|
||||
}
|
||||
for (const tag of req.tags ?? []) await addTag(modelId, tag);
|
||||
const state = pendingApproval ? "pending_approval" : "queued";
|
||||
return { created: true, modelId, jobId, state, requestedBytes: requestBytes, files: paths, message: stateMessage(state, true) };
|
||||
}
|
||||
|
||||
async function pendingJob(jobId: string) {
|
||||
const job = await db().query.jobs.findFirst({ where: eq(jobs.id, jobId) });
|
||||
if (!job) throw new JobError("not_found", "Job not found.", 404);
|
||||
if (job.state !== "pending_approval") throw new JobError("not_cancellable", `This job doesn't wait for approval (it is ${job.state}).`, 409);
|
||||
return job;
|
||||
}
|
||||
|
||||
/** Let an API-requested download start. */
|
||||
export async function approveJob(jobId: string): Promise<void> {
|
||||
const job = await pendingJob(jobId);
|
||||
const d = db();
|
||||
await d.batch([
|
||||
d.update(jobs).set({ state: "queued" }).where(and(eq(jobs.id, job.id), eq(jobs.state, "pending_approval"))),
|
||||
d.update(models).set({ status: "downloading" }).where(eq(models.id, job.modelId)),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn an API-requested download down. A new model that was only added by this request leaves the
|
||||
* library again; for added files, the model's previous selection is restored.
|
||||
*/
|
||||
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean }> {
|
||||
const job = await pendingJob(jobId);
|
||||
await db()
|
||||
.update(jobs)
|
||||
.set({ state: "cancelled", finishedAt: new Date(), errorMessage: "Rejected by the user." })
|
||||
.where(eq(jobs.id, job.id));
|
||||
if (job.purpose === "initial") {
|
||||
// Only this request ever touched the model: nothing on disk, so it leaves the library again.
|
||||
const [{ n }] = await db().select({ n: sql<number>`count(*)` }).from(jobs).where(and(eq(jobs.modelId, job.modelId), ne(jobs.id, job.id)));
|
||||
if (Number(n) === 0) {
|
||||
await purgeModelRows(job.modelId);
|
||||
return { removedModel: true };
|
||||
}
|
||||
}
|
||||
// A pending job never changed the model's status, so only the selection needs restoring.
|
||||
if (job.result?.previousRule) await restoreSelection(job.modelId, job.result.previousRule);
|
||||
return { removedModel: false };
|
||||
}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
// Guardrails for downloads requested through the API (an autonomous agent, not a person in the
|
||||
// UI). Pure: settings parsing and the checks themselves; the request flow is in agent-downloads.ts.
|
||||
|
||||
export const APPROVAL_MODES = ["approve", "auto"] as const;
|
||||
export type ApprovalMode = (typeof APPROVAL_MODES)[number];
|
||||
|
||||
export type Guardrails = {
|
||||
/** approve: requests wait as "pending approval" until someone confirms them in the UI. */
|
||||
approvalMode: ApprovalMode;
|
||||
/** Largest download one request may add. */
|
||||
maxRequestBytes: number;
|
||||
/** Free space that must remain on the models folder after the download. */
|
||||
minFreeBytes: number;
|
||||
/** API-requested jobs that may be pending approval, queued or running at once (all tokens). */
|
||||
maxOpenJobs: number;
|
||||
/** Hub authors (orgs/users) the API may download from; empty = any. Case-insensitive. */
|
||||
allowedAuthors: string[];
|
||||
};
|
||||
|
||||
const GB = 1_000_000_000;
|
||||
|
||||
export const DEFAULT_GUARDRAILS: Guardrails = {
|
||||
approvalMode: "approve",
|
||||
maxRequestBytes: 60 * GB,
|
||||
minFreeBytes: 100 * GB,
|
||||
maxOpenJobs: 2,
|
||||
allowedAuthors: [],
|
||||
};
|
||||
|
||||
export class GuardrailError extends Error {
|
||||
constructor(
|
||||
public code: "too_large" | "disk_space" | "disk_unknown" | "too_many_jobs" | "author_not_allowed",
|
||||
message: string,
|
||||
public status = 422,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const AUTHOR_RE = /^[A-Za-z0-9][\w.-]{0,95}$/;
|
||||
|
||||
/** Stored value merged over the defaults; anything invalid falls back to the default. */
|
||||
export function parseGuardrails(v: unknown): Guardrails {
|
||||
const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
|
||||
const num = (x: unknown, min: number, def: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? Math.round(x) : def);
|
||||
return {
|
||||
approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_GUARDRAILS.approvalMode,
|
||||
maxRequestBytes: num(o.maxRequestBytes, 1, DEFAULT_GUARDRAILS.maxRequestBytes),
|
||||
minFreeBytes: num(o.minFreeBytes, 0, DEFAULT_GUARDRAILS.minFreeBytes),
|
||||
maxOpenJobs: num(o.maxOpenJobs, 1, DEFAULT_GUARDRAILS.maxOpenJobs),
|
||||
allowedAuthors: Array.isArray(o.allowedAuthors) ? o.allowedAuthors.filter((a): a is string => typeof a === "string" && AUTHOR_RE.test(a)) : [],
|
||||
};
|
||||
}
|
||||
|
||||
/** "unsloth, ggml-org Qwen" → ["unsloth", "ggml-org", "Qwen"]; throws on an invalid name. */
|
||||
export function parseAuthorList(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const a of text.split(/[\s,]+/).filter(Boolean)) {
|
||||
if (!AUTHOR_RE.test(a)) throw new Error(`"${a}" is not a valid Hugging Face user or organization name.`);
|
||||
if (!out.some((x) => x.toLowerCase() === a.toLowerCase())) out.push(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Plain GB (10^9), as the Hub and the settings use: "74.2 GB". */
|
||||
export function gb(bytes: number): string {
|
||||
return `${(bytes / GB).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
export type GuardrailInput = {
|
||||
repoId: string;
|
||||
/** Bytes this request would download. */
|
||||
requestBytes: number;
|
||||
/** Free bytes on the models folder (worker heartbeat), or null if unknown. */
|
||||
freeBytes: number | null;
|
||||
/** Bytes other open jobs still have to download. */
|
||||
reservedBytes: number;
|
||||
/** API-requested jobs that are pending approval, queued or running right now. */
|
||||
openAgentJobs: number;
|
||||
};
|
||||
|
||||
/** The author allowlist alone (checked before anything goes to the Hub). */
|
||||
export function checkAuthor(g: Guardrails, repoId: string): void {
|
||||
const author = repoId.split("/")[0];
|
||||
if (g.allowedAuthors.length > 0 && !g.allowedAuthors.some((a) => a.toLowerCase() === author.toLowerCase())) {
|
||||
throw new GuardrailError(
|
||||
"author_not_allowed",
|
||||
`author "${author}" is not on the allowlist (${g.allowedAuthors.join(", ")}). Pick a repo from one of these authors, or ask the user to extend the allowlist.`,
|
||||
403,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Throws a GuardrailError with a message an agent can act on; returns normally if allowed. */
|
||||
export function checkGuardrails(g: Guardrails, x: GuardrailInput): void {
|
||||
checkAuthor(g, x.repoId);
|
||||
if (x.requestBytes > g.maxRequestBytes) {
|
||||
throw new GuardrailError(
|
||||
"too_large",
|
||||
`exceeds max size per request ${gb(g.maxRequestBytes)}: requested ${gb(x.requestBytes)}. Pick a smaller quant or fewer files.`,
|
||||
);
|
||||
}
|
||||
if (x.openAgentJobs >= g.maxOpenJobs) {
|
||||
throw new GuardrailError(
|
||||
"too_many_jobs",
|
||||
`too many agent downloads at once: ${x.openAgentJobs} pending or running, the limit is ${g.maxOpenJobs}. Wait until one has finished (or been approved and finished) before requesting another.`,
|
||||
429,
|
||||
);
|
||||
}
|
||||
if (x.freeBytes == null) {
|
||||
throw new GuardrailError("disk_unknown", "free disk space is unknown (the Kaname worker is offline). Try again later.", 503);
|
||||
}
|
||||
const after = x.freeBytes - x.reservedBytes - x.requestBytes;
|
||||
if (after < g.minFreeBytes) {
|
||||
throw new GuardrailError(
|
||||
"disk_space",
|
||||
`not enough disk space: ${gb(x.requestBytes)} requested, ${gb(x.freeBytes)} free` +
|
||||
(x.reservedBytes > 0 ? ` (${gb(x.reservedBytes)} of it reserved by other downloads)` : "") +
|
||||
`, and at least ${gb(g.minFreeBytes)} must stay free (${gb(Math.max(0, after))} would be left). Pick a smaller quant or ask the user to free space.`,
|
||||
507,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function describeGuardrails(g: Guardrails): string {
|
||||
return [
|
||||
g.approvalMode === "approve" ? "requests wait for approval" : "downloads start immediately",
|
||||
`max ${gb(g.maxRequestBytes)} per request`,
|
||||
`${gb(g.minFreeBytes)} must stay free`,
|
||||
`max ${g.maxOpenJobs} agent jobs at once`,
|
||||
g.allowedAuthors.length ? `authors: ${g.allowedAuthors.join(", ")}` : "any author",
|
||||
].join(" · ");
|
||||
}
|
||||
@@ -1,285 +0,0 @@
|
||||
import "server-only";
|
||||
import { and, desc, eq, or } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { checkRun, TuningError, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
import { gpuLoad } from "@/lib/agent-deployments";
|
||||
import type { TokenIdentity } from "@/lib/api-tokens";
|
||||
import { metaRows } from "@/lib/benchmark-meta";
|
||||
import { headline } from "@/lib/benchmark-view";
|
||||
import { BENCHMARK_PHASES, type BenchmarkSummary, benchmarkRuns, QUALITY_SECTIONS, type QualityResult, type RunMeta } from "@/lib/db/schema";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { BenchmarkBody, type BenchmarkRow, createBenchmark, getBenchmark, getBenchmarks } from "@/lib/benchmarks";
|
||||
import { getDeployment } from "@/lib/deployments";
|
||||
import { getTuning } from "@/lib/settings";
|
||||
import { MAX_SWEEP_PARAMS, splitValues } from "@/lib/sweep";
|
||||
import { createSweep, getSweep, type SweepRow } from "@/lib/sweeps";
|
||||
|
||||
// Benchmark runs, A/B runs and sweeps through the API: on the token's own deployments only, one at a
|
||||
// time across all agents, with time limits and (by default) the user's approval.
|
||||
|
||||
export const AgentRunBody = z
|
||||
.object({
|
||||
/** run: BetterBench speed; ab: paired A/B; eval: the quality eval (tool calling, coding, retrieval). */
|
||||
kind: z.enum(["run", "ab", "eval"]).default("run"),
|
||||
deploymentId: z.string().min(1),
|
||||
/** A/B: the second deployment (same model). */
|
||||
deploymentBId: z.string().min(1).optional(),
|
||||
label: z.string().trim().max(120).optional(),
|
||||
description: z.string().trim().max(4000).optional(),
|
||||
/** quick: 5 passes, a smoke check; full (default): 20 passes, comparable. */
|
||||
quick: z.boolean().default(false),
|
||||
passes: z.number().int().min(1).max(200).optional(),
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
mdePct: z.number().min(0.1).max(50).optional(),
|
||||
maxPairs: z.number().int().min(12).max(2000).optional(),
|
||||
/** eval: which sections (default all). */
|
||||
sections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const AgentSweepBody = z
|
||||
.object({
|
||||
baseDeploymentId: z.string().min(1),
|
||||
label: z.string().trim().max(80).optional(),
|
||||
/** One or two settings with their values, e.g. [{ key: "kvCache", values: ["f16", "q8_0"] }]. */
|
||||
params: z
|
||||
.array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }).strict())
|
||||
.min(1)
|
||||
.max(MAX_SWEEP_PARAMS),
|
||||
quick: z.boolean().default(true),
|
||||
passes: z.number().int().min(1).max(200).optional(),
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
/** Also run the quality eval on each variant. */
|
||||
quality: z.boolean().default(false),
|
||||
})
|
||||
.strict();
|
||||
|
||||
/** A deployment this token may benchmark: its own, not protected, running. */
|
||||
async function benchmarkable(token: TokenIdentity, id: string, role: string) {
|
||||
const d = await getDeployment(id);
|
||||
if (!d) throw new TuningError("not_owner", `${role} not found.`, 404);
|
||||
if (d.protected) throw new TuningError("protected", `"${d.name}" is protected; agents can't benchmark it.`, 403);
|
||||
if (d.requestedByTokenId !== token.id) throw new TuningError("not_owner", `"${d.name}" wasn't created by this token; agents only benchmark their own deployments. Deploy the model yourself (POST /api/v1/deployments).`, 403);
|
||||
return d;
|
||||
}
|
||||
|
||||
const requested = (token: TokenIdentity) => ({ tokenId: token.id, name: token.name });
|
||||
|
||||
/** Queue a run or A/B against the token's own running deployment(s). */
|
||||
export async function requestRun(token: TokenIdentity, body: z.infer<typeof AgentRunBody>, g?: TuningGuardrails) {
|
||||
const guard = g ?? (await getTuning());
|
||||
await benchmarkable(token, body.deploymentId, body.kind === "ab" ? "Deployment A" : "The deployment");
|
||||
if (body.kind === "ab") {
|
||||
if (!body.deploymentBId) throw new TuningError("not_owner", "An A/B needs deploymentBId (your second deployment of the same model).", 400);
|
||||
await benchmarkable(token, body.deploymentBId, "Deployment B");
|
||||
}
|
||||
checkRun(await gpuLoad());
|
||||
const pending = guard.approvalMode === "approve";
|
||||
const row = await createBenchmark(
|
||||
BenchmarkBody.parse({
|
||||
deploymentId: body.deploymentId,
|
||||
deploymentBId: body.kind === "ab" ? body.deploymentBId : null,
|
||||
label: body.label ?? null,
|
||||
description: body.description ?? null,
|
||||
quick: body.quick,
|
||||
passes: body.passes ?? null,
|
||||
phases: body.phases,
|
||||
mdePct: body.mdePct ?? null,
|
||||
maxPairs: body.maxPairs ?? null,
|
||||
kind: body.kind,
|
||||
evalSections: body.sections,
|
||||
}),
|
||||
{ requestedBy: requested(token), pendingApproval: pending, timeLimitS: guard.maxRunMinutes * 60 },
|
||||
);
|
||||
return { id: row.id, state: pending ? "pending_approval" : "queued", timeLimitMinutes: guard.maxRunMinutes };
|
||||
}
|
||||
|
||||
/** Queue a sweep from the token's own base deployment (each variant deploys and is removed again). */
|
||||
export async function requestSweep(token: TokenIdentity, body: z.infer<typeof AgentSweepBody>, g?: TuningGuardrails) {
|
||||
const guard = g ?? (await getTuning());
|
||||
const base = await benchmarkable(token, body.baseDeploymentId, "The base deployment");
|
||||
const load = await gpuLoad();
|
||||
checkRun(load);
|
||||
// Each variant starts its own deployment; an agent deployment still running would share the GPU.
|
||||
if (load.agentDeployments > 0) {
|
||||
throw new TuningError("gpu_busy", "an agent deployment is still running or waiting to start; a sweep deploys each variant itself. Stop yours first (POST /api/v1/deployments/{id}/stop).", 429);
|
||||
}
|
||||
const count = body.params.reduce((n, p) => n * splitValues(p.values.join(",")).length, 1);
|
||||
if (count > guard.maxSweepVariants) {
|
||||
throw new TuningError("too_many_variants", `That's ${count} variants; agents may run at most ${guard.maxSweepVariants} per sweep. Vary fewer values.`);
|
||||
}
|
||||
const pending = guard.approvalMode === "approve";
|
||||
const row = await createSweep(
|
||||
{ baseDeploymentId: base.id, label: body.label ?? null, params: body.params, quick: body.quick, passes: body.passes ?? null, phases: body.phases, quality: body.quality },
|
||||
{
|
||||
requestedBy: requested(token),
|
||||
pendingApproval: pending,
|
||||
timeLimitS: guard.maxSweepMinutes * 60,
|
||||
runTimeLimitS: guard.maxRunMinutes * 60,
|
||||
maxVariants: guard.maxSweepVariants,
|
||||
},
|
||||
);
|
||||
return { id: row.id, state: pending ? "pending_approval" : "queued", variants: count, timeLimitMinutes: guard.maxSweepMinutes };
|
||||
}
|
||||
|
||||
/** Cancel a run or sweep this token asked for. */
|
||||
export async function ownRun(token: TokenIdentity, id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
if (!run) throw new TuningError("not_owner", "No benchmark run with this id.", 404);
|
||||
if (run.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This run wasn't started by this token; agents only cancel their own runs.", 403);
|
||||
return run;
|
||||
}
|
||||
|
||||
export async function ownSweep(token: TokenIdentity, id: string) {
|
||||
const s = await getSweep(id);
|
||||
if (!s) throw new TuningError("not_owner", "No sweep with this id.", 404);
|
||||
if (s.sweep.requestedByTokenId !== token.id) throw new TuningError("not_owner", "This sweep wasn't started by this token; agents only cancel their own sweeps.", 403);
|
||||
return s;
|
||||
}
|
||||
|
||||
const r1 = (v: number | null | undefined) => (v == null ? null : Math.round(v * 10) / 10);
|
||||
|
||||
/** The quality eval in short: overall score and per section. */
|
||||
export function qualityView(q: QualityResult | null | undefined) {
|
||||
if (!q) return null;
|
||||
return {
|
||||
evalSet: q.evalSet,
|
||||
score: q.score,
|
||||
sections: Object.fromEntries(q.sections.map((s) => [s.section, s.unsupported ? `n/a (${s.unsupported})` : `${s.passed}/${s.total}`])),
|
||||
};
|
||||
}
|
||||
|
||||
/** Headline numbers + the setup (section 1 metadata) as key/value. */
|
||||
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null, quality?: QualityResult | null) {
|
||||
const h = headline(summary);
|
||||
return {
|
||||
...(quality ? { quality: qualityView(quality) } : {}),
|
||||
headline: {
|
||||
decodeTps: r1(h.decode),
|
||||
prefillTps: r1(h.prefill?.tps),
|
||||
prefillDepth: h.prefill?.depth ?? null,
|
||||
ttftMs: r1(h.ttftMs),
|
||||
peakParallelTps: r1(h.peak?.tps),
|
||||
peakParallelLevel: h.peak?.level ?? null,
|
||||
},
|
||||
setup: meta ? Object.fromEntries(metaRows(meta).map((r) => [r.key, r.value])) : null,
|
||||
};
|
||||
}
|
||||
|
||||
const RUN_NEXT: Record<string, string> = {
|
||||
pending_approval: "Waiting for the user's approval in Kaname. Don't retry or poll; tell the user and stop.",
|
||||
queued: "Queued (one benchmark at a time). GET it with ?wait=900 instead of polling.",
|
||||
running: "Running. GET it with ?wait=900 instead of polling.",
|
||||
completed: "Done. Compare runs with GET /api/v1/benchmarks/compare?ids=…",
|
||||
failed: "Failed; see error. Fix the cause before trying again.",
|
||||
cancelled: "Cancelled or rejected by the user (or by you).",
|
||||
};
|
||||
|
||||
export const runSettled = (state: string) => state !== "queued" && state !== "running";
|
||||
|
||||
/** Compact run state: headline numbers, setup, resources; the full summary with `full`. */
|
||||
export function runView(r: BenchmarkRow, token: TokenIdentity, full = false) {
|
||||
const res = r.resources;
|
||||
return {
|
||||
id: r.id,
|
||||
kind: r.kind,
|
||||
state: r.state,
|
||||
label: r.label,
|
||||
description: r.description,
|
||||
deploymentId: r.deploymentId,
|
||||
deploymentBId: r.deploymentBId,
|
||||
deployment: r.snapshot.deploymentName,
|
||||
requestedBy: r.requestedBy,
|
||||
mine: r.requestedByTokenId === token.id,
|
||||
settings: r.settings,
|
||||
phase: r.phase,
|
||||
error: r.error,
|
||||
timeLimitMinutes: r.timeLimitS ? Math.round(r.timeLimitS / 60) : null,
|
||||
startedAt: r.startedAt ? new Date(r.startedAt).toISOString() : null,
|
||||
finishedAt: r.finishedAt ? new Date(r.finishedAt).toISOString() : null,
|
||||
...compact(r.summary, r.meta, r.quality),
|
||||
...(r.kind === "eval" && r.quality && full ? { failed: r.quality.items.filter((i) => !i.pass) } : {}),
|
||||
...(r.kind === "ab" && r.ab
|
||||
? {
|
||||
ab: {
|
||||
pairs: r.ab.pairs,
|
||||
verdict: r.ab.decode_tps.verdict,
|
||||
decodeDiffPct: r1(r.ab.decode_tps.pct_diff),
|
||||
ciPct: [r1(r.ab.decode_tps.ci_low_pct), r1(r.ab.decode_tps.ci_high_pct)],
|
||||
significant: r.ab.decode_tps.significant,
|
||||
setupB: r.metaB ? Object.fromEntries(metaRows(r.metaB).map((x) => [x.key, x.value])) : null,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
resources: res
|
||||
? {
|
||||
cpuAvgCores: r1(res.containers[0]?.cpuAvg),
|
||||
ramPeakBytes: res.containers[0]?.memPeakBytes ?? null,
|
||||
gpus: res.gpus.map((g) => ({ name: g.name, vramPeakMb: g.vramPeakMb, vramTotalMb: g.vramTotalMb, utilAvg: r1(g.utilAvg), powerAvgW: r1(g.powerAvgW), tempPeakC: r1(g.tempPeakC) })),
|
||||
}
|
||||
: null,
|
||||
next: RUN_NEXT[r.state] ?? null,
|
||||
...(full ? { summary: r.summary } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export function sweepView(data: NonNullable<Awaited<ReturnType<typeof getSweep>>>, token: TokenIdentity) {
|
||||
const s: SweepRow = data.sweep;
|
||||
return {
|
||||
id: s.id,
|
||||
state: s.state,
|
||||
label: s.label,
|
||||
baseDeploymentId: s.baseDeploymentId,
|
||||
params: s.params,
|
||||
settings: s.settings,
|
||||
requestedBy: s.requestedBy,
|
||||
mine: s.requestedByTokenId === token.id,
|
||||
error: s.error,
|
||||
timeLimitMinutes: s.timeLimitS ? Math.round(s.timeLimitS / 60) : null,
|
||||
variants: s.variants.map((v) => {
|
||||
const run = data.runs.find((r) => r.id === v.runId);
|
||||
const ev = data.runs.find((r) => r.id === v.evalRunId);
|
||||
return {
|
||||
label: v.label,
|
||||
overrides: v.overrides,
|
||||
state: v.state,
|
||||
runId: v.runId ?? null,
|
||||
evalRunId: v.evalRunId ?? null,
|
||||
error: v.error ?? null,
|
||||
...compact(run?.summary ?? null, run?.meta ?? null, ev?.quality ?? null),
|
||||
};
|
||||
}),
|
||||
startedAt: s.startedAt?.toISOString() ?? null,
|
||||
finishedAt: s.finishedAt?.toISOString() ?? null,
|
||||
next: s.state === "pending_approval" ? RUN_NEXT.pending_approval : s.state === "queued" || s.state === "running" ? "Running variant by variant. GET it with ?wait=900 instead of polling." : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs side by side: headline numbers and the setup keys whose values differ. */
|
||||
export async function compareRuns(ids: string[]) {
|
||||
const runs = await getBenchmarks(ids);
|
||||
const rows = runs.map((r) => ({ id: r.id, kind: r.kind, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta, r.quality) }));
|
||||
const keys = [...new Set(rows.flatMap((r) => Object.keys(r.setup ?? {})))];
|
||||
const differs = keys.filter((k) => new Set(rows.map((r) => r.setup?.[k] ?? "")).size > 1);
|
||||
return {
|
||||
runs: rows.map((r) => ({ ...r, setup: undefined, differs: Object.fromEntries(differs.map((k) => [k, r.setup?.[k] ?? null])) })),
|
||||
same: Object.fromEntries(keys.filter((k) => !differs.includes(k)).map((k) => [k, rows[0]?.setup?.[k] ?? null])),
|
||||
note: "Headline: decode t/s (weighted), prefill t/s at the deepest prompt, TTFT p50 ms; quality: the eval score 0–100 (same evalSet only). Differences under ~2 % between separate speed runs are noise; use an A/B for small effects.",
|
||||
};
|
||||
}
|
||||
|
||||
/** Recent runs, newest first, optionally of one deployment or token. */
|
||||
export async function listRunsFor(filter: { deploymentId?: string; requestedBy?: string; limit: number }) {
|
||||
const rows = await db()
|
||||
.select({ id: benchmarkRuns.id })
|
||||
.from(benchmarkRuns)
|
||||
.where(
|
||||
and(
|
||||
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
|
||||
filter.requestedBy ? eq(benchmarkRuns.requestedBy, filter.requestedBy.toLowerCase()) : undefined,
|
||||
),
|
||||
)
|
||||
.orderBy(desc(benchmarkRuns.createdAt))
|
||||
.limit(filter.limit);
|
||||
return getBenchmarks(rows.map((r) => r.id));
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
// Which files an API download request means, from a quant name or include globs, the same way the
|
||||
// Add model dialog picks them. Pure.
|
||||
|
||||
import { fileRole, type FileRole } from "@/lib/file-roles";
|
||||
import { recommendFiles } from "@/lib/recommend";
|
||||
import { matchesAny, quantGroup } from "@/lib/selection";
|
||||
|
||||
type File = { path: string; size: number };
|
||||
|
||||
export class SelectionError extends Error {
|
||||
code = "empty_selection";
|
||||
status = 400;
|
||||
}
|
||||
|
||||
/** Quant group of a model-weight file (not mmproj/MTP/imatrix), e.g. "Q4_K_M", "UD-Q4_K_XL". */
|
||||
function weightQuant(path: string): string | null {
|
||||
return fileRole(path) === "model" ? quantGroup(path) : null;
|
||||
}
|
||||
|
||||
/** Quants in a repo (model weights only) with file count and total size, in file order. */
|
||||
export function quantSummary(files: File[]): { quant: string; files: number; bytes: number }[] {
|
||||
const out = new Map<string, { quant: string; files: number; bytes: number }>();
|
||||
for (const f of files) {
|
||||
const q = weightQuant(f.path);
|
||||
if (!q) continue;
|
||||
const e = out.get(q) ?? { quant: q, files: 0, bytes: 0 };
|
||||
e.files++;
|
||||
e.bytes += f.size;
|
||||
out.set(q, e);
|
||||
}
|
||||
return [...out.values()];
|
||||
}
|
||||
|
||||
/**
|
||||
* Paths for a request: the weight files of `quant` (all split parts) plus the companion files of the
|
||||
* recommended kinds (Settings → Downloads), or every file matching one of the `include` globs.
|
||||
*/
|
||||
export function resolveRequestPaths(files: File[], req: { quant?: string; include?: string[] }, recommendedRoles: FileRole[]): string[] {
|
||||
if (req.quant) {
|
||||
const want = req.quant.trim().toLowerCase();
|
||||
const weights = files.filter((f) => weightQuant(f.path)?.toLowerCase() === want).map((f) => f.path);
|
||||
if (weights.length === 0) {
|
||||
const available = quantSummary(files).map((q) => q.quant);
|
||||
throw new SelectionError(
|
||||
available.length
|
||||
? `quant "${req.quant}" not found in this repo. Available: ${available.join(", ")}.`
|
||||
: `quant "${req.quant}" not found: this repo has no GGUF quants. Use "include" globs instead (e.g. ["*.safetensors", "*.json"]).`,
|
||||
);
|
||||
}
|
||||
return [...new Set([...weights, ...recommendFiles(files, weights, recommendedRoles)])].sort();
|
||||
}
|
||||
const globs = req.include ?? [];
|
||||
const paths = files.filter((f) => matchesAny(f.path, globs)).map((f) => f.path);
|
||||
if (paths.length === 0) throw new SelectionError(`no file in this repo matches ${JSON.stringify(globs)}. Look up the repo to see its files.`);
|
||||
return paths.sort();
|
||||
}
|
||||
|
||||
/** Files a request adds to what's already selected, for size checks and idempotency. */
|
||||
export function newPaths(requested: string[], selected: Iterable<string>): string[] {
|
||||
const have = new Set(selected);
|
||||
return requested.filter((p) => !have.has(p));
|
||||
}
|
||||
@@ -1,155 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { checkArgs, checkHostPort, checkLimits, checkRun, checkStart, checkVram, DEFAULT_TUNING, overTime, parseFlagList, parseTuning, type TuningError } from "./agent-tuning";
|
||||
import { parseWait, waitFor } from "./wait";
|
||||
|
||||
const g = DEFAULT_TUNING;
|
||||
const rejects = (fn: () => void, code: TuningError["code"], message?: RegExp) =>
|
||||
assert.throws(fn, (e: TuningError) => e.code === code && (!message || message.test(e.message)));
|
||||
|
||||
describe("tuning guardrails: settings", () => {
|
||||
it("defaults: approve, 1 deployment, 30/180 min, 8 variants, no ports, no caps", () => {
|
||||
assert.deepEqual(parseTuning(null), DEFAULT_TUNING);
|
||||
assert.equal(g.approvalMode, "approve");
|
||||
assert.equal(g.maxAgentDeployments, 1);
|
||||
assert.equal(g.maxRunMinutes, 30);
|
||||
assert.equal(g.maxSweepMinutes, 180);
|
||||
assert.equal(g.maxSweepVariants, 8);
|
||||
assert.equal(g.hostPortRange, null);
|
||||
});
|
||||
|
||||
it("falls back to defaults for invalid stored values and drops non-flags", () => {
|
||||
const t = parseTuning({ approvalMode: "yolo", maxAgentDeployments: 0, maxSweepVariants: 99, hostPortRange: { from: 9000, to: 80 }, allowedArgs: { "llama.cpp": ["--no-mmap", "rm -rf"], vllm: "x" } });
|
||||
assert.equal(t.approvalMode, "approve");
|
||||
assert.equal(t.maxAgentDeployments, 1);
|
||||
assert.equal(t.maxSweepVariants, 8);
|
||||
assert.equal(t.hostPortRange, null);
|
||||
assert.deepEqual(t.allowedArgs["llama.cpp"], ["--no-mmap"]);
|
||||
assert.deepEqual(t.allowedArgs.vllm, DEFAULT_TUNING.allowedArgs.vllm);
|
||||
assert.deepEqual(parseFlagList("--no-mmap, -ctk --mlock --no-mmap"), ["--no-mmap", "-ctk", "--mlock"]);
|
||||
assert.throws(() => parseFlagList("--ok /etc/passwd"), /isn't a flag/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: extra arguments", () => {
|
||||
it("passes allowlisted flags with values", () => {
|
||||
checkArgs(g, "llama.cpp", ["--no-mmap", "-ctk", "q8_0", "--override-tensor=blk\\..*_exps=CPU", "-n", "-1"]);
|
||||
checkArgs(g, "vllm", ["--kv-cache-dtype", "fp8", "--enable-prefix-caching"]);
|
||||
});
|
||||
|
||||
it("refuses flags not on the engine's list, naming them", () => {
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--host", "0.0.0.0"]), "arg_not_allowed", /"--host"/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--api-key=x"]), "arg_not_allowed", /"--api-key"/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["-m", "x.gguf"]), "arg_not_allowed", /"-m"/);
|
||||
rejects(() => checkArgs(g, "vllm", ["--trust-remote-code"]), "arg_not_allowed", /"--trust-remote-code"/);
|
||||
rejects(() => checkArgs(g, "vllm", ["--no-mmap"]), "arg_not_allowed", /on vllm/);
|
||||
});
|
||||
|
||||
it("refuses paths, URLs and stray values", () => {
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--chat-template", "/etc/passwd"]), "arg_not_allowed", /path or URL/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--chat-template=../x"]), "arg_not_allowed", /path or URL/);
|
||||
rejects(() => checkArgs(g, "vllm", ["--compilation-config", "http://evil/x"]), "arg_not_allowed", /path or URL/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["q8_0"]), "arg_not_allowed", /isn't a value of a flag/);
|
||||
rejects(() => checkArgs(g, "llama.cpp", ["--no-mmap=1", "extra"]), "arg_not_allowed", /isn't a value/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: ports and limits", () => {
|
||||
it("allows no host ports unless a range is set", () => {
|
||||
checkHostPort(g, null);
|
||||
rejects(() => checkHostPort(g, 18080), "port_not_allowed", /none configured/);
|
||||
const r = { ...g, hostPortRange: { from: 18000, to: 18099 } };
|
||||
checkHostPort(r, 18080);
|
||||
rejects(() => checkHostPort(r, 19000), "port_not_allowed", /18000–18099/);
|
||||
});
|
||||
|
||||
it("applies the memory cap to the given limit or the estimate, and the CPU cap", () => {
|
||||
const capped = { ...g, maxMemoryMb: 16384, maxCpus: 8 };
|
||||
assert.deepEqual(checkLimits(capped, { memoryMb: null, cpus: null, estimateMb: 9000, hostMemoryMb: 65536, hostCpus: 32 }), { memoryMb: 9000, cpus: 8 });
|
||||
rejects(() => checkLimits(capped, { memoryMb: 20000, cpus: null, estimateMb: 9000, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /16384 MiB/);
|
||||
rejects(() => checkLimits(capped, { memoryMb: null, cpus: null, estimateMb: 30000, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /the estimate/);
|
||||
rejects(() => checkLimits(capped, { memoryMb: 1024, cpus: 12, estimateMb: 900, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded", /8 cores/);
|
||||
// Without caps, the host's size is the cap.
|
||||
rejects(() => checkLimits(g, { memoryMb: 70000, cpus: null, estimateMb: 1, hostMemoryMb: 65536, hostCpus: 32 }), "limit_exceeded");
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: one GPU job at a time", () => {
|
||||
const idle = { agentDeployments: 0, agentRuns: 0, agentStarting: 0 };
|
||||
it("lets a deployment start when nothing of an agent runs", () => {
|
||||
checkStart(g, idle);
|
||||
checkRun(idle);
|
||||
});
|
||||
|
||||
it("refuses starts while an agent run is open or a deployment is loading, and over the count", () => {
|
||||
rejects(() => checkStart(g, { ...idle, agentRuns: 1 }), "gpu_busy", /benchmark or sweep/);
|
||||
rejects(() => checkStart(g, { ...idle, agentStarting: 1 }), "gpu_busy", /starting/);
|
||||
rejects(() => checkStart(g, { ...idle, agentDeployments: 1 }), "too_many_deployments", /the limit is 1/);
|
||||
checkStart({ ...g, maxAgentDeployments: 2 }, { ...idle, agentDeployments: 1 });
|
||||
});
|
||||
|
||||
it("refuses a second run, and runs while a deployment is loading", () => {
|
||||
rejects(() => checkRun({ ...idle, agentRuns: 1 }), "gpu_busy", /only one at a time/);
|
||||
rejects(() => checkRun({ ...idle, agentStarting: 1 }), "gpu_busy", /still starting/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tuning guardrails: protected deployments' VRAM", () => {
|
||||
it("ignores GPUs without protected deployments", () => {
|
||||
checkVram({ protectedNames: [], newMb: null, runningMb: [30000], totalMb: 32768 });
|
||||
});
|
||||
|
||||
it("refuses what wouldn't fit next to a protected deployment", () => {
|
||||
checkVram({ protectedNames: ["prod"], newMb: 8000, runningMb: [20000], totalMb: 32768 });
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: 12000, runningMb: [20000], totalMb: 32768 }), "vram_protected", /crowd protected deployment\(s\) prod/);
|
||||
});
|
||||
|
||||
it("refuses when the need can't be estimated", () => {
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: null, runningMb: [20000], totalMb: 32768 }), "vram_protected", /can't be estimated/);
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: 1000, runningMb: [-1], totalMb: 32768 }), "vram_protected");
|
||||
rejects(() => checkVram({ protectedNames: ["prod"], newMb: 1000, runningMb: [], totalMb: null }), "vram_protected");
|
||||
});
|
||||
|
||||
it("knows when a run or sweep is over its time limit", () => {
|
||||
const start = new Date(1_000_000);
|
||||
assert.equal(overTime(start, 60, 1_000_000 + 59_000), false);
|
||||
assert.equal(overTime(start, 60, 1_000_000 + 61_000), true);
|
||||
assert.equal(overTime(null, 60), false);
|
||||
assert.equal(overTime(start, null), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("?wait=", () => {
|
||||
it("parses and caps the seconds", () => {
|
||||
assert.equal(parseWait(new URLSearchParams("wait=30")), 30);
|
||||
assert.equal(parseWait(new URLSearchParams("wait=5000")), 900);
|
||||
assert.equal(parseWait(new URLSearchParams("wait=-1")), 0);
|
||||
assert.equal(parseWait(new URLSearchParams("")), 0);
|
||||
});
|
||||
|
||||
it("returns once the state settles", async () => {
|
||||
let n = 0;
|
||||
const r = await waitFor(async () => ++n, (v) => v >= 3, 5, { pollMs: 10 });
|
||||
assert.equal(r.value, 3);
|
||||
assert.equal(r.timedOut, false);
|
||||
});
|
||||
|
||||
it("returns right away when already settled, and after the wait otherwise", async () => {
|
||||
let loads = 0;
|
||||
const now = await waitFor(async () => (loads++, "done"), () => true, 900, { pollMs: 10 });
|
||||
assert.equal(loads, 1);
|
||||
assert.equal(now.waitedS, 0);
|
||||
const t0 = Date.now();
|
||||
const late = await waitFor(async () => "running", () => false, 1, { pollMs: 50 });
|
||||
assert.ok(Date.now() - t0 >= 950);
|
||||
assert.equal(late.timedOut, true);
|
||||
});
|
||||
|
||||
it("stops waiting when the client goes away", async () => {
|
||||
const ac = new AbortController();
|
||||
setTimeout(() => ac.abort(), 50);
|
||||
const t0 = Date.now();
|
||||
await waitFor(async () => "running", () => false, 30, { pollMs: 20, signal: ac.signal });
|
||||
assert.ok(Date.now() - t0 < 1000);
|
||||
});
|
||||
});
|
||||
@@ -1,351 +0,0 @@
|
||||
// Guardrails for deployments and benchmarks requested through the API (an agent tuning launch
|
||||
// options, not a person in the UI). Pure: settings parsing and the checks; the request flows are in
|
||||
// agent-deployments.ts and agent-runs.ts.
|
||||
|
||||
import { APPROVAL_MODES, type ApprovalMode } from "@/lib/agent-guardrails";
|
||||
import type { RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
/**
|
||||
* Extra arguments an agent may pass, per engine: tuning flags only. Not allowed (not listed): paths
|
||||
* and files (-m, --log-file, --chat-template-file, --slot-save-path, --download-dir), network and
|
||||
* auth (--host, --port, --api-key, --rpc, --ssl-*), anything that fetches or runs code from
|
||||
* elsewhere (-hf, --model-url, --trust-remote-code, --tokenizer, --speculative-config, --lora).
|
||||
* Docker-level options (devices, volumes, privileges, capabilities, network) aren't arguments at
|
||||
* all: they come from the runtime, which tokens can't change.
|
||||
*/
|
||||
export const DEFAULT_ALLOWED_ARGS: Record<RuntimeEngine, string[]> = {
|
||||
"llama.cpp": [
|
||||
"--no-mmap",
|
||||
"--mlock",
|
||||
"--numa",
|
||||
"-fa",
|
||||
"--flash-attn",
|
||||
"-ctk",
|
||||
"--cache-type-k",
|
||||
"-ctv",
|
||||
"--cache-type-v",
|
||||
"-nkvo",
|
||||
"--no-kv-offload",
|
||||
"-kvu",
|
||||
"--kv-unified",
|
||||
"--no-kv-unified",
|
||||
"--swa-full",
|
||||
"-dt",
|
||||
"--defrag-thold",
|
||||
"-cb",
|
||||
"--cont-batching",
|
||||
"-nocb",
|
||||
"--no-cont-batching",
|
||||
"--cache-reuse",
|
||||
"--context-shift",
|
||||
"--no-context-shift",
|
||||
"-b",
|
||||
"--batch-size",
|
||||
"-ub",
|
||||
"--ubatch-size",
|
||||
"-t",
|
||||
"--threads",
|
||||
"-tb",
|
||||
"--threads-batch",
|
||||
"--prio",
|
||||
"--poll",
|
||||
"-sm",
|
||||
"--split-mode",
|
||||
"-ts",
|
||||
"--tensor-split",
|
||||
"-mg",
|
||||
"--main-gpu",
|
||||
"-ot",
|
||||
"--override-tensor",
|
||||
"--cpu-moe",
|
||||
"-cmoe",
|
||||
"--n-cpu-moe",
|
||||
"-ncmoe",
|
||||
"--rope-scaling",
|
||||
"--rope-scale",
|
||||
"--rope-freq-base",
|
||||
"--rope-freq-scale",
|
||||
"--yarn-orig-ctx",
|
||||
"--yarn-ext-factor",
|
||||
"--yarn-attn-factor",
|
||||
"--yarn-beta-slow",
|
||||
"--yarn-beta-fast",
|
||||
"--draft-max",
|
||||
"--draft-min",
|
||||
"--draft-p-min",
|
||||
"-ngld",
|
||||
"--gpu-layers-draft",
|
||||
"--spec-replace",
|
||||
"--jinja",
|
||||
"--no-jinja",
|
||||
"--chat-template",
|
||||
"--reasoning-format",
|
||||
"--reasoning-budget",
|
||||
"--slot-prompt-similarity",
|
||||
"--temp",
|
||||
"--top-k",
|
||||
"--top-p",
|
||||
"--min-p",
|
||||
"--repeat-penalty",
|
||||
"--presence-penalty",
|
||||
"-n",
|
||||
"--n-predict",
|
||||
"--threads-http",
|
||||
],
|
||||
vllm: [
|
||||
"--kv-cache-dtype",
|
||||
"--max-num-batched-tokens",
|
||||
"--enable-chunked-prefill",
|
||||
"--no-enable-chunked-prefill",
|
||||
"--enable-prefix-caching",
|
||||
"--no-enable-prefix-caching",
|
||||
"--block-size",
|
||||
"--swap-space",
|
||||
"--cpu-offload-gb",
|
||||
"--enforce-eager",
|
||||
"--max-seq-len-to-capture",
|
||||
"--compilation-config",
|
||||
"-O",
|
||||
"--quantization",
|
||||
"-q",
|
||||
"--pipeline-parallel-size",
|
||||
"-pp",
|
||||
"--enable-expert-parallel",
|
||||
"--async-scheduling",
|
||||
"--enable-auto-tool-choice",
|
||||
"--tool-call-parser",
|
||||
"--reasoning-parser",
|
||||
"--max-logprobs",
|
||||
"--seed",
|
||||
"--override-generation-config",
|
||||
"--limit-mm-per-prompt",
|
||||
"--mm-processor-kwargs",
|
||||
"--disable-log-requests",
|
||||
"--disable-log-stats",
|
||||
],
|
||||
};
|
||||
|
||||
export type TuningGuardrails = {
|
||||
/** approve: agent starts, runs and sweeps wait as "pending approval" until someone confirms them. */
|
||||
approvalMode: ApprovalMode;
|
||||
/** Agent deployments running (or waiting to start) at once, all tokens together. */
|
||||
maxAgentDeployments: number;
|
||||
maxRunMinutes: number;
|
||||
maxSweepMinutes: number;
|
||||
maxSweepVariants: number;
|
||||
/** Runtime ids agents may use; empty = every runtime with a pulled image. */
|
||||
allowedRuntimeIds: string[];
|
||||
/** Extra argument flags agents may use, per engine. */
|
||||
allowedArgs: Record<RuntimeEngine, string[]>;
|
||||
/** Host ports agents may publish; null = none (Kaname reaches deployments over the Docker network). */
|
||||
hostPortRange: { from: number; to: number } | null;
|
||||
/** Caps for an agent deployment's limits; null = the host's size. Agent deployments always get a memory limit. */
|
||||
maxMemoryMb: number | null;
|
||||
maxCpus: number | null;
|
||||
};
|
||||
|
||||
export const DEFAULT_TUNING: TuningGuardrails = {
|
||||
approvalMode: "approve",
|
||||
maxAgentDeployments: 1,
|
||||
maxRunMinutes: 30,
|
||||
maxSweepMinutes: 180,
|
||||
maxSweepVariants: 8,
|
||||
allowedRuntimeIds: [],
|
||||
allowedArgs: DEFAULT_ALLOWED_ARGS,
|
||||
hostPortRange: null,
|
||||
maxMemoryMb: null,
|
||||
maxCpus: null,
|
||||
};
|
||||
|
||||
export const TUNING_KEY = "agent.tuning";
|
||||
|
||||
export type TuningErrorCode =
|
||||
| "runtime_not_allowed"
|
||||
| "runtime_not_pulled"
|
||||
| "arg_not_allowed"
|
||||
| "port_not_allowed"
|
||||
| "limit_exceeded"
|
||||
| "too_many_deployments"
|
||||
| "gpu_busy"
|
||||
| "protected"
|
||||
| "not_owner"
|
||||
| "vram_protected"
|
||||
| "too_many_variants"
|
||||
| "approval_pending";
|
||||
|
||||
export class TuningError extends Error {
|
||||
constructor(
|
||||
public code: TuningErrorCode,
|
||||
message: string,
|
||||
public status = 422,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const FLAG_RE = /^--?[A-Za-z][\w-]*$/;
|
||||
const int = (x: unknown, min: number, max: number, def: number) => (typeof x === "number" && Number.isInteger(x) && x >= min && x <= max ? x : def);
|
||||
const numOrNull = (x: unknown, min: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? x : null);
|
||||
|
||||
/** Stored value merged over the defaults; anything invalid falls back to the default. */
|
||||
export function parseTuning(v: unknown): TuningGuardrails {
|
||||
const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
|
||||
const args = (o.allowedArgs ?? {}) as Record<string, unknown>;
|
||||
const flags = (x: unknown, def: string[]) => (Array.isArray(x) ? [...new Set(x.filter((f): f is string => typeof f === "string" && FLAG_RE.test(f)))] : def);
|
||||
const range = o.hostPortRange as { from?: unknown; to?: unknown } | null | undefined;
|
||||
const from = int(range?.from, 1024, 65_535, 0);
|
||||
const to = int(range?.to, 1024, 65_535, 0);
|
||||
return {
|
||||
approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_TUNING.approvalMode,
|
||||
maxAgentDeployments: int(o.maxAgentDeployments, 1, 16, DEFAULT_TUNING.maxAgentDeployments),
|
||||
maxRunMinutes: int(o.maxRunMinutes, 1, 24 * 60, DEFAULT_TUNING.maxRunMinutes),
|
||||
maxSweepMinutes: int(o.maxSweepMinutes, 1, 7 * 24 * 60, DEFAULT_TUNING.maxSweepMinutes),
|
||||
maxSweepVariants: int(o.maxSweepVariants, 2, 16, DEFAULT_TUNING.maxSweepVariants),
|
||||
allowedRuntimeIds: Array.isArray(o.allowedRuntimeIds) ? o.allowedRuntimeIds.filter((x): x is string => typeof x === "string" && x.length <= 64) : [],
|
||||
allowedArgs: { "llama.cpp": flags(args["llama.cpp"], DEFAULT_ALLOWED_ARGS["llama.cpp"]), vllm: flags(args.vllm, DEFAULT_ALLOWED_ARGS.vllm) },
|
||||
hostPortRange: from && to && from <= to ? { from, to } : null,
|
||||
maxMemoryMb: numOrNull(o.maxMemoryMb, 256),
|
||||
maxCpus: numOrNull(o.maxCpus, 0.1),
|
||||
};
|
||||
}
|
||||
|
||||
/** "--no-mmap -ctk, --flash-attn" → flags; throws on something that isn't one. */
|
||||
export function parseFlagList(text: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (const f of text.split(/[\s,]+/).filter(Boolean)) {
|
||||
if (!FLAG_RE.test(f)) throw new Error(`"${f}" isn't a flag (e.g. --no-mmap).`);
|
||||
if (!out.includes(f)) out.push(f);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extra arguments: every flag must be on the engine's allowlist, every value must follow a flag and
|
||||
* may not be a path or URL. The error names the offending argument.
|
||||
*/
|
||||
export function checkArgs(g: TuningGuardrails, engine: RuntimeEngine, args: string[]): void {
|
||||
const allowed = g.allowedArgs[engine];
|
||||
let pending: string | null = null; // a flag still waiting for its value
|
||||
for (const raw of args) {
|
||||
const a = raw.trim();
|
||||
if (!a) continue;
|
||||
if (a.startsWith("-") && !/^-\d/.test(a)) {
|
||||
const flag = a.split("=")[0];
|
||||
if (!allowed.includes(flag)) {
|
||||
throw new TuningError(
|
||||
"arg_not_allowed",
|
||||
`extra argument "${flag}" isn't allowed for agents on ${engine}. The allowed flags are listed per runtime in GET /api/v1/runtimes (allowedExtraArgs); use the structured options (contextSize, gpuLayers, cacheTypeK, …) where there is one.`,
|
||||
403,
|
||||
);
|
||||
}
|
||||
const value = a.includes("=") ? a.slice(a.indexOf("=") + 1) : null;
|
||||
if (value != null) checkValue(flag, value);
|
||||
pending = value == null ? flag : null;
|
||||
continue;
|
||||
}
|
||||
if (!pending) throw new TuningError("arg_not_allowed", `extra argument "${a}" isn't a value of a flag. Pass flags as "--flag value" or "--flag=value".`, 403);
|
||||
checkValue(pending, a);
|
||||
pending = null;
|
||||
}
|
||||
}
|
||||
|
||||
function checkValue(flag: string, value: string) {
|
||||
if (/^[/~]|(^|[\\/])\.\.([\\/]|$)|:\/\//.test(value)) {
|
||||
throw new TuningError("arg_not_allowed", `value "${value}" of ${flag} looks like a path or URL; agents can't pass those.`, 403);
|
||||
}
|
||||
}
|
||||
|
||||
/** A host port must be in the configured range (none configured: no host ports for agents). */
|
||||
export function checkHostPort(g: TuningGuardrails, port: number | null | undefined): void {
|
||||
if (port == null) return;
|
||||
const r = g.hostPortRange;
|
||||
if (!r) throw new TuningError("port_not_allowed", "agents can't publish host ports (none configured). Leave hostPort out; Kaname reaches the deployment itself.", 403);
|
||||
if (port < r.from || port > r.to) throw new TuningError("port_not_allowed", `host port ${port} is outside the range agents may use (${r.from}–${r.to}).`, 403);
|
||||
}
|
||||
|
||||
/** Memory and CPU limits within the caps (null cap: the host's size). Returns the memory limit to use. */
|
||||
export function checkLimits(
|
||||
g: TuningGuardrails,
|
||||
x: { memoryMb: number | null | undefined; cpus: number | null | undefined; estimateMb: number; hostMemoryMb: number | null; hostCpus: number | null },
|
||||
): { memoryMb: number; cpus: number | null } {
|
||||
const memCap = g.maxMemoryMb ?? x.hostMemoryMb;
|
||||
const cpuCap = g.maxCpus ?? x.hostCpus;
|
||||
const memoryMb = x.memoryMb ?? x.estimateMb;
|
||||
if (memCap != null && memoryMb > memCap) {
|
||||
throw new TuningError(
|
||||
"limit_exceeded",
|
||||
`memory limit ${memoryMb} MiB exceeds the cap of ${Math.floor(memCap)} MiB for agent deployments${x.memoryMb == null ? " (the estimate for this model and context)" : ""}. Use a smaller quant or context, or ask the user to raise the cap.`,
|
||||
);
|
||||
}
|
||||
if (x.cpus != null && cpuCap != null && x.cpus > cpuCap) throw new TuningError("limit_exceeded", `CPU limit ${x.cpus} exceeds the cap of ${cpuCap} cores for agent deployments.`);
|
||||
return { memoryMb, cpus: x.cpus ?? (g.maxCpus ?? null) };
|
||||
}
|
||||
|
||||
export type GpuLoad = {
|
||||
/** Agent deployments running, starting or waiting to start (all tokens), not counting `self`. */
|
||||
agentDeployments: number;
|
||||
/** Agent runs and sweeps pending approval, queued or running. */
|
||||
agentRuns: number;
|
||||
/** Agent deployments currently starting (loading weights). */
|
||||
agentStarting: number;
|
||||
};
|
||||
|
||||
/** Starting an agent deployment: within the count, and nothing of an agent is being measured or loaded. */
|
||||
export function checkStart(g: TuningGuardrails, load: GpuLoad): void {
|
||||
if (load.agentRuns > 0) {
|
||||
throw new TuningError("gpu_busy", "an agent benchmark or sweep is pending or running; starting a deployment now would disturb it. Wait for it (GET …?wait=) and start afterwards.", 429);
|
||||
}
|
||||
if (load.agentStarting > 0) throw new TuningError("gpu_busy", "another agent deployment is starting; wait until it is running.", 429);
|
||||
if (load.agentDeployments >= g.maxAgentDeployments) {
|
||||
throw new TuningError(
|
||||
"too_many_deployments",
|
||||
`${load.agentDeployments} agent deployment(s) already running or waiting to start; the limit is ${g.maxAgentDeployments}. Stop one of yours first (POST /api/v1/deployments/{id}/stop).`,
|
||||
429,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Starting a run or sweep: one agent run/sweep at a time, and no agent deployment still loading. */
|
||||
export function checkRun(load: GpuLoad): void {
|
||||
if (load.agentRuns > 0) throw new TuningError("gpu_busy", "an agent benchmark or sweep is already pending or running; only one at a time. Wait for it to finish (GET …?wait=).", 429);
|
||||
if (load.agentStarting > 0) throw new TuningError("gpu_busy", "an agent deployment is still starting; wait until it is running.", 429);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starting next to a running protected deployment on the same GPUs: the estimated VRAM of everything
|
||||
* running there plus the new deployment must fit, with a margin, so the protected one isn't pushed out.
|
||||
*/
|
||||
export function checkVram(x: { protectedNames: string[]; newMb: number | null; runningMb: number[]; totalMb: number | null; marginMb?: number }): void {
|
||||
if (x.protectedNames.length === 0) return;
|
||||
const names = x.protectedNames.join(", ");
|
||||
if (x.newMb == null || x.totalMb == null || x.runningMb.some((m) => m < 0)) {
|
||||
throw new TuningError(
|
||||
"vram_protected",
|
||||
`protected deployment(s) ${names} run on these GPUs and the VRAM need can't be estimated (only some layers on the GPU, or VRAM unknown). Use gpuLayers "auto" or "all", or ask the user.`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
const margin = x.marginMb ?? 1024;
|
||||
const used = x.runningMb.reduce((s, m) => s + m, 0);
|
||||
if (used + x.newMb + margin > x.totalMb) {
|
||||
throw new TuningError(
|
||||
"vram_protected",
|
||||
`would crowd protected deployment(s) ${names} out of VRAM: about ${x.newMb} MiB needed, ${used} MiB in use of ${x.totalMb} MiB (keeping ${margin} MiB free). Use a smaller quant or context, or a quantized KV cache.`,
|
||||
409,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Seconds since `startedAt` past the limit? */
|
||||
export const overTime = (startedAt: Date | null, limitS: number | null, now = Date.now()) => !!startedAt && !!limitS && now - startedAt.getTime() > limitS * 1000;
|
||||
|
||||
export function describeTuning(g: TuningGuardrails): string {
|
||||
return [
|
||||
g.approvalMode === "approve" ? "starts, runs and sweeps wait for approval" : "starts, runs and sweeps go ahead",
|
||||
`max ${g.maxAgentDeployments} agent deployment(s)`,
|
||||
"one agent run/sweep at a time",
|
||||
`runs ≤ ${g.maxRunMinutes} min, sweeps ≤ ${g.maxSweepMinutes} min and ${g.maxSweepVariants} variants`,
|
||||
g.allowedRuntimeIds.length ? `${g.allowedRuntimeIds.length} allowed runtime(s)` : "any pulled runtime",
|
||||
g.hostPortRange ? `host ports ${g.hostPortRange.from}–${g.hostPortRange.to}` : "no host ports",
|
||||
].join(" · ");
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, it } from "node:test";
|
||||
import { checkAuthor, checkGuardrails, DEFAULT_GUARDRAILS, type GuardrailError, type GuardrailInput, parseAuthorList, parseGuardrails } from "./agent-guardrails";
|
||||
import { newPaths, quantSummary, resolveRequestPaths } from "./agent-selection";
|
||||
import { bearerToken, generateToken, hashToken, isScope } from "./api-token-core";
|
||||
import { parseModelFilters } from "./api-v1-filters";
|
||||
import { EMPTY_FILTERS, facetValues, matchesFilters, type SearchableModel } from "./search";
|
||||
|
||||
const GB = 1e9;
|
||||
|
||||
describe("API tokens", () => {
|
||||
it("generates kn_ tokens whose hash and prefix match", () => {
|
||||
const t = generateToken();
|
||||
assert.match(t.token, /^kn_[A-Za-z0-9_-]{43}$/);
|
||||
assert.equal(t.hash, hashToken(t.token));
|
||||
assert.ok(t.token.startsWith(t.prefix));
|
||||
assert.notEqual(generateToken().token, t.token);
|
||||
});
|
||||
|
||||
it("reads only well-formed bearer headers", () => {
|
||||
const { token } = generateToken();
|
||||
assert.equal(bearerToken(`Bearer ${token}`), token);
|
||||
assert.equal(bearerToken(`bearer ${token} `), token);
|
||||
assert.equal(bearerToken(token), null);
|
||||
assert.equal(bearerToken("Bearer kn_short"), null);
|
||||
assert.equal(bearerToken("Basic abc"), null);
|
||||
assert.equal(bearerToken(null), null);
|
||||
});
|
||||
|
||||
it("knows the scopes", () => {
|
||||
assert.ok(isScope("models:read"));
|
||||
assert.ok(isScope("downloads:create"));
|
||||
assert.ok(!isScope("models:delete"));
|
||||
assert.ok(!isScope("settings:write"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("guardrails", () => {
|
||||
const ok: GuardrailInput = { repoId: "unsloth/Qwen3-8B-GGUF", requestBytes: 5 * GB, freeBytes: 500 * GB, reservedBytes: 0, openAgentJobs: 0 };
|
||||
const rejects = (g: Partial<typeof DEFAULT_GUARDRAILS>, x: Partial<GuardrailInput>, code: GuardrailError["code"], message: RegExp) =>
|
||||
assert.throws(
|
||||
() => checkGuardrails({ ...DEFAULT_GUARDRAILS, ...g }, { ...ok, ...x }),
|
||||
(err: GuardrailError) => err.code === code && message.test(err.message),
|
||||
);
|
||||
|
||||
it("defaults: approve, 60 GB, 100 GB free, 2 jobs, any author", () => {
|
||||
assert.deepEqual(parseGuardrails(null), DEFAULT_GUARDRAILS);
|
||||
assert.equal(DEFAULT_GUARDRAILS.approvalMode, "approve");
|
||||
assert.equal(DEFAULT_GUARDRAILS.maxRequestBytes, 60 * GB);
|
||||
assert.equal(DEFAULT_GUARDRAILS.minFreeBytes, 100 * GB);
|
||||
assert.equal(DEFAULT_GUARDRAILS.maxOpenJobs, 2);
|
||||
assert.deepEqual(DEFAULT_GUARDRAILS.allowedAuthors, []);
|
||||
});
|
||||
|
||||
it("falls back to defaults for invalid stored values", () => {
|
||||
const g = parseGuardrails({ approvalMode: "yolo", maxRequestBytes: -1, minFreeBytes: "x", maxOpenJobs: 0, allowedAuthors: ["ok", "../bad"] });
|
||||
assert.equal(g.approvalMode, "approve");
|
||||
assert.equal(g.maxRequestBytes, DEFAULT_GUARDRAILS.maxRequestBytes);
|
||||
assert.equal(g.minFreeBytes, DEFAULT_GUARDRAILS.minFreeBytes);
|
||||
assert.equal(g.maxOpenJobs, DEFAULT_GUARDRAILS.maxOpenJobs);
|
||||
assert.deepEqual(g.allowedAuthors, ["ok"]);
|
||||
});
|
||||
|
||||
it("passes a request within all limits", () => {
|
||||
checkGuardrails(DEFAULT_GUARDRAILS, ok);
|
||||
});
|
||||
|
||||
it("rejects requests over the max size, with both sizes in the message", () => {
|
||||
rejects({}, { requestBytes: 74.2 * GB }, "too_large", /exceeds max size per request 60\.0 GB: requested 74\.2 GB/);
|
||||
});
|
||||
|
||||
it("rejects when the minimum free space would not remain", () => {
|
||||
rejects({}, { requestBytes: 20 * GB, freeBytes: 110 * GB }, "disk_space", /at least 100\.0 GB must stay free/);
|
||||
});
|
||||
|
||||
it("counts space reserved by other open downloads", () => {
|
||||
checkGuardrails(DEFAULT_GUARDRAILS, { ...ok, requestBytes: 20 * GB, freeBytes: 130 * GB });
|
||||
rejects({}, { requestBytes: 20 * GB, freeBytes: 130 * GB, reservedBytes: 20 * GB }, "disk_space", /20\.0 GB of it reserved/);
|
||||
});
|
||||
|
||||
it("rejects when free space is unknown (worker offline)", () => {
|
||||
rejects({}, { freeBytes: null }, "disk_unknown", /worker is offline/);
|
||||
});
|
||||
|
||||
it("rejects when too many agent jobs are open", () => {
|
||||
rejects({}, { openAgentJobs: 2 }, "too_many_jobs", /2 pending or running, the limit is 2/);
|
||||
checkGuardrails({ ...DEFAULT_GUARDRAILS, maxOpenJobs: 3 }, { ...ok, openAgentJobs: 2 });
|
||||
});
|
||||
|
||||
it("enforces the author allowlist case-insensitively", () => {
|
||||
const g = { allowedAuthors: ["unsloth", "ggml-org"] };
|
||||
checkAuthor({ ...DEFAULT_GUARDRAILS, ...g }, "Unsloth/x");
|
||||
rejects(g, { repoId: "TheBloke/x-GGUF" }, "author_not_allowed", /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
|
||||
});
|
||||
|
||||
it("parses the allowlist text", () => {
|
||||
assert.deepEqual(parseAuthorList("unsloth, ggml-org Qwen,unsloth"), ["unsloth", "ggml-org", "Qwen"]);
|
||||
assert.deepEqual(parseAuthorList(" "), []);
|
||||
assert.throws(() => parseAuthorList("ok, ../x"), /not a valid/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("request file selection", () => {
|
||||
const files = [
|
||||
{ path: "Qwen3-8B-Q4_K_M.gguf", size: 5 * GB },
|
||||
{ path: "Qwen3-8B-Q8_0.gguf", size: 8.7 * GB },
|
||||
{ path: "mmproj-F16.gguf", size: 0.6 * GB },
|
||||
{ path: "BF16/Qwen3-8B-BF16-00001-of-00002.gguf", size: 8 * GB },
|
||||
{ path: "BF16/Qwen3-8B-BF16-00002-of-00002.gguf", size: 8 * GB },
|
||||
{ path: "README.md", size: 1000 },
|
||||
];
|
||||
|
||||
it("summarizes quants (weights only, split parts together)", () => {
|
||||
assert.deepEqual(
|
||||
quantSummary(files).map((q) => [q.quant, q.files]),
|
||||
[
|
||||
["Q4_K_M", 1],
|
||||
["Q8_0", 1],
|
||||
["BF16", 2],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves a quant to its weights plus recommended companions", () => {
|
||||
assert.deepEqual(resolveRequestPaths(files, { quant: "q4_k_m" }, ["vision"]), ["Qwen3-8B-Q4_K_M.gguf", "mmproj-F16.gguf"]);
|
||||
assert.deepEqual(resolveRequestPaths(files, { quant: "Q4_K_M" }, []), ["Qwen3-8B-Q4_K_M.gguf"]);
|
||||
assert.deepEqual(resolveRequestPaths(files, { quant: "BF16" }, []), ["BF16/Qwen3-8B-BF16-00001-of-00002.gguf", "BF16/Qwen3-8B-BF16-00002-of-00002.gguf"]);
|
||||
});
|
||||
|
||||
it("explains a missing quant with the available ones", () => {
|
||||
assert.throws(() => resolveRequestPaths(files, { quant: "Q2_K" }, []), /quant "Q2_K" not found in this repo\. Available: .*Q4_K_M/);
|
||||
assert.throws(() => resolveRequestPaths([{ path: "model.safetensors", size: 1 }], { quant: "Q4_K_M" }, []), /no GGUF quants\. Use "include"/);
|
||||
});
|
||||
|
||||
it("resolves include globs and rejects ones that match nothing", () => {
|
||||
assert.deepEqual(resolveRequestPaths(files, { include: ["*Q8_0*", "README.md"] }, []), ["Qwen3-8B-Q8_0.gguf", "README.md"]);
|
||||
assert.throws(() => resolveRequestPaths(files, { include: ["*.safetensors"] }, []), /no file in this repo matches/);
|
||||
});
|
||||
|
||||
it("finds what a request adds to the selection", () => {
|
||||
assert.deepEqual(newPaths(["a", "b", "c"], ["b"]), ["a", "c"]);
|
||||
assert.deepEqual(newPaths(["a"], ["a", "b"]), []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("GET /api/v1/models filters", () => {
|
||||
it("reads repeated and comma-separated values, requested_by → requester", () => {
|
||||
const { query, filters } = parseModelFilters(new URLSearchParams("q=qwen 8b&author=unsloth,bartowski&quant=Q4_K_M&quant=Q8_0&requested_by=hermes&status=pending_approval"));
|
||||
assert.equal(query, "qwen 8b");
|
||||
assert.deepEqual(filters, { ...EMPTY_FILTERS, author: ["unsloth", "bartowski"], quant: ["Q4_K_M", "Q8_0"], requester: ["hermes"], status: ["pending_approval"] });
|
||||
});
|
||||
|
||||
it("filters by requester and pending approval like the library", () => {
|
||||
const m: SearchableModel = {
|
||||
repoId: "unsloth/Qwen3-8B-GGUF",
|
||||
author: "unsloth",
|
||||
families: ["Qwen"],
|
||||
baseModels: [],
|
||||
architecture: null,
|
||||
quants: ["Q4_K_M"],
|
||||
tags: [],
|
||||
hubTags: [],
|
||||
pipelineTag: null,
|
||||
license: null,
|
||||
status: "pending",
|
||||
hubStatus: null,
|
||||
requestedBy: "hermes",
|
||||
pendingApproval: true,
|
||||
};
|
||||
assert.deepEqual(facetValues(m, "status"), ["pending", "pending_approval"]);
|
||||
assert.ok(matchesFilters(m, { ...EMPTY_FILTERS, requester: ["Hermes"] }));
|
||||
assert.ok(!matchesFilters({ ...m, requestedBy: null }, { ...EMPTY_FILTERS, requester: ["hermes"] }));
|
||||
});
|
||||
});
|
||||
|
||||
describe("proxy", () => {
|
||||
// The OIDC gate must skip exactly /api/v1 (bearer tokens), nothing that merely starts like it.
|
||||
const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");
|
||||
const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string;
|
||||
const gated = (path: string) => new RegExp(`^${matcher}$`).test(path);
|
||||
|
||||
it("leaves /api/v1 to token auth and gates everything else", () => {
|
||||
assert.ok(!gated("/api/v1"));
|
||||
assert.ok(!gated("/api/v1/models"));
|
||||
assert.ok(!gated("/api/v1/jobs/01ABC"));
|
||||
assert.ok(gated("/api/v1x"));
|
||||
assert.ok(gated("/api/models"));
|
||||
assert.ok(gated("/api/api-tokens"));
|
||||
assert.ok(gated("/settings/api-tokens"));
|
||||
});
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
import "server-only";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { apiKeys } from "@/lib/db/schema";
|
||||
|
||||
export class ApiKeyError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "conflict",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
// No whitespace or commas: llama.cpp takes several keys as one comma-separated list.
|
||||
export const ApiKeyBody = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
key: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(16, "at least 16 characters")
|
||||
.max(256)
|
||||
.regex(/^[\x21-\x7e]+$/, "printable characters without spaces")
|
||||
.refine((k) => !k.includes(","), "no commas")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export const generateApiKey = () => `sk-kaname-${randomBytes(24).toString("base64url")}`;
|
||||
|
||||
/** "…" plus the last 4 characters: enough to tell keys apart without showing them. */
|
||||
const mask = (key: string) => `…${key.slice(-4)}`;
|
||||
|
||||
export type ApiKeyRow = { id: string; name: string; hint: string; createdAt: number };
|
||||
|
||||
export async function listApiKeys(): Promise<ApiKeyRow[]> {
|
||||
const rows = await db().select().from(apiKeys).orderBy(asc(apiKeys.createdAt));
|
||||
return rows.map((r) => ({ id: r.id, name: r.name, hint: mask(r.key), createdAt: r.createdAt.getTime() }));
|
||||
}
|
||||
|
||||
/** Returns the full key once, so the user can copy it. */
|
||||
export async function createApiKey(input: z.infer<typeof ApiKeyBody>) {
|
||||
const key = input.key ?? generateApiKey();
|
||||
const clash = await db().query.apiKeys.findFirst({ columns: { id: true }, where: eq(apiKeys.key, key) });
|
||||
if (clash) throw new ApiKeyError("conflict", "This key already exists.", 409);
|
||||
const [row] = await db().insert(apiKeys).values({ name: input.name, key }).returning();
|
||||
return { id: row.id, name: row.name, key, hint: mask(key), createdAt: row.createdAt.getTime() };
|
||||
}
|
||||
|
||||
export async function deleteApiKey(id: string) {
|
||||
const res = await db().delete(apiKeys).where(eq(apiKeys.id, id)).returning({ id: apiKeys.id });
|
||||
if (res.length === 0) throw new ApiKeyError("not_found", "API key not found.", 404);
|
||||
}
|
||||
|
||||
/** All key values (for runtime containers and Kaname's own requests to them). */
|
||||
export async function apiKeyValues(): Promise<string[]> {
|
||||
return (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt))).map((r) => r.key);
|
||||
}
|
||||
|
||||
/** One key's value, for "show key" in Settings. */
|
||||
export async function revealApiKey(id: string): Promise<string> {
|
||||
const row = await db().query.apiKeys.findFirst({ columns: { key: true }, where: eq(apiKeys.id, id) });
|
||||
if (!row) throw new ApiKeyError("not_found", "API key not found.", 404);
|
||||
return row.key;
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// API token format, hashing and scope checks. Pure (no DB), shared by the server code and tests.
|
||||
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
|
||||
|
||||
/** "kn_" + 32 random bytes as base64url (43 chars). */
|
||||
export const TOKEN_PREFIX = "kn_";
|
||||
const TOKEN_RE = /^kn_[A-Za-z0-9_-]{43}$/;
|
||||
/** Characters of the token kept for display ("kn_AbCd…"). */
|
||||
const DISPLAY_CHARS = 7;
|
||||
|
||||
export const TOKEN_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/;
|
||||
|
||||
export function generateToken(): { token: string; prefix: string; hash: string } {
|
||||
const token = TOKEN_PREFIX + randomBytes(32).toString("base64url");
|
||||
return { token, prefix: token.slice(0, DISPLAY_CHARS), hash: hashToken(token) };
|
||||
}
|
||||
|
||||
/** SHA-256 is enough: the tokens are 256 random bits, not passwords that need a slow hash. */
|
||||
export function hashToken(token: string): string {
|
||||
return createHash("sha256").update(token).digest("hex");
|
||||
}
|
||||
|
||||
/** The token from an `Authorization: Bearer …` header, or null if it's missing or malformed. */
|
||||
export function bearerToken(header: string | null): string | null {
|
||||
const m = header?.match(/^Bearer\s+(\S+)\s*$/i);
|
||||
return m && TOKEN_RE.test(m[1]) ? m[1] : null;
|
||||
}
|
||||
|
||||
export function isScope(v: unknown): v is TokenScope {
|
||||
return typeof v === "string" && (TOKEN_SCOPES as readonly string[]).includes(v);
|
||||
}
|
||||
@@ -1,110 +0,0 @@
|
||||
import "server-only";
|
||||
import { and, desc, eq, isNotNull, isNull } from "drizzle-orm";
|
||||
import { NextResponse } from "next/server";
|
||||
import { bearerToken, generateToken, hashToken, isScope, TOKEN_NAME_RE } from "@/lib/api-token-core";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { apiTokens, type TokenScope } from "@/lib/db/schema";
|
||||
|
||||
export class TokenError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "exists" | "not_found",
|
||||
message: string,
|
||||
public status = 400,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export type ApiTokenRow = Omit<typeof apiTokens.$inferSelect, "hash">;
|
||||
|
||||
/** lastUsedAt is written at most this often per token, not on every request. */
|
||||
const TOUCH_MS = 60_000;
|
||||
|
||||
export async function listTokens(): Promise<ApiTokenRow[]> {
|
||||
return db()
|
||||
.select({
|
||||
id: apiTokens.id,
|
||||
name: apiTokens.name,
|
||||
prefix: apiTokens.prefix,
|
||||
scopes: apiTokens.scopes,
|
||||
lastUsedAt: apiTokens.lastUsedAt,
|
||||
revokedAt: apiTokens.revokedAt,
|
||||
createdAt: apiTokens.createdAt,
|
||||
})
|
||||
.from(apiTokens)
|
||||
.orderBy(desc(apiTokens.createdAt));
|
||||
}
|
||||
|
||||
/** Create a token; the plain token is returned only here and never stored. */
|
||||
export async function createToken(name: string, scopes: string[]): Promise<{ id: string; token: string }> {
|
||||
const n = name.trim().toLowerCase();
|
||||
if (!TOKEN_NAME_RE.test(n)) throw new TokenError("invalid", "Name: 1–40 characters, lowercase letters, digits, . _ - (e.g. hermes).");
|
||||
const s = [...new Set(scopes)];
|
||||
if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
|
||||
if (await db().query.apiTokens.findFirst({ columns: { id: true }, where: eq(apiTokens.name, n) })) {
|
||||
throw new TokenError("exists", `A token named "${n}" already exists. Delete it first or pick another name.`, 409);
|
||||
}
|
||||
const t = generateToken();
|
||||
const [row] = await db().insert(apiTokens).values({ name: n, prefix: t.prefix, hash: t.hash, scopes: s as TokenScope[] }).returning({ id: apiTokens.id });
|
||||
return { id: row.id, token: t.token };
|
||||
}
|
||||
|
||||
export async function revokeToken(id: string): Promise<void> {
|
||||
const res = await db().update(apiTokens).set({ revokedAt: new Date() }).where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
|
||||
if (res.length === 0) throw new TokenError("not_found", "Token not found or already revoked.", 404);
|
||||
}
|
||||
|
||||
/** Change what an active token may do (takes effect on its next request). */
|
||||
export async function updateTokenScopes(id: string, scopes: string[]): Promise<void> {
|
||||
const s = [...new Set(scopes)];
|
||||
if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
|
||||
const res = await db()
|
||||
.update(apiTokens)
|
||||
.set({ scopes: s as TokenScope[] })
|
||||
.where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt)))
|
||||
.returning({ id: apiTokens.id });
|
||||
if (res.length === 0) throw new TokenError("not_found", "Token not found or revoked.", 404);
|
||||
}
|
||||
|
||||
/** Only revoked tokens can be deleted (frees the name; "requested by" labels keep it). */
|
||||
export async function deleteToken(id: string): Promise<void> {
|
||||
const res = await db().delete(apiTokens).where(and(eq(apiTokens.id, id), isNotNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
|
||||
if (res.length === 0) throw new TokenError("not_found", "Revoke the token before deleting it.", 409);
|
||||
}
|
||||
|
||||
export type TokenIdentity = { id: string; name: string; scopes: TokenScope[] };
|
||||
|
||||
/** The active token behind a request's bearer header, or null. */
|
||||
export async function tokenFromRequest(req: Request): Promise<TokenIdentity | null> {
|
||||
const token = bearerToken(req.headers.get("authorization"));
|
||||
if (!token) return null;
|
||||
const row = await db().query.apiTokens.findFirst({ where: and(eq(apiTokens.hash, hashToken(token)), isNull(apiTokens.revokedAt)) });
|
||||
if (!row) return null;
|
||||
if (!row.lastUsedAt || Date.now() - row.lastUsedAt.getTime() > TOUCH_MS) {
|
||||
await db().update(apiTokens).set({ lastUsedAt: new Date() }).where(eq(apiTokens.id, row.id));
|
||||
}
|
||||
return { id: row.id, name: row.name, scopes: row.scopes };
|
||||
}
|
||||
|
||||
function v1Error(status: number, code: string, message: string) {
|
||||
return NextResponse.json({ error: { code, message } }, { status, headers: status === 401 ? { "WWW-Authenticate": 'Bearer realm="kaname"' } : undefined });
|
||||
}
|
||||
|
||||
type Handler<Ctx> = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promise<Response> | Response;
|
||||
|
||||
/**
|
||||
* Wraps a /api/v1 route: requires `Authorization: Bearer <token>` with `scope` (null: any valid
|
||||
* token). Login sessions don't count here; the rest of the app is OIDC-only.
|
||||
*/
|
||||
export function withToken<Ctx = unknown>(scope: TokenScope | null, handler: Handler<Ctx>) {
|
||||
return async (req: Request, ctx: Ctx) => {
|
||||
const token = await tokenFromRequest(req);
|
||||
if (!token) {
|
||||
return v1Error(401, "unauthorized", "Missing or invalid API token. Send it as \"Authorization: Bearer kn_…\"; tokens are created in Kaname under Settings → API tokens.");
|
||||
}
|
||||
if (scope && !token.scopes.includes(scope)) {
|
||||
return v1Error(403, "forbidden", `This token lacks the scope "${scope}" (it has: ${token.scopes.join(", ")}). Ask the user to grant it in Settings → API tokens.`);
|
||||
}
|
||||
return handler(req, { ...ctx, token });
|
||||
};
|
||||
}
|
||||
@@ -1,581 +0,0 @@
|
||||
// /api/v1 deployments and benchmarks end to end against a temporary SQLite database (no worker, no
|
||||
// Docker: deployment states are set directly). Scopes, ownership, protected deployments, every
|
||||
// guardrail rejection, approval, the activity log and ?wait=.
|
||||
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
|
||||
|
||||
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, beforeEach, describe, it } from "node:test";
|
||||
import { eq, isNotNull } from "drizzle-orm";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "kaname-agent-"));
|
||||
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
|
||||
process.env.MODELS_DIR = join(dir, "models");
|
||||
|
||||
const GiB = 2 ** 30;
|
||||
|
||||
type Mods = {
|
||||
db: typeof import("./db/client");
|
||||
schema: typeof import("./db/schema");
|
||||
tokens: typeof import("./api-tokens");
|
||||
settings: typeof import("./settings");
|
||||
deployments: typeof import("./deployments");
|
||||
v1: typeof import("../app/api/v1/route");
|
||||
runtimes: typeof import("../app/api/v1/runtimes/route");
|
||||
deps: typeof import("../app/api/v1/deployments/route");
|
||||
dep: typeof import("../app/api/v1/deployments/[id]/route");
|
||||
start: typeof import("../app/api/v1/deployments/[id]/start/route");
|
||||
stop: typeof import("../app/api/v1/deployments/[id]/stop/route");
|
||||
runs: typeof import("../app/api/v1/benchmarks/route");
|
||||
run: typeof import("../app/api/v1/benchmarks/[id]/route");
|
||||
cancel: typeof import("../app/api/v1/benchmarks/[id]/cancel/route");
|
||||
compare: typeof import("../app/api/v1/benchmarks/compare/route");
|
||||
sweeps: typeof import("../app/api/v1/sweeps/route");
|
||||
};
|
||||
let M: Mods;
|
||||
let hermes: string; // all scopes
|
||||
let other: string; // all scopes, another agent
|
||||
let downloadsOnly: string; // the 0.10 scopes
|
||||
let modelId: string;
|
||||
let sycl: string; // llama.cpp on /dev/dri, pulled
|
||||
let notPulled: string;
|
||||
let userProtected: string; // the user's own, protected, running on the GPU
|
||||
|
||||
type Res = { status: number; body: Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
const call = async (handler: (req: Request, ctx: never) => Promise<Response>, path: string, opts: { token?: string; method?: string; body?: unknown; params?: Record<string, string> } = {}): Promise<Res> => {
|
||||
const req = new Request(`http://kaname.test${path}`, {
|
||||
method: opts.method ?? (opts.body ? "POST" : "GET"),
|
||||
headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
|
||||
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
|
||||
return { status: res.status, body: (await res.json()) as Res["body"] };
|
||||
};
|
||||
|
||||
const deployBody = (o: Record<string, unknown> = {}) => ({
|
||||
runtimeId: sycl,
|
||||
modelId,
|
||||
options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 8192, extraArgs: [] as string[], ...((o.options as object) ?? {}) },
|
||||
...Object.fromEntries(Object.entries(o).filter(([k]) => k !== "options")),
|
||||
});
|
||||
const create = (o: Record<string, unknown> = {}, token = hermes) => call(M.deps.POST, "/api/v1/deployments", { token, body: deployBody(o) });
|
||||
const setState = async (id: string, state: "running" | "stopped" | "starting", desired: "running" | "stopped" = state === "stopped" ? "stopped" : "running") => {
|
||||
await M.db
|
||||
.db()
|
||||
.update(M.schema.deployments)
|
||||
.set({ state, desiredState: desired, startRequestedAt: null, containerName: state === "running" ? `kaname-test-${id.slice(-6)}` : null })
|
||||
.where(eq(M.schema.deployments.id, id));
|
||||
};
|
||||
const tuning = (t: Record<string, unknown>) => M.settings.saveTuning(t);
|
||||
|
||||
before(async () => {
|
||||
const { runMigrations } = await import("./db/migrate");
|
||||
await runMigrations();
|
||||
M = {
|
||||
db: await import("./db/client"),
|
||||
schema: await import("./db/schema"),
|
||||
tokens: await import("./api-tokens"),
|
||||
settings: await import("./settings"),
|
||||
deployments: await import("./deployments"),
|
||||
v1: await import("../app/api/v1/route"),
|
||||
runtimes: await import("../app/api/v1/runtimes/route"),
|
||||
deps: await import("../app/api/v1/deployments/route"),
|
||||
dep: await import("../app/api/v1/deployments/[id]/route"),
|
||||
start: await import("../app/api/v1/deployments/[id]/start/route"),
|
||||
stop: await import("../app/api/v1/deployments/[id]/stop/route"),
|
||||
runs: await import("../app/api/v1/benchmarks/route"),
|
||||
run: await import("../app/api/v1/benchmarks/[id]/route"),
|
||||
cancel: await import("../app/api/v1/benchmarks/[id]/cancel/route"),
|
||||
compare: await import("../app/api/v1/benchmarks/compare/route"),
|
||||
sweeps: await import("../app/api/v1/sweeps/route"),
|
||||
} as Mods;
|
||||
const scopes = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"];
|
||||
hermes = (await M.tokens.createToken("hermes", scopes)).token;
|
||||
other = (await M.tokens.createToken("other", scopes)).token;
|
||||
downloadsOnly = (await M.tokens.createToken("old", ["models:read", "downloads:create"])).token;
|
||||
|
||||
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",
|
||||
os: "Debian",
|
||||
architecture: "x86_64",
|
||||
cpus: 32,
|
||||
memoryBytes: 64 * GiB,
|
||||
cpuModel: null,
|
||||
cpuFeatures: [],
|
||||
network: "kaname_default",
|
||||
modelsSource: { type: "bind", source: "/srv/models" },
|
||||
hardware: {
|
||||
gpus: [{ vendor: "intel", pciAddress: "0000:03:00.0", name: "Intel Arc Pro B65", vramMb: 32768, driver: "xe", driverVersion: null, linkCurrent: null, linkMax: null, barMb: 32768, rebar: true }],
|
||||
p2p: null,
|
||||
cpu: { model: null, cores: 16, threads: 32 },
|
||||
memoryBytes: 64 * GiB,
|
||||
kernel: null,
|
||||
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
|
||||
storage: null,
|
||||
checkedAt: now.toISOString(),
|
||||
},
|
||||
checkedAt: now.toISOString(),
|
||||
},
|
||||
});
|
||||
const [model] = await d.insert(s.models).values({ repoId: "unsloth/Test-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Test-GGUF", status: "ready" }).returning();
|
||||
modelId = model.id;
|
||||
await d.insert(s.modelFiles).values([
|
||||
{ modelId, path: "Small-Q4_K_M.gguf", size: 4 * GiB, selected: true, state: "present" },
|
||||
{ modelId, path: "Big-Q8_0.gguf", size: 20 * GiB, selected: true, state: "present" },
|
||||
]);
|
||||
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", imageState: "present" }).returning();
|
||||
sycl = rt.id;
|
||||
const [missing] = await d.insert(s.runtimes).values({ name: "vLLM (XPU)", engine: "vllm", accelerator: "dri", image: "vllm/vllm-openai-xpu:v0.31.0", imageState: "missing" }).returning();
|
||||
notPulled = missing.id;
|
||||
// The user's production deployment: 4 GiB model + KV at 32k ≈ 10 GiB of VRAM.
|
||||
const [prod] = await d
|
||||
.insert(s.deployments)
|
||||
.values({ name: "prod", runtimeId: sycl, modelId, options: { modelFile: "Small-Q4_K_M.gguf", contextSize: 32768, extraArgs: [] }, state: "running", desiredState: "running", protected: true })
|
||||
.returning();
|
||||
userProtected = prod.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.
|
||||
}
|
||||
});
|
||||
|
||||
/** Each test starts from: approval "approve", default limits, no agent deployments or runs. */
|
||||
beforeEach(async () => {
|
||||
if (!M) return;
|
||||
const d = M.db.db();
|
||||
const s = M.schema;
|
||||
await M.settings.saveTuning({ ...(await import("./agent-tuning")).DEFAULT_TUNING });
|
||||
await d.delete(s.deployments).where(isNotNull(s.deployments.requestedByTokenId));
|
||||
await d.delete(s.benchmarkRuns);
|
||||
await d.delete(s.benchmarkSweeps);
|
||||
});
|
||||
|
||||
describe("scopes", () => {
|
||||
it("tokens from before 0.13 can't touch deployments or benchmarks", async () => {
|
||||
assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: downloadsOnly })).status, 403);
|
||||
assert.equal((await call(M.runtimes.GET, "/api/v1/runtimes", { token: downloadsOnly })).status, 403);
|
||||
const r = await call(M.deps.POST, "/api/v1/deployments", { token: downloadsOnly, body: deployBody() });
|
||||
assert.equal(r.status, 403);
|
||||
assert.match(r.body.error.message, /deployments:write/);
|
||||
assert.equal((await call(M.runs.GET, "/api/v1/benchmarks", { token: downloadsOnly })).status, 403);
|
||||
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: downloadsOnly, body: { deploymentId: "x" } })).status, 403);
|
||||
assert.equal((await call(M.sweeps.POST, "/api/v1/sweeps", { token: downloadsOnly, body: {} })).status, 403);
|
||||
});
|
||||
|
||||
it("read scopes don't allow writing", async () => {
|
||||
const reader = (await M.tokens.createToken("reader", ["deployments:read", "benchmarks:read"])).token;
|
||||
assert.equal((await call(M.deps.GET, "/api/v1/deployments", { token: reader })).status, 200);
|
||||
assert.equal((await call(M.deps.POST, "/api/v1/deployments", { token: reader, body: deployBody() })).status, 403);
|
||||
assert.equal((await call(M.start.POST, "/x", { token: reader, params: { id: userProtected } })).status, 403);
|
||||
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: reader, body: { deploymentId: userProtected } })).status, 403);
|
||||
});
|
||||
|
||||
it("lists pulled runtimes with what agents may use", async () => {
|
||||
const r = await call(M.runtimes.GET, "/api/v1/runtimes", { token: hermes });
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(r.body.runtimes.map((x: { id: string }) => x.id), [sycl]);
|
||||
assert.ok(r.body.runtimes[0].allowedExtraArgs.includes("--no-mmap"));
|
||||
assert.equal(r.body.gpus[0].name, "Intel Arc Pro B65");
|
||||
});
|
||||
});
|
||||
|
||||
describe("creating deployments", () => {
|
||||
it("dry run: the command and estimates, nothing created", async () => {
|
||||
const r = await create({ dryRun: true, options: { cacheTypeK: "q8_0", cacheTypeV: "q8_0" } });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.dryRun, true);
|
||||
assert.match(r.body.command, /docker run .*llama\.cpp:server-intel .*-c 8192 .*-ctk q8_0/);
|
||||
assert.ok(r.body.estimates.vramMb > 4096 && r.body.estimates.vramMb < 32768);
|
||||
assert.equal(r.body.estimates.gpuVramMb, 32768);
|
||||
assert.ok(r.body.limits.memoryMb > 0);
|
||||
assert.equal((await call(M.deps.GET, "/api/v1/deployments?mine=1", { token: hermes })).body.count, 0);
|
||||
});
|
||||
|
||||
it("waits for approval by default and records who asked", async () => {
|
||||
const r = await create();
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal(r.body.state, "pending_approval");
|
||||
assert.match(r.body.message, /approval/);
|
||||
const d = await M.deployments.getDeployment(r.body.id);
|
||||
assert.equal(d?.desiredState, "stopped");
|
||||
assert.ok(d?.startRequestedAt);
|
||||
assert.equal(d?.requestedBy, "hermes");
|
||||
assert.ok(d?.memoryMb, "agent deployments always get a memory limit");
|
||||
const view = await call(M.dep.GET, "/x", { token: hermes, params: { id: r.body.id } });
|
||||
assert.equal(view.body.state, "pending_approval");
|
||||
assert.equal(view.body.mine, true);
|
||||
// The user approves (Start in the UI): it starts.
|
||||
await M.deployments.setDesiredState(r.body.id, "running");
|
||||
assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
|
||||
});
|
||||
|
||||
it("starts right away in automatic mode", async () => {
|
||||
await tuning({ approvalMode: "auto" });
|
||||
const r = await create();
|
||||
assert.equal(r.body.state, "starting");
|
||||
assert.equal((await M.deployments.getDeployment(r.body.id))?.desiredState, "running");
|
||||
});
|
||||
|
||||
it("can be created stopped", async () => {
|
||||
const r = await create({ start: false });
|
||||
assert.equal(r.body.state, "stopped");
|
||||
});
|
||||
|
||||
it("rejects unknown fields instead of ignoring them", async () => {
|
||||
const r = await create({ options: { gpuLayerz: "all" } });
|
||||
assert.equal(r.status, 400);
|
||||
assert.equal(r.body.error.code, "invalid_request");
|
||||
assert.match(r.body.error.message, /gpuLayerz/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("deployment guardrails", () => {
|
||||
it("runtime not pulled / not on the allowlist", async () => {
|
||||
const r = await create({ runtimeId: notPulled, options: { modelFile: "" } });
|
||||
assert.equal(r.body.error.code, "runtime_not_pulled");
|
||||
await tuning({ allowedRuntimeIds: ["something-else"] });
|
||||
const a = await create();
|
||||
assert.equal(a.status, 403);
|
||||
assert.equal(a.body.error.code, "runtime_not_allowed");
|
||||
});
|
||||
|
||||
it("extra arguments outside the allowlist, naming the argument", async () => {
|
||||
const r = await create({ options: { extraArgs: ["--host", "0.0.0.0"] } });
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal(r.body.error.code, "arg_not_allowed");
|
||||
assert.match(r.body.error.message, /"--host"/);
|
||||
const p = await create({ options: { extraArgs: ["--chat-template", "/models/../etc/passwd"] } });
|
||||
assert.equal(p.body.error.code, "arg_not_allowed");
|
||||
assert.equal((await create({ dryRun: true, options: { extraArgs: ["--no-mmap", "-ctk", "q8_0"] } })).status, 200);
|
||||
});
|
||||
|
||||
it("host ports outside the configured range", async () => {
|
||||
const r = await create({ hostPort: 18080 });
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal(r.body.error.code, "port_not_allowed");
|
||||
await tuning({ hostPortRange: { from: 18000, to: 18099 } });
|
||||
assert.equal((await create({ hostPort: 18080, dryRun: true })).status, 200);
|
||||
assert.equal((await create({ hostPort: 18100, dryRun: true })).body.error.code, "port_not_allowed");
|
||||
});
|
||||
|
||||
it("memory and CPU caps", async () => {
|
||||
await tuning({ maxMemoryMb: 4096, maxCpus: 4 });
|
||||
const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
|
||||
assert.equal(big.body.error.code, "limit_exceeded");
|
||||
assert.match(big.body.error.message, /the estimate/);
|
||||
assert.equal((await create({ memoryMb: 8192 })).body.error.code, "limit_exceeded");
|
||||
assert.equal((await create({ cpus: 8 })).body.error.code, "limit_exceeded");
|
||||
});
|
||||
|
||||
it("one agent deployment at a time (pending ones count)", async () => {
|
||||
assert.equal((await create()).status, 201);
|
||||
const second = await create();
|
||||
assert.equal(second.status, 429);
|
||||
assert.equal(second.body.error.code, "too_many_deployments");
|
||||
// Creating a stopped one is fine; starting it isn't.
|
||||
const stopped = await create({ start: false });
|
||||
assert.equal(stopped.status, 201);
|
||||
const s = await call(M.start.POST, "/x", { token: hermes, params: { id: stopped.body.id } });
|
||||
assert.equal(s.body.error.code, "too_many_deployments");
|
||||
});
|
||||
|
||||
it("no start while an agent deployment is still loading or an agent run is open", async () => {
|
||||
await tuning({ maxAgentDeployments: 3 });
|
||||
const a = await create();
|
||||
await setState(a.body.id, "starting");
|
||||
assert.equal((await create()).body.error.code, "gpu_busy");
|
||||
await setState(a.body.id, "running");
|
||||
await M.db.db().insert(M.schema.benchmarkRuns).values({
|
||||
deploymentId: a.body.id,
|
||||
modelId,
|
||||
settings: { quick: true, passes: null, warmup: null, phases: [] },
|
||||
snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
|
||||
state: "running",
|
||||
requestedByTokenId: "someone",
|
||||
requestedBy: "other",
|
||||
});
|
||||
const r = await create();
|
||||
assert.equal(r.body.error.code, "gpu_busy");
|
||||
assert.match(r.body.error.message, /benchmark or sweep/);
|
||||
});
|
||||
|
||||
it("can't crowd a running protected deployment out of VRAM", async () => {
|
||||
await tuning({ approvalMode: "auto" });
|
||||
// prod ≈ 10 GiB; the 20 GB Q8_0 at 8k context needs ~22 GiB more: over 32 GiB.
|
||||
const big = await create({ options: { modelFile: "Big-Q8_0.gguf" } });
|
||||
assert.equal(big.status, 409);
|
||||
assert.equal(big.body.error.code, "vram_protected");
|
||||
assert.match(big.body.error.message, /prod/);
|
||||
// Partial offload can't be estimated next to a protected deployment.
|
||||
assert.equal((await create({ options: { gpuLayers: "20" } })).body.error.code, "vram_protected");
|
||||
// The small one fits.
|
||||
assert.equal((await create()).status, 201);
|
||||
});
|
||||
});
|
||||
|
||||
describe("ownership and protection", () => {
|
||||
it("agents can't change, start, stop or delete the user's or another token's deployments", async () => {
|
||||
for (const [handler, method] of [
|
||||
[M.start.POST, "POST"],
|
||||
[M.stop.POST, "POST"],
|
||||
[M.dep.DELETE, "DELETE"],
|
||||
] as const) {
|
||||
const r = await call(handler, "/x", { token: hermes, method, params: { id: userProtected } });
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal(r.body.error.code, "protected");
|
||||
}
|
||||
const theirs = await create({ start: false }, other);
|
||||
const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: theirs.body.id } });
|
||||
assert.equal(r.body.error.code, "not_owner");
|
||||
assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: theirs.body.id } })).body.error.code, "not_owner");
|
||||
});
|
||||
|
||||
it("not even their own once the user protects it", async () => {
|
||||
const mine = await create({ start: false });
|
||||
await M.deployments.setProtected(mine.body.id, true);
|
||||
const r = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } });
|
||||
assert.equal(r.body.error.code, "protected");
|
||||
});
|
||||
|
||||
it("edits, stops and deletes their own deployments", async () => {
|
||||
const mine = await create({ start: false });
|
||||
const p = await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 16384, extraArgs: ["--no-mmap"] } }, params: { id: mine.body.id } });
|
||||
assert.equal(p.status, 200);
|
||||
assert.equal(p.body.deployment.options.contextSize, 16384);
|
||||
assert.match(p.body.command, /-c 16384 .*--no-mmap/);
|
||||
// Changing a running deployment needs a stop first.
|
||||
await setState(mine.body.id, "running");
|
||||
assert.equal((await call(M.dep.PATCH, "/x", { token: hermes, method: "PATCH", body: { options: { contextSize: 4096 } }, params: { id: mine.body.id } })).body.error.code, "busy");
|
||||
assert.equal((await call(M.stop.POST, "/x", { token: hermes, params: { id: mine.body.id } })).status, 200);
|
||||
assert.equal((await M.deployments.getDeployment(mine.body.id))?.desiredState, "stopped");
|
||||
assert.equal((await call(M.dep.DELETE, "/x", { token: hermes, method: "DELETE", params: { id: mine.body.id } })).status, 200);
|
||||
assert.equal(await M.deployments.getDeployment(mine.body.id), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("benchmark runs and sweeps", () => {
|
||||
async function runningOwn(token = hermes) {
|
||||
const d = await create({ start: false }, token);
|
||||
await setState(d.body.id, "running");
|
||||
return d.body.id as string;
|
||||
}
|
||||
|
||||
it("only on the token's own, unprotected deployments", async () => {
|
||||
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: userProtected } });
|
||||
assert.equal(r.body.error.code, "protected");
|
||||
const theirs = await runningOwn(other);
|
||||
assert.equal((await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: theirs } })).body.error.code, "not_owner");
|
||||
});
|
||||
|
||||
it("waits for approval, with the time limit, and one at a time", async () => {
|
||||
const id = await runningOwn();
|
||||
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id, quick: true, description: "baseline" } });
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal(r.body.state, "pending_approval");
|
||||
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
|
||||
assert.equal(row?.timeLimitS, 30 * 60);
|
||||
assert.equal(row?.requestedBy, "hermes");
|
||||
const second = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: id } });
|
||||
assert.equal(second.status, 429);
|
||||
assert.equal(second.body.error.code, "gpu_busy");
|
||||
// Cancelling is for the token that started it.
|
||||
assert.equal((await call(M.cancel.POST, "/x", { token: other, params: { id: r.body.id } })).body.error.code, "not_owner");
|
||||
assert.equal((await call(M.cancel.POST, "/x", { token: hermes, params: { id: r.body.id } })).status, 200);
|
||||
const view = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
|
||||
assert.equal(view.body.state, "cancelled");
|
||||
});
|
||||
|
||||
it("a stopped deployment can't be benchmarked", async () => {
|
||||
const d = await create({ start: false });
|
||||
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: d.body.id } });
|
||||
assert.equal(r.status, 409);
|
||||
assert.match(r.body.error.message, /running server/);
|
||||
});
|
||||
|
||||
it("sweeps: within the variant limit, with no agent deployment running", async () => {
|
||||
const base = await create({ start: false });
|
||||
const many = await call(M.sweeps.POST, "/api/v1/sweeps", {
|
||||
token: hermes,
|
||||
body: { baseDeploymentId: base.body.id, params: [{ key: "contextSize", values: ["1024", "2048", "4096"] }, { key: "kvCache", values: ["f16", "q8_0", "q4_0"] }] },
|
||||
});
|
||||
assert.equal(many.body.error.code, "too_many_variants");
|
||||
const running = await runningOwn();
|
||||
const busy = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
|
||||
assert.equal(busy.body.error.code, "gpu_busy");
|
||||
await setState(running, "stopped");
|
||||
const ok = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: base.body.id, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
|
||||
assert.equal(ok.status, 201);
|
||||
assert.equal(ok.body.state, "pending_approval");
|
||||
assert.equal(ok.body.variants, 2);
|
||||
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, ok.body.id) });
|
||||
assert.equal(row?.timeLimitS, 180 * 60);
|
||||
assert.equal(row?.runTimeLimitS, 30 * 60);
|
||||
});
|
||||
|
||||
it("compares runs: headline numbers and what differs", async () => {
|
||||
const id = await runningOwn();
|
||||
const ids: string[] = [];
|
||||
for (const decode of [100, 120]) {
|
||||
const [r] = await M.db
|
||||
.db()
|
||||
.insert(M.schema.benchmarkRuns)
|
||||
.values({
|
||||
deploymentId: id,
|
||||
modelId,
|
||||
settings: { quick: false, passes: null, warmup: null, phases: [] },
|
||||
snapshot: { deploymentName: "x", repoId: "x", runtimeName: "x", engine: "llama.cpp", image: "x", imageId: null, options: { modelFile: "", contextSize: 1, extraArgs: [] }, cpus: null, memoryMb: null, command: "" },
|
||||
state: "completed",
|
||||
summary: { combined: { decode, ttft_p50: 50, itl_low1: null, update_p50: null, update_p99: null }, single: [], prefill: [], concurrency: [], phases: [], cacheHits: 0, betterbenchVersion: "0.6.1", corpusVersion: "1", passes: 20, quick: false },
|
||||
meta: {
|
||||
v: 1,
|
||||
gpus: [],
|
||||
p2p: "n/a",
|
||||
rebar: null,
|
||||
runtime: { image: "x", tag: null, digest: null, engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b1" },
|
||||
model: { repoId: "a/b", file: null, quant: "Q4_K_M", kvCache: decode === 100 ? "f16" : "q8_0" },
|
||||
contextSize: 8192,
|
||||
concurrency: 4,
|
||||
overridden: [],
|
||||
},
|
||||
})
|
||||
.returning();
|
||||
ids.push(r.id);
|
||||
}
|
||||
const c = await call(M.compare.GET, `/api/v1/benchmarks/compare?ids=${ids.join(",")}`, { token: hermes });
|
||||
assert.equal(c.status, 200);
|
||||
assert.deepEqual(c.body.runs.map((r: { headline: { decodeTps: number } }) => r.headline.decodeTps), [100, 120]);
|
||||
assert.deepEqual(Object.keys(c.body.runs[0].differs), ["model"]);
|
||||
assert.equal(c.body.same.ctx, "8,192");
|
||||
});
|
||||
});
|
||||
|
||||
describe("?wait=", () => {
|
||||
it("returns as soon as a starting deployment is running", async () => {
|
||||
await tuning({ approvalMode: "auto" });
|
||||
const d = await create();
|
||||
await setState(d.body.id, "starting");
|
||||
setTimeout(() => void setState(d.body.id, "running"), 300);
|
||||
const t0 = Date.now();
|
||||
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=10`, { token: hermes, params: { id: d.body.id } });
|
||||
assert.equal(r.body.state, "running");
|
||||
assert.equal(r.body.timedOut, false);
|
||||
assert.ok(Date.now() - t0 < 5000);
|
||||
});
|
||||
|
||||
it("gives up after the wait and says so", async () => {
|
||||
const d = await create({ start: false });
|
||||
await setState(d.body.id, "starting");
|
||||
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=1`, { token: hermes, params: { id: d.body.id } });
|
||||
assert.equal(r.body.state, "starting");
|
||||
assert.equal(r.body.timedOut, true);
|
||||
assert.equal(r.body.waitedSeconds, 1);
|
||||
});
|
||||
|
||||
it("doesn't wait on something that waits for approval", async () => {
|
||||
const d = await create();
|
||||
const t0 = Date.now();
|
||||
const r = await call(M.dep.GET, `/api/v1/deployments/${d.body.id}?wait=60`, { token: hermes, params: { id: d.body.id } });
|
||||
assert.equal(r.body.state, "pending_approval");
|
||||
assert.ok(Date.now() - t0 < 2000);
|
||||
});
|
||||
|
||||
it("waits on a run until it finishes", async () => {
|
||||
const dep = await create({ start: false });
|
||||
await setState(dep.body.id, "running");
|
||||
await tuning({ approvalMode: "auto" });
|
||||
const run = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { deploymentId: dep.body.id } });
|
||||
assert.equal(run.body.state, "queued");
|
||||
setTimeout(
|
||||
// A drizzle query only runs once it is awaited.
|
||||
async () => await M.db.db().update(M.schema.benchmarkRuns).set({ state: "completed", finishedAt: new Date() }).where(eq(M.schema.benchmarkRuns.id, run.body.id)),
|
||||
300,
|
||||
);
|
||||
const r = await call(M.run.GET, `/api/v1/benchmarks/${run.body.id}?wait=10`, { token: hermes, params: { id: run.body.id } });
|
||||
assert.equal(r.body.state, "completed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("activity log", () => {
|
||||
it("records requests and refusals with the error code", async () => {
|
||||
await create();
|
||||
await create({ options: { extraArgs: ["--host", "x"] } });
|
||||
const tokenId = (await M.tokens.listTokens()).find((t) => t.name === "hermes")!.id;
|
||||
const rows = await (await import("./agent-activity")).listActivity(tokenId, 10);
|
||||
assert.equal(rows[0].outcome, "refused");
|
||||
assert.equal(rows[0].code, "arg_not_allowed");
|
||||
assert.equal(rows[1].action, "deployment.create");
|
||||
assert.equal(rows[1].outcome, "pending_approval");
|
||||
assert.equal(rows[1].targetType, "deployment");
|
||||
});
|
||||
});
|
||||
|
||||
describe("the index", () => {
|
||||
it("shows the deployment guardrails and the new endpoints", async () => {
|
||||
const r = await call(M.v1.GET, "/api/v1", { token: hermes });
|
||||
assert.equal(r.body.deploymentGuardrails.maxAgentDeployments, 1);
|
||||
assert.equal(r.body.deploymentGuardrails.maxRunMinutes, 30);
|
||||
assert.ok(r.body.endpoints.some((e: string) => e.includes("/api/v1/deployments/{id}[?wait=600]")));
|
||||
});
|
||||
});
|
||||
|
||||
describe("quality eval through the API", () => {
|
||||
it("requests an eval run on the token's own deployment and reads its score", async () => {
|
||||
const d = await create({ start: false });
|
||||
await setState(d.body.id, "running");
|
||||
const r = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["tools", "retrieval"] } });
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal(r.body.state, "pending_approval");
|
||||
const row = await M.db.db().query.benchmarkRuns.findFirst({ where: eq(M.schema.benchmarkRuns.id, r.body.id) });
|
||||
assert.equal(row?.kind, "eval");
|
||||
assert.deepEqual(row?.settings.evalSections, ["tools", "retrieval"]);
|
||||
await M.db
|
||||
.db()
|
||||
.update(M.schema.benchmarkRuns)
|
||||
.set({
|
||||
state: "completed",
|
||||
quality: {
|
||||
evalSet: "kaname-eval-1",
|
||||
score: 75,
|
||||
sections: [
|
||||
{ section: "tools", passed: 9, total: 12, score: 75, seconds: 20 },
|
||||
{ section: "retrieval", passed: 0, total: 0, score: null, unsupported: "the context length is unknown", seconds: 0 },
|
||||
],
|
||||
items: [{ section: "tools", id: "timer-12", pass: false, detail: "no tool call" }],
|
||||
config: { temperature: 0, seed: 1, thinking: false, contextTokens: null },
|
||||
},
|
||||
})
|
||||
.where(eq(M.schema.benchmarkRuns.id, r.body.id));
|
||||
const v = await call(M.run.GET, "/x", { token: hermes, params: { id: r.body.id } });
|
||||
assert.deepEqual(v.body.quality, { evalSet: "kaname-eval-1", score: 75, sections: { tools: "9/12", retrieval: "n/a (the context length is unknown)" } });
|
||||
const full = await call(M.run.GET, `/api/v1/benchmarks/${r.body.id}?full=1`, { token: hermes, params: { id: r.body.id } });
|
||||
assert.equal(full.body.failed[0].id, "timer-12");
|
||||
});
|
||||
|
||||
it("refuses unknown sections, and sweeps can add the eval per variant", async () => {
|
||||
const d = await create({ start: false });
|
||||
await setState(d.body.id, "running");
|
||||
const bad = await call(M.runs.POST, "/api/v1/benchmarks", { token: hermes, body: { kind: "eval", deploymentId: d.body.id, sections: ["vibes"] } });
|
||||
assert.equal(bad.status, 400);
|
||||
await setState(d.body.id, "stopped");
|
||||
const s = await call(M.sweeps.POST, "/api/v1/sweeps", { token: hermes, body: { baseDeploymentId: d.body.id, quality: true, params: [{ key: "kvCache", values: ["f16", "q8_0"] }] } });
|
||||
assert.equal(s.status, 201);
|
||||
const row = await M.db.db().query.benchmarkSweeps.findFirst({ where: eq(M.schema.benchmarkSweeps.id, s.body.id) });
|
||||
assert.equal(row?.settings.quality, true);
|
||||
});
|
||||
});
|
||||
@@ -1,26 +0,0 @@
|
||||
// Query-string filters for GET /api/v1/models, with the library's search semantics
|
||||
// (terms AND-ed in `q`; OR within a facet, AND across facets). Pure.
|
||||
|
||||
import { EMPTY_FILTERS, type Facet, type Filters } from "@/lib/search";
|
||||
|
||||
/** Query parameter per facet; each may repeat or hold a comma-separated list. */
|
||||
const PARAM: Record<Facet, string> = {
|
||||
author: "author",
|
||||
family: "family",
|
||||
quant: "quant",
|
||||
tag: "tag",
|
||||
status: "status",
|
||||
requester: "requested_by",
|
||||
};
|
||||
|
||||
export function parseModelFilters(params: URLSearchParams): { query: string; filters: Filters } {
|
||||
const filters = { ...EMPTY_FILTERS };
|
||||
for (const facet of Object.keys(PARAM) as Facet[]) {
|
||||
filters[facet] = params
|
||||
.getAll(PARAM[facet])
|
||||
.flatMap((v) => v.split(","))
|
||||
.map((v) => v.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
return { query: params.get("q")?.trim() ?? "", filters };
|
||||
}
|
||||
@@ -1,306 +0,0 @@
|
||||
// /api/v1 end to end against a temporary SQLite database and a stubbed Hugging Face API:
|
||||
// token auth, scopes, every guardrail rejection, idempotency, approve/reject.
|
||||
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
|
||||
|
||||
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";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "kaname-api-"));
|
||||
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
|
||||
process.env.MODELS_DIR = join(dir, "models");
|
||||
delete process.env.HF_TOKEN;
|
||||
|
||||
const GB = 1e9;
|
||||
const SHA = { a: "a".repeat(40), b: "b".repeat(40), c: "c".repeat(40), d: "d".repeat(40) };
|
||||
|
||||
/** Fake Hub: repo → commit + files. */
|
||||
const REPOS: Record<string, { sha: string; files: [string, number][] }> = {
|
||||
"unsloth/Test-GGUF": {
|
||||
sha: SHA.a,
|
||||
files: [
|
||||
["Test-Q4_K_M.gguf", 5 * GB],
|
||||
["Test-Q8_0.gguf", 9 * GB],
|
||||
["Test-F16.gguf", 70 * GB],
|
||||
["README.md", 1000],
|
||||
],
|
||||
},
|
||||
"unsloth/Other-GGUF": { sha: SHA.b, files: [["Other-Q4_K_M.gguf", 2 * GB]] },
|
||||
"ggml-org/Third-GGUF": { sha: SHA.c, files: [["Third-Q4_K_M.gguf", 3 * GB]] },
|
||||
"TheBloke/Old-GGUF": { sha: SHA.d, files: [["Old-Q4_K_M.gguf", 1 * GB]] },
|
||||
};
|
||||
|
||||
const realFetch = globalThis.fetch;
|
||||
globalThis.fetch = (async (input: string | URL | Request) => {
|
||||
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
|
||||
const m = url.pathname.match(/^\/api\/models\/([^/]+\/[^/]+)\/(revision|tree)\/([^/]+)/);
|
||||
// Like the Hub: repo ids are case-insensitive, the response has the canonical one.
|
||||
const id = m && Object.keys(REPOS).find((k) => k.toLowerCase() === decodeURIComponent(m[1]).toLowerCase());
|
||||
const repo = id && REPOS[id];
|
||||
if (!m || !id || !repo) return new Response("not found", { status: 404 });
|
||||
const rev = decodeURIComponent(m[3]);
|
||||
if (rev !== "main" && rev !== repo.sha) return new Response("", { status: 404, headers: { "x-error-code": "RevisionNotFound" } });
|
||||
if (m[2] === "revision") return Response.json({ id, sha: repo.sha, gated: false, private: false, tags: [] });
|
||||
return Response.json(repo.files.map(([path, size]) => ({ type: "file", path, size, oid: "0".repeat(40), lfs: { oid: "e".repeat(64), size } })));
|
||||
}) as typeof fetch;
|
||||
|
||||
type Mods = {
|
||||
db: typeof import("./db/client");
|
||||
schema: typeof import("./db/schema");
|
||||
tokens: typeof import("./api-tokens");
|
||||
settings: typeof import("./settings");
|
||||
agent: typeof import("./agent-downloads");
|
||||
v1: typeof import("../app/api/v1/route");
|
||||
downloads: typeof import("../app/api/v1/downloads/route");
|
||||
job: typeof import("../app/api/v1/jobs/[id]/route");
|
||||
models: typeof import("../app/api/v1/models/route");
|
||||
disk: typeof import("../app/api/v1/disk/route");
|
||||
};
|
||||
let M: Mods;
|
||||
let full: string; // models:read + downloads:create
|
||||
let readOnly: string;
|
||||
|
||||
const call = async (handler: (req: Request, ctx: never) => Promise<Response>, path: string, opts: { token?: string; body?: unknown; params?: Record<string, string> } = {}) => {
|
||||
const req = new Request(`http://kaname.test${path}`, {
|
||||
method: opts.body ? "POST" : "GET",
|
||||
headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
|
||||
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
||||
});
|
||||
const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
|
||||
return { status: res.status, body: (await res.json()) as Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
|
||||
};
|
||||
const request = (body: unknown, token = full) => call(M.downloads.POST, "/api/v1/downloads", { token, body });
|
||||
|
||||
async function setFree(bytes: number) {
|
||||
const { db } = M.db;
|
||||
const now = new Date();
|
||||
await db()
|
||||
.insert(M.schema.workerState)
|
||||
.values({ id: "worker", startedAt: now, heartbeatAt: now, modelsDirFreeBytes: bytes, modelsDirTotalBytes: 2000 * GB })
|
||||
.onConflictDoUpdate({ target: M.schema.workerState.id, set: { heartbeatAt: now, modelsDirFreeBytes: bytes } });
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
const { runMigrations } = await import("./db/migrate");
|
||||
await runMigrations();
|
||||
M = {
|
||||
db: await import("./db/client"),
|
||||
schema: await import("./db/schema"),
|
||||
tokens: await import("./api-tokens"),
|
||||
settings: await import("./settings"),
|
||||
agent: await import("./agent-downloads"),
|
||||
v1: await import("../app/api/v1/route"),
|
||||
downloads: await import("../app/api/v1/downloads/route"),
|
||||
job: await import("../app/api/v1/jobs/[id]/route"),
|
||||
models: await import("../app/api/v1/models/route"),
|
||||
disk: await import("../app/api/v1/disk/route"),
|
||||
};
|
||||
full = (await M.tokens.createToken("hermes", ["models:read", "downloads:create"])).token;
|
||||
readOnly = (await M.tokens.createToken("reader", ["models:read"])).token;
|
||||
await setFree(500 * GB);
|
||||
});
|
||||
|
||||
after(() => {
|
||||
globalThis.fetch = realFetch;
|
||||
// Close the database first; Windows can't delete an open file.
|
||||
(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; a leftover temp dir is harmless.
|
||||
}
|
||||
});
|
||||
|
||||
describe("token auth", () => {
|
||||
it("rejects missing, malformed and unknown tokens with 401", async () => {
|
||||
assert.equal((await call(M.v1.GET, "/api/v1")).status, 401);
|
||||
assert.equal((await call(M.v1.GET, "/api/v1", { token: "kn_nope" })).status, 401);
|
||||
const unknown = (await import("./api-token-core")).generateToken().token;
|
||||
const r = await call(M.v1.GET, "/api/v1", { token: unknown });
|
||||
assert.equal(r.status, 401);
|
||||
assert.match(r.body.error.message, /Settings → API tokens/);
|
||||
});
|
||||
|
||||
it("answers with the token's name, scopes and the guardrails", async () => {
|
||||
const r = await call(M.v1.GET, "/api/v1", { token: readOnly });
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(r.body.token, { name: "reader", scopes: ["models:read"] });
|
||||
assert.equal(r.body.guardrails.approvalMode, "approve");
|
||||
assert.equal(r.body.guardrails.maxRequestSize, "60.0 GB");
|
||||
});
|
||||
|
||||
it("enforces scopes with 403", async () => {
|
||||
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M" }, readOnly);
|
||||
assert.equal(r.status, 403);
|
||||
assert.match(r.body.error.message, /lacks the scope "downloads:create"/);
|
||||
assert.equal((await call(M.disk.GET, "/api/v1/disk", { token: readOnly })).status, 200);
|
||||
});
|
||||
|
||||
it("records last use and stops accepting a revoked token", async () => {
|
||||
const t = await M.tokens.createToken("temp", ["models:read"]);
|
||||
assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 200);
|
||||
const row = (await M.tokens.listTokens()).find((x) => x.name === "temp")!;
|
||||
assert.ok(row.lastUsedAt);
|
||||
await M.tokens.revokeToken(t.id);
|
||||
assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 401);
|
||||
await M.tokens.deleteToken(t.id);
|
||||
});
|
||||
|
||||
it("never stores the token itself", async () => {
|
||||
const rows = await M.db.db().select().from(M.schema.apiTokens);
|
||||
assert.ok(rows.every((r) => r.hash !== full && r.hash.length === 64 && !r.hash.startsWith("kn_")));
|
||||
});
|
||||
});
|
||||
|
||||
describe("download requests", () => {
|
||||
let first: { modelId: string; jobId: string };
|
||||
|
||||
it("validates the body", async () => {
|
||||
const r = await request({ repoId: "unsloth/Test-GGUF", sha: "main", quant: "Q4_K_M" });
|
||||
assert.equal(r.status, 400);
|
||||
assert.match(r.body.error.message, /40-character commit SHA/);
|
||||
assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a })).status, 400);
|
||||
assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q2_K" })).status, 400);
|
||||
});
|
||||
|
||||
it("creates a model and a job that waits for approval, marked with the token name", async () => {
|
||||
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M", tags: ["agent"] });
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal(r.body.state, "pending_approval");
|
||||
assert.equal(r.body.requestedSize, "5.0 GB");
|
||||
assert.deepEqual(r.body.files, ["Test-Q4_K_M.gguf"]);
|
||||
assert.match(r.body.message, /Do not retry/);
|
||||
first = { modelId: r.body.modelId, jobId: r.body.jobId };
|
||||
|
||||
const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}`, { token: readOnly, params: { id: first.jobId } });
|
||||
assert.equal(job.body.state, "pending_approval");
|
||||
assert.equal(job.body.requestedBy, "hermes");
|
||||
assert.equal(job.body.log, undefined);
|
||||
assert.deepEqual(job.body.files.map((f: { path: string }) => f.path), ["Test-Q4_K_M.gguf"]);
|
||||
|
||||
const model = await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, first.modelId) });
|
||||
assert.equal(model?.requestedBy, "hermes");
|
||||
assert.equal(model?.status, "pending"); // not "downloading" until approved
|
||||
});
|
||||
|
||||
it("is idempotent: the same repo + commit + files returns the existing job", async () => {
|
||||
const r = await request({ repoId: "unsloth/test-gguf", sha: SHA.a, quant: "q4_k_m" });
|
||||
assert.equal(r.status, 200);
|
||||
assert.equal(r.body.created, false);
|
||||
assert.equal(r.body.jobId, first.jobId);
|
||||
const n = await M.db.db().select().from(M.schema.jobs);
|
||||
assert.equal(n.length, 1);
|
||||
});
|
||||
|
||||
it("refuses other files while the model has an open job", async () => {
|
||||
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
|
||||
assert.equal(r.status, 409);
|
||||
assert.match(r.body.error.message, /still pending approval/);
|
||||
});
|
||||
|
||||
it("refuses a different commit of a model in the library", async () => {
|
||||
REPOS["unsloth/Test-GGUF"].sha = SHA.d;
|
||||
try {
|
||||
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.d, quant: "Q4_K_M" });
|
||||
assert.equal(r.status, 409);
|
||||
assert.match(r.body.error.message, /pinned to commit a{40}.*Updating a model is done by the user/);
|
||||
} finally {
|
||||
REPOS["unsloth/Test-GGUF"].sha = SHA.a;
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects over the max agent jobs at once", async () => {
|
||||
const second = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, quant: "Q4_K_M" });
|
||||
assert.equal(second.status, 201);
|
||||
const third = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
|
||||
assert.equal(third.status, 429);
|
||||
assert.equal(third.body.error.code, "too_many_jobs");
|
||||
assert.match(third.body.error.message, /2 pending or running, the limit is 2/);
|
||||
// Reject the second request again; the model it added leaves the library.
|
||||
assert.deepEqual(await M.agent.rejectJob(second.body.jobId), { removedModel: true });
|
||||
assert.equal(await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, second.body.modelId) }), undefined);
|
||||
});
|
||||
|
||||
it("rejects requests over the max size", async () => {
|
||||
await M.settings.saveGuardrails({ maxOpenJobs: 10 });
|
||||
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
|
||||
assert.equal(r.status, 201);
|
||||
await M.agent.rejectJob(r.body.jobId);
|
||||
await M.settings.saveGuardrails({ maxRequestBytes: 2.5 * GB });
|
||||
const big = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
|
||||
assert.equal(big.status, 422);
|
||||
assert.equal(big.body.error.message, "exceeds max size per request 2.5 GB: requested 3.0 GB. Pick a smaller quant or fewer files.");
|
||||
await M.settings.saveGuardrails({ maxRequestBytes: 60 * GB });
|
||||
});
|
||||
|
||||
it("rejects when the minimum free space would not remain (counting reserved bytes)", async () => {
|
||||
await setFree(107 * GB); // 5 GB reserved by the pending first request
|
||||
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
|
||||
assert.equal(r.status, 507);
|
||||
assert.equal(r.body.error.code, "disk_space");
|
||||
assert.match(r.body.error.message, /107\.0 GB free \(5\.0 GB of it reserved by other downloads\), and at least 100\.0 GB must stay free/);
|
||||
const disk = await call(M.disk.GET, "/api/v1/disk", { token: readOnly });
|
||||
assert.equal(disk.body.reservedBytes, 5 * GB);
|
||||
assert.equal(disk.body.availableForRequestsBytes, 2 * GB);
|
||||
await setFree(500 * GB);
|
||||
});
|
||||
|
||||
it("rejects when the worker is offline (free space unknown)", async () => {
|
||||
const { db } = M.db;
|
||||
await db().update(M.schema.workerState).set({ heartbeatAt: new Date(0) });
|
||||
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
|
||||
assert.equal(r.status, 503);
|
||||
assert.equal(r.body.error.code, "disk_unknown");
|
||||
await setFree(500 * GB);
|
||||
});
|
||||
|
||||
it("rejects authors outside the allowlist before asking the Hub", async () => {
|
||||
await M.settings.saveGuardrails({ allowedAuthors: ["unsloth", "ggml-org"] });
|
||||
const r = await request({ repoId: "TheBloke/Old-GGUF", sha: SHA.d, quant: "Q4_K_M" });
|
||||
assert.equal(r.status, 403);
|
||||
assert.equal(r.body.error.code, "author_not_allowed");
|
||||
assert.match(r.body.error.message, /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
|
||||
await M.settings.saveGuardrails({ allowedAuthors: [] });
|
||||
});
|
||||
|
||||
it("approve queues the job; the model then shows as downloading", async () => {
|
||||
await M.agent.approveJob(first.jobId);
|
||||
const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}?log=5`, { token: readOnly, params: { id: first.jobId } });
|
||||
assert.equal(job.body.state, "queued");
|
||||
assert.ok(Array.isArray(job.body.log));
|
||||
await assert.rejects(M.agent.approveJob(first.jobId), /doesn't wait for approval/);
|
||||
});
|
||||
|
||||
it("extra files of a finished model are added; rejecting restores the selection", async () => {
|
||||
const { db } = M.db;
|
||||
await db().update(M.schema.jobs).set({ state: "completed", finishedAt: new Date() }).where((await import("drizzle-orm")).eq(M.schema.jobs.id, first.jobId));
|
||||
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal(r.body.requestedSize, "9.0 GB");
|
||||
const selected = async () =>
|
||||
(await db().query.modelFiles.findMany({ where: (f, { and, eq }) => and(eq(f.modelId, first.modelId), eq(f.selected, true)) })).map((f) => f.path).sort();
|
||||
assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf", "Test-Q8_0.gguf"]);
|
||||
assert.deepEqual(await M.agent.rejectJob(r.body.jobId), { removedModel: false });
|
||||
assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf"]);
|
||||
});
|
||||
|
||||
it("auto approval queues right away", async () => {
|
||||
await M.settings.saveGuardrails({ approvalMode: "auto" });
|
||||
const r = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, include: ["*.gguf"] });
|
||||
assert.equal(r.status, 201);
|
||||
assert.equal(r.body.state, "queued");
|
||||
await M.settings.saveGuardrails({ approvalMode: "approve" });
|
||||
});
|
||||
|
||||
it("lists models with the library filters, including requested_by", async () => {
|
||||
const all = await call(M.models.GET, "/api/v1/models", { token: readOnly });
|
||||
assert.equal(all.body.count, 2);
|
||||
const mine = await call(M.models.GET, "/api/v1/models?requested_by=hermes&quant=Q4_K_M&author=unsloth", { token: readOnly });
|
||||
assert.deepEqual(mine.body.models.map((m: { repoId: string }) => m.repoId).sort(), ["unsloth/Other-GGUF", "unsloth/Test-GGUF"]);
|
||||
assert.equal(mine.body.models[0].requestedBy, "hermes");
|
||||
const none = await call(M.models.GET, "/api/v1/models?requested_by=someone-else", { token: readOnly });
|
||||
assert.equal(none.body.count, 0);
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import "server-only";
|
||||
import { NextResponse } from "next/server";
|
||||
import { z } from "zod";
|
||||
import { GuardrailError } from "@/lib/agent-guardrails";
|
||||
import { SelectionError } from "@/lib/agent-selection";
|
||||
import { TuningError } from "@/lib/agent-tuning";
|
||||
import { BenchmarkError } from "@/lib/benchmarks";
|
||||
import { DeploymentError } from "@/lib/deployments";
|
||||
import { SweepRequestError } from "@/lib/sweeps";
|
||||
import { HubError } from "@/lib/hub/client";
|
||||
import { JobError } from "@/lib/jobs";
|
||||
import { ModelError } from "@/lib/models";
|
||||
import { TagError } from "@/lib/tags";
|
||||
|
||||
// Shared by the /api/v1 routes: compact JSON for an agent to read, errors as
|
||||
// { error: { code, message } } with a message that says what to do next.
|
||||
|
||||
export function v1Json(data: unknown, status = 200) {
|
||||
return NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
export function v1Error(status: number, code: string, message: string) {
|
||||
return v1Json({ error: { code, message } }, status);
|
||||
}
|
||||
|
||||
const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
|
||||
invalid_repo_id: 400,
|
||||
repo_not_found: 404,
|
||||
revision_not_found: 404,
|
||||
gated_no_token: 403,
|
||||
gated_no_access: 403,
|
||||
rate_limited: 429,
|
||||
network: 502,
|
||||
};
|
||||
|
||||
/** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */
|
||||
export function v1Catch(err: unknown) {
|
||||
if (err instanceof GuardrailError || err instanceof TuningError) return v1Error(err.status, err.code, err.message);
|
||||
if (err instanceof DeploymentError || err instanceof BenchmarkError || err instanceof SweepRequestError) return v1Error(err.status, err.code, err.message);
|
||||
if (err instanceof SelectionError) return v1Error(err.status, err.code, err.message);
|
||||
if (err instanceof ModelError || err instanceof JobError || err instanceof TagError) return v1Error(err.status, err.code, err.message);
|
||||
if (err instanceof HubError) return v1Error(HUB_STATUS[err.code] ?? 502, err.code, err.message);
|
||||
if (err instanceof z.ZodError) {
|
||||
return v1Error(400, "invalid_request", err.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; "));
|
||||
}
|
||||
if (err instanceof SyntaxError) return v1Error(400, "invalid_json", "The request body is not valid JSON.");
|
||||
console.error("[api/v1]", err);
|
||||
return v1Error(500, "internal", "Internal error in Kaname. Tell the user; retrying won't help.");
|
||||
}
|
||||
|
||||
/** "74.2 GB" next to byte counts, so a reader doesn't have to convert. */
|
||||
export function size(bytes: number | null | undefined): string | null {
|
||||
return bytes == null ? null : `${(bytes / 1e9).toFixed(1)} GB`;
|
||||
}
|
||||
+75
-187
@@ -1,217 +1,105 @@
|
||||
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";
|
||||
import { endpointRunMeta, endpointSystem, gpuLabel, imageTag, metaNotes, metaRows, modelLabel, pcieLabel, quantFromName } from "./benchmark-meta";
|
||||
import type { EndpointHardware, EndpointSnapshot } from "./db/schema";
|
||||
import { formatLinkPair, parseLinkText, systemSummaryText } 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,
|
||||
const hardware: EndpointHardware = {
|
||||
gpuName: "Intel Arc Pro B65",
|
||||
gpuCount: 2,
|
||||
vramGb: 32,
|
||||
pcie: "Gen5 x16",
|
||||
p2p: "off",
|
||||
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",
|
||||
gpuDriver: "xe (kernel 6.17.1)",
|
||||
cpu: "AMD EPYC 9124 16-Core Processor",
|
||||
memoryGb: 128,
|
||||
os: "Debian GNU/Linux 13 (trixie)",
|
||||
virtualization: "Proxmox VM with GPU passthrough",
|
||||
kvCache: "q8_0",
|
||||
description: "testing q8 KV",
|
||||
};
|
||||
|
||||
const opts: DeploymentOptions = { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 8192, extraArgs: [], cacheTypeK: "q8_0", cacheTypeV: "q8_0", parallel: 2 };
|
||||
const snap = (h: EndpointHardware = hardware, over: Partial<EndpointSnapshot> = {}): EndpointSnapshot => ({
|
||||
type: "endpoint",
|
||||
endpointName: "arc-box llama",
|
||||
model: "Qwen3-8B-Q4_K_M.gguf",
|
||||
engine: "llama.cpp",
|
||||
engineVersion: "b6123",
|
||||
contextSize: 32768,
|
||||
hardware: h,
|
||||
...over,
|
||||
});
|
||||
|
||||
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);
|
||||
describe("PCIe links", () => {
|
||||
it("formats current vs maximum and parses typed links", () => {
|
||||
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.deepEqual(parseLinkText("gen 4 x8"), { gen: 4, width: 8 });
|
||||
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"]);
|
||||
describe("run metadata from an endpoint", () => {
|
||||
it("takes the GPUs, link and model facts from the hardware notes", () => {
|
||||
const m = endpointRunMeta(snap());
|
||||
assert.equal(gpuLabel(m), "2× Intel Arc Pro B65 (32 GiB)");
|
||||
assert.equal(pcieLabel(m), "Gen5 x16");
|
||||
assert.equal(m.p2p, "off");
|
||||
assert.equal(m.rebar, true);
|
||||
assert.equal(m.runtime.engineName, "llama.cpp");
|
||||
assert.equal(m.runtime.engineVersion, "b6123");
|
||||
assert.equal(modelLabel(m), "Qwen3-8B-Q4_K_M.gguf Q4_K_M with q8_0 KV cache");
|
||||
assert.equal(m.contextSize, 32768);
|
||||
assert.equal(endpointRunMeta(snap(hardware, { slots: 4 })).concurrency, 4, "slots the server reported");
|
||||
assert.equal(endpointRunMeta(snap({ ...hardware, concurrency: 2 }, { slots: 4 })).concurrency, 2, "the notes win");
|
||||
});
|
||||
|
||||
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("lets the notes override what the server reported, and leaves out what nobody knows", () => {
|
||||
const m = endpointRunMeta(snap({ engineName: "ik_llama.cpp", engineVersion: "4012", contextSize: 16384, quant: "IQ4_XS" }, { engine: null, engineVersion: null }));
|
||||
assert.equal(m.runtime.engineName, "ik_llama.cpp");
|
||||
assert.equal(m.runtime.engineVersion, "4012");
|
||||
assert.equal(m.model.quant, "IQ4_XS");
|
||||
assert.equal(m.contextSize, 16384);
|
||||
assert.equal(gpuLabel(m), null, "no GPU in the notes");
|
||||
const keys = metaRows(m).map((r) => r.key);
|
||||
assert.ok(!keys.includes("image") && !keys.includes("digest") && !keys.includes("pcie"));
|
||||
});
|
||||
|
||||
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/);
|
||||
it("finds the quant in model names", () => {
|
||||
assert.equal(quantFromName("Qwen3-8B-Q4_K_M.gguf"), "Q4_K_M");
|
||||
assert.equal(quantFromName("unsloth/Qwen3-8B-GGUF:UD-IQ3_XXS"), "UD-IQ3_XXS");
|
||||
assert.equal(quantFromName("GLM-4.6-Q8_0-00001-of-00008.gguf"), "Q8_0");
|
||||
assert.equal(quantFromName("Qwen/Qwen3.8-27B-FP8"), "FP8");
|
||||
assert.equal(quantFromName("qwen3:8b"), null);
|
||||
assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
|
||||
});
|
||||
});
|
||||
|
||||
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("lists the facts from the notes", () => {
|
||||
const text = systemSummaryText(endpointSystem(hardware, "0.15.0"));
|
||||
assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor/);
|
||||
assert.match(text, /RAM: 128/);
|
||||
assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\)/);
|
||||
assert.match(text, /GPU driver: xe \(kernel 6\.17\.1\)/);
|
||||
assert.match(text, /Virtualization: VM \(Proxmox VM with GPU passthrough\)/);
|
||||
assert.match(text, /Kaname 0\.15\.0/);
|
||||
assert.match(systemSummaryText(endpointSystem({ virtualization: "bare metal" }, "x")), /Virtualization: bare metal/);
|
||||
});
|
||||
|
||||
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")]);
|
||||
it("never contains the endpoint's address, the hostname, user or paths", () => {
|
||||
const s = endpointSystem(hardware, "0.15.0");
|
||||
const notes = metaNotes(endpointRunMeta(snap()), s, hardware.description ?? null);
|
||||
const published = JSON.stringify([s, notes]);
|
||||
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/);
|
||||
assert.doesNotMatch(published, /https?:\/\//);
|
||||
assert.equal(notes.description, "testing q8 KV");
|
||||
assert.equal(notes.gpus, "2× Intel Arc Pro B65 (32 GiB)");
|
||||
assert.equal(notes.pcie_max, "Gen5 x16");
|
||||
// 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);
|
||||
});
|
||||
});
|
||||
+61
-88
@@ -1,9 +1,9 @@
|
||||
// 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.
|
||||
// What a benchmark run records about its setup (RunMeta, SystemSummary) and the BetterBench notes
|
||||
// made from it. Kaname can't see the machine behind an endpoint, so both come from the endpoint's
|
||||
// hardware notes plus what the server reports. 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";
|
||||
import type { EndpointEngine, EndpointHardware, EndpointSnapshot, RunMeta, SystemSummary } from "@/lib/db/schema";
|
||||
import { formatLink, formatLinkPair, onOff, parseLinkText, systemSummaryText } from "@/lib/hardware";
|
||||
|
||||
/** "ghcr.io/org/img:tag@sha256:…" → "tag" (null: no tag, i.e. "latest" or digest only). */
|
||||
export function imageTag(ref: string): string | null {
|
||||
@@ -13,82 +13,69 @@ export function imageTag(ref: string): string | null {
|
||||
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);
|
||||
const NAME_QUANT = /[-_.:]((?:UD-)?(?:I?Q\d(?:_[A-Z0-9]+)*|BF16|F16|F32|MXFP4(?:_MOE)?|TQ\d_\d))$/i;
|
||||
|
||||
/** The quant named in a model name: a GGUF quant tag ("Q4_K_M", "IQ3_XXS") or FP8, AWQ, … */
|
||||
export function quantFromName(name: string): string | null {
|
||||
const base = name.trim().replace(/\.gguf$/i, "").replace(/-\d{5}-of-\d{5}$/, "");
|
||||
const gguf = base.match(NAME_QUANT);
|
||||
if (gguf) return gguf[1];
|
||||
const m = base.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}`;
|
||||
}
|
||||
export const ENGINE_LABEL: Record<EndpointEngine, string> = { "llama.cpp": "llama.cpp", vllm: "vLLM", sglang: "SGLang", ollama: "Ollama", other: "OpenAI-compatible server" };
|
||||
|
||||
/** 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";
|
||||
/** The run's setup from the endpoint snapshot: the hardware notes win over what the server reported. */
|
||||
export function endpointRunMeta(s: EndpointSnapshot): RunMeta {
|
||||
const h = s.hardware;
|
||||
const count = h.gpuName?.trim() ? Math.max(1, h.gpuCount ?? 1) : 0;
|
||||
const link = h.pcie ? parseLinkText(h.pcie) : null;
|
||||
const engine = s.engine ?? "other";
|
||||
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,
|
||||
gpus: Array.from({ length: count }, () => ({
|
||||
name: h.gpuName!.trim(),
|
||||
vramMb: h.vramGb ? Math.round(h.vramGb * 1024) : null,
|
||||
linkCurrent: link,
|
||||
linkMax: link,
|
||||
rebar: h.rebar ?? null,
|
||||
})),
|
||||
// Typed in by the user, not sampled at idle.
|
||||
linkUnderLoad: true,
|
||||
p2p: count < 2 ? "n/a" : (h.p2p ?? null),
|
||||
rebar: count ? (h.rebar ?? null) : 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,
|
||||
image: h.image?.trim() ?? "",
|
||||
tag: h.image?.trim() ? imageTag(h.image.trim()) : null,
|
||||
digest: null,
|
||||
engine,
|
||||
engineName: h.engineName?.trim() || ENGINE_LABEL[engine],
|
||||
engineVersion: h.engineVersion?.trim() || s.engineVersion,
|
||||
},
|
||||
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 ?? [],
|
||||
model: { repoId: s.model, file: null, quant: h.quant?.trim() || quantFromName(s.model), kvCache: h.kvCache?.trim() || null },
|
||||
contextSize: h.contextSize ?? s.contextSize,
|
||||
concurrency: h.concurrency ?? s.slots ?? null,
|
||||
overridden: [],
|
||||
};
|
||||
}
|
||||
|
||||
/** The publishable system summary from the notes: CPU, RAM, OS, driver, virtualization, Kaname. */
|
||||
export function endpointSystem(h: EndpointHardware, kaname: string): SystemSummary {
|
||||
const virt = h.virtualization?.trim() || null;
|
||||
const bare = !!virt && /bare[\s-]*metal/i.test(virt);
|
||||
return {
|
||||
cpu: { model: h.cpu?.trim() || null, cores: null, threads: null },
|
||||
// GB as entered (formatBytes shows decimal units too).
|
||||
memoryBytes: h.memoryGb ? Math.round(h.memoryGb * 1e9) : null,
|
||||
storage: null,
|
||||
os: h.os?.trim() || null,
|
||||
kernel: null,
|
||||
gpuDrivers: h.gpuDriver?.trim() ? [h.gpuDriver.trim()] : [],
|
||||
virtualization: { vm: virt ? !bare : null, hypervisor: virt && !bare ? virt : null, gpuPassthrough: null },
|
||||
kaname,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -117,19 +104,6 @@ export function pcieMaxLabel(m: RunMeta): string | null {
|
||||
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" */
|
||||
@@ -146,8 +120,8 @@ export function metaRows(m: RunMeta): { key: string; label: string; value: strin
|
||||
...(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" },
|
||||
...(m.runtime.image ? [{ key: "image", label: "Image", value: m.runtime.image }] : []),
|
||||
...(m.runtime.digest ? [{ key: "digest", label: "Digest", value: m.runtime.digest }] : []),
|
||||
{ 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" },
|
||||
@@ -161,7 +135,7 @@ export function metaRows(m: RunMeta): { key: string; label: string; value: strin
|
||||
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.image ? { 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 } : {}),
|
||||
@@ -170,7 +144,6 @@ export function metaNotes(m: RunMeta, system: SystemSummary | null, description:
|
||||
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);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { describeHardware, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled } from "./benchmark-report";
|
||||
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
|
||||
import type { BenchmarkSummary, DeploymentSnapshot, EndpointSnapshot } from "./db/schema";
|
||||
|
||||
const snap = {
|
||||
deploymentName: "bench test",
|
||||
@@ -15,7 +15,7 @@ const snap = {
|
||||
memoryMb: 2640,
|
||||
command: "",
|
||||
host: { cpuModel: "AMD Ryzen 7 9850X3D 8-Core Processor", threads: 16, memoryBytes: 32e9, os: null },
|
||||
} as BenchmarkSnapshot;
|
||||
} as DeploymentSnapshot;
|
||||
|
||||
const summary: BenchmarkSummary = {
|
||||
v: 2,
|
||||
@@ -50,7 +50,25 @@ const summary: BenchmarkSummary = {
|
||||
|
||||
const run = { label: null, snapshot: snap, settings: { quick: true, passes: null, warmup: null, phases: [] }, summary };
|
||||
|
||||
const endpointSnap: EndpointSnapshot = {
|
||||
type: "endpoint",
|
||||
endpointName: "arc box",
|
||||
model: "Qwen3-8B-Q4_K_M.gguf",
|
||||
engine: "llama.cpp",
|
||||
engineVersion: "b6123",
|
||||
contextSize: 32768,
|
||||
hardware: { gpuName: "Intel Arc Pro B65", gpuCount: 2 },
|
||||
};
|
||||
|
||||
describe("benchmark report (launch80 conventions)", () => {
|
||||
it("describes an endpoint run from its hardware notes, without the endpoint's name", () => {
|
||||
assert.equal(describeHardware(endpointSnap), "2× Intel Arc Pro B65");
|
||||
assert.equal(describeHardware({ ...endpointSnap, hardware: { cpu: "AMD EPYC 7282 16-Core Processor" } }), "an AMD EPYC 7282");
|
||||
const s = reportSummary({ ...run, snapshot: endpointSnap });
|
||||
assert.match(s, /Qwen3-8B-Q4_K_M\.gguf \(Q4_K_M, 32,768-token context\) on llama\.cpp b6123, 2× Intel Arc Pro B65/);
|
||||
assert.doesNotMatch(s, /arc box/);
|
||||
});
|
||||
|
||||
it("describes hardware, subtitle and summary", () => {
|
||||
assert.equal(describeHardware(snap), "4 CPU cores of an AMD Ryzen 7 9850X3D");
|
||||
assert.equal(describeHardware({ ...snap, gpuNames: ["NVIDIA GeForce RTX 3080", "NVIDIA GeForce RTX 3080"] }), "2× NVIDIA GeForce RTX 3080");
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
// say so first, under-sampled percentiles are flagged, truncated and batched runs are called out,
|
||||
// and no endpoint or host name appears. Pure, for tests.
|
||||
|
||||
import { quantFromName } from "@/lib/benchmark-meta";
|
||||
import { engineName, isEndpointSnapshot, modelName } from "@/lib/benchmark-view";
|
||||
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
@@ -23,21 +25,31 @@ export function isBatched(sum: BenchmarkSummary | null): boolean {
|
||||
return !!sum?.single.some((r) => r.batched);
|
||||
}
|
||||
|
||||
/** "RTX 3080" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
|
||||
const shortCpu = (cpu: string | null | undefined) =>
|
||||
cpu
|
||||
?.replace(/\s+\d+-Core Processor$/i, "")
|
||||
.replace(/\(R\)|\(TM\)/g, "")
|
||||
.trim();
|
||||
|
||||
/** "RTX 3080" / "2× Arc Pro B65" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
|
||||
export function describeHardware(s: BenchmarkSnapshot): string {
|
||||
if (isEndpointSnapshot(s)) {
|
||||
const h = s.hardware;
|
||||
if (h.gpuName?.trim()) return (h.gpuCount ?? 1) > 1 ? `${h.gpuCount}× ${h.gpuName.trim()}` : h.gpuName.trim();
|
||||
const cpu = shortCpu(h.cpu);
|
||||
return cpu ? `an ${cpu}` : "unknown hardware";
|
||||
}
|
||||
if (s.gpuNames?.length) {
|
||||
const names = [...new Set(s.gpuNames)];
|
||||
return s.gpuNames.length > 1 && names.length === 1 ? `${s.gpuNames.length}× ${names[0]}` : names.join(" + ");
|
||||
}
|
||||
const cpu = s.host?.cpuModel
|
||||
?.replace(/\s+\d+-Core Processor$/i, "")
|
||||
.replace(/\(R\)|\(TM\)/g, "")
|
||||
.trim();
|
||||
const cpu = shortCpu(s.host?.cpuModel);
|
||||
if (s.cpus) return `${s.cpus} CPU core${s.cpus === 1 ? "" : "s"}${cpu ? ` of an ${cpu}` : ""}`;
|
||||
return cpu ? `an ${cpu}${s.host?.threads ? ` (${s.host.threads} threads)` : ""}` : "CPU";
|
||||
}
|
||||
|
||||
export function weightsLabel(s: BenchmarkSnapshot): string {
|
||||
if (isEndpointSnapshot(s)) return s.hardware.quant?.trim() || quantFromName(s.model) || "weights not stated";
|
||||
return s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors";
|
||||
}
|
||||
|
||||
@@ -53,13 +65,19 @@ export function reportSubtitle(run: Run): string {
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
/** The context window the run had (endpoint notes, the server's report, or the launch options). */
|
||||
export function contextOf(s: BenchmarkSnapshot): number | null {
|
||||
return isEndpointSnapshot(s) ? (s.hardware.contextSize ?? s.contextSize) : s.options.contextSize;
|
||||
}
|
||||
|
||||
export function reportSummary(run: Run): string {
|
||||
const s = run.snapshot;
|
||||
const ctx = contextOf(s);
|
||||
const sum = run.summary;
|
||||
const out: string[] = [];
|
||||
if (isQuick(sum)) out.push("Quick smoke run, not a publishable measurement.");
|
||||
out.push(
|
||||
`${s.repoId} (${weightsLabel(s)}, ${int(s.options.contextSize)}-token context) on ${s.runtimeName}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
|
||||
`${modelName(s)} (${weightsLabel(s)}${ctx ? `, ${int(ctx)}-token context` : ""}) on ${engineName(s)}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
|
||||
sum?.single.length ? `: ${sum.passes} measured passes per category over ${sum.single.length} categories` : ""
|
||||
}.`.replace(" ,", ","),
|
||||
);
|
||||
@@ -158,7 +176,7 @@ export function reportCaveats(run: Run): string[] {
|
||||
const concFail = sum.concurrency.filter((c) => c.ok < c.requests).map((c) => `level ${c.level}: ${c.ok}/${c.requests} ok`);
|
||||
if (concFail.length) out.push(`Concurrency requests failed at ${concFail.join("; ")}. Aggregate throughput counts only completed requests.`);
|
||||
const skipped = sum.prefill.filter((p) => p.skipped).map((p) => int(p.target_depth));
|
||||
if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context of ${int(sum.maxModelLen ?? run.snapshot.options.contextSize)}).`);
|
||||
if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context${(sum.maxModelLen ?? contextOf(run.snapshot)) ? ` of ${int((sum.maxModelLen ?? contextOf(run.snapshot))!)}` : ""}).`);
|
||||
if (sum.cacheHits > 0) out.push(`${sum.cacheHits} request(s) were partly served from the server's prefix cache although the run asked for a cold cache; those prefill figures may be cache lookups.`);
|
||||
return out.slice(0, 8);
|
||||
}
|
||||
|
||||
@@ -1,167 +0,0 @@
|
||||
// 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");
|
||||
});
|
||||
});
|
||||
@@ -1,103 +1,40 @@
|
||||
// What a benchmark run records about the deployment it measures. Shared by the web app and the worker
|
||||
// (sweeps create runs there), so no "server-only" here.
|
||||
// What a benchmark run records about the endpoint it measures. Shared by the web app (when a run is
|
||||
// queued) and the worker (refreshed when it starts), so no "server-only" here.
|
||||
|
||||
import { and, eq, isNull } from "drizzle-orm";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
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) {
|
||||
const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
|
||||
const h = ws?.docker;
|
||||
const gpus = h?.gpus ?? [];
|
||||
return {
|
||||
gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [],
|
||||
host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null },
|
||||
};
|
||||
}
|
||||
|
||||
/** The deployment as it is now; null when it doesn't exist (or is being deleted). */
|
||||
export async function deploymentSnapshot(deploymentId: string): Promise<{ id: string; modelId: string; state: string; snapshot: BenchmarkSnapshot } | null> {
|
||||
const [d] = await db()
|
||||
.select({
|
||||
id: deployments.id,
|
||||
name: deployments.name,
|
||||
state: deployments.state,
|
||||
options: deployments.options,
|
||||
cpus: deployments.cpus,
|
||||
memoryMb: deployments.memoryMb,
|
||||
command: deployments.command,
|
||||
imageId: deployments.imageId,
|
||||
modelId: deployments.modelId,
|
||||
repoId: models.repoId,
|
||||
runtimeName: runtimes.name,
|
||||
engine: runtimes.engine,
|
||||
accelerator: runtimes.accelerator,
|
||||
image: runtimes.image,
|
||||
})
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.innerJoin(models, eq(models.id, deployments.modelId))
|
||||
.where(and(eq(deployments.id, deploymentId), isNull(deployments.deleteRequestedAt)));
|
||||
if (!d) return null;
|
||||
return {
|
||||
id: d.id,
|
||||
modelId: d.modelId,
|
||||
state: d.state,
|
||||
snapshot: {
|
||||
deploymentName: d.name,
|
||||
repoId: d.repoId,
|
||||
runtimeName: d.runtimeName,
|
||||
engine: d.engine,
|
||||
accelerator: d.accelerator,
|
||||
...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")),
|
||||
image: d.image,
|
||||
imageId: d.imageId,
|
||||
options: d.options,
|
||||
cpus: d.cpus,
|
||||
memoryMb: d.memoryMb,
|
||||
command: [d.image, ...(d.command ?? [])].join(" "),
|
||||
},
|
||||
};
|
||||
}
|
||||
import { type EndpointProbe, type EndpointSnapshot, endpoints, models } from "@/lib/db/schema";
|
||||
import { pickModel } from "@/lib/endpoint-probe";
|
||||
|
||||
/** 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 };
|
||||
/** The endpoint's snapshot for a run of `model`, with what the server last reported. */
|
||||
export function snapshotOf(e: typeof endpoints.$inferSelect, model: string, probe: EndpointProbe | null): EndpointSnapshot {
|
||||
return {
|
||||
type: "endpoint",
|
||||
endpointName: e.name,
|
||||
model,
|
||||
engine: e.engine ?? probe?.engine ?? null,
|
||||
engineVersion: probe?.engineVersion ?? null,
|
||||
contextSize: probe?.contextSize ?? null,
|
||||
slots: probe?.slots ?? null,
|
||||
hardware: e.hardware,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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()) };
|
||||
/** The model to run: the one asked for, the endpoint's, or the only one the server lists. */
|
||||
export function modelFor(e: typeof endpoints.$inferSelect, probe: EndpointProbe, requested?: string | null) {
|
||||
return pickModel(requested?.trim() || e.model, probe);
|
||||
}
|
||||
|
||||
/**
|
||||
* A downloaded model the server serves, by name: vLLM serves the repo id ("Qwen/Qwen3-8B"),
|
||||
* llama.cpp's -hf alias is "<repo>:<quant>". GGUF file names are matched in M4.
|
||||
*/
|
||||
export async function libraryModelId(name: string): Promise<string | null> {
|
||||
const repo = name.trim().split(":")[0].toLowerCase();
|
||||
if (!repo.includes("/")) return null;
|
||||
const row = await db().query.models.findFirst({ columns: { id: true }, where: eq(sql`lower(${models.repoId})`, repo) });
|
||||
return row?.id ?? null;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { configChips, deltaPct, describeSettings, headline } from "./benchmark-view";
|
||||
import { configChips, deltaPct, describeSettings, engineName, headline, modelName, targetName } from "./benchmark-view";
|
||||
import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
|
||||
|
||||
const summary: BenchmarkSummary = {
|
||||
@@ -36,7 +36,24 @@ describe("benchmark view", () => {
|
||||
cpus: 8,
|
||||
memoryMb: null,
|
||||
} as unknown as BenchmarkSnapshot;
|
||||
assert.deepEqual(configChips(snap), ["Q4_K_M", "context 4096", "threads 8", "kv cache k / v q8_0 / f16", "cpu limit 8 cores"]);
|
||||
assert.deepEqual(configChips(snap), ["context 4096", "kv cache q8_0 / f16", "Q4_K_M", "threads 8", "cpu limit 8 cores"]);
|
||||
});
|
||||
|
||||
it("lists an endpoint's notes as chips, and names it, its model and engine", () => {
|
||||
const snap: BenchmarkSnapshot = {
|
||||
type: "endpoint",
|
||||
endpointName: "arc box",
|
||||
model: "Qwen3-8B-Q4_K_M.gguf",
|
||||
engine: "vllm",
|
||||
engineVersion: "0.31.0",
|
||||
contextSize: 32768,
|
||||
hardware: { gpuName: "Intel Arc Pro B65", gpuCount: 2, kvCache: "fp8", concurrency: 4 },
|
||||
};
|
||||
assert.deepEqual(configChips(snap), ["2× Intel Arc Pro B65", "Q4_K_M", "context 32768", "parallel slots 4", "kv cache fp8"]);
|
||||
assert.equal(targetName(snap), "arc box");
|
||||
assert.equal(modelName(snap), "Qwen3-8B-Q4_K_M.gguf");
|
||||
assert.equal(engineName(snap), "vLLM 0.31.0");
|
||||
assert.equal(engineName({ ...snap, hardware: { engineName: "vllm-radiance" } }), "vllm-radiance 0.31.0");
|
||||
});
|
||||
|
||||
it("describes settings and deltas", () => {
|
||||
|
||||
+47
-28
@@ -1,6 +1,7 @@
|
||||
// Display helpers for benchmark runs. Pure; shared by list, detail and compare pages.
|
||||
|
||||
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
|
||||
import { ENGINE_LABEL, quantFromName } from "@/lib/benchmark-meta";
|
||||
import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary, DeploymentSnapshot, EndpointSnapshot } from "@/lib/db/schema";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
export type Headline = {
|
||||
@@ -25,37 +26,55 @@ export function headline(s: BenchmarkSummary | null): Headline {
|
||||
};
|
||||
}
|
||||
|
||||
export const isEndpointSnapshot = (s: BenchmarkSnapshot): s is EndpointSnapshot => s.type === "endpoint";
|
||||
|
||||
/** What was measured: the endpoint's name (or, before 0.15, the deployment's). */
|
||||
export const targetName = (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? s.endpointName : s.deploymentName);
|
||||
/** The model name requested (before 0.15: the repo). */
|
||||
export const modelName = (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? s.model : s.repoId);
|
||||
/** "llama.cpp b6123", "vLLM 0.31.0", or the runtime's name before 0.15. */
|
||||
export function engineName(s: BenchmarkSnapshot): string {
|
||||
if (!isEndpointSnapshot(s)) return s.runtimeName;
|
||||
const h = s.hardware;
|
||||
const name = h.engineName?.trim() || (s.engine ? ENGINE_LABEL[s.engine] : "server");
|
||||
const version = h.engineVersion?.trim() || s.engineVersion;
|
||||
return version ? `${name} ${version}` : name;
|
||||
}
|
||||
|
||||
export type ConfigRow = { key: string; label: string; value: (s: BenchmarkSnapshot) => string | null };
|
||||
|
||||
const n = (v: number | null | undefined, unit = "") => (v != null ? `${v}${unit}` : null);
|
||||
const ep = (f: (s: EndpointSnapshot) => string | null) => (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? f(s) : null);
|
||||
const dep = (f: (s: DeploymentSnapshot) => string | null) => (s: BenchmarkSnapshot) => (isEndpointSnapshot(s) ? null : f(s));
|
||||
|
||||
/** Launch settings worth comparing between runs, in display order. */
|
||||
/** Settings worth comparing between runs, in display order (endpoint notes, then pre-0.15 launch options). */
|
||||
export const CONFIG_ROWS: ConfigRow[] = [
|
||||
{ key: "runtime", label: "Runtime", value: (s) => s.runtimeName },
|
||||
{ key: "image", label: "Image", value: (s) => s.image },
|
||||
{ key: "accel", label: "Runs on", value: (s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null) },
|
||||
{ key: "gpus", label: "GPUs", value: (s) => (s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
|
||||
{ key: "ngl", label: "GPU layers", value: (s) => s.options.gpuLayers ?? null },
|
||||
{ key: "sm", label: "Split mode", value: (s) => s.options.splitMode ?? null },
|
||||
{ key: "ts", label: "Tensor split", value: (s) => s.options.tensorSplit ?? null },
|
||||
{ key: "moe", label: "MoE experts in RAM", value: (s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null) },
|
||||
{ key: "tp", label: "Tensor parallel", value: (s) => n(s.options.tensorParallel) },
|
||||
{ key: "gmu", label: "GPU memory share", value: (s) => n(s.options.gpuMemoryUtilization) },
|
||||
{ key: "cram", label: "Prompt cache (MiB)", value: (s) => n(s.options.cacheRamMb) },
|
||||
{ key: "file", label: "Weights", value: (s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors") },
|
||||
{ key: "ctx", label: "Context", value: (s) => n(s.options.contextSize) },
|
||||
{ key: "threads", label: "Threads", value: (s) => n(s.options.threads) },
|
||||
{ key: "parallel", label: "Parallel slots", value: (s) => n(s.options.parallel) },
|
||||
{ key: "batch", label: "Batch / micro-batch", value: (s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null) },
|
||||
{ key: "kv", label: "KV cache K / V", value: (s) => (s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
|
||||
{ key: "fa", label: "Flash attention", value: (s) => s.options.flashAttn ?? null },
|
||||
{ key: "draft", label: "Speculative", value: (s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null) },
|
||||
{ key: "dtype", label: "Data type", value: (s) => s.options.dtype ?? null },
|
||||
{ key: "seqs", label: "Max sequences", value: (s) => n(s.options.maxNumSeqs) },
|
||||
{ key: "kvgb", label: "KV cache (GiB)", value: (s) => n(s.options.kvCacheGb) },
|
||||
{ key: "cpus", label: "CPU limit", value: (s) => n(s.cpus, " cores") },
|
||||
{ key: "mem", label: "Memory limit", value: (s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null) },
|
||||
{ key: "args", label: "Extra arguments", value: (s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null) },
|
||||
{ key: "runtime", label: "Engine", value: (s) => engineName(s) },
|
||||
{ key: "image", label: "Image", value: (s) => (isEndpointSnapshot(s) ? s.hardware.image?.trim() || null : s.image) },
|
||||
{ key: "gpus", label: "GPUs", value: (s) => (isEndpointSnapshot(s) ? (s.hardware.gpuName ? `${s.hardware.gpuCount ?? 1}× ${s.hardware.gpuName}` : null) : s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
|
||||
{ key: "quant", label: "Quant", value: ep((s) => s.hardware.quant?.trim() || quantFromName(s.model)) },
|
||||
{ key: "ctx", label: "Context", value: (s) => (isEndpointSnapshot(s) ? n(s.hardware.contextSize ?? s.contextSize) : n(s.options.contextSize)) },
|
||||
{ key: "concurrency", label: "Parallel slots", value: (s) => (isEndpointSnapshot(s) ? n(s.hardware.concurrency ?? s.slots) : n(s.options.parallel)) },
|
||||
{ key: "kv", label: "KV cache", value: (s) => (isEndpointSnapshot(s) ? s.hardware.kvCache?.trim() || null : s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
|
||||
{ key: "accel", label: "Runs on", value: dep((s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null)) },
|
||||
{ key: "ngl", label: "GPU layers", value: dep((s) => s.options.gpuLayers ?? null) },
|
||||
{ key: "sm", label: "Split mode", value: dep((s) => s.options.splitMode ?? null) },
|
||||
{ key: "ts", label: "Tensor split", value: dep((s) => s.options.tensorSplit ?? null) },
|
||||
{ key: "moe", label: "MoE experts in RAM", value: dep((s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null)) },
|
||||
{ key: "tp", label: "Tensor parallel", value: dep((s) => n(s.options.tensorParallel)) },
|
||||
{ key: "gmu", label: "GPU memory share", value: dep((s) => n(s.options.gpuMemoryUtilization)) },
|
||||
{ key: "cram", label: "Prompt cache (MiB)", value: dep((s) => n(s.options.cacheRamMb)) },
|
||||
{ key: "file", label: "Weights", value: dep((s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors")) },
|
||||
{ key: "threads", label: "Threads", value: dep((s) => n(s.options.threads)) },
|
||||
{ key: "batch", label: "Batch / micro-batch", value: dep((s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null)) },
|
||||
{ key: "fa", label: "Flash attention", value: dep((s) => s.options.flashAttn ?? null) },
|
||||
{ key: "draft", label: "Speculative", value: dep((s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null)) },
|
||||
{ key: "dtype", label: "Data type", value: dep((s) => s.options.dtype ?? null) },
|
||||
{ key: "seqs", label: "Max sequences", value: dep((s) => n(s.options.maxNumSeqs)) },
|
||||
{ key: "kvgb", label: "KV cache (GiB)", value: dep((s) => n(s.options.kvCacheGb)) },
|
||||
{ key: "cpus", label: "CPU limit", value: dep((s) => n(s.cpus, " cores")) },
|
||||
{ key: "mem", label: "Memory limit", value: dep((s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null)) },
|
||||
{ key: "args", label: "Extra arguments", value: dep((s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null)) },
|
||||
];
|
||||
|
||||
/** Short chips for a list row: the settings that are set. */
|
||||
@@ -64,7 +83,7 @@ export function configChips(s: BenchmarkSnapshot): string[] {
|
||||
return CONFIG_ROWS.filter((r) => !skip.has(r.key))
|
||||
.map((r) => {
|
||||
const v = r.value(s);
|
||||
return v == null ? null : r.key === "file" ? v : `${r.label.toLowerCase()} ${v}`;
|
||||
return v == null ? null : r.key === "file" || r.key === "quant" || r.key === "gpus" ? v : `${r.label.toLowerCase()} ${v}`;
|
||||
})
|
||||
.filter((v): v is string => v != null);
|
||||
}
|
||||
|
||||
+40
-74
@@ -3,9 +3,10 @@ import { rm } from "node:fs/promises";
|
||||
import { and, asc, desc, eq, gt, inArray, or } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { runDir } from "@/lib/benchmark-paths";
|
||||
import { deploymentSnapshot } from "@/lib/benchmark-snapshot";
|
||||
import { libraryModelId, modelFor, snapshotOf } from "@/lib/benchmark-snapshot";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, QUALITY_SECTIONS } from "@/lib/db/schema";
|
||||
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, endpoints, QUALITY_SECTIONS } from "@/lib/db/schema";
|
||||
import { probeEndpoint } from "@/lib/endpoint-probe";
|
||||
|
||||
export class BenchmarkError extends Error {
|
||||
constructor(
|
||||
@@ -20,7 +21,9 @@ export class BenchmarkError extends Error {
|
||||
export const DESCRIPTION_MAX = 4000;
|
||||
|
||||
export const BenchmarkBody = z.object({
|
||||
deploymentId: z.string().min(1),
|
||||
endpointId: z.string().min(1),
|
||||
/** The model to request; default: the endpoint's (or the only one it serves). */
|
||||
model: z.string().trim().max(300).nullable().optional(),
|
||||
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(),
|
||||
@@ -29,53 +32,50 @@ export const BenchmarkBody = z.object({
|
||||
warmup: z.number().int().min(0).max(50).nullable().optional(),
|
||||
/** Empty: all phases. */
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
/** A/B: the second deployment (B), the target minimum detectable effect in % and the pair ceiling. */
|
||||
deploymentBId: z.string().min(1).nullable().optional(),
|
||||
/** A/B: the second endpoint (B), the target minimum detectable effect in % and the pair ceiling. */
|
||||
endpointBId: z.string().min(1).nullable().optional(),
|
||||
mdePct: z.number().min(0.1).max(50).nullable().optional(),
|
||||
maxPairs: z.number().int().min(12).max(2000).nullable().optional(),
|
||||
/** Set by sweeps. */
|
||||
sweepId: z.string().nullable().optional(),
|
||||
/** "eval": the quality eval instead of BetterBench (default: run, or ab with deploymentBId). */
|
||||
/** "eval": the quality eval instead of BetterBench (default: run, or ab with endpointBId). */
|
||||
kind: z.enum(["run", "ab", "eval"]).optional(),
|
||||
/** eval: which sections (empty: all). */
|
||||
evalSections: z.array(z.enum(QUALITY_SECTIONS)).max(3).optional(),
|
||||
});
|
||||
export type BenchmarkInput = z.infer<typeof BenchmarkBody>;
|
||||
|
||||
/** A running deployment as it is now: what a run measures and records. */
|
||||
async function snapshotOf(deploymentId: string, role: string) {
|
||||
const d = await deploymentSnapshot(deploymentId);
|
||||
if (!d) throw new BenchmarkError("not_found", `${role} not found.`, 404);
|
||||
if (d.state !== "running") throw new BenchmarkError("invalid", `Start ${role.toLowerCase()} first; benchmarks run against a running server.`, 409);
|
||||
return d;
|
||||
/** The endpoint, asked right now: a run against a server that doesn't answer fails at once. */
|
||||
async function endpointFor(id: string, role: string) {
|
||||
const e = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) });
|
||||
if (!e) throw new BenchmarkError("not_found", `${role} not found.`, 404);
|
||||
const probe = await probeEndpoint({ baseUrl: e.baseUrl, apiKey: e.apiKey, engine: e.engine });
|
||||
await db().update(endpoints).set({ probe }).where(eq(endpoints.id, e.id));
|
||||
if (!probe.ok) throw new BenchmarkError("invalid", `${role} (${e.name}): ${probe.error}`, 409);
|
||||
return { e, probe };
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a run against a running deployment, or a paired A/B between two running deployments of the
|
||||
* same model (BetterBench sends one model name to both). The worker runs one benchmark at a time.
|
||||
* Queue a run against an endpoint, or a paired A/B between two endpoints serving the same model
|
||||
* (BetterBench sends one model name to both). The worker runs one benchmark at a time.
|
||||
*/
|
||||
/** Requested through the API: who asked, whether it waits for approval, and its time limit. */
|
||||
export type AgentRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number };
|
||||
|
||||
export async function createBenchmark(input: BenchmarkInput, agent?: AgentRequest) {
|
||||
const kind = input.kind ?? (input.deploymentBId ? "ab" : "run");
|
||||
export async function createBenchmark(input: BenchmarkInput) {
|
||||
const kind = input.kind ?? (input.endpointBId ? "ab" : "run");
|
||||
const ab = kind === "ab";
|
||||
if (ab && !input.deploymentBId) throw new BenchmarkError("invalid", "An A/B needs a second deployment.", 400);
|
||||
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
|
||||
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
|
||||
if (b) {
|
||||
if (b.id === a.id) throw new BenchmarkError("invalid", "Pick two different deployments for an A/B.", 400);
|
||||
if (b.snapshot.repoId !== a.snapshot.repoId) {
|
||||
throw new BenchmarkError("invalid", "An A/B compares two deployments of the same model (BetterBench requests one model name from both).", 400);
|
||||
}
|
||||
if (ab && !input.endpointBId) throw new BenchmarkError("invalid", "An A/B needs a second endpoint.", 400);
|
||||
if (ab && input.endpointBId === input.endpointId) throw new BenchmarkError("invalid", "Pick two different endpoints for an A/B.", 400);
|
||||
const a = await endpointFor(input.endpointId, ab ? "Endpoint A" : "The endpoint");
|
||||
const picked = modelFor(a.e, a.probe, input.model);
|
||||
if ("error" in picked) throw new BenchmarkError("invalid", picked.error, 400);
|
||||
const b = ab ? await endpointFor(input.endpointBId!, "Endpoint B") : null;
|
||||
if (b && b.probe.models.length && !b.probe.models.includes(picked.model)) {
|
||||
throw new BenchmarkError("invalid", `Endpoint B doesn't serve "${picked.model}". An A/B sends the same model name to both servers.`, 400);
|
||||
}
|
||||
const [row] = await db()
|
||||
.insert(benchmarkRuns)
|
||||
.values({
|
||||
kind,
|
||||
deploymentId: a.id,
|
||||
deploymentBId: b?.id ?? null,
|
||||
modelId: a.modelId,
|
||||
endpointId: a.e.id,
|
||||
endpointBId: b?.e.id ?? null,
|
||||
modelId: await libraryModelId(picked.model),
|
||||
label: input.label || null,
|
||||
description: input.description || null,
|
||||
settings:
|
||||
@@ -88,17 +88,8 @@ export async function createBenchmark(input: BenchmarkInput, agent?: AgentReques
|
||||
phases: input.phases,
|
||||
...(ab ? { mdePct: input.mdePct ?? null, maxPairs: input.maxPairs ?? null } : {}),
|
||||
},
|
||||
snapshot: a.snapshot,
|
||||
snapshotB: b?.snapshot ?? null,
|
||||
sweepId: input.sweepId ?? null,
|
||||
...(agent
|
||||
? {
|
||||
requestedByTokenId: agent.requestedBy.tokenId,
|
||||
requestedBy: agent.requestedBy.name,
|
||||
timeLimitS: agent.timeLimitS,
|
||||
state: agent.pendingApproval ? ("pending_approval" as const) : ("queued" as const),
|
||||
}
|
||||
: {}),
|
||||
snapshot: snapshotOf(a.e, picked.model, a.probe),
|
||||
snapshotB: b ? snapshotOf(b.e, picked.model, b.probe) : null,
|
||||
})
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
return row;
|
||||
@@ -106,7 +97,7 @@ export async function createBenchmark(input: BenchmarkInput, agent?: AgentReques
|
||||
|
||||
const listColumns = {
|
||||
id: benchmarkRuns.id,
|
||||
deploymentId: benchmarkRuns.deploymentId,
|
||||
endpointId: benchmarkRuns.endpointId,
|
||||
modelId: benchmarkRuns.modelId,
|
||||
tool: benchmarkRuns.tool,
|
||||
label: benchmarkRuns.label,
|
||||
@@ -121,15 +112,10 @@ const listColumns = {
|
||||
summary: benchmarkRuns.summary,
|
||||
hasReport: benchmarkRuns.hasReport,
|
||||
kind: benchmarkRuns.kind,
|
||||
deploymentBId: benchmarkRuns.deploymentBId,
|
||||
endpointBId: benchmarkRuns.endpointBId,
|
||||
snapshotB: benchmarkRuns.snapshotB,
|
||||
ab: benchmarkRuns.ab,
|
||||
resources: benchmarkRuns.resources,
|
||||
quality: benchmarkRuns.quality,
|
||||
sweepId: benchmarkRuns.sweepId,
|
||||
requestedBy: benchmarkRuns.requestedBy,
|
||||
requestedByTokenId: benchmarkRuns.requestedByTokenId,
|
||||
timeLimitS: benchmarkRuns.timeLimitS,
|
||||
meta: benchmarkRuns.meta,
|
||||
metaB: benchmarkRuns.metaB,
|
||||
system: benchmarkRuns.system,
|
||||
@@ -139,13 +125,13 @@ const listColumns = {
|
||||
|
||||
export type BenchmarkRow = Awaited<ReturnType<typeof listBenchmarks>>[number];
|
||||
|
||||
export async function listBenchmarks(filter: { deploymentId?: string; modelId?: string } = {}) {
|
||||
export async function listBenchmarks(filter: { endpointId?: string; modelId?: string } = {}) {
|
||||
return db()
|
||||
.select(listColumns)
|
||||
.from(benchmarkRuns)
|
||||
.where(
|
||||
and(
|
||||
filter.deploymentId ? or(eq(benchmarkRuns.deploymentId, filter.deploymentId), eq(benchmarkRuns.deploymentBId, filter.deploymentId)) : undefined,
|
||||
filter.endpointId ? or(eq(benchmarkRuns.endpointId, filter.endpointId), eq(benchmarkRuns.endpointBId, filter.endpointId)) : undefined,
|
||||
filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
|
||||
),
|
||||
)
|
||||
@@ -163,37 +149,17 @@ export async function getBenchmarks(ids: string[]) {
|
||||
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
|
||||
}
|
||||
|
||||
/** Queued (or still unapproved) runs are cancelled right away; a running one is stopped by the worker. */
|
||||
/** Queued runs are cancelled right away; a running one is stopped by the worker. */
|
||||
export async function cancelBenchmark(id: string) {
|
||||
const run = await getBenchmark(id);
|
||||
if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
|
||||
if (run.state === "queued" || run.state === "pending_approval") {
|
||||
if (run.state === "queued") {
|
||||
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, run.state)));
|
||||
} else if (run.state === "running") {
|
||||
await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
|
||||
}
|
||||
}
|
||||
|
||||
/** Let a run an agent asked for start (it joins the queue). */
|
||||
export async function approveBenchmark(id: string) {
|
||||
const res = await db()
|
||||
.update(benchmarkRuns)
|
||||
.set({ state: "queued" })
|
||||
.where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
|
||||
}
|
||||
|
||||
/** Turn down a run an agent asked for. */
|
||||
export async function rejectBenchmark(id: string) {
|
||||
const res = await db()
|
||||
.update(benchmarkRuns)
|
||||
.set({ state: "cancelled", finishedAt: new Date(), error: "Rejected by the user." })
|
||||
.where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "pending_approval")))
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
if (res.length === 0) throw new BenchmarkError("invalid", "This run doesn't wait for approval.", 409);
|
||||
}
|
||||
|
||||
/** 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> = {};
|
||||
|
||||
+94
-362
@@ -3,7 +3,6 @@ import {
|
||||
index,
|
||||
integer,
|
||||
primaryKey,
|
||||
real,
|
||||
sqliteTable,
|
||||
text,
|
||||
uniqueIndex,
|
||||
@@ -73,8 +72,6 @@ export type JobResult = {
|
||||
removePaths?: string[];
|
||||
/** Delete jobs: files that were kept because they don't belong to the repo. */
|
||||
kept?: string[];
|
||||
/** API "add files" requests: the selection rule before, restored if the request is rejected. */
|
||||
previousRule?: { include: string[]; exclude: string[] };
|
||||
};
|
||||
|
||||
export const models = sqliteTable(
|
||||
@@ -126,9 +123,6 @@ export const models = sqliteTable(
|
||||
/** Hub tags, minus noise like arxiv:/region:/deploy:. */
|
||||
hubTags: text("hub_tags", { mode: "json" }).$type<string[]>(),
|
||||
metadataFetchedAt: ts("metadata_fetched_at"),
|
||||
/** Added through the API: the token that asked for it, and its name at the time. */
|
||||
requestedByTokenId: text("requested_by_token_id"),
|
||||
requestedBy: text("requested_by"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
@@ -229,7 +223,6 @@ export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as
|
||||
export type JobPurpose = (typeof JOB_PURPOSES)[number];
|
||||
|
||||
export const JOB_STATES = [
|
||||
"pending_approval", // requested through the API, waits for a human to approve it
|
||||
"queued",
|
||||
"downloading",
|
||||
"verifying",
|
||||
@@ -275,9 +268,6 @@ export const jobs = sqliteTable(
|
||||
result: text("result", { mode: "json" }).$type<JobResult>(),
|
||||
/** Set by the web app; the worker picks it up and stops the job. */
|
||||
cancelRequestedAt: ts("cancel_requested_at"),
|
||||
/** Requested through the API: the token, and its name at the time. */
|
||||
requestedByTokenId: text("requested_by_token_id"),
|
||||
requestedBy: text("requested_by"),
|
||||
startedAt: ts("started_at"),
|
||||
finishedAt: ts("finished_at"),
|
||||
createdAt: createdAt(),
|
||||
@@ -352,150 +342,11 @@ export const workerState = sqliteTable("worker_state", {
|
||||
heartbeatAt: ts("heartbeat_at").notNull(),
|
||||
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
|
||||
scanRequestedAt: ts("scan_requested_at"),
|
||||
/** Docker connection and host facts, reported by the worker (null: no DOCKER_HOST). */
|
||||
docker: text("docker", { mode: "json" }).$type<DockerHostInfo>(),
|
||||
});
|
||||
|
||||
export type DockerHostInfo = {
|
||||
connected: boolean;
|
||||
error: string | null;
|
||||
serverVersion: string | null;
|
||||
os: string | null;
|
||||
architecture: string | null;
|
||||
cpus: number | null;
|
||||
memoryBytes: number | null;
|
||||
cpuModel: string | null;
|
||||
/** Relevant CPU features (avx2, avx512f, avx512_bf16, amx_bf16, …). */
|
||||
cpuFeatures: string[];
|
||||
/** Docker network inference containers join, so the worker can reach them. */
|
||||
network: string | null;
|
||||
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
|
||||
modelsSource: { type: "bind" | "volume"; source: string } | null;
|
||||
/** Docker has the NVIDIA runtime / CDI devices, so GPUs can be requested. */
|
||||
nvidia?: boolean;
|
||||
/** GPUs found by a probe container (nvidia-smi); empty when none or not probed. */
|
||||
gpus?: HostGpu[];
|
||||
gpuError?: string | null;
|
||||
gpuCheckedAt?: string | null;
|
||||
/** Group IDs owning /dev/dri on the host (render, video); given to Intel/AMD runtime containers. */
|
||||
driGroups?: number[];
|
||||
/** 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;
|
||||
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, …)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** How Kaname builds the command line and talks to the server. */
|
||||
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
|
||||
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
|
||||
|
||||
/**
|
||||
* What the image computes on. nvidia: GPUs requested through Docker (NVIDIA Container Toolkit);
|
||||
* dri: Intel/AMD GPUs via /dev/dri (Vulkan, SYCL, XPU); rocm: AMD via /dev/kfd + /dev/dri.
|
||||
*/
|
||||
export const RUNTIME_ACCELERATORS = ["cpu", "nvidia", "dri", "rocm"] as const;
|
||||
export type RuntimeAccelerator = (typeof RUNTIME_ACCELERATORS)[number];
|
||||
|
||||
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
|
||||
export type ImageState = (typeof IMAGE_STATES)[number];
|
||||
|
||||
export const runtimes = sqliteTable("runtimes", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
|
||||
accelerator: text("accelerator", { enum: RUNTIME_ACCELERATORS }).notNull().default("cpu"),
|
||||
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
|
||||
image: text("image").notNull(),
|
||||
description: text("description"),
|
||||
/** Environment variables for the container. */
|
||||
env: text("env", { mode: "json" }).$type<Record<string, string>>().notNull().default(sql`'{}'`),
|
||||
/** Appended to the generated command line (fork-specific flags). */
|
||||
extraArgs: text("extra_args", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
|
||||
/** Host devices to pass through, e.g. "/dev/dri" (later: Intel GPUs). */
|
||||
devices: text("devices", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
|
||||
shmSizeMb: integer("shm_size_mb"),
|
||||
/** vLLM's NUMA optimizations: adds CAP_SYS_NICE and seccomp=unconfined. Off unless enabled. */
|
||||
numaTuning: integer("numa_tuning", { mode: "boolean" }).notNull().default(false),
|
||||
/** Preset this runtime was created from, if any. */
|
||||
preset: text("preset"),
|
||||
imageState: text("image_state", { enum: IMAGE_STATES }).notNull().default("unknown"),
|
||||
imageId: text("image_id"),
|
||||
imageSize: integer("image_size"),
|
||||
imageCreated: text("image_created"),
|
||||
/** Set by "Pull"; the worker pulls when this is newer than the last pull. */
|
||||
pullRequestedAt: ts("pull_requested_at"),
|
||||
pullStartedAt: ts("pull_started_at"),
|
||||
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(),
|
||||
});
|
||||
|
||||
/**
|
||||
* Folders in MODELS_DIR (`<org>/<name>`, like `hf download --local-dir` layouts) that no model uses,
|
||||
* found by the worker's scan. Rewritten on every scan; the web app offers them for import.
|
||||
@@ -513,14 +364,14 @@ export const localFolders = sqliteTable("local_folders", {
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Deployments: a model served by a runtime container
|
||||
// Before 0.15 Kaname ran the servers itself (runtimes, deployments). Benchmark runs from then keep
|
||||
// a snapshot of the deployment; these types describe it.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** What the worker is doing with the container. */
|
||||
export const DEPLOYMENT_STATES = ["stopped", "starting", "running", "stopping", "failed"] as const;
|
||||
export type DeploymentState = (typeof DEPLOYMENT_STATES)[number];
|
||||
export type RuntimeEngine = "llama.cpp" | "vllm";
|
||||
export type RuntimeAccelerator = "cpu" | "nvidia" | "dri" | "rocm";
|
||||
|
||||
/** Launch options. Engine-specific fields are ignored by the other engine. */
|
||||
/** A deployment's launch options (legacy). */
|
||||
export type DeploymentOptions = {
|
||||
/** Model file (llama.cpp: the GGUF, first part of a split) or "" for the repo folder (vLLM). */
|
||||
modelFile: string;
|
||||
@@ -564,131 +415,85 @@ export type DeploymentOptions = {
|
||||
extraArgs: string[];
|
||||
};
|
||||
|
||||
export type DeploymentStats = { cpuPercent: number; memoryBytes: number; memoryLimitBytes: number; at: string };
|
||||
// ---------------------------------------------------------------------------
|
||||
// Endpoints: OpenAI-compatible servers to benchmark (llama.cpp, vLLM, SGLang, …), run elsewhere
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const deployments = sqliteTable("deployments", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
runtimeId: text("runtime_id")
|
||||
.notNull()
|
||||
.references(() => runtimes.id),
|
||||
modelId: text("model_id")
|
||||
.notNull()
|
||||
.references(() => models.id),
|
||||
options: text("options", { mode: "json" }).$type<DeploymentOptions>().notNull(),
|
||||
/** CPU limit in cores (fractions allowed) and memory limit; null = no limit. */
|
||||
cpus: real("cpus"),
|
||||
memoryMb: integer("memory_mb"),
|
||||
/** Publish the API on this host port (optional; Kaname itself uses the Docker network). */
|
||||
hostPort: integer("host_port"),
|
||||
/** Set by the web app; the worker starts/stops the container to match. */
|
||||
desiredState: text("desired_state", { enum: ["running", "stopped"] }).notNull().default("stopped"),
|
||||
state: text("state", { enum: DEPLOYMENT_STATES }).notNull().default("stopped"),
|
||||
/** Delete requested: the worker removes the container, then the row. */
|
||||
deleteRequestedAt: ts("delete_requested_at"),
|
||||
containerId: text("container_id"),
|
||||
containerName: text("container_name"),
|
||||
/** Command line the container was started with (for display and reproducibility). */
|
||||
command: text("command", { mode: "json" }).$type<string[]>(),
|
||||
imageId: text("image_id"),
|
||||
startedAt: ts("started_at"),
|
||||
readyAt: ts("ready_at"),
|
||||
stoppedAt: ts("stopped_at"),
|
||||
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"),
|
||||
/** Created through the API: the token and its name at the time. */
|
||||
requestedByTokenId: text("requested_by_token_id"),
|
||||
requestedBy: text("requested_by"),
|
||||
/** Agents can't edit, stop, delete or benchmark it, nor start anything that would crowd it out of VRAM. */
|
||||
protected: integer("protected", { mode: "boolean" }).notNull().default(false),
|
||||
/** An agent asked to start it; it starts once someone approves (approval mode "approve"). */
|
||||
startRequestedAt: ts("start_requested_at"),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
});
|
||||
|
||||
export const deploymentLogs = sqliteTable(
|
||||
"deployment_logs",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
deploymentId: text("deployment_id")
|
||||
.notNull()
|
||||
.references(() => deployments.id),
|
||||
ts: ts("ts")
|
||||
.notNull()
|
||||
.$defaultFn(() => new Date()),
|
||||
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
|
||||
line: text("line").notNull(),
|
||||
},
|
||||
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
|
||||
);
|
||||
export const ENDPOINT_ENGINES = ["llama.cpp", "vllm", "sglang", "ollama", "other"] as const;
|
||||
export type EndpointEngine = (typeof ENDPOINT_ENGINES)[number];
|
||||
|
||||
/**
|
||||
* API keys that deployments with `requireApiKey` accept. Stored in plain text because the worker
|
||||
* hands them to the runtime container; never logged or written into a stored command line.
|
||||
* What runs behind an endpoint, as the user describes it (Kaname can't see that machine). Copied into
|
||||
* every run; goes into BetterBench notes and launch80. Nothing here may identify the host.
|
||||
*/
|
||||
export const apiKeys = sqliteTable("api_keys", {
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
key: text("key").notNull().unique(),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
export type EndpointHardware = {
|
||||
gpuName?: string | null;
|
||||
gpuCount?: number | null;
|
||||
/** Per GPU. */
|
||||
vramGb?: number | null;
|
||||
/** e.g. "Gen4 x16". */
|
||||
pcie?: string | null;
|
||||
p2p?: "on" | "off" | "partial" | null;
|
||||
rebar?: boolean | null;
|
||||
gpuDriver?: string | null;
|
||||
cpu?: string | null;
|
||||
memoryGb?: number | null;
|
||||
os?: string | null;
|
||||
/** e.g. "Proxmox VM with GPU passthrough". */
|
||||
virtualization?: string | null;
|
||||
/** Shown instead of the detected engine, e.g. "ik_llama.cpp". */
|
||||
engineName?: string | null;
|
||||
engineVersion?: string | null;
|
||||
image?: string | null;
|
||||
quant?: string | null;
|
||||
kvCache?: string | null;
|
||||
contextSize?: number | null;
|
||||
/** Parallel slots / max sequences. */
|
||||
concurrency?: number | null;
|
||||
/** Free text: launch flags, anything else worth knowing. */
|
||||
description?: string | null;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API tokens: machine clients (e.g. an AI agent) calling /api/v1 with a bearer token
|
||||
// ---------------------------------------------------------------------------
|
||||
/** The last "Test connection" (or check before a run). */
|
||||
export type EndpointProbe = {
|
||||
ok: boolean;
|
||||
at: string;
|
||||
error: string | null;
|
||||
latencyMs: number | null;
|
||||
/** Model names from /v1/models. */
|
||||
models: string[];
|
||||
engine: EndpointEngine | null;
|
||||
engineVersion: string | null;
|
||||
contextSize: number | null;
|
||||
slots: number | null;
|
||||
};
|
||||
|
||||
/** What a token may do. Nothing can delete, change settings or manage runtimes/tokens. */
|
||||
export const TOKEN_SCOPES = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"] as const;
|
||||
export type TokenScope = (typeof TOKEN_SCOPES)[number];
|
||||
|
||||
export const apiTokens = sqliteTable(
|
||||
"api_tokens",
|
||||
export const endpoints = sqliteTable(
|
||||
"endpoints",
|
||||
{
|
||||
id: id(),
|
||||
name: text("name").notNull(),
|
||||
/** First characters of the token, shown in the UI to tell tokens apart. */
|
||||
prefix: text("prefix").notNull(),
|
||||
/** SHA-256 of the token (hex); the token itself is never stored. */
|
||||
hash: text("hash").notNull().unique(),
|
||||
scopes: text("scopes", { mode: "json" }).$type<TokenScope[]>().notNull(),
|
||||
lastUsedAt: ts("last_used_at"),
|
||||
revokedAt: ts("revoked_at"),
|
||||
/** Server root, e.g. "http://gpu-box:8080" (Kaname appends /v1). */
|
||||
baseUrl: text("base_url").notNull(),
|
||||
/** Sent as a bearer token; never leaves the server (not shown, logged or put into a run). */
|
||||
apiKey: text("api_key"),
|
||||
/** Model to benchmark; null: the only one the server lists. */
|
||||
model: text("model"),
|
||||
/** null: detect from the server. */
|
||||
engine: text("engine", { enum: ENDPOINT_ENGINES }),
|
||||
hardware: text("hardware", { mode: "json" }).$type<EndpointHardware>().notNull().default(sql`'{}'`),
|
||||
probe: text("probe", { mode: "json" }).$type<EndpointProbe>(),
|
||||
createdAt: createdAt(),
|
||||
updatedAt: updatedAt(),
|
||||
},
|
||||
(t) => [uniqueIndex("api_tokens_name_uq").on(t.name)],
|
||||
);
|
||||
|
||||
/** What tokens did: every request that creates or changes something, and refusals by a guardrail. */
|
||||
export const agentActivity = sqliteTable(
|
||||
"agent_activity",
|
||||
{
|
||||
id: id(),
|
||||
tokenId: text("token_id").notNull(),
|
||||
tokenName: text("token_name").notNull(),
|
||||
/** e.g. "deployment.create", "deployment.start", "benchmark.run", "sweep.create", "download.request". */
|
||||
action: text("action").notNull(),
|
||||
targetType: text("target_type"),
|
||||
targetId: text("target_id"),
|
||||
/** ok, pending_approval or refused (then `code` is the error code). */
|
||||
outcome: text("outcome", { enum: ["ok", "pending_approval", "refused"] }).notNull(),
|
||||
code: text("code"),
|
||||
message: text("message"),
|
||||
createdAt: createdAt(),
|
||||
},
|
||||
(t) => [index("agent_activity_token_idx").on(t.tokenId, t.createdAt)],
|
||||
(t) => [uniqueIndex("endpoints_name_uq").on(t.name)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Benchmarks (BetterBench runs against a running deployment)
|
||||
// Benchmarks (BetterBench runs against an endpoint)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const BENCHMARK_STATES = ["pending_approval", "queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
|
||||
|
||||
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
|
||||
@@ -703,9 +508,8 @@ export type BenchmarkSettings = {
|
||||
/** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */
|
||||
mdePct?: number | null;
|
||||
maxPairs?: number | null;
|
||||
/** eval: which sections (empty: all). Sweeps: also run the quality eval for each variant. */
|
||||
/** eval: which sections (empty: all). */
|
||||
evalSections?: QualitySection[];
|
||||
quality?: boolean;
|
||||
};
|
||||
|
||||
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
|
||||
@@ -766,42 +570,23 @@ export type AbSummary = {
|
||||
config: { greedy?: boolean | null; temperature?: number | null; warmup?: number | null; unique_nonce?: boolean | null; ab_min_pairs?: number | null };
|
||||
};
|
||||
|
||||
/** Resource use sampled during a run (every ~2 s), per deployment and per GPU. */
|
||||
export type ResourceStats = {
|
||||
samples: number;
|
||||
seconds: number;
|
||||
containers: {
|
||||
side: "a" | "b";
|
||||
cpuAvg: number | null;
|
||||
cpuPeak: number | null;
|
||||
memAvgBytes: number | null;
|
||||
memPeakBytes: number | null;
|
||||
memLimitBytes: number | null;
|
||||
}[];
|
||||
/** Fastest PCIe link seen per GPU (PCI address) during the run. */
|
||||
links?: Record<string, PcieLink>;
|
||||
/**
|
||||
* Whole-GPU figures, not per process: nvidia-smi; hwmon/sysfs for AMD; hwmon plus the DRM fdinfo
|
||||
* of all processes for Intel. null where a source doesn't report it.
|
||||
*/
|
||||
gpus: {
|
||||
index: number;
|
||||
name: string;
|
||||
pciAddress?: string;
|
||||
vramTotalMb: number | null;
|
||||
vramPeakMb: number | null;
|
||||
vramAvgMb: number | null;
|
||||
utilAvg: number | null;
|
||||
utilPeak: number | null;
|
||||
powerAvgW: number | null;
|
||||
powerPeakW: number | null;
|
||||
tempAvgC?: number | null;
|
||||
tempPeakC?: number | null;
|
||||
}[];
|
||||
/** The endpoint as it was when the run started, so results stay comparable after edits. */
|
||||
export type EndpointSnapshot = {
|
||||
type: "endpoint";
|
||||
endpointName: string;
|
||||
/** The model name sent to the server (what /v1/models lists). */
|
||||
model: string;
|
||||
engine: EndpointEngine | null;
|
||||
engineVersion: string | null;
|
||||
contextSize: number | null;
|
||||
/** Parallel slots the server reported (llama.cpp). */
|
||||
slots?: number | null;
|
||||
hardware: EndpointHardware;
|
||||
};
|
||||
|
||||
/** The deployment as it was when the run started, so results stay comparable after edits. */
|
||||
export type BenchmarkSnapshot = {
|
||||
/** Runs before 0.15: the deployment Kaname ran, as it was when the run started. */
|
||||
export type DeploymentSnapshot = {
|
||||
type?: "deployment";
|
||||
deploymentName: string;
|
||||
repoId: string;
|
||||
runtimeName: string;
|
||||
@@ -820,7 +605,9 @@ export type BenchmarkSnapshot = {
|
||||
command: string;
|
||||
};
|
||||
|
||||
/** What was measured on what, recorded when a run starts (Settings → Hardware overrides applied). */
|
||||
export type BenchmarkSnapshot = EndpointSnapshot | DeploymentSnapshot;
|
||||
|
||||
/** What was measured on what, recorded when a run starts (from the endpoint's hardware notes). */
|
||||
export type RunMeta = {
|
||||
v: 1;
|
||||
gpus: { pciAddress?: string; name: string | null; vramMb: number | null; linkCurrent: PcieLink | null; linkMax: PcieLink | null; rebar: boolean | null }[];
|
||||
@@ -833,12 +620,12 @@ export type RunMeta = {
|
||||
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 };
|
||||
runtime: { image: string; tag: string | null; digest: string | null; engine: string; 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. */
|
||||
/** Runs before 0.15: fields taken from Settings → Hardware instead of detection. */
|
||||
overridden: string[];
|
||||
};
|
||||
|
||||
@@ -947,8 +734,11 @@ export const benchmarkRuns = sqliteTable(
|
||||
"benchmark_runs",
|
||||
{
|
||||
id: id(),
|
||||
/** Null once the deployment is deleted; the snapshot keeps what was measured. */
|
||||
deploymentId: text("deployment_id"),
|
||||
/** Null once the endpoint is deleted; the snapshot keeps what was measured. */
|
||||
endpointId: text("endpoint_id"),
|
||||
/** A/B: the second endpoint (B); `endpointId` is A. */
|
||||
endpointBId: text("endpoint_b_id"),
|
||||
/** A downloaded model the endpoint serves (matched by repo id), if any. */
|
||||
modelId: text("model_id"),
|
||||
tool: text("tool").notNull().default("betterbench"),
|
||||
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
|
||||
@@ -965,20 +755,10 @@ export const benchmarkRuns = sqliteTable(
|
||||
/** Files under BENCHMARKS_DIR/<id>/: results.json and results.html. */
|
||||
hasReport: integer("has_report", { mode: "boolean" }).notNull().default(false),
|
||||
kind: text("kind", { enum: BENCHMARK_KINDS }).notNull().default("run"),
|
||||
/** A/B: the second deployment (B); `deploymentId` is A. */
|
||||
deploymentBId: text("deployment_b_id"),
|
||||
snapshotB: text("snapshot_b", { mode: "json" }).$type<BenchmarkSnapshot>(),
|
||||
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
|
||||
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
|
||||
/** kind "eval": the quality eval's result. */
|
||||
quality: text("quality", { mode: "json" }).$type<QualityResult>(),
|
||||
/** Run of a sweep variant. */
|
||||
sweepId: text("sweep_id"),
|
||||
/** Requested through the API: the token and its name at the time. */
|
||||
requestedByTokenId: text("requested_by_token_id"),
|
||||
requestedBy: text("requested_by"),
|
||||
/** Agent runs: cancelled after this many seconds of running. */
|
||||
timeLimitS: integer("time_limit_s"),
|
||||
/** 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>(),
|
||||
@@ -1037,51 +817,3 @@ export const benchmarkPublications = sqliteTable(
|
||||
},
|
||||
(t) => [index("benchmark_publications_run_idx").on(t.runId)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Benchmark sweeps: one base deployment, one or two settings varied, a run per variant
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const SWEEP_STATES = ["pending_approval", "queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export type SweepState = (typeof SWEEP_STATES)[number];
|
||||
|
||||
/** A setting a sweep varies; values are strings as entered (parsed per key). */
|
||||
export type SweepParam = { key: string; values: string[] };
|
||||
|
||||
export type SweepVariant = {
|
||||
index: number;
|
||||
/** Option overrides for this variant, e.g. { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }. */
|
||||
overrides: Record<string, unknown>;
|
||||
label: string;
|
||||
state: "pending" | "deploying" | "benchmarking" | "evaluating" | "done" | "failed" | "skipped";
|
||||
deploymentId?: string | null;
|
||||
runId?: string | null;
|
||||
/** The quality eval run of this variant (sweeps with quality: true). */
|
||||
evalRunId?: string | null;
|
||||
error?: string | null;
|
||||
};
|
||||
|
||||
export const benchmarkSweeps = sqliteTable("benchmark_sweeps", {
|
||||
id: id(),
|
||||
label: text("label"),
|
||||
/** The deployment the variants are copied from (may be deleted later; `base` keeps it). */
|
||||
baseDeploymentId: text("base_deployment_id"),
|
||||
base: text("base", { mode: "json" })
|
||||
.$type<{ name: string; runtimeId: string; modelId: string; options: DeploymentOptions; cpus: number | null; memoryMb: number | null }>()
|
||||
.notNull(),
|
||||
params: text("params", { mode: "json" }).$type<SweepParam[]>().notNull(),
|
||||
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
|
||||
variants: text("variants", { mode: "json" }).$type<SweepVariant[]>().notNull(),
|
||||
state: text("state", { enum: SWEEP_STATES }).notNull().default("queued"),
|
||||
cancelRequestedAt: ts("cancel_requested_at"),
|
||||
startedAt: ts("started_at"),
|
||||
finishedAt: ts("finished_at"),
|
||||
error: text("error"),
|
||||
/** Requested through the API: the token and its name at the time. */
|
||||
requestedByTokenId: text("requested_by_token_id"),
|
||||
requestedBy: text("requested_by"),
|
||||
/** Agent sweeps: the sweep is stopped after this many seconds, each of its runs after runTimeLimitS. */
|
||||
timeLimitS: integer("time_limit_s"),
|
||||
runTimeLimitS: integer("run_time_limit_s"),
|
||||
createdAt: createdAt(),
|
||||
});
|
||||
@@ -1,36 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { modelCandidates, servableBy } from "./deploy-candidates";
|
||||
|
||||
const f = (path: string, size = 10) => ({ path, size });
|
||||
|
||||
describe("modelCandidates", () => {
|
||||
it("lists GGUF weights (split as first part), mmproj and MTP/draft files", () => {
|
||||
const c = modelCandidates([
|
||||
f("Qwen3.8-27B-UD-Q4_K_XL.gguf"),
|
||||
f("BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf"),
|
||||
f("BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf"),
|
||||
f("mmproj-F16.gguf"),
|
||||
f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"),
|
||||
f("imatrix_unsloth.gguf"),
|
||||
f("config.json"),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
c.gguf.map((g) => [g.path, g.parts]),
|
||||
[
|
||||
["Qwen3.8-27B-UD-Q4_K_XL.gguf", 1],
|
||||
["BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", 2],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(c.mmproj.map((m) => m.path), ["mmproj-F16.gguf"]);
|
||||
assert.deepEqual(c.drafts.map((d) => [d.path, d.type]), [["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "draft-mtp"]]);
|
||||
assert.equal(c.vllm, null);
|
||||
assert.ok(servableBy(c, "llama.cpp") && !servableBy(c, "vllm"));
|
||||
});
|
||||
|
||||
it("recognizes a safetensors repo for vLLM", () => {
|
||||
const c = modelCandidates([f("config.json", 1), f("model.safetensors", 100), f("tokenizer.json", 5)]);
|
||||
assert.deepEqual(c.vllm, { size: 106 });
|
||||
assert.equal(c.gguf.length, 0);
|
||||
});
|
||||
});
|
||||
@@ -1,41 +0,0 @@
|
||||
// Which downloaded files a runtime can serve. Pure; shared by the server and the deployment form.
|
||||
|
||||
import type { RuntimeEngine } from "@/lib/db/schema";
|
||||
import { groupSplitFiles } from "@/lib/file-groups";
|
||||
import { fileRole } from "@/lib/file-roles";
|
||||
|
||||
export type LocalFile = { path: string; size: number };
|
||||
export type CandidateFile = { path: string; size: number; parts: number };
|
||||
export type DraftFile = CandidateFile & { type: "draft-mtp" | "draft-simple" };
|
||||
|
||||
export type ModelCandidates = {
|
||||
/** llama.cpp: loadable GGUF weights (split files as their first part), plus optional extras. */
|
||||
gguf: CandidateFile[];
|
||||
mmproj: CandidateFile[];
|
||||
drafts: DraftFile[];
|
||||
/** vLLM: the repo folder has a config.json and safetensors weights. */
|
||||
vllm: { size: number } | null;
|
||||
};
|
||||
|
||||
const isGguf = (p: string) => p.toLowerCase().endsWith(".gguf");
|
||||
|
||||
/** `files`: the model's files that are on disk (present or verified). */
|
||||
export function modelCandidates(files: LocalFile[]): ModelCandidates {
|
||||
const entries = (pred: (p: string) => boolean) =>
|
||||
groupSplitFiles(files.filter((f) => pred(f.path))).map((g) => ({ path: g.parts[0].path, size: g.size, parts: g.totalParts }));
|
||||
|
||||
const gguf = entries((p) => isGguf(p) && fileRole(p) === "model");
|
||||
const mmproj = entries((p) => isGguf(p) && fileRole(p) === "vision");
|
||||
const drafts: DraftFile[] = [
|
||||
...entries((p) => isGguf(p) && fileRole(p) === "mtp").map((f) => ({ ...f, type: "draft-mtp" as const })),
|
||||
...entries((p) => isGguf(p) && fileRole(p) === "draft").map((f) => ({ ...f, type: "draft-simple" as const })),
|
||||
];
|
||||
const hasConfig = files.some((f) => f.path === "config.json");
|
||||
const safetensors = files.filter((f) => f.path.endsWith(".safetensors") && fileRole(f.path) === "model");
|
||||
const vllm = hasConfig && safetensors.length > 0 ? { size: files.reduce((s, f) => s + f.size, 0) } : null;
|
||||
return { gguf, mmproj, drafts, vllm };
|
||||
}
|
||||
|
||||
export function servableBy(c: ModelCandidates, engine: RuntimeEngine): boolean {
|
||||
return engine === "llama.cpp" ? c.gguf.length > 0 : c.vllm !== null;
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { buildCommand, estimateMemoryMb, redactCommand, renderCommand } from "./deploy-command";
|
||||
|
||||
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
|
||||
|
||||
describe("buildCommand", () => {
|
||||
it("builds llama-server arguments with mmproj and MTP draft", () => {
|
||||
const cmd = buildCommand({
|
||||
engine: "llama.cpp",
|
||||
model,
|
||||
runtime: { env: {}, extraArgs: ["--jinja"] },
|
||||
options: {
|
||||
modelFile: "Qwen3-0.6B-Q4_K_M.gguf",
|
||||
mmproj: "mmproj-F16.gguf",
|
||||
draftFile: "MTP/mtp-Q4_0.gguf",
|
||||
draftType: "draft-mtp",
|
||||
contextSize: 4096,
|
||||
threads: 8,
|
||||
parallel: 1,
|
||||
cacheTypeK: "q8_0",
|
||||
extraArgs: ["--temp", "0.7"],
|
||||
},
|
||||
});
|
||||
assert.equal(cmd.port, 8080);
|
||||
assert.deepEqual(cmd.args.slice(0, 2), ["-m", "/models/unsloth/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q4_K_M.gguf"]);
|
||||
const s = cmd.args.join(" ");
|
||||
assert.match(s, /-c 4096 -t 8 -tb 8 -np 1 -ctk q8_0/);
|
||||
assert.match(s, /--mmproj \/models\/unsloth\/Qwen3-0\.6B-GGUF\/mmproj-F16\.gguf/);
|
||||
assert.match(s, /-md \/models\/unsloth\/Qwen3-0\.6B-GGUF\/MTP\/mtp-Q4_0\.gguf --spec-type draft-mtp/);
|
||||
assert.ok(s.endsWith("--metrics --jinja --temp 0.7"));
|
||||
assert.ok(!s.includes("-b "), "unset options are left out");
|
||||
});
|
||||
|
||||
it("builds vllm serve arguments; deployment dtype and KV cache override the runtime", () => {
|
||||
const cmd = buildCommand({
|
||||
engine: "vllm",
|
||||
model: { repoId: "HuggingFaceTB/SmolLM2-135M-Instruct", localPath: "HuggingFaceTB/SmolLM2-135M-Instruct" },
|
||||
runtime: { env: { VLLM_CPU_KVCACHE_SPACE: "4" }, extraArgs: ["--dtype=bfloat16", "--enforce-eager"] },
|
||||
options: { modelFile: "", contextSize: 2048, maxNumSeqs: 4, dtype: "float32", kvCacheGb: 2, extraArgs: [] },
|
||||
});
|
||||
assert.equal(cmd.port, 8000);
|
||||
assert.equal(cmd.args[0], "/models/HuggingFaceTB/SmolLM2-135M-Instruct");
|
||||
assert.equal(cmd.env.VLLM_CPU_KVCACHE_SPACE, "2");
|
||||
const s = cmd.args.join(" ");
|
||||
assert.ok(!s.includes("bfloat16") && s.includes("--dtype float32") && s.includes("--enforce-eager"));
|
||||
assert.match(renderCommand("vllm/vllm-openai-cpu:v0.31.0", cmd), /^docker run -e VLLM_CPU_KVCACHE_SPACE=2 /);
|
||||
const keep = buildCommand({
|
||||
engine: "vllm",
|
||||
model: { repoId: "a/b", localPath: "a/b" },
|
||||
runtime: { env: {}, extraArgs: ["--dtype", "bfloat16"] },
|
||||
options: { modelFile: "", contextSize: 2048, extraArgs: [] },
|
||||
});
|
||||
assert.ok(keep.args.join(" ").includes("--dtype bfloat16"));
|
||||
});
|
||||
|
||||
it("turns llama.cpp's web UI off only when asked", () => {
|
||||
const args = (webui?: boolean | null) =>
|
||||
buildCommand({
|
||||
engine: "llama.cpp",
|
||||
model: { repoId: "a/b", localPath: "a/b" },
|
||||
runtime: { env: {}, extraArgs: [] },
|
||||
options: { modelFile: "m.gguf", contextSize: 2048, webui, extraArgs: [] },
|
||||
}).args;
|
||||
assert.ok(!args().includes("--no-webui") && !args(true).includes("--no-webui"));
|
||||
assert.ok(args(false).includes("--no-webui"));
|
||||
});
|
||||
|
||||
it("passes API keys via the environment and redacts them", () => {
|
||||
const base = { model: { repoId: "a/b", localPath: "a/b" }, runtime: { env: {}, extraArgs: [] } };
|
||||
const opts = { modelFile: "m.gguf", contextSize: 2048, requireApiKey: true, extraArgs: [] };
|
||||
const llama = buildCommand({ ...base, engine: "llama.cpp", options: opts, apiKeys: ["sk-one-1234567890", "sk-two-1234567890"] });
|
||||
assert.equal(llama.env.LLAMA_API_KEY, "sk-one-1234567890,sk-two-1234567890");
|
||||
assert.ok(!llama.args.join(" ").includes("sk-"));
|
||||
const shown = renderCommand("img", redactCommand(llama, ["sk-one-1234567890", "sk-two-1234567890"]));
|
||||
assert.ok(!shown.includes("sk-") && shown.includes("<api-key>,<api-key>"));
|
||||
|
||||
const one = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["sk-one-1234567890"] });
|
||||
assert.equal(one.env.VLLM_API_KEY, "sk-one-1234567890");
|
||||
const two = buildCommand({ ...base, engine: "vllm", options: { ...opts, modelFile: "" }, apiKeys: ["k1-1234567890123456", "k2-1234567890123456"] });
|
||||
assert.deepEqual(two.args.slice(two.args.indexOf("--api-key"), two.args.indexOf("--api-key") + 3), ["--api-key", "k1-1234567890123456", "k2-1234567890123456"]);
|
||||
|
||||
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
|
||||
assert.equal(off.env.LLAMA_API_KEY, undefined);
|
||||
});
|
||||
|
||||
it("adds GPU flags only on GPU runtimes", () => {
|
||||
const model = { repoId: "a/b", localPath: "a/b" };
|
||||
const options = { modelFile: "m.gguf", contextSize: 4096, gpuLayers: "all", splitMode: "layer" as const, nCpuMoe: 8, cacheRamMb: 1024, extraArgs: [] };
|
||||
const gpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } }).args.join(" ");
|
||||
assert.match(gpu, /-cram 1024 -ngl all -sm layer -ncmoe 8 --metrics/);
|
||||
const cpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [] } }).args.join(" ");
|
||||
assert.ok(cpu.includes("-cram 1024") && !cpu.includes("-ngl") && !cpu.includes("-ncmoe"));
|
||||
const auto = buildCommand({ engine: "llama.cpp", model, options: { ...options, gpuLayers: "auto" }, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } });
|
||||
assert.ok(!auto.args.includes("-ngl"));
|
||||
|
||||
const vllm = buildCommand({
|
||||
engine: "vllm",
|
||||
model,
|
||||
options: { modelFile: "", contextSize: 4096, tensorParallel: 2, gpuMemoryUtilization: 0.85, kvCacheGb: 4, extraArgs: [] },
|
||||
runtime: { env: {}, extraArgs: [], accelerator: "nvidia" },
|
||||
});
|
||||
assert.match(vllm.args.join(" "), /--tensor-parallel-size 2 --gpu-memory-utilization 0.85/);
|
||||
assert.equal(vllm.env.VLLM_CPU_KVCACHE_SPACE, undefined);
|
||||
});
|
||||
|
||||
it("counts the prompt cache and KV cache in the llama.cpp memory estimate", () => {
|
||||
const file = 400 * 2 ** 20;
|
||||
const small = estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024 });
|
||||
const unset = estimateMemoryMb(file, 4096, "llama.cpp", {});
|
||||
assert.ok(small > 2048 && small < 3072, String(small));
|
||||
assert.equal(unset - small, 8192 - 1024);
|
||||
assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }) < small);
|
||||
assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, accelerator: "nvidia" }) < small);
|
||||
});
|
||||
});
|
||||
@@ -1,182 +0,0 @@
|
||||
// Container command lines for deployments, per engine type. Pure: used by the worker to start
|
||||
// containers and by the UI for the live preview. Flags verified against llama.cpp build 11429
|
||||
// (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`).
|
||||
|
||||
import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
/** Where the models folder is mounted inside every runtime container (read-only). */
|
||||
export const CONTAINER_MODELS_DIR = "/models";
|
||||
|
||||
export const ENGINE_PORT: Record<RuntimeEngine, number> = { "llama.cpp": 8080, vllm: 8000 };
|
||||
|
||||
export type CommandInput = {
|
||||
engine: RuntimeEngine;
|
||||
options: DeploymentOptions;
|
||||
model: { repoId: string; localPath: string };
|
||||
/** `accelerator` unset: CPU. */
|
||||
runtime: { env: Record<string, string>; extraArgs: string[]; accelerator?: RuntimeAccelerator };
|
||||
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
|
||||
apiKeys?: string[];
|
||||
};
|
||||
|
||||
/** Stands in for key values in everything Kaname shows or stores. */
|
||||
export const API_KEY_PLACEHOLDER = "<api-key>";
|
||||
|
||||
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
|
||||
|
||||
const inModels = (localPath: string, file?: string | null) =>
|
||||
[CONTAINER_MODELS_DIR, localPath, file].filter(Boolean).join("/").replace(/\/+/g, "/");
|
||||
|
||||
const num = (flag: string, v: number | null | undefined) => (v != null && Number.isFinite(v) ? [flag, String(v)] : []);
|
||||
const str = (flag: string, v: string | null | undefined) => (v ? [flag, v] : []);
|
||||
|
||||
/** `args` without `flag` ("--flag value" or "--flag=value"). */
|
||||
function withoutFlag(args: string[], flag: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
if (args[i] === flag) i++;
|
||||
else if (!args[i].startsWith(`${flag}=`)) out.push(args[i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
|
||||
const port = ENGINE_PORT[engine];
|
||||
const keys = o.requireApiKey ? apiKeys : [];
|
||||
const gpu = !!runtime.accelerator && runtime.accelerator !== "cpu";
|
||||
if (engine === "llama.cpp") {
|
||||
// The image's entrypoint is llama-server, so these are its arguments.
|
||||
const args = [
|
||||
"-m",
|
||||
inModels(model.localPath, o.modelFile),
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--port",
|
||||
String(port),
|
||||
"-a",
|
||||
model.repoId,
|
||||
...num("-c", o.contextSize),
|
||||
...num("-t", o.threads),
|
||||
...num("-tb", o.threads),
|
||||
...num("-b", o.batchSize),
|
||||
...num("-ub", o.ubatchSize),
|
||||
...num("-np", o.parallel),
|
||||
...str("-ctk", o.cacheTypeK),
|
||||
...str("-ctv", o.cacheTypeV),
|
||||
...str("-fa", o.flashAttn),
|
||||
...num("-cram", o.cacheRamMb),
|
||||
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
|
||||
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
|
||||
...(o.webui === false ? ["--no-webui"] : []),
|
||||
// GPU offload (-ngl defaults to "auto", which fits layers into free VRAM).
|
||||
...(gpu ? str("-ngl", o.gpuLayers && o.gpuLayers !== "auto" ? o.gpuLayers : null) : []),
|
||||
...(gpu ? str("-sm", o.splitMode) : []),
|
||||
...(gpu ? str("-ts", o.tensorSplit) : []),
|
||||
...(gpu && o.cpuMoe ? ["-cmoe"] : []),
|
||||
...(gpu && !o.cpuMoe ? num("-ncmoe", o.nCpuMoe) : []),
|
||||
"--metrics",
|
||||
...runtime.extraArgs,
|
||||
...o.extraArgs,
|
||||
];
|
||||
// Via the environment, not the command line; several keys as one comma-separated list.
|
||||
const env = { ...runtime.env, ...(keys.length ? { LLAMA_API_KEY: keys.join(",") } : {}) };
|
||||
return { args, env, port };
|
||||
}
|
||||
|
||||
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
|
||||
const env = { ...runtime.env };
|
||||
if (!gpu && o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
|
||||
// VLLM_API_KEY holds a single key; more than one needs --api-key.
|
||||
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
|
||||
const args = [
|
||||
inModels(model.localPath, o.modelFile || null),
|
||||
"--host",
|
||||
"0.0.0.0",
|
||||
"--port",
|
||||
String(port),
|
||||
"--served-model-name",
|
||||
model.repoId,
|
||||
...num("--max-model-len", o.contextSize),
|
||||
...num("--max-num-seqs", o.maxNumSeqs),
|
||||
...(gpu ? num("--tensor-parallel-size", o.tensorParallel) : []),
|
||||
...(gpu ? num("--gpu-memory-utilization", o.gpuMemoryUtilization) : []),
|
||||
...(keys.length > 1 ? ["--api-key", ...keys] : []),
|
||||
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
|
||||
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
|
||||
...str("--dtype", o.dtype),
|
||||
...o.extraArgs,
|
||||
];
|
||||
return { args, env, port };
|
||||
}
|
||||
|
||||
/** The command with every key replaced by {@link API_KEY_PLACEHOLDER}. */
|
||||
export function redactCommand(cmd: ContainerCommand, keys: string[]): ContainerCommand {
|
||||
const hide = (v: string) => keys.filter(Boolean).reduce((acc, k) => acc.split(k).join(API_KEY_PLACEHOLDER), v);
|
||||
return { ...cmd, args: cmd.args.map(hide), env: Object.fromEntries(Object.entries(cmd.env).map(([k, v]) => [k, hide(v)])) };
|
||||
}
|
||||
|
||||
/** Shell-style rendering for display ("docker run … image args"). */
|
||||
export function renderCommand(image: string, cmd: ContainerCommand): string {
|
||||
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
||||
const env = Object.entries(cmd.env).map(([k, v]) => `-e ${q(`${k}=${v}`)}`);
|
||||
return ["docker run", ...env, `-v <models>:${CONTAINER_MODELS_DIR}:ro`, q(image), ...cmd.args.map(q)].join(" ");
|
||||
}
|
||||
|
||||
/** Rough memory need: model files plus KV cache and runtime overhead. */
|
||||
/** llama-server's default --cache-ram (MiB): prompts kept in RAM for reuse. */
|
||||
export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192;
|
||||
|
||||
const KV_TYPE_FACTOR: Record<string, number> = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 };
|
||||
|
||||
/** llama.cpp KV cache in MiB for a model of `modelMb`: the per-token heuristic below, scaled by the cache type. */
|
||||
function kvCacheMb(modelMb: number, contextSize: number, o: Pick<DeploymentOptions, "cacheTypeK" | "cacheTypeV">): number {
|
||||
const perTokenKiB = 96 + 24 * Math.sqrt(modelMb / 1024);
|
||||
const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
|
||||
return (contextSize * perTokenKiB * kvFactor) / 1024;
|
||||
}
|
||||
|
||||
/** llama.cpp compute buffers and runtime state on the GPU (measured order of magnitude, not exact). */
|
||||
const GPU_OVERHEAD_MB = 1024;
|
||||
|
||||
/**
|
||||
* Rough VRAM need of a GPU deployment in MiB, for NVIDIA and Intel/AMD (/dev/dri) alike; null when it
|
||||
* can't be told without reading the model (only some layers or the MoE experts offloaded).
|
||||
* - vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU's VRAM up front.
|
||||
* - llama.cpp with all layers on the GPU ("auto" fits as many as there is room for): weights + KV
|
||||
* cache + compute buffers.
|
||||
*/
|
||||
export function estimateVramMb(
|
||||
fileBytes: number,
|
||||
contextSize: number,
|
||||
engine: RuntimeEngine,
|
||||
o: Pick<DeploymentOptions, "gpuLayers" | "cacheTypeK" | "cacheTypeV" | "cpuMoe" | "nCpuMoe" | "gpuMemoryUtilization">,
|
||||
vramTotalMb: number | null,
|
||||
): number | null {
|
||||
if (engine === "vllm") return vramTotalMb ? Math.ceil(vramTotalMb * (o.gpuMemoryUtilization ?? 0.9)) : null;
|
||||
const layers = o.gpuLayers ?? "auto";
|
||||
if ((layers !== "auto" && layers !== "all") || o.cpuMoe || (o.nCpuMoe ?? 0) > 0) return null;
|
||||
const model = fileBytes / 2 ** 20;
|
||||
return Math.ceil(model + kvCacheMb(model, contextSize, o) + GPU_OVERHEAD_MB);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size
|
||||
* per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA.
|
||||
* Measured (llama.cpp b11429, Qwen3-0.6B Q4_K_M, ctx 4096): ~1.2 GiB without the prompt cache.
|
||||
*/
|
||||
export function estimateMemoryMb(
|
||||
fileBytes: number,
|
||||
contextSize: number,
|
||||
engine: RuntimeEngine,
|
||||
o: Pick<DeploymentOptions, "kvCacheGb" | "cacheRamMb" | "cacheTypeK" | "cacheTypeV"> & { accelerator?: RuntimeAccelerator } = {},
|
||||
): number {
|
||||
const model = fileBytes / 2 ** 20;
|
||||
const gpu = !!o.accelerator && o.accelerator !== "cpu";
|
||||
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
|
||||
// On a GPU the weights and KV cache live in VRAM; RAM holds the processes.
|
||||
if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072);
|
||||
const kv = kvCacheMb(model, contextSize, o);
|
||||
const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb;
|
||||
// The memory-mapped model counts against the container's limit (page cache), even when offloaded.
|
||||
return Math.ceil(model + (gpu ? 0 : kv) + cache + 768);
|
||||
}
|
||||
@@ -1,367 +0,0 @@
|
||||
import "server-only";
|
||||
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { apiKeys, deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
|
||||
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
|
||||
export class DeploymentError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "busy",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const int = (min: number, max: number) => z.number().int().min(min).max(max);
|
||||
|
||||
export const DeploymentBody = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
runtimeId: z.string().min(1),
|
||||
modelId: z.string().min(1),
|
||||
options: z.object({
|
||||
modelFile: z.string().max(1024),
|
||||
mmproj: z.string().max(1024).nullable().optional(),
|
||||
draftFile: z.string().max(1024).nullable().optional(),
|
||||
draftType: z.enum(["draft-mtp", "draft-simple"]).nullable().optional(),
|
||||
contextSize: int(128, 1_048_576),
|
||||
threads: int(1, 1024).nullable().optional(),
|
||||
batchSize: int(1, 65_536).nullable().optional(),
|
||||
ubatchSize: int(1, 65_536).nullable().optional(),
|
||||
parallel: int(1, 256).nullable().optional(),
|
||||
cacheTypeK: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
|
||||
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
|
||||
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
|
||||
webui: z.boolean().nullable().optional(),
|
||||
requireApiKey: z.boolean().nullable().optional(),
|
||||
cacheRamMb: int(-1, 1_048_576).nullable().optional(),
|
||||
gpus: z.array(z.string().regex(/^GPU-[0-9a-f-]{36}$/i, "a GPU UUID")).max(64).nullable().optional(),
|
||||
gpuLayers: z
|
||||
.string()
|
||||
.regex(/^(auto|all|\d{1,4})$/, "auto, all or a number")
|
||||
.nullable()
|
||||
.optional(),
|
||||
splitMode: z.enum(["none", "layer", "row", "tensor"]).nullable().optional(),
|
||||
tensorSplit: z
|
||||
.string()
|
||||
.regex(/^\d+(\.\d+)?(,\d+(\.\d+)?)*$/, "proportions like 3,1")
|
||||
.nullable()
|
||||
.optional(),
|
||||
cpuMoe: z.boolean().nullable().optional(),
|
||||
nCpuMoe: int(0, 1000).nullable().optional(),
|
||||
tensorParallel: int(1, 64).nullable().optional(),
|
||||
gpuMemoryUtilization: z.number().min(0.05).max(1).nullable().optional(),
|
||||
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
|
||||
maxNumSeqs: int(1, 1024).nullable().optional(),
|
||||
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
|
||||
extraArgs: z.array(z.string().max(4000).refine((a) => !/[\r\n\0]/.test(a), "single line")).max(100),
|
||||
}),
|
||||
cpus: z.number().min(0.1).max(1024).nullable().optional(),
|
||||
memoryMb: int(256, 4_194_304).nullable().optional(),
|
||||
hostPort: int(1024, 65_535).nullable().optional(),
|
||||
});
|
||||
export type DeploymentInput = z.infer<typeof DeploymentBody>;
|
||||
|
||||
/** Downloaded files of a model (selected and on disk). */
|
||||
async function localFiles(modelId: string) {
|
||||
return db()
|
||||
.select({ path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
|
||||
}
|
||||
|
||||
export type DeployableModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
|
||||
|
||||
/** Library models with something a runtime can serve. */
|
||||
export async function listDeployableModels(): Promise<DeployableModel[]> {
|
||||
const rows = await db().select({ id: models.id, repoId: models.repoId, localPath: models.localPath }).from(models).orderBy(asc(models.repoId));
|
||||
const files = await db()
|
||||
.select({ modelId: modelFiles.modelId, path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
|
||||
const byModel = new Map<string, { path: string; size: number }[]>();
|
||||
for (const f of files) byModel.set(f.modelId, [...(byModel.get(f.modelId) ?? []), f]);
|
||||
return rows
|
||||
.map((m) => ({ ...m, candidates: modelCandidates(byModel.get(m.id) ?? []) }))
|
||||
.filter((m) => m.candidates.gguf.length > 0 || m.candidates.vllm);
|
||||
}
|
||||
|
||||
/** Bytes of the files a deployment loads (llama.cpp: the GGUF, mmproj and draft; vLLM: the repo's files). */
|
||||
export async function deploymentFileBytes(modelId: string, options: Pick<DeploymentOptions, "modelFile" | "mmproj" | "draftFile">, engine: "llama.cpp" | "vllm"): Promise<number> {
|
||||
const files = await localFiles(modelId);
|
||||
if (engine === "vllm") return modelCandidates(files).vllm?.size ?? files.reduce((s, f) => s + f.size, 0);
|
||||
const want = [options.modelFile, options.mmproj, options.draftFile].filter(Boolean);
|
||||
// A split GGUF is named by its first part; the other parts belong to it.
|
||||
const first = files.find((f) => f.path === options.modelFile);
|
||||
const group = first ? quantGroup(first.path) : null;
|
||||
return files
|
||||
.filter((f) => want.includes(f.path) || (group != null && f.path !== options.modelFile && quantGroup(f.path) === group && f.path.toLowerCase().endsWith(".gguf") && !f.path.toLowerCase().includes("mmproj")))
|
||||
.reduce((s, f) => s + f.size, 0);
|
||||
}
|
||||
|
||||
/** Check that runtime, model and files fit together; returns normalized options. */
|
||||
export async function validateDeployment(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
|
||||
const runtime = await db().query.runtimes.findFirst({ where: eq(runtimes.id, input.runtimeId) });
|
||||
if (!runtime) throw new DeploymentError("invalid", "Runtime not found.", 400);
|
||||
const model = await db().query.models.findFirst({ where: eq(models.id, input.modelId) });
|
||||
if (!model) throw new DeploymentError("invalid", "Model not found.", 400);
|
||||
const c = modelCandidates(await localFiles(model.id));
|
||||
if (!servableBy(c, runtime.engine)) {
|
||||
throw new DeploymentError("invalid", `${model.repoId} has no downloaded files ${runtime.name} can serve.`, 400);
|
||||
}
|
||||
const o = input.options;
|
||||
const options: DeploymentOptions = { ...o, extraArgs: o.extraArgs.map((a) => a.trim()).filter(Boolean) };
|
||||
if (runtime.engine === "llama.cpp") {
|
||||
if (!c.gguf.some((g) => g.path === o.modelFile)) throw new DeploymentError("invalid", "Pick one of the model's downloaded GGUF files.", 400);
|
||||
if (o.mmproj && !c.mmproj.some((m) => m.path === o.mmproj)) throw new DeploymentError("invalid", "Unknown mmproj file.", 400);
|
||||
const draft = o.draftFile ? c.drafts.find((d) => d.path === o.draftFile) : null;
|
||||
if (o.draftFile && !draft) throw new DeploymentError("invalid", "Unknown draft/MTP file.", 400);
|
||||
options.draftType = draft?.type ?? null;
|
||||
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null, tensorParallel: null, gpuMemoryUtilization: null });
|
||||
} else {
|
||||
Object.assign(options, {
|
||||
modelFile: "",
|
||||
mmproj: null,
|
||||
draftFile: null,
|
||||
draftType: null,
|
||||
batchSize: null,
|
||||
ubatchSize: null,
|
||||
cacheTypeK: null,
|
||||
cacheTypeV: null,
|
||||
flashAttn: null,
|
||||
webui: null,
|
||||
cacheRamMb: null,
|
||||
gpuLayers: null,
|
||||
splitMode: null,
|
||||
tensorSplit: null,
|
||||
cpuMoe: null,
|
||||
nCpuMoe: null,
|
||||
});
|
||||
}
|
||||
// GPU settings only mean something on a GPU runtime; GPU picking only on NVIDIA.
|
||||
if (runtime.accelerator === "cpu") {
|
||||
Object.assign(options, { gpus: null, gpuLayers: null, splitMode: null, tensorSplit: null, cpuMoe: null, nCpuMoe: null, tensorParallel: null, gpuMemoryUtilization: null });
|
||||
} else {
|
||||
if (runtime.accelerator !== "nvidia") options.gpus = null;
|
||||
options.kvCacheGb = null;
|
||||
}
|
||||
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
|
||||
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
|
||||
}
|
||||
if (input.hostPort) {
|
||||
const clash = await db().query.deployments.findFirst({
|
||||
columns: { name: true },
|
||||
where: and(eq(deployments.hostPort, input.hostPort), selfId ? ne(deployments.id, selfId) : undefined, isNull(deployments.deleteRequestedAt)),
|
||||
});
|
||||
if (clash) throw new DeploymentError("invalid", `Port ${input.hostPort} is already used by "${clash.name}".`, 409);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
export async function createDeployment(
|
||||
input: DeploymentInput,
|
||||
startNow: boolean,
|
||||
agent?: { requestedBy: { tokenId: string; name: string }; startPendingApproval: boolean },
|
||||
) {
|
||||
const options = await validateDeployment(input);
|
||||
const [row] = await db()
|
||||
.insert(deployments)
|
||||
.values({
|
||||
name: input.name,
|
||||
runtimeId: input.runtimeId,
|
||||
modelId: input.modelId,
|
||||
options,
|
||||
cpus: input.cpus ?? null,
|
||||
memoryMb: input.memoryMb ?? null,
|
||||
hostPort: input.hostPort ?? null,
|
||||
desiredState: startNow && !agent?.startPendingApproval ? "running" : "stopped",
|
||||
...(agent
|
||||
? { requestedByTokenId: agent.requestedBy.tokenId, requestedBy: agent.requestedBy.name, startRequestedAt: startNow && agent.startPendingApproval ? new Date() : null }
|
||||
: {}),
|
||||
})
|
||||
.returning({ id: deployments.id });
|
||||
return row;
|
||||
}
|
||||
|
||||
async function get(id: string) {
|
||||
const d = await db().query.deployments.findFirst({ where: and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)) });
|
||||
if (!d) throw new DeploymentError("not_found", "Deployment not found.", 404);
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Change launch options; only while stopped (a running container keeps its command). */
|
||||
export async function updateDeployment(id: string, input: DeploymentInput) {
|
||||
const d = await get(id);
|
||||
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment before changing it.", 409);
|
||||
const options = await validateDeployment(input, id);
|
||||
await db()
|
||||
.update(deployments)
|
||||
.set({
|
||||
name: input.name,
|
||||
runtimeId: input.runtimeId,
|
||||
modelId: input.modelId,
|
||||
options,
|
||||
cpus: input.cpus ?? null,
|
||||
memoryMb: input.memoryMb ?? null,
|
||||
hostPort: input.hostPort ?? null,
|
||||
})
|
||||
.where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
export async function setDesiredState(id: string, desired: "running" | "stopped") {
|
||||
const d = await get(id);
|
||||
if (d.desiredState === desired && !d.startRequestedAt) return;
|
||||
await db()
|
||||
.update(deployments)
|
||||
// Starting or stopping it by hand settles a start an agent asked for.
|
||||
.set({ desiredState: desired, startRequestedAt: null, ...(desired === "running" ? { error: null } : {}) })
|
||||
.where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
/** Mark a deployment as protected: agents can't touch it or crowd it out of VRAM. */
|
||||
export async function setProtected(id: string, value: boolean) {
|
||||
await get(id);
|
||||
await db().update(deployments).set({ protected: value }).where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
/** Turn down a start an agent asked for (the deployment stays stopped). */
|
||||
export async function rejectStart(id: string) {
|
||||
const d = await get(id);
|
||||
if (!d.startRequestedAt) throw new DeploymentError("invalid", "This deployment doesn't wait for a start approval.", 409);
|
||||
await db().update(deployments).set({ startRequestedAt: null }).where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
/** The worker stops the container and deletes the row. */
|
||||
export async function requestDelete(id: string) {
|
||||
await get(id);
|
||||
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
const listColumns = {
|
||||
id: deployments.id,
|
||||
name: deployments.name,
|
||||
state: deployments.state,
|
||||
desiredState: deployments.desiredState,
|
||||
options: deployments.options,
|
||||
cpus: deployments.cpus,
|
||||
memoryMb: deployments.memoryMb,
|
||||
hostPort: deployments.hostPort,
|
||||
containerName: deployments.containerName,
|
||||
command: deployments.command,
|
||||
startedAt: deployments.startedAt,
|
||||
readyAt: deployments.readyAt,
|
||||
stoppedAt: deployments.stoppedAt,
|
||||
exitCode: deployments.exitCode,
|
||||
error: deployments.error,
|
||||
stats: deployments.stats,
|
||||
createdAt: deployments.createdAt,
|
||||
runtimeId: deployments.runtimeId,
|
||||
runtimeName: runtimes.name,
|
||||
runtimeImage: runtimes.image,
|
||||
accelerator: runtimes.accelerator,
|
||||
sweepId: deployments.sweepId,
|
||||
protected: deployments.protected,
|
||||
requestedBy: deployments.requestedBy,
|
||||
requestedByTokenId: deployments.requestedByTokenId,
|
||||
startRequestedAt: deployments.startRequestedAt,
|
||||
engineInfo: deployments.engineInfo,
|
||||
engine: runtimes.engine,
|
||||
modelId: deployments.modelId,
|
||||
repoId: models.repoId,
|
||||
};
|
||||
|
||||
export type DeploymentRow = Awaited<ReturnType<typeof listDeployments>>[number];
|
||||
|
||||
export async function listDeployments() {
|
||||
return db()
|
||||
.select(listColumns)
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.innerJoin(models, eq(models.id, deployments.modelId))
|
||||
.where(isNull(deployments.deleteRequestedAt))
|
||||
.orderBy(desc(deployments.createdAt));
|
||||
}
|
||||
|
||||
export async function getDeployment(id: string) {
|
||||
const [row] = await db()
|
||||
.select(listColumns)
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.innerJoin(models, eq(models.id, deployments.modelId))
|
||||
.where(and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)));
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function listDeploymentLogs(id: string, afterId: number, tail = 500) {
|
||||
const rows =
|
||||
afterId > 0
|
||||
? await db()
|
||||
.select()
|
||||
.from(deploymentLogs)
|
||||
.where(and(eq(deploymentLogs.deploymentId, id), gt(deploymentLogs.id, afterId)))
|
||||
.orderBy(asc(deploymentLogs.id))
|
||||
.limit(2000)
|
||||
: (
|
||||
await db().select().from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(tail)
|
||||
).reverse();
|
||||
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
|
||||
}
|
||||
|
||||
/** Deployments that use a model or runtime (deleting those is refused while any exist). */
|
||||
export async function deploymentsUsing(by: { modelId?: string; runtimeId?: string }) {
|
||||
return db()
|
||||
.select({ id: deployments.id, name: deployments.name })
|
||||
.from(deployments)
|
||||
.where(
|
||||
and(
|
||||
isNull(deployments.deleteRequestedAt),
|
||||
by.modelId ? eq(deployments.modelId, by.modelId) : undefined,
|
||||
by.runtimeId ? eq(deployments.runtimeId, by.runtimeId) : undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export type ModelDeployment = { id: string; name: string; state: DeploymentRow["state"]; desiredState: DeploymentRow["desiredState"]; runtimeName: string };
|
||||
|
||||
/** Deployments per model id (for links from the library and model pages). */
|
||||
export async function deploymentsByModel(): Promise<Map<string, ModelDeployment[]>> {
|
||||
const rows = await db()
|
||||
.select({
|
||||
modelId: deployments.modelId,
|
||||
id: deployments.id,
|
||||
name: deployments.name,
|
||||
state: deployments.state,
|
||||
desiredState: deployments.desiredState,
|
||||
runtimeName: runtimes.name,
|
||||
})
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(isNull(deployments.deleteRequestedAt))
|
||||
.orderBy(asc(deployments.name));
|
||||
const out = new Map<string, ModelDeployment[]>();
|
||||
for (const { modelId, ...d } of rows) out.set(modelId, [...(out.get(modelId) ?? []), d]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Form defaults for "Deploy" from the library: the first runtime with a pulled image that can serve the model. */
|
||||
export async function deployPreset(modelId: string) {
|
||||
const model = (await listDeployableModels()).find((m) => m.id === modelId);
|
||||
if (!model) return null;
|
||||
const rts = await db().select({ id: runtimes.id, engine: runtimes.engine }).from(runtimes).where(eq(runtimes.imageState, "present")).orderBy(asc(runtimes.createdAt));
|
||||
const runtime = rts.find((r) => servableBy(model.candidates, r.engine));
|
||||
if (!runtime) return null;
|
||||
const gguf = runtime.engine === "llama.cpp" ? model.candidates.gguf[0] : undefined;
|
||||
const quant = gguf ? quantGroup(gguf.path) : null;
|
||||
return {
|
||||
name: `${model.repoId.split("/")[1]}${quant ? ` ${quant}` : ""}`,
|
||||
runtimeId: runtime.id,
|
||||
modelId: model.id,
|
||||
options: { modelFile: gguf?.path ?? "", mmproj: gguf ? (model.candidates.mmproj[0]?.path ?? null) : null, contextSize: 4096, extraArgs: [] },
|
||||
cpus: null,
|
||||
memoryMb: null,
|
||||
hostPort: null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
import { detectEngine, normalizeBaseUrl, pickModel, probeEndpoint } from "./endpoint-probe";
|
||||
|
||||
describe("endpoint URLs", () => {
|
||||
it("keeps the server root and drops /v1 and slashes", () => {
|
||||
assert.equal(normalizeBaseUrl(" http://192.168.1.20:8080/v1/ "), "http://192.168.1.20:8080");
|
||||
assert.equal(normalizeBaseUrl("https://llm.example.org/proxy/v1"), "https://llm.example.org/proxy");
|
||||
assert.equal(normalizeBaseUrl("http://box:8000"), "http://box:8000");
|
||||
});
|
||||
|
||||
it("refuses other schemes, credentials in the URL and queries", () => {
|
||||
assert.throws(() => normalizeBaseUrl("ftp://box"), /http/);
|
||||
assert.throws(() => normalizeBaseUrl("http://user:secret@box:8080"), /API key/);
|
||||
assert.throws(() => normalizeBaseUrl("http://box:8080/?key=1"), /query/);
|
||||
assert.throws(() => normalizeBaseUrl("box:8080 x"), /URL/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("engine detection", () => {
|
||||
it("tells llama.cpp, vLLM, SGLang and Ollama apart", () => {
|
||||
const none = { props: null, version: null, sglang: null, ollama: null, models: null };
|
||||
assert.equal(detectEngine({ ...none, props: { build_info: "b6123-abc", default_generation_settings: {} } }), "llama.cpp");
|
||||
assert.equal(detectEngine({ ...none, models: { data: [{ id: "Qwen/Qwen3-8B", owned_by: "vllm" }] } }), "vllm");
|
||||
assert.equal(detectEngine({ ...none, version: { version: "0.31.0" } }), "vllm");
|
||||
assert.equal(detectEngine({ ...none, sglang: { version: "0.5.0" }, version: { version: "0.5.0" } }), "sglang");
|
||||
assert.equal(detectEngine({ ...none, ollama: { version: "0.12.0" }, version: { version: "x" } }), "ollama");
|
||||
assert.equal(detectEngine(none), null);
|
||||
});
|
||||
});
|
||||
|
||||
describe("probing a server", () => {
|
||||
let server: Server;
|
||||
let base = "";
|
||||
const seen: { url: string; auth: string | undefined }[] = [];
|
||||
before(async () => {
|
||||
server = createServer((req, res) => {
|
||||
seen.push({ url: req.url!, auth: req.headers.authorization });
|
||||
const json = (status: number, v: unknown) => {
|
||||
res.writeHead(status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(v));
|
||||
};
|
||||
if (req.headers.authorization !== "Bearer sk-test") return json(401, { error: "no" });
|
||||
if (req.url === "/v1/models") return json(200, { data: [{ id: "Qwen3-8B-Q4_K_M.gguf", owned_by: "llamacpp" }] });
|
||||
if (req.url === "/props") return json(200, { build_info: "b6123-d812350", total_slots: 4, default_generation_settings: { n_ctx: 32768 } });
|
||||
if (req.url === "/redirect") {
|
||||
res.writeHead(302, { Location: "http://example.org/" });
|
||||
return res.end();
|
||||
}
|
||||
return json(404, {});
|
||||
});
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
after(() => server.close());
|
||||
|
||||
it("reads models, engine, version, context and slots, with the key as a bearer token", async () => {
|
||||
const p = await probeEndpoint({ baseUrl: base, apiKey: "sk-test", engine: null });
|
||||
assert.equal(p.ok, true);
|
||||
assert.deepEqual(p.models, ["Qwen3-8B-Q4_K_M.gguf"]);
|
||||
assert.equal(p.engine, "llama.cpp");
|
||||
assert.equal(p.engineVersion, "b6123-d812350");
|
||||
assert.equal(p.contextSize, 32768);
|
||||
assert.equal(p.slots, 4);
|
||||
assert.ok(seen.every((s) => s.auth === "Bearer sk-test"));
|
||||
assert.ok(seen.every((s) => !s.url.includes("sk-test")), "the key never goes into a URL");
|
||||
});
|
||||
|
||||
it("explains a refused key and an unreachable server", async () => {
|
||||
const refused = await probeEndpoint({ baseUrl: base, apiKey: "wrong", engine: null });
|
||||
assert.equal(refused.ok, false);
|
||||
assert.match(refused.error!, /API key/);
|
||||
const down = await probeEndpoint({ baseUrl: "http://127.0.0.1:9", apiKey: null, engine: null });
|
||||
assert.equal(down.ok, false);
|
||||
assert.match(down.error!, /Couldn't reach/);
|
||||
});
|
||||
|
||||
it("picks the model to run", () => {
|
||||
const probe = { ok: true, at: "", error: null, latencyMs: 1, models: ["a", "b"], engine: null, engineVersion: null, contextSize: null, slots: null };
|
||||
assert.deepEqual(pickModel("b", probe), { model: "b" });
|
||||
assert.match((pickModel("c", probe) as { error: string }).error, /doesn't list "c"/);
|
||||
assert.match((pickModel(null, probe) as { error: string }).error, /several models/);
|
||||
assert.deepEqual(pickModel(null, { ...probe, models: ["a"] }), { model: "a" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("login gate", () => {
|
||||
// proxy.ts gates every page and API route except Auth.js, the login page and static files.
|
||||
const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");
|
||||
const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string;
|
||||
const gated = (path: string) => new RegExp(`^${matcher}$`).test(path);
|
||||
|
||||
it("gates every API route, including the old token API paths", () => {
|
||||
for (const p of ["/api/endpoints", "/api/endpoints/x/test", "/api/benchmarks", "/api/v1", "/api/v1/models", "/settings", "/loginx", "/"]) assert.ok(gated(p), p);
|
||||
for (const p of ["/api/auth/signin", "/login", "/_next/static/x.js", "/favicon.ico"]) assert.ok(!gated(p), p);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
// What an OpenAI-compatible server says about itself: the models it serves (/v1/models), and where it
|
||||
// tells, the engine, version, context and slots. Shared by the web app ("Test connection") and the
|
||||
// worker (checked again before every run). The API key goes only into the Authorization header.
|
||||
//
|
||||
// llama.cpp GET /props: build_info "b11429-d81235049", total_slots, default_generation_settings.n_ctx
|
||||
// vLLM GET /version {"version"}; /v1/models data[].max_model_len, owned_by "vllm"
|
||||
// SGLang GET /get_server_info {"version", "context_length"?}
|
||||
// Ollama GET /api/version {"version"}
|
||||
|
||||
import type { EndpointEngine, EndpointProbe } 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 class EndpointUrlError extends Error {}
|
||||
|
||||
/**
|
||||
* The server root from what the user typed: "http://box:8080/v1/" → "http://box:8080". Only http(s),
|
||||
* no credentials in the URL (the API key has its own field).
|
||||
*/
|
||||
export function normalizeBaseUrl(input: string): string {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(input.trim());
|
||||
} catch {
|
||||
throw new EndpointUrlError("Enter the server's URL, e.g. http://192.168.1.20:8080.");
|
||||
}
|
||||
if (u.protocol !== "http:" && u.protocol !== "https:") throw new EndpointUrlError("The URL must start with http:// or https://.");
|
||||
if (u.username || u.password) throw new EndpointUrlError("Put the API key in its own field, not into the URL.");
|
||||
if (u.search || u.hash) throw new EndpointUrlError("The URL can't have a query or fragment.");
|
||||
const path = u.pathname.replace(/\/+$/, "").replace(/\/v1$/, "");
|
||||
return `${u.origin}${path}`;
|
||||
}
|
||||
|
||||
export function parseLlamaProps(props: Json | null) {
|
||||
const gen = (props?.default_generation_settings ?? {}) as Json;
|
||||
return { version: str(props?.build_info), slots: int(props?.total_slots), contextSize: int(gen.n_ctx) };
|
||||
}
|
||||
|
||||
/** Model names from /v1/models (OpenAI format; llama.cpp also has `models[].name`). */
|
||||
export function modelNames(models: Json | null): string[] {
|
||||
const data = Array.isArray(models?.data) ? (models.data as Json[]) : [];
|
||||
return [...new Set(data.map((m) => str(m.id)).filter((x): x is string => !!x))].slice(0, 200);
|
||||
}
|
||||
|
||||
export function detectEngine(x: { props: Json | null; version: Json | null; sglang: Json | null; ollama: Json | null; models: Json | null }): EndpointEngine | null {
|
||||
if (x.props && ("default_generation_settings" in x.props || "build_info" in x.props)) return "llama.cpp";
|
||||
const data = Array.isArray(x.models?.data) ? (x.models.data as Json[]) : [];
|
||||
if (data.some((m) => m.owned_by === "vllm")) return "vllm";
|
||||
if (x.sglang) return "sglang";
|
||||
if (x.ollama || data.some((m) => m.owned_by === "library")) return "ollama";
|
||||
// vLLM forks may report another owner, but still answer /version.
|
||||
if (x.version && typeof x.version.version === "string") return "vllm";
|
||||
return null;
|
||||
}
|
||||
|
||||
type Fetcher = typeof fetch;
|
||||
|
||||
async function getJson(f: Fetcher, url: string, key: string | null, timeoutMs: number): Promise<{ json: Json | null; status: number | null; error: string | null }> {
|
||||
try {
|
||||
const res = await f(url, {
|
||||
headers: { Accept: "application/json", ...(key ? { Authorization: `Bearer ${key}` } : {}) },
|
||||
// A redirect could carry the key to another host.
|
||||
redirect: "error",
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (!res.ok) return { json: null, status: res.status, error: `HTTP ${res.status}` };
|
||||
const json = (await res.json().catch(() => null)) as Json | null;
|
||||
return { json: json && typeof json === "object" && !Array.isArray(json) ? json : null, status: res.status, error: null };
|
||||
} catch (err) {
|
||||
const e = err as Error & { cause?: { code?: string; message?: string } };
|
||||
const why = e.name === "TimeoutError" ? "timed out" : (e.cause?.code ?? e.cause?.message ?? e.message);
|
||||
return { json: null, status: null, error: why };
|
||||
}
|
||||
}
|
||||
|
||||
/** Ask the server; never throws. `ok` once /v1/models answers. */
|
||||
export async function probeEndpoint(
|
||||
ep: { baseUrl: string; apiKey: string | null; engine: EndpointEngine | null },
|
||||
f: Fetcher = fetch,
|
||||
): Promise<EndpointProbe> {
|
||||
const at = new Date().toISOString();
|
||||
const t0 = performance.now();
|
||||
const models = await getJson(f, `${ep.baseUrl}/v1/models`, ep.apiKey, 10_000);
|
||||
const latencyMs = Math.round(performance.now() - t0);
|
||||
if (!models.json) {
|
||||
const error =
|
||||
models.status === 401 || models.status === 403
|
||||
? `The server refused the request (HTTP ${models.status}): check the API key.`
|
||||
: models.status === 404
|
||||
? "No /v1/models here (HTTP 404): is this the server's root URL?"
|
||||
: `Couldn't reach ${ep.baseUrl}/v1/models: ${models.error ?? "no JSON answer"}.`;
|
||||
return { ok: false, at, error, latencyMs: models.status ? latencyMs : null, models: [], engine: ep.engine, engineVersion: null, contextSize: null, slots: null };
|
||||
}
|
||||
const extra = (path: string) => getJson(f, `${ep.baseUrl}${path}`, ep.apiKey, 3_000).then((r) => r.json);
|
||||
const [props, version, sglang, ollama] = await Promise.all([extra("/props"), extra("/version"), extra("/get_server_info"), extra("/api/version")]);
|
||||
const engine = ep.engine ?? detectEngine({ props, version, sglang, ollama, models: models.json });
|
||||
const data = Array.isArray(models.json.data) ? (models.json.data as Json[]) : [];
|
||||
let engineVersion: string | null = null;
|
||||
let contextSize: number | null = null;
|
||||
let slots: number | null = null;
|
||||
if (engine === "llama.cpp") ({ version: engineVersion, contextSize, slots } = parseLlamaProps(props));
|
||||
else if (engine === "vllm") {
|
||||
engineVersion = str(version?.version);
|
||||
contextSize = int(data[0]?.max_model_len);
|
||||
} else if (engine === "sglang") {
|
||||
engineVersion = str(sglang?.version);
|
||||
contextSize = int(sglang?.context_length) ?? int(data[0]?.max_model_len);
|
||||
} else if (engine === "ollama") engineVersion = str(ollama?.version);
|
||||
return { ok: true, at, error: null, latencyMs, models: modelNames(models.json), engine, engineVersion, contextSize, slots };
|
||||
}
|
||||
|
||||
/** The model to benchmark: the configured one, else the only one the server lists. */
|
||||
export function pickModel(configured: string | null, probe: EndpointProbe): { model: string } | { error: string } {
|
||||
if (configured) {
|
||||
if (probe.models.length && !probe.models.includes(configured)) {
|
||||
return { error: `The server doesn't list "${configured}" (it has: ${probe.models.slice(0, 5).join(", ")}${probe.models.length > 5 ? ", …" : ""}).` };
|
||||
}
|
||||
return { model: configured };
|
||||
}
|
||||
if (probe.models.length === 1) return { model: probe.models[0] };
|
||||
return { error: probe.models.length ? "The server lists several models; pick one for this endpoint." : "The server lists no model." };
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
// Endpoints and queuing runs against them, on a temporary SQLite database with a fake server.
|
||||
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { after, before, describe, it } from "node:test";
|
||||
import { eq } from "drizzle-orm";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "kaname-endpoints-"));
|
||||
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
|
||||
process.env.MODELS_DIR = join(dir, "models");
|
||||
|
||||
type Mods = {
|
||||
db: typeof import("./db/client");
|
||||
schema: typeof import("./db/schema");
|
||||
endpoints: typeof import("./endpoints");
|
||||
benchmarks: typeof import("./benchmarks");
|
||||
};
|
||||
let M: Mods;
|
||||
let server: Server;
|
||||
let base = "";
|
||||
const auth: (string | undefined)[] = [];
|
||||
|
||||
before(async () => {
|
||||
const { runMigrations } = await import("./db/migrate");
|
||||
await runMigrations();
|
||||
M = {
|
||||
db: await import("./db/client"),
|
||||
schema: await import("./db/schema"),
|
||||
endpoints: await import("./endpoints"),
|
||||
benchmarks: await import("./benchmarks"),
|
||||
};
|
||||
server = createServer((req, res) => {
|
||||
auth.push(req.headers.authorization);
|
||||
res.writeHead(req.url === "/v1/models" ? 200 : 404, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(req.url === "/v1/models" ? { data: [{ id: "Qwen/Qwen3-8B", owned_by: "vllm" }, { id: "Qwen/Qwen3-0.6B", owned_by: "vllm" }] } : {}));
|
||||
});
|
||||
await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
server.close();
|
||||
// Windows keeps the open database file locked; the temp folder is cleaned up eventually anyway.
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {}
|
||||
});
|
||||
|
||||
describe("endpoints", () => {
|
||||
it("never hands out the API key; edits keep, replace or remove it", async () => {
|
||||
const e = await M.endpoints.createEndpoint({ name: "box", baseUrl: `${base}/v1/`, apiKey: "sk-secret", hardware: { gpuName: "RTX 4090", gpuCount: 1, vramGb: 24, cpu: "" } });
|
||||
assert.equal(e.baseUrl, base);
|
||||
assert.equal(e.hasApiKey, true);
|
||||
assert.ok(!JSON.stringify(e).includes("sk-secret"));
|
||||
assert.deepEqual(e.hardware, { gpuName: "RTX 4090", gpuCount: 1, vramGb: 24 }, "empty fields aren't stored");
|
||||
assert.ok(!JSON.stringify(await M.endpoints.listEndpoints()).includes("sk-secret"));
|
||||
|
||||
await M.endpoints.updateEndpoint(e.id, { name: "box", baseUrl: base, hardware: {} });
|
||||
const row = await M.db.db().query.endpoints.findFirst({ where: eq(M.schema.endpoints.id, e.id) });
|
||||
assert.equal(row!.apiKey, "sk-secret", "left out: kept");
|
||||
await M.endpoints.updateEndpoint(e.id, { name: "box", baseUrl: base, apiKey: "" });
|
||||
assert.equal((await M.endpoints.getEndpoint(e.id))!.hasApiKey, false, '"": removed');
|
||||
await M.endpoints.updateEndpoint(e.id, { name: "box", baseUrl: base, apiKey: "sk-secret" });
|
||||
});
|
||||
|
||||
it("validates names, URLs and hardware notes", async () => {
|
||||
await assert.rejects(M.endpoints.createEndpoint({ name: "box", baseUrl: base }), /already exists/);
|
||||
await assert.rejects(M.endpoints.createEndpoint({ name: "x", baseUrl: "file:///etc" }), /http/);
|
||||
await assert.rejects(M.endpoints.createEndpoint({ name: "y", baseUrl: base, hardware: { gpuCount: 0 } }), /gpuCount/);
|
||||
await assert.rejects(M.endpoints.createEndpoint({ name: "z", baseUrl: base, hardware: { pcie: "very fast" } }), /Gen4 x16/);
|
||||
});
|
||||
|
||||
it("tests a form's values without sending the stored key to another URL", async () => {
|
||||
const [e] = await M.endpoints.listEndpoints();
|
||||
auth.length = 0;
|
||||
const p = await M.endpoints.testEndpoint(e.id);
|
||||
assert.equal(p.ok, true);
|
||||
assert.deepEqual(p.models, ["Qwen/Qwen3-8B", "Qwen/Qwen3-0.6B"]);
|
||||
assert.equal(p.engine, "vllm");
|
||||
assert.ok(auth.every((a) => a === "Bearer sk-secret"));
|
||||
auth.length = 0;
|
||||
await M.endpoints.testEndpoint(e.id, { name: "box", baseUrl: base.replace("127.0.0.1", "localhost") });
|
||||
assert.ok(auth.length > 0 && auth.every((a) => a === undefined), "another URL doesn't get the stored key");
|
||||
});
|
||||
});
|
||||
|
||||
describe("queuing runs", () => {
|
||||
it("needs a model when the server serves several, and records no URL or key", async () => {
|
||||
const [e] = await M.endpoints.listEndpoints();
|
||||
const body = { endpointId: e.id, quick: true, phases: [] };
|
||||
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse(body)), /several models/);
|
||||
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ ...body, model: "nope" })), /doesn't list "nope"/);
|
||||
const { id } = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ ...body, model: "Qwen/Qwen3-8B" }));
|
||||
const run = await M.benchmarks.getBenchmark(id);
|
||||
assert.equal(run!.state, "queued");
|
||||
assert.equal(run!.endpointId, e.id);
|
||||
assert.deepEqual(run!.snapshot, {
|
||||
type: "endpoint",
|
||||
endpointName: "box",
|
||||
model: "Qwen/Qwen3-8B",
|
||||
engine: "vllm",
|
||||
engineVersion: null,
|
||||
contextSize: null,
|
||||
slots: null,
|
||||
hardware: {},
|
||||
});
|
||||
assert.ok(!JSON.stringify(run).includes(base) && !JSON.stringify(run).includes("sk-secret"));
|
||||
await assert.rejects(M.endpoints.deleteEndpoint(e.id), /queued or running/);
|
||||
await M.benchmarks.cancelBenchmark(id);
|
||||
await M.endpoints.deleteEndpoint(e.id);
|
||||
assert.equal((await M.benchmarks.getBenchmark(id))!.endpointId, null, "the run stays, unlinked");
|
||||
});
|
||||
|
||||
it("refuses a run against a server that doesn't answer, and A/B between different models", async () => {
|
||||
const down = await M.endpoints.createEndpoint({ name: "down", baseUrl: "http://127.0.0.1:9" });
|
||||
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: down.id })), /Couldn't reach/);
|
||||
const a = await M.endpoints.createEndpoint({ name: "a", baseUrl: base, model: "Qwen/Qwen3-8B" });
|
||||
const b = await M.endpoints.createEndpoint({ name: "b", baseUrl: base });
|
||||
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: a.id, endpointBId: a.id })), /two different/);
|
||||
await assert.rejects(M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: a.id, model: "other" })), /doesn't list/);
|
||||
const ab = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ endpointId: a.id, endpointBId: b.id }));
|
||||
const run = await M.benchmarks.getBenchmark(ab.id);
|
||||
assert.equal(run!.kind, "ab");
|
||||
assert.equal(run!.snapshotB && "model" in run!.snapshotB ? run!.snapshotB.model : null, "Qwen/Qwen3-8B");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import "server-only";
|
||||
import { asc, eq, inArray } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { benchmarkRuns, ENDPOINT_ENGINES, type EndpointHardware, type EndpointProbe, endpoints } from "@/lib/db/schema";
|
||||
import { EndpointUrlError, normalizeBaseUrl, probeEndpoint } from "@/lib/endpoint-probe";
|
||||
|
||||
export class EndpointError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "already_exists" | "busy",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** An endpoint as the browser sees it: never the API key, only whether one is set. */
|
||||
export type EndpointView = {
|
||||
id: string;
|
||||
name: string;
|
||||
baseUrl: string;
|
||||
hasApiKey: boolean;
|
||||
model: string | null;
|
||||
engine: (typeof ENDPOINT_ENGINES)[number] | null;
|
||||
hardware: EndpointHardware;
|
||||
probe: EndpointProbe | null;
|
||||
createdAt: number;
|
||||
updatedAt: number;
|
||||
};
|
||||
|
||||
export function toView(e: typeof endpoints.$inferSelect): EndpointView {
|
||||
return {
|
||||
id: e.id,
|
||||
name: e.name,
|
||||
baseUrl: e.baseUrl,
|
||||
hasApiKey: !!e.apiKey,
|
||||
model: e.model,
|
||||
engine: e.engine,
|
||||
hardware: e.hardware,
|
||||
probe: e.probe,
|
||||
createdAt: e.createdAt.getTime(),
|
||||
updatedAt: e.updatedAt.getTime(),
|
||||
};
|
||||
}
|
||||
|
||||
const line = (max: number) =>
|
||||
z
|
||||
.string()
|
||||
.trim()
|
||||
.max(max, `at most ${max} characters`)
|
||||
.refine((v) => !/[\r\n\0]/.test(v), "one line only")
|
||||
.transform((v) => v || null)
|
||||
.nullish();
|
||||
const num = (min: number, max: number, int = false) =>
|
||||
z
|
||||
.union([z.number(), z.literal(""), z.null()])
|
||||
.optional()
|
||||
.transform((v) => (v === "" || v == null ? null : v))
|
||||
.refine((v) => v == null || (v >= min && v <= max && (!int || Number.isInteger(v))), `must be ${int ? "a whole number " : ""}between ${min} and ${max}`);
|
||||
|
||||
export const hardwareSchema = z.object({
|
||||
gpuName: line(80),
|
||||
gpuCount: num(1, 64, true),
|
||||
vramGb: num(0.5, 4096),
|
||||
pcie: line(20).refine((v) => !v || /^(?:gen\s*[1-6])?\s*(?:x\s*\d{1,2})?$/i.test(v), 'e.g. "Gen4 x16"'),
|
||||
p2p: z.enum(["on", "off", "partial"]).nullish(),
|
||||
rebar: z.boolean().nullish(),
|
||||
gpuDriver: line(80),
|
||||
cpu: line(80),
|
||||
memoryGb: num(0.5, 65_536),
|
||||
os: line(80),
|
||||
virtualization: line(80),
|
||||
engineName: line(60),
|
||||
engineVersion: line(60),
|
||||
image: line(200),
|
||||
quant: line(40),
|
||||
kvCache: line(40),
|
||||
contextSize: num(128, 100_000_000, true),
|
||||
concurrency: num(1, 4096, true),
|
||||
description: z.string().trim().max(2000, "at most 2000 characters").transform((v) => v || null).nullish(),
|
||||
});
|
||||
|
||||
const inputSchema = z.object({
|
||||
name: z.string().trim().min(1, "required").max(60, "at most 60 characters"),
|
||||
baseUrl: z.string().trim().min(1, "required").max(500),
|
||||
/** undefined: keep the stored key (edit); "" or null: remove it. */
|
||||
apiKey: z.string().trim().max(500).nullish(),
|
||||
model: line(300),
|
||||
engine: z.enum(ENDPOINT_ENGINES).nullish(),
|
||||
hardware: hardwareSchema.optional(),
|
||||
});
|
||||
export type EndpointInput = z.input<typeof inputSchema>;
|
||||
|
||||
function parse(input: unknown) {
|
||||
const r = inputSchema.safeParse(input);
|
||||
if (!r.success) {
|
||||
throw new EndpointError("invalid", r.error.issues.map((i) => `${i.path.join(".") || "input"}: ${i.message}`).join("; "), 400);
|
||||
}
|
||||
let baseUrl: string;
|
||||
try {
|
||||
baseUrl = normalizeBaseUrl(r.data.baseUrl);
|
||||
} catch (err) {
|
||||
if (err instanceof EndpointUrlError) throw new EndpointError("invalid", err.message, 400);
|
||||
throw err;
|
||||
}
|
||||
// Drop empty fields so the stored notes only hold what was entered.
|
||||
const hardware = Object.fromEntries(Object.entries(r.data.hardware ?? {}).filter(([, v]) => v != null)) as EndpointHardware;
|
||||
return { ...r.data, baseUrl, hardware };
|
||||
}
|
||||
|
||||
async function nameTaken(name: string, exceptId?: string) {
|
||||
const row = await db().query.endpoints.findFirst({ columns: { id: true }, where: eq(endpoints.name, name) });
|
||||
return !!row && row.id !== exceptId;
|
||||
}
|
||||
|
||||
export async function listEndpoints(): Promise<EndpointView[]> {
|
||||
return (await db().select().from(endpoints).orderBy(asc(endpoints.name))).map(toView);
|
||||
}
|
||||
|
||||
export async function getEndpoint(id: string): Promise<EndpointView | null> {
|
||||
const e = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) });
|
||||
return e ? toView(e) : null;
|
||||
}
|
||||
|
||||
export async function createEndpoint(input: unknown): Promise<EndpointView> {
|
||||
const v = parse(input);
|
||||
if (await nameTaken(v.name)) throw new EndpointError("already_exists", `An endpoint named "${v.name}" already exists.`, 409);
|
||||
const [row] = await db()
|
||||
.insert(endpoints)
|
||||
.values({ name: v.name, baseUrl: v.baseUrl, apiKey: v.apiKey || null, model: v.model ?? null, engine: v.engine ?? null, hardware: v.hardware })
|
||||
.returning();
|
||||
return toView(row);
|
||||
}
|
||||
|
||||
export async function updateEndpoint(id: string, input: unknown): Promise<EndpointView> {
|
||||
const existing = await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) });
|
||||
if (!existing) throw new EndpointError("not_found", "Endpoint not found.", 404);
|
||||
const v = parse(input);
|
||||
if (await nameTaken(v.name, id)) throw new EndpointError("already_exists", `An endpoint named "${v.name}" already exists.`, 409);
|
||||
const moved = v.baseUrl !== existing.baseUrl;
|
||||
const [row] = await db()
|
||||
.update(endpoints)
|
||||
.set({
|
||||
name: v.name,
|
||||
baseUrl: v.baseUrl,
|
||||
// The key never reaches the browser, so the form leaves it out to keep it.
|
||||
apiKey: v.apiKey === undefined ? existing.apiKey : v.apiKey || null,
|
||||
model: v.model ?? null,
|
||||
engine: v.engine ?? null,
|
||||
hardware: v.hardware,
|
||||
// A probe of another server says nothing about this one.
|
||||
probe: moved ? null : existing.probe,
|
||||
})
|
||||
.where(eq(endpoints.id, id))
|
||||
.returning();
|
||||
return toView(row);
|
||||
}
|
||||
|
||||
/** Runs keep their snapshot; queued or running ones must finish or be cancelled first. */
|
||||
export async function deleteEndpoint(id: string): Promise<void> {
|
||||
const busy = await db().query.benchmarkRuns.findFirst({
|
||||
columns: { id: true },
|
||||
where: (r, { and, or }) => and(or(eq(r.endpointId, id), eq(r.endpointBId, id)), inArray(r.state, ["queued", "running"])),
|
||||
});
|
||||
if (busy) throw new EndpointError("busy", "A benchmark of this endpoint is queued or running. Cancel it first.", 409);
|
||||
const res = await db().delete(endpoints).where(eq(endpoints.id, id)).returning({ id: endpoints.id });
|
||||
if (!res.length) throw new EndpointError("not_found", "Endpoint not found.", 404);
|
||||
await db().update(benchmarkRuns).set({ endpointId: null }).where(eq(benchmarkRuns.endpointId, id));
|
||||
await db().update(benchmarkRuns).set({ endpointBId: null }).where(eq(benchmarkRuns.endpointBId, id));
|
||||
}
|
||||
|
||||
/** "Test connection": ask the server, store what it said. Unsaved form values can be tested too. */
|
||||
export async function testEndpoint(id: string | null, draft?: unknown): Promise<EndpointProbe> {
|
||||
let target: { baseUrl: string; apiKey: string | null; engine: (typeof ENDPOINT_ENGINES)[number] | null };
|
||||
const stored = id ? await db().query.endpoints.findFirst({ where: eq(endpoints.id, id) }) : null;
|
||||
if (id && !stored) throw new EndpointError("not_found", "Endpoint not found.", 404);
|
||||
if (draft) {
|
||||
const v = parse(draft);
|
||||
// The stored key only goes to the URL it was saved for.
|
||||
const keep = v.apiKey === undefined && stored?.baseUrl === v.baseUrl;
|
||||
target = { baseUrl: v.baseUrl, apiKey: keep ? stored!.apiKey : v.apiKey || null, engine: v.engine ?? null };
|
||||
} else target = { baseUrl: stored!.baseUrl, apiKey: stored!.apiKey, engine: stored!.engine };
|
||||
const probe = await probeEndpoint(target);
|
||||
if (stored && !draft) await db().update(endpoints).set({ probe }).where(eq(endpoints.id, stored.id));
|
||||
return probe;
|
||||
}
|
||||
+2
-8
@@ -22,14 +22,8 @@ const coreSchema = z.object({
|
||||
),
|
||||
/** hf CLI home (token cache, Xet logs/cache). Not the model storage. */
|
||||
HF_HOME: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/**
|
||||
* Docker API for runtimes (worker only), e.g. tcp://docker-proxy:2375 or unix:///var/run/docker.sock.
|
||||
* Unset: runtimes are disabled.
|
||||
*/
|
||||
DOCKER_HOST: z.preprocess(emptyToUndefined, z.string().regex(/^(tcp|unix):\/\//, "must start with tcp:// or unix://").optional()),
|
||||
/** Override the auto-detected Docker network / models source (needed when the worker isn't a container). */
|
||||
KANAME_DOCKER_NETWORK: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
KANAME_MODELS_SOURCE: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/** Exchange folder with the code sandbox (quality eval, coding). Unset: coding doesn't run. */
|
||||
SANDBOX_DIR: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/** BetterBench results and HTML reports. Default: "benchmarks" next to the SQLite database. */
|
||||
BENCHMARKS_DIR: z.preprocess(emptyToUndefined, z.string().optional()),
|
||||
/** The betterbench executable (the image ships one). Unset and not on PATH: benchmarks are disabled. */
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { argsToRows, rowsToArgs } from "./extra-args";
|
||||
|
||||
describe("extra args rows", () => {
|
||||
it("pairs flags with their values", () => {
|
||||
const tokens = ["--temp", "0.7", "--no-mmap", "--dtype=bfloat16", "--seed", "-1", "positional"];
|
||||
const rows = argsToRows(tokens);
|
||||
assert.deepEqual(rows, [
|
||||
{ flag: "--temp", value: "0.7" },
|
||||
{ flag: "--no-mmap", value: "" },
|
||||
{ flag: "--dtype=bfloat16", value: "" },
|
||||
{ flag: "--seed", value: "-1" },
|
||||
{ flag: "", value: "positional" },
|
||||
]);
|
||||
assert.deepEqual(rowsToArgs(rows), tokens);
|
||||
});
|
||||
|
||||
it("drops empty rows and trims", () => {
|
||||
assert.deepEqual(rowsToArgs([{ flag: " --top-k ", value: " 40 " }, { flag: "", value: "" }]), ["--top-k", "40"]);
|
||||
});
|
||||
});
|
||||
@@ -1,24 +0,0 @@
|
||||
// Extra command-line arguments as editable flag/value rows. Pure; shared by the runtime and
|
||||
// deployment forms. The stored form stays a token list (one argv entry per item).
|
||||
|
||||
export type ArgRow = { flag: string; value: string };
|
||||
|
||||
const isFlag = (t: string) => t.startsWith("-") && !/^-\d/.test(t);
|
||||
|
||||
/** Tokens → rows: a flag takes the following non-flag token as its value. */
|
||||
export function argsToRows(tokens: string[]): ArgRow[] {
|
||||
const rows: ArgRow[] = [];
|
||||
for (const t of tokens) {
|
||||
const last = rows.at(-1);
|
||||
// "--flag=value" stays one token, so it is shown (and passed) exactly as written.
|
||||
if (!isFlag(t) && last && last.flag && !last.value && !last.flag.includes("=")) last.value = t;
|
||||
else if (isFlag(t)) rows.push({ flag: t, value: "" });
|
||||
else rows.push({ flag: "", value: t });
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** Rows → tokens, skipping empty rows. */
|
||||
export function rowsToArgs(rows: ArgRow[]): string[] {
|
||||
return rows.flatMap((r) => [r.flag.trim(), r.value.trim()].filter(Boolean));
|
||||
}
|
||||
+3
-162
@@ -1,24 +1,9 @@
|
||||
// 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.
|
||||
// Hardware as a benchmark run reports it: PCIe links and the system summary. Pure; shared by the
|
||||
// web app, the worker and tests.
|
||||
|
||||
import type { HardwareGpu, HardwareOverrides, HostHardware, PcieLink, SystemSummary } from "@/lib/db/schema";
|
||||
import type { 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(" ");
|
||||
@@ -40,85 +25,8 @@ export function parseLinkText(text: string): PcieLink | 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. */
|
||||
@@ -141,70 +49,3 @@ export function systemSummaryLines(s: SystemSummary): string[] {
|
||||
}
|
||||
|
||||
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 {};
|
||||
}
|
||||
}
|
||||
+7
-20
@@ -24,8 +24,8 @@ export class JobError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Jobs that block another job for the same model; pending approval counts (it will run). */
|
||||
export const OPEN_STATES = ["pending_approval", "queued", ...ACTIVE_JOB_STATES] as const;
|
||||
/** Jobs that block another job for the same model. */
|
||||
export const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
|
||||
const INSERT_CHUNK = 500;
|
||||
|
||||
/** True if the model has a queued or running job (only one job per model at a time). */
|
||||
@@ -37,19 +37,15 @@ export async function hasOpenJob(modelId: string): Promise<boolean> {
|
||||
return !!open;
|
||||
}
|
||||
|
||||
/** Who asked for a job through the API (token id + its name at the time). */
|
||||
export type RequestedBy = { tokenId: string; name: string };
|
||||
|
||||
/**
|
||||
* Queue a download of all selected files of a model at its pinned SHA. hf skips files that are
|
||||
* already complete, so this also serves as resume and repair. `removePaths`: files of an older
|
||||
* revision to delete once the download succeeded (updates). `pendingApproval`: the job waits in
|
||||
* "pending_approval" (the worker only picks up "queued") until someone approves it.
|
||||
* revision to delete once the download succeeded (updates).
|
||||
*/
|
||||
export async function queueDownload(
|
||||
modelId: string,
|
||||
purpose: JobPurpose = "initial",
|
||||
options: { removePaths?: string[]; pendingApproval?: boolean; requestedBy?: RequestedBy; previousRule?: JobResult["previousRule"] } = {},
|
||||
options: { removePaths?: string[] } = {},
|
||||
): Promise<{ jobId: string }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
@@ -69,23 +65,19 @@ export async function queueDownload(
|
||||
const rows = files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size }));
|
||||
const result: JobResult = {};
|
||||
if (options.removePaths?.length) result.removePaths = options.removePaths;
|
||||
if (options.previousRule) result.previousRule = options.previousRule;
|
||||
await d.batch([
|
||||
d.insert(jobs).values({
|
||||
id: jobId,
|
||||
modelId,
|
||||
kind: "download",
|
||||
purpose,
|
||||
state: options.pendingApproval ? "pending_approval" : "queued",
|
||||
state: "queued",
|
||||
targetSha: model.pinnedSha,
|
||||
totalBytes: files.reduce((s, f) => s + f.size, 0),
|
||||
result: Object.keys(result).length ? result : null,
|
||||
requestedByTokenId: options.requestedBy?.tokenId ?? null,
|
||||
requestedBy: options.requestedBy?.name ?? null,
|
||||
}),
|
||||
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
|
||||
// A job waiting for approval doesn't download yet; the model keeps its status.
|
||||
...(options.pendingApproval ? [] : [d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId))]),
|
||||
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
|
||||
]);
|
||||
return { jobId };
|
||||
}
|
||||
@@ -122,8 +114,6 @@ export async function queueVerify(modelId: string, deep: boolean): Promise<{ job
|
||||
|
||||
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
|
||||
export async function requestCancel(jobId: string): Promise<void> {
|
||||
const pending = await db().query.jobs.findFirst({ columns: { id: true }, where: and(eq(jobs.id, jobId), eq(jobs.state, "pending_approval")) });
|
||||
if (pending) throw new JobError("not_cancellable", "This download waits for approval. Approve or reject it instead.", 409);
|
||||
const res = await db()
|
||||
.update(jobs)
|
||||
.set({ cancelRequestedAt: new Date() })
|
||||
@@ -157,8 +147,6 @@ export type JobSnapshot = {
|
||||
errorMessage: string | null;
|
||||
result: JobResult | null;
|
||||
cancelRequested: boolean;
|
||||
/** Token name if the job was requested through the API. */
|
||||
requestedBy: string | null;
|
||||
createdAt: number;
|
||||
startedAt: number | null;
|
||||
finishedAt: number | null;
|
||||
@@ -191,13 +179,12 @@ const jobColumns = {
|
||||
errorMessage: jobs.errorMessage,
|
||||
result: jobs.result,
|
||||
cancelRequestedAt: jobs.cancelRequestedAt,
|
||||
requestedBy: jobs.requestedBy,
|
||||
createdAt: jobs.createdAt,
|
||||
startedAt: jobs.startedAt,
|
||||
finishedAt: jobs.finishedAt,
|
||||
};
|
||||
|
||||
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt" | "requestedByTokenId"> & { repoId: string };
|
||||
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt"> & { repoId: string };
|
||||
|
||||
function toSnapshot(r: JobRow): JobSnapshot {
|
||||
const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r;
|
||||
|
||||
+1
-13
@@ -1,8 +1,7 @@
|
||||
import "server-only";
|
||||
import { and, asc, desc, eq, sql } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
|
||||
import { jobs, modelFiles, models, modelTags, tags } from "@/lib/db/schema";
|
||||
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
|
||||
import { modelFamilies } from "@/lib/hub/metadata";
|
||||
import { fileRole } from "@/lib/file-roles";
|
||||
import { quantGroup } from "@/lib/selection";
|
||||
@@ -30,7 +29,6 @@ export async function listLibrary() {
|
||||
pipelineTag: models.pipelineTag,
|
||||
license: models.license,
|
||||
hubTags: models.hubTags,
|
||||
requestedBy: models.requestedBy,
|
||||
fileCount: sql<number>`count(${modelFiles.id})`,
|
||||
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
|
||||
/** Selected files that are on disk (present or verified). */
|
||||
@@ -56,13 +54,6 @@ export async function listLibrary() {
|
||||
const tagsByModel = new Map<string, Tag[]>();
|
||||
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
|
||||
|
||||
const pending = new Set(
|
||||
(await d.select({ modelId: jobs.modelId }).from(jobs).where(eq(jobs.state, "pending_approval"))).map((j) => j.modelId),
|
||||
);
|
||||
|
||||
const [byModel, deployable] = await Promise.all([deploymentsByModel(), listDeployableModels()]);
|
||||
const deployableIds = new Set(deployable.map((m) => m.id));
|
||||
|
||||
return rows.map(({ updateDiff, ...r }) => ({
|
||||
...r,
|
||||
updateAvailable: !!updateDiff && updateDiff.sha === r.remoteSha && r.remoteSha !== r.pinnedSha,
|
||||
@@ -72,9 +63,6 @@ export async function listLibrary() {
|
||||
hubTags: r.hubTags ?? [],
|
||||
quants: [...(quants.get(r.id) ?? [])].sort(),
|
||||
tags: tagsByModel.get(r.id) ?? [],
|
||||
deployable: deployableIds.has(r.id),
|
||||
pendingApproval: pending.has(r.id),
|
||||
deployments: byModel.get(r.id) ?? [],
|
||||
}));
|
||||
}
|
||||
|
||||
|
||||
+5
-36
@@ -6,8 +6,7 @@ import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from
|
||||
import { hubMissingMessage } from "@/lib/hub/availability";
|
||||
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
|
||||
import { metadataColumns } from "@/lib/hub/refresh";
|
||||
import { deploymentsUsing } from "@/lib/deployments";
|
||||
import { hasOpenJob, queueDownload, type RequestedBy } from "@/lib/jobs";
|
||||
import { hasOpenJob, queueDownload } from "@/lib/jobs";
|
||||
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
|
||||
import { purgeModelRows } from "@/lib/model-purge";
|
||||
import { contentId } from "@/lib/update-diff";
|
||||
@@ -36,8 +35,6 @@ export async function addModel(input: {
|
||||
rule: SelectionRule;
|
||||
/** Import: use this existing folder in MODELS_DIR (must be one the worker's scan found). */
|
||||
localPath?: string;
|
||||
/** Added through the API by this token. */
|
||||
requestedBy?: RequestedBy;
|
||||
}): Promise<{ id: string }> {
|
||||
const info = await getRepoInfo(input.repoId, input.sha);
|
||||
const repoId = info.repoId;
|
||||
@@ -84,8 +81,6 @@ export async function addModel(input: {
|
||||
localPath,
|
||||
includePatterns: input.rule.include,
|
||||
excludePatterns: input.rule.exclude,
|
||||
requestedByTokenId: input.requestedBy?.tokenId ?? null,
|
||||
requestedBy: input.requestedBy?.name ?? null,
|
||||
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
|
||||
}),
|
||||
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
|
||||
@@ -107,10 +102,6 @@ export async function deleteModel(id: string, options: { deleteFiles: boolean })
|
||||
if (await hasOpenJob(id)) {
|
||||
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
|
||||
}
|
||||
const using = await deploymentsUsing({ modelId: id });
|
||||
if (using.length > 0) {
|
||||
throw new ModelError("busy", `Deployments use this model (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
|
||||
}
|
||||
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
|
||||
const neverDownloaded = model.status === "pending" && n === 0;
|
||||
if (!options.deleteFiles || neverDownloaded) {
|
||||
@@ -206,11 +197,7 @@ function chunk<T>(items: T[], size: number): T[][] {
|
||||
* rule as exact includes; exclude patterns that would block one of them are dropped, then the
|
||||
* rule is re-applied to the whole file list so `selected` always matches the stored rule.
|
||||
*/
|
||||
export async function addFilesToModel(
|
||||
modelId: string,
|
||||
paths: string[],
|
||||
options: { pendingApproval?: boolean; requestedBy?: RequestedBy } = {},
|
||||
): Promise<{ jobId: string; added: number }> {
|
||||
export async function addFilesToModel(modelId: string, paths: string[]): Promise<{ jobId: string; added: number }> {
|
||||
const d = db();
|
||||
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
|
||||
if (!model) throw new ModelError("not_found", "Model not found.", 404);
|
||||
@@ -219,9 +206,9 @@ export async function addFilesToModel(
|
||||
|
||||
const open = await d.query.jobs.findFirst({
|
||||
columns: { id: true },
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["pending_approval", "queued", "downloading", "verifying"])),
|
||||
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", "downloading", "verifying"])),
|
||||
});
|
||||
if (open) throw new ModelError("busy", "A download for this model is still pending, queued or running. Add files when it has finished.", 409);
|
||||
if (open) throw new ModelError("busy", "A download for this model is still queued or running. Add files when it has finished.", 409);
|
||||
|
||||
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
|
||||
const known = new Map(files.map((f) => [f.path, f]));
|
||||
@@ -241,24 +228,6 @@ export async function addFilesToModel(
|
||||
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
|
||||
),
|
||||
]);
|
||||
const { jobId } = await queueDownload(modelId, "add", {
|
||||
...options,
|
||||
// API requests can be rejected; the rule before goes with the job so it can be restored.
|
||||
previousRule: options.requestedBy ? { include: model.includePatterns, exclude: model.excludePatterns } : undefined,
|
||||
});
|
||||
const { jobId } = await queueDownload(modelId, "add");
|
||||
return { jobId, added: changed.filter((f) => !f.selected).length };
|
||||
}
|
||||
|
||||
/** Put a model's selection rule back (a rejected API "add files" request) and re-apply it. */
|
||||
export async function restoreSelection(modelId: string, rule: SelectionRule): Promise<void> {
|
||||
const d = db();
|
||||
const files = await d
|
||||
.select({ id: modelFiles.id, path: modelFiles.path, selected: modelFiles.selected })
|
||||
.from(modelFiles)
|
||||
.where(eq(modelFiles.modelId, modelId));
|
||||
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
|
||||
await d.batch([
|
||||
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
|
||||
...changed.map((f) => d.update(modelFiles).set({ selected: !f.selected }).where(eq(modelFiles.id, f.id))),
|
||||
]);
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// The quality eval: a small, deterministic check of what a deployment produces (not how fast), so
|
||||
// The quality eval: a small, deterministic check of what an endpoint produces (not how fast), so
|
||||
// launch options that change the output (quant, KV cache type, context, sampling bugs in a build)
|
||||
// show up next to the speed numbers. Pure: the eval set, prompt building and scoring; the worker
|
||||
// (src/worker/quality.ts) talks to the server and the code sandbox.
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { parseEnvLines, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "./runtimes-shared";
|
||||
|
||||
const base = { name: "x", engine: "vllm" as const, image: "vllm/vllm-openai-cpu:v0.31.0" };
|
||||
|
||||
describe("validateRuntime", () => {
|
||||
it("accepts the presets and common image references", () => {
|
||||
for (const p of RUNTIME_PRESETS) assert.doesNotThrow(() => validateRuntime(p));
|
||||
for (const image of [
|
||||
"ghcr.io/ggml-org/llama.cpp:server",
|
||||
"git.linxweiler.xyz/me/vllm-arc:0.9-patched",
|
||||
"localhost:5000/vllm",
|
||||
`vllm/vllm-openai-xpu@sha256:${"a".repeat(64)}`,
|
||||
]) {
|
||||
assert.equal(validateRuntime({ ...base, image }).image, image);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects bad images, env names, devices and multi-line values", () => {
|
||||
const bad = (patch: object) => assert.throws(() => validateRuntime({ ...base, ...patch }), RuntimeValidationError);
|
||||
bad({ image: "Vllm/Upper:tag" });
|
||||
bad({ image: "vllm/vllm --privileged" });
|
||||
bad({ env: { "BAD-KEY": "1" } });
|
||||
bad({ env: { OK: "a\nb" } });
|
||||
bad({ devices: ["/dev/sda"] });
|
||||
bad({ devices: ["/"] });
|
||||
bad({ extraArgs: ["--a\n--b"] });
|
||||
bad({ name: " " });
|
||||
assert.deepEqual(validateRuntime({ ...base, devices: ["/dev/dri", "/dev/dri/renderD128"] }).devices, [
|
||||
"/dev/dri",
|
||||
"/dev/dri/renderD128",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseEnvLines", () => {
|
||||
it("parses KEY=value lines, skipping blanks and comments", () => {
|
||||
assert.deepEqual(parseEnvLines("A=1\n\n# note\nB = x=y \n"), { A: "1", B: "x=y" });
|
||||
assert.throws(() => parseEnvLines("novalue"), RuntimeValidationError);
|
||||
});
|
||||
});
|
||||
@@ -1,196 +0,0 @@
|
||||
// Runtime presets and validation. Pure (no DB), shared by the web app, the worker and tests.
|
||||
|
||||
import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
|
||||
|
||||
export const ACCELERATOR_LABEL: Record<RuntimeAccelerator, string> = {
|
||||
cpu: "CPU",
|
||||
nvidia: "NVIDIA (CUDA)",
|
||||
dri: "Intel / AMD via /dev/dri",
|
||||
rocm: "AMD ROCm",
|
||||
};
|
||||
|
||||
/** Device nodes an accelerator needs passed through (NVIDIA GPUs are requested from Docker instead). */
|
||||
export const ACCELERATOR_DEVICES: Record<RuntimeAccelerator, string[]> = { cpu: [], nvidia: [], dri: ["/dev/dri"], rocm: ["/dev/kfd", "/dev/dri"] };
|
||||
|
||||
export type RuntimeInput = {
|
||||
name: string;
|
||||
engine: RuntimeEngine;
|
||||
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[];
|
||||
shmSizeMb?: number | null;
|
||||
numaTuning?: boolean;
|
||||
};
|
||||
|
||||
export type RuntimePreset = RuntimeInput & { id: string; summary: string };
|
||||
|
||||
/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0; all tags exist). */
|
||||
export const RUNTIME_PRESETS: RuntimePreset[] = [
|
||||
{
|
||||
id: "llama.cpp-cpu",
|
||||
name: "llama.cpp (CPU)",
|
||||
engine: "llama.cpp",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server",
|
||||
summary: "Official llama-server image, CPU build. Serves GGUF models.",
|
||||
description: "Official llama.cpp server, CPU build. Pin a build tag (e.g. server-b11429) for reproducible tests.",
|
||||
},
|
||||
{
|
||||
id: "vllm-cpu",
|
||||
name: "vLLM (CPU)",
|
||||
engine: "vllm",
|
||||
image: "vllm/vllm-openai-cpu:v0.31.0",
|
||||
summary: "Official vLLM CPU image. Serves safetensors models (BF16 recommended on AMD Zen).",
|
||||
description: "Official vLLM CPU build. VLLM_CPU_KVCACHE_SPACE is the KV cache size in GiB.",
|
||||
env: { VLLM_CPU_KVCACHE_SPACE: "4" },
|
||||
extraArgs: ["--dtype=bfloat16"],
|
||||
shmSizeMb: 4096,
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-cuda",
|
||||
name: "llama.cpp (CUDA)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "nvidia",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-cuda",
|
||||
summary: "llama-server for NVIDIA GPUs. Needs the NVIDIA Container Toolkit on the Docker host.",
|
||||
description: "Official llama.cpp server, CUDA build. Layers go to the GPU automatically (-ngl auto); set GPU layers per deployment.",
|
||||
},
|
||||
{
|
||||
id: "vllm-cuda",
|
||||
name: "vLLM (CUDA)",
|
||||
engine: "vllm",
|
||||
accelerator: "nvidia",
|
||||
image: "vllm/vllm-openai:v0.31.0",
|
||||
summary: "Official vLLM image for NVIDIA GPUs (large download). Needs the NVIDIA Container Toolkit.",
|
||||
description: "Official vLLM, CUDA build. vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU up front.",
|
||||
shmSizeMb: 8192,
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-vulkan",
|
||||
name: "llama.cpp (Vulkan)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "dri",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-vulkan",
|
||||
summary: "llama-server over Vulkan: Intel Arc (incl. B-series) and AMD GPUs via /dev/dri.",
|
||||
description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri; compare it with the SYCL build on Intel.",
|
||||
devices: ["/dev/dri"],
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-intel",
|
||||
name: "llama.cpp (Intel SYCL)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "dri",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-intel",
|
||||
summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs (A- and B-series, Arc Pro).",
|
||||
description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri). ZES_ENABLE_SYSMAN=1 lets it see free VRAM, which -ngl auto needs.",
|
||||
env: { ZES_ENABLE_SYSMAN: "1" },
|
||||
devices: ["/dev/dri"],
|
||||
},
|
||||
{
|
||||
id: "llama.cpp-rocm",
|
||||
name: "llama.cpp (ROCm)",
|
||||
engine: "llama.cpp",
|
||||
accelerator: "rocm",
|
||||
image: "ghcr.io/ggml-org/llama.cpp:server-rocm",
|
||||
summary: "llama-server for AMD GPUs with ROCm (/dev/kfd, /dev/dri).",
|
||||
description: "Official llama.cpp server, ROCm build for AMD GPUs.",
|
||||
devices: ["/dev/kfd", "/dev/dri"],
|
||||
},
|
||||
{
|
||||
id: "vllm-xpu",
|
||||
name: "vLLM (Intel XPU)",
|
||||
engine: "vllm",
|
||||
accelerator: "dri",
|
||||
image: "vllm/vllm-openai-xpu:v0.31.0",
|
||||
summary: "Official vLLM image for Intel GPUs (Arc incl. B-series, Data Center GPU Max) via /dev/dri.",
|
||||
description: "Official vLLM, XPU build for Intel GPUs. vLLM reserves --gpu-memory-utilization (default 0.9) of the VRAM up front.",
|
||||
devices: ["/dev/dri"],
|
||||
shmSizeMb: 8192,
|
||||
},
|
||||
{
|
||||
id: "vllm-rocm",
|
||||
name: "vLLM (ROCm)",
|
||||
engine: "vllm",
|
||||
accelerator: "rocm",
|
||||
image: "vllm/vllm-openai-rocm:v0.31.0",
|
||||
summary: "Official vLLM image for AMD GPUs with ROCm.",
|
||||
description: "Official vLLM, ROCm build for AMD GPUs.",
|
||||
devices: ["/dev/kfd", "/dev/dri"],
|
||||
shmSizeMb: 8192,
|
||||
},
|
||||
];
|
||||
|
||||
export const RUNTIME_NAME_MAX = 60;
|
||||
// [registry[:port]/]path[:tag][@sha256:digest], lowercase path components as Docker requires.
|
||||
const IMAGE_RE =
|
||||
/^(?:[a-z0-9]+(?:[.-][a-z0-9]+)*(?::\d+)?\/)?[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*(?:\/[a-z0-9]+(?:(?:[._]|__|-+)[a-z0-9]+)*)*(?::[\w][\w.-]{0,127})?(?:@sha256:[a-f0-9]{64})?$/;
|
||||
const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
||||
/** Device passthrough is limited to GPU device nodes (Intel/AMD: /dev/dri, AMD: /dev/kfd). */
|
||||
const DEVICE_RE = /^\/dev\/(dri(\/[\w.-]+)?|kfd)$/;
|
||||
|
||||
export class RuntimeValidationError extends Error {}
|
||||
|
||||
/** Normalize and validate a runtime definition; throws RuntimeValidationError with a readable message. */
|
||||
export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
|
||||
const name = input.name.trim().replace(/\s+/g, " ");
|
||||
if (!name || name.length > RUNTIME_NAME_MAX) throw new RuntimeValidationError(`Name must be 1–${RUNTIME_NAME_MAX} characters.`);
|
||||
if (input.engine !== "llama.cpp" && input.engine !== "vllm") throw new RuntimeValidationError("Unknown engine type.");
|
||||
const accelerator = input.accelerator ?? "cpu";
|
||||
if (!RUNTIME_ACCELERATORS.includes(accelerator)) throw new RuntimeValidationError("Unknown accelerator.");
|
||||
const image = input.image.trim();
|
||||
if (!IMAGE_RE.test(image)) throw new RuntimeValidationError(`"${image}" is not a valid image reference (e.g. ghcr.io/org/image:tag).`);
|
||||
|
||||
const env: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(input.env ?? {})) {
|
||||
if (!ENV_KEY_RE.test(k)) throw new RuntimeValidationError(`Invalid environment variable name "${k}".`);
|
||||
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);
|
||||
for (const d of devices) {
|
||||
if (!DEVICE_RE.test(d)) throw new RuntimeValidationError(`Device "${d}" isn't allowed (only /dev/dri… and /dev/kfd).`);
|
||||
}
|
||||
const shm = input.shmSizeMb ?? null;
|
||||
if (shm != null && (!Number.isInteger(shm) || shm < 64 || shm > 262_144)) {
|
||||
throw new RuntimeValidationError("Shared memory must be between 64 MiB and 256 GiB.");
|
||||
}
|
||||
return {
|
||||
name,
|
||||
engine: input.engine,
|
||||
accelerator,
|
||||
image,
|
||||
description: input.description?.trim() || null,
|
||||
engineName,
|
||||
env,
|
||||
extraArgs,
|
||||
devices,
|
||||
shmSizeMb: shm,
|
||||
numaTuning: !!input.numaTuning,
|
||||
};
|
||||
}
|
||||
|
||||
/** "KEY=value" lines ⇄ env object (for the editor). */
|
||||
export function parseEnvLines(text: string): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
for (const raw of text.split(/\r?\n/)) {
|
||||
const line = raw.trim();
|
||||
if (!line || line.startsWith("#")) continue;
|
||||
const eq = line.indexOf("=");
|
||||
if (eq <= 0) throw new RuntimeValidationError(`"${line}" isn't KEY=value.`);
|
||||
out[line.slice(0, eq).trim()] = line.slice(eq + 1).trim();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const formatEnvLines = (env: Record<string, string>) =>
|
||||
Object.entries(env)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join("\n");
|
||||
@@ -1,104 +0,0 @@
|
||||
import "server-only";
|
||||
import { asc, eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type DockerHostInfo, RUNTIME_ACCELERATORS, runtimes, workerState } from "@/lib/db/schema";
|
||||
import { deploymentsUsing } from "@/lib/deployments";
|
||||
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
|
||||
|
||||
export type Runtime = typeof runtimes.$inferSelect;
|
||||
|
||||
/** Request body for creating/updating a runtime (validated further by validateRuntime). */
|
||||
export const RuntimeBody = z.object({
|
||||
name: z.string().max(200),
|
||||
engine: z.enum(["llama.cpp", "vllm"]),
|
||||
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(),
|
||||
shmSizeMb: z.number().int().nullable().optional(),
|
||||
numaTuning: z.boolean().optional(),
|
||||
});
|
||||
|
||||
export class RuntimeError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function validated(input: RuntimeInput) {
|
||||
try {
|
||||
return validateRuntime(input);
|
||||
} catch (err) {
|
||||
if (err instanceof RuntimeValidationError) throw new RuntimeError("invalid", err.message, 400);
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export async function listRuntimes(): Promise<Runtime[]> {
|
||||
return db().select().from(runtimes).orderBy(asc(runtimes.createdAt));
|
||||
}
|
||||
|
||||
export async function getRuntime(id: string): Promise<Runtime> {
|
||||
const r = await db().query.runtimes.findFirst({ where: eq(runtimes.id, id) });
|
||||
if (!r) throw new RuntimeError("not_found", "Runtime not found.", 404);
|
||||
return r;
|
||||
}
|
||||
|
||||
export async function createRuntime(input: RuntimeInput & { preset?: string }): Promise<Runtime> {
|
||||
const v = validated(input);
|
||||
const preset = input.preset && RUNTIME_PRESETS.some((p) => p.id === input.preset) ? input.preset : null;
|
||||
const [row] = await db()
|
||||
.insert(runtimes)
|
||||
.values({ ...v, preset })
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function updateRuntime(id: string, input: RuntimeInput): Promise<Runtime> {
|
||||
const current = await getRuntime(id);
|
||||
const v = validated(input);
|
||||
const imageChanged = v.image !== current.image;
|
||||
const [row] = await db()
|
||||
.update(runtimes)
|
||||
.set({
|
||||
...v,
|
||||
// A different image has to be looked up (and maybe pulled) again.
|
||||
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, pullError: null } : {}),
|
||||
})
|
||||
.where(eq(runtimes.id, id))
|
||||
.returning();
|
||||
return row;
|
||||
}
|
||||
|
||||
export async function deleteRuntime(id: string): Promise<void> {
|
||||
await getRuntime(id);
|
||||
const using = await deploymentsUsing({ runtimeId: id });
|
||||
if (using.length > 0) {
|
||||
throw new RuntimeError("invalid", `Deployments use this runtime (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
|
||||
}
|
||||
await db().delete(runtimes).where(eq(runtimes.id, id));
|
||||
}
|
||||
|
||||
/** Ask the worker to pull (or re-pull, to update a moving tag) the runtime's image. */
|
||||
export async function requestPull(id: string): Promise<void> {
|
||||
await getRuntime(id);
|
||||
await db().update(runtimes).set({ pullRequestedAt: new Date(), pullError: null }).where(eq(runtimes.id, id));
|
||||
}
|
||||
|
||||
/** Docker facts as last reported by the worker; null when DOCKER_HOST isn't configured. */
|
||||
export async function getDockerInfo(): Promise<DockerHostInfo | null> {
|
||||
try {
|
||||
const row = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
|
||||
return row?.docker ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -56,8 +56,6 @@ const model = (over: Partial<SearchableModel>): SearchableModel => ({
|
||||
license: "apache-2.0",
|
||||
status: "ready",
|
||||
hubStatus: null,
|
||||
requestedBy: null,
|
||||
pendingApproval: false,
|
||||
...over,
|
||||
});
|
||||
|
||||
|
||||
+3
-13
@@ -14,20 +14,13 @@ export type SearchableModel = {
|
||||
status: string;
|
||||
/** Extra status value when the repo or commit is gone from the Hub, e.g. "deleted on Hub". */
|
||||
hubStatus: string | null;
|
||||
/** API token name if the model was requested through the API. */
|
||||
requestedBy: string | null;
|
||||
/** A download of it waits for approval. */
|
||||
pendingApproval: boolean;
|
||||
};
|
||||
|
||||
/** Status facet value for models with a download waiting for approval. */
|
||||
export const PENDING_APPROVAL = "pending_approval";
|
||||
|
||||
export const FACETS = ["author", "family", "quant", "tag", "status", "requester"] as const;
|
||||
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
|
||||
export type Facet = (typeof FACETS)[number];
|
||||
export type Filters = Record<Facet, string[]>;
|
||||
|
||||
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [], requester: [] };
|
||||
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] };
|
||||
|
||||
export function facetValues(m: SearchableModel, facet: Facet): string[] {
|
||||
switch (facet) {
|
||||
@@ -40,9 +33,7 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] {
|
||||
case "tag":
|
||||
return m.tags;
|
||||
case "status":
|
||||
return [m.status, m.hubStatus, m.pendingApproval ? PENDING_APPROVAL : null].filter((v): v is string => !!v);
|
||||
case "requester":
|
||||
return m.requestedBy ? [m.requestedBy] : [];
|
||||
return [m.status, m.hubStatus].filter((v): v is string => !!v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,7 +51,6 @@ function haystack(m: SearchableModel): string {
|
||||
m.license,
|
||||
m.status,
|
||||
m.hubStatus,
|
||||
m.requestedBy,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ")
|
||||
|
||||
+1
-70
@@ -1,11 +1,8 @@
|
||||
import "server-only";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { type HardwareOverrides, settings } from "@/lib/db/schema";
|
||||
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
|
||||
import { parseTuning, TUNING_KEY, type TuningGuardrails } from "@/lib/agent-tuning";
|
||||
import { settings } from "@/lib/db/schema";
|
||||
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";
|
||||
@@ -102,69 +99,3 @@ export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Pro
|
||||
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
|
||||
return getDownloadSpeedLimit();
|
||||
}
|
||||
|
||||
const GUARDRAILS_KEY = "agent.guardrails";
|
||||
|
||||
/** Limits for downloads requested through the API (Settings → API tokens). */
|
||||
export async function getGuardrails(): Promise<Guardrails> {
|
||||
return parseGuardrails(await read<unknown>(GUARDRAILS_KEY));
|
||||
}
|
||||
|
||||
export async function saveGuardrails(input: Partial<Guardrails>): Promise<Guardrails> {
|
||||
const next = { ...(await getGuardrails()), ...input };
|
||||
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
|
||||
if (!(next.maxRequestBytes >= 1_000_000)) throw new SettingsError("Max size per request must be at least 0.001 GB.");
|
||||
if (!(next.minFreeBytes >= 0)) throw new SettingsError("Minimum free space can't be negative.");
|
||||
if (!Number.isInteger(next.maxOpenJobs) || next.maxOpenJobs < 1 || next.maxOpenJobs > 50) throw new SettingsError("Max agent jobs at once must be 1–50.");
|
||||
const parsed = parseGuardrails(next);
|
||||
if (parsed.allowedAuthors.length !== next.allowedAuthors.length) throw new SettingsError("The author allowlist contains an invalid name.");
|
||||
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;
|
||||
}
|
||||
|
||||
/** Limits for deployments and benchmarks requested through the API (Settings → API tokens). */
|
||||
export async function getTuning(): Promise<TuningGuardrails> {
|
||||
return parseTuning(await read<unknown>(TUNING_KEY));
|
||||
}
|
||||
|
||||
export async function saveTuning(input: Partial<TuningGuardrails>): Promise<TuningGuardrails> {
|
||||
const next = { ...(await getTuning()), ...input };
|
||||
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
|
||||
const intIn = (v: number, min: number, max: number, what: string) => {
|
||||
if (!Number.isInteger(v) || v < min || v > max) throw new SettingsError(`${what} must be ${min}–${max}.`);
|
||||
};
|
||||
intIn(next.maxAgentDeployments, 1, 16, "Agent deployments at once");
|
||||
intIn(next.maxRunMinutes, 1, 24 * 60, "Max minutes per run");
|
||||
intIn(next.maxSweepMinutes, 1, 7 * 24 * 60, "Max minutes per sweep");
|
||||
intIn(next.maxSweepVariants, 2, 16, "Max sweep variants");
|
||||
const r = next.hostPortRange;
|
||||
if (r && (!Number.isInteger(r.from) || !Number.isInteger(r.to) || r.from < 1024 || r.to > 65_535 || r.from > r.to)) {
|
||||
throw new SettingsError("Host port range must be within 1024–65535, from ≤ to.");
|
||||
}
|
||||
if (next.maxMemoryMb != null && !(next.maxMemoryMb >= 256)) throw new SettingsError("Memory cap must be at least 256 MiB, or empty.");
|
||||
if (next.maxCpus != null && !(next.maxCpus >= 0.1)) throw new SettingsError("CPU cap must be at least 0.1 cores, or empty.");
|
||||
const parsed = parseTuning(next);
|
||||
for (const engine of ["llama.cpp", "vllm"] as const) {
|
||||
if (parsed.allowedArgs[engine].length !== new Set(next.allowedArgs[engine]).size) throw new SettingsError(`The ${engine} argument allowlist contains something that isn't a flag.`);
|
||||
}
|
||||
await write(TUNING_KEY, parsed);
|
||||
return parsed;
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { describe, it } from "node:test";
|
||||
import { applyOverrides, expandSweep, splitValues, SweepError, sweepKeysFor } from "./sweep";
|
||||
|
||||
describe("sweeps", () => {
|
||||
it("expands two settings into a cartesian product with labels", () => {
|
||||
const v = expandSweep(
|
||||
[
|
||||
{ key: "contextSize", values: ["4096", "8192"] },
|
||||
{ key: "kvCache", values: ["f16", "q8_0"] },
|
||||
],
|
||||
"llama.cpp",
|
||||
"cpu",
|
||||
);
|
||||
assert.equal(v.length, 4);
|
||||
assert.deepEqual(v[0], { index: 0, overrides: { contextSize: 4096, cacheTypeK: null, cacheTypeV: null }, label: "ctx 4096 · KV f16" });
|
||||
assert.deepEqual(v[3].overrides, { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" });
|
||||
});
|
||||
|
||||
it("rejects bad values, keys and sizes", () => {
|
||||
assert.throws(() => expandSweep([{ key: "contextSize", values: ["big", "8192"] }], "llama.cpp", "cpu"), SweepError);
|
||||
assert.throws(() => expandSweep([{ key: "gpuLayers", values: ["10", "20"] }], "llama.cpp", "cpu"), /can't be varied/);
|
||||
assert.throws(() => expandSweep([{ key: "dtype", values: ["float32", "bfloat16"] }], "llama.cpp", "cpu"), /can't be varied/);
|
||||
assert.throws(() => expandSweep([{ key: "threads", values: ["4"] }], "llama.cpp", "cpu"), /at least two variants/);
|
||||
assert.throws(
|
||||
() =>
|
||||
expandSweep(
|
||||
[
|
||||
{ key: "threads", values: ["1", "2", "3", "4", "5"] },
|
||||
{ key: "parallel", values: ["1", "2", "3", "4"] },
|
||||
],
|
||||
"llama.cpp",
|
||||
"cpu",
|
||||
),
|
||||
/20 variants/,
|
||||
);
|
||||
assert.throws(() => expandSweep([{ key: "modelFile", values: ["a.gguf", "x.gguf"] }], "llama.cpp", "cpu", { modelFiles: ["a.gguf", "b.gguf"] }), /x\.gguf/);
|
||||
});
|
||||
|
||||
it("offers GPU keys only on GPU runtimes and applies overrides", () => {
|
||||
assert.ok(sweepKeysFor("llama.cpp", "nvidia").some((d) => d.key === "gpuLayers"));
|
||||
assert.ok(!sweepKeysFor("vllm", "nvidia").some((d) => d.key === "kvCacheGb"));
|
||||
assert.deepEqual(splitValues("4096, 8192 8192;16384"), ["4096", "8192", "16384"]);
|
||||
const r = applyOverrides({ options: { modelFile: "m.gguf", contextSize: 4096, threads: 4, extraArgs: [] }, cpus: 4 }, { threads: 8, cpus: 8 });
|
||||
assert.deepEqual(r, { options: { modelFile: "m.gguf", contextSize: 4096, threads: 8, extraArgs: [] }, cpus: 8 });
|
||||
});
|
||||
});
|
||||
@@ -1,101 +0,0 @@
|
||||
// Benchmark sweeps: which settings can vary, how their values parse, and the variant list (the
|
||||
// cartesian product of up to two settings). Pure; shared by the form, the API and the worker.
|
||||
|
||||
import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine, SweepParam } from "@/lib/db/schema";
|
||||
|
||||
export const MAX_SWEEP_VARIANTS = 16;
|
||||
export const MAX_SWEEP_PARAMS = 2;
|
||||
|
||||
/** Overrides for one variant: deployment options plus the container's CPU limit. */
|
||||
export type VariantOverrides = Partial<DeploymentOptions> & { cpus?: number | null };
|
||||
|
||||
type Def = {
|
||||
key: string;
|
||||
label: string;
|
||||
/** Which runtimes it applies to. */
|
||||
engines: RuntimeEngine[];
|
||||
gpuOnly?: boolean;
|
||||
cpuOnly?: boolean;
|
||||
/** Example values for the form. */
|
||||
hint: string;
|
||||
parse: (v: string) => VariantOverrides | null;
|
||||
/** Short form for labels, e.g. "ctx 8192". */
|
||||
short: (v: string) => string;
|
||||
};
|
||||
|
||||
const int = (min: number, max: number) => (v: string) => {
|
||||
const n = Number(v);
|
||||
return Number.isInteger(n) && n >= min && n <= max ? n : null;
|
||||
};
|
||||
const num = (min: number, max: number) => (v: string) => {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) && n >= min && n <= max ? n : null;
|
||||
};
|
||||
const oneOf = <T extends string>(...xs: T[]) => (v: string) => (xs.includes(v as T) ? (v as T) : null);
|
||||
const wrap = <T>(f: (v: string) => T | null, to: (x: T) => VariantOverrides) => (v: string) => {
|
||||
const x = f(v.trim());
|
||||
return x == null ? null : to(x);
|
||||
};
|
||||
|
||||
export const SWEEP_KEYS: Def[] = [
|
||||
{ key: "contextSize", label: "Context size", engines: ["llama.cpp", "vllm"], hint: "4096, 8192, 16384", parse: wrap(int(128, 1_048_576), (x) => ({ contextSize: x })), short: (v) => `ctx ${v}` },
|
||||
{ key: "modelFile", label: "Model file (quant)", engines: ["llama.cpp"], hint: "pick downloaded GGUF files", parse: (v) => (v.trim() ? { modelFile: v.trim() } : null), short: (v) => v.replace(/\.gguf$/i, "").split(/[/-]/).slice(-1)[0] },
|
||||
{ key: "kvCache", label: "KV cache type (K and V)", engines: ["llama.cpp"], hint: "f16, q8_0, q4_0", parse: wrap(oneOf("f16", "q8_0", "q4_0"), (x) => ({ cacheTypeK: x === "f16" ? null : x, cacheTypeV: x === "f16" ? null : x })), short: (v) => `KV ${v}` },
|
||||
{ key: "threads", label: "Threads", engines: ["llama.cpp"], hint: "4, 8, 16", parse: wrap(int(1, 1024), (x) => ({ threads: x })), short: (v) => `${v} threads` },
|
||||
{ key: "parallel", label: "Parallel slots", engines: ["llama.cpp"], hint: "1, 2, 4", parse: wrap(int(1, 256), (x) => ({ parallel: x })), short: (v) => `np ${v}` },
|
||||
{ key: "batchSize", label: "Batch size", engines: ["llama.cpp"], hint: "512, 1024, 2048", parse: wrap(int(1, 65_536), (x) => ({ batchSize: x })), short: (v) => `b ${v}` },
|
||||
{ key: "ubatchSize", label: "Micro-batch size", engines: ["llama.cpp"], hint: "128, 256, 512", parse: wrap(int(1, 65_536), (x) => ({ ubatchSize: x })), short: (v) => `ub ${v}` },
|
||||
{ key: "flashAttn", label: "Flash attention", engines: ["llama.cpp"], hint: "on, off", parse: wrap(oneOf("auto", "on", "off"), (x) => ({ flashAttn: x })), short: (v) => `fa ${v}` },
|
||||
{ key: "cacheRamMb", label: "Prompt cache in RAM (MiB)", engines: ["llama.cpp"], hint: "0, 1024, 8192", parse: wrap(int(-1, 1_048_576), (x) => ({ cacheRamMb: x })), short: (v) => `cram ${v}` },
|
||||
{ key: "gpuLayers", label: "GPU layers", engines: ["llama.cpp"], gpuOnly: true, hint: "auto, 20, all", parse: (v) => (/^(auto|all|\d{1,4})$/.test(v.trim()) ? { gpuLayers: v.trim() } : null), short: (v) => `ngl ${v}` },
|
||||
{ key: "dtype", label: "Data type", engines: ["vllm"], hint: "bfloat16, float32", parse: wrap(oneOf("auto", "bfloat16", "float16", "float32"), (x) => ({ dtype: x })), short: (v) => v },
|
||||
{ key: "maxNumSeqs", label: "Max sequences", engines: ["vllm"], hint: "8, 16, 32", parse: wrap(int(1, 1024), (x) => ({ maxNumSeqs: x })), short: (v) => `seqs ${v}` },
|
||||
{ key: "kvCacheGb", label: "KV cache (GiB)", engines: ["vllm"], cpuOnly: true, hint: "1, 2, 4", parse: wrap(num(0.25, 1024), (x) => ({ kvCacheGb: x })), short: (v) => `KV ${v} GiB` },
|
||||
{ key: "gpuMemoryUtilization", label: "GPU memory share", engines: ["vllm"], gpuOnly: true, hint: "0.8, 0.9", parse: wrap(num(0.05, 1), (x) => ({ gpuMemoryUtilization: x })), short: (v) => `gmu ${v}` },
|
||||
{ key: "cpus", label: "CPU limit (cores)", engines: ["llama.cpp", "vllm"], hint: "2, 4, 8", parse: wrap(num(0.1, 1024), (x) => ({ cpus: x })), short: (v) => `${v} cores` },
|
||||
];
|
||||
|
||||
export function sweepKeysFor(engine: RuntimeEngine, accelerator: RuntimeAccelerator): Def[] {
|
||||
const gpu = accelerator !== "cpu";
|
||||
return SWEEP_KEYS.filter((d) => d.engines.includes(engine) && !(d.gpuOnly && !gpu) && !(d.cpuOnly && gpu));
|
||||
}
|
||||
|
||||
/** "4096, 8192 16384" → ["4096", "8192", "16384"] (deduplicated, order kept). */
|
||||
export function splitValues(text: string): string[] {
|
||||
return [...new Set(text.split(/[\s,;]+/).map((v) => v.trim()).filter(Boolean))];
|
||||
}
|
||||
|
||||
export class SweepError extends Error {}
|
||||
|
||||
export type Variant = { index: number; overrides: VariantOverrides; label: string };
|
||||
|
||||
/** Validate the parameters and expand them into variants (cartesian product). Throws SweepError. */
|
||||
export function expandSweep(params: SweepParam[], engine: RuntimeEngine, accelerator: RuntimeAccelerator, opts: { modelFiles?: string[] } = {}): Variant[] {
|
||||
if (params.length === 0 || params.length > MAX_SWEEP_PARAMS) throw new SweepError(`Vary one or two settings.`);
|
||||
const allowed = sweepKeysFor(engine, accelerator);
|
||||
if (new Set(params.map((p) => p.key)).size !== params.length) throw new SweepError("Each setting can only be varied once.");
|
||||
const axes = params.map((p) => {
|
||||
const def = allowed.find((d) => d.key === p.key);
|
||||
if (!def) throw new SweepError(`"${p.key}" can't be varied for this runtime.`);
|
||||
const values = [...new Set(p.values.map((v) => v.trim()).filter(Boolean))];
|
||||
if (values.length < 1) throw new SweepError(`Give at least one value for ${def.label}.`);
|
||||
return values.map((v) => {
|
||||
const o = def.parse(v);
|
||||
if (!o) throw new SweepError(`"${v}" isn't a valid value for ${def.label} (e.g. ${def.hint}).`);
|
||||
if (p.key === "modelFile" && opts.modelFiles && !opts.modelFiles.includes(v)) throw new SweepError(`${v} isn't a downloaded GGUF file of this model.`);
|
||||
return { o, s: def.short(v) };
|
||||
});
|
||||
});
|
||||
const total = axes.reduce((n, a) => n * a.length, 1);
|
||||
if (total < 2) throw new SweepError("A sweep needs at least two variants.");
|
||||
if (total > MAX_SWEEP_VARIANTS) throw new SweepError(`That's ${total} variants; the limit is ${MAX_SWEEP_VARIANTS}.`);
|
||||
let combos: { o: VariantOverrides; s: string[] }[] = [{ o: {}, s: [] }];
|
||||
for (const axis of axes) combos = combos.flatMap((c) => axis.map((v) => ({ o: { ...c.o, ...v.o }, s: [...c.s, v.s] })));
|
||||
return combos.map((c, index) => ({ index, overrides: c.o, label: c.s.join(" · ") }));
|
||||
}
|
||||
|
||||
/** Apply a variant's overrides to the base deployment's options / CPU limit. */
|
||||
export function applyOverrides(base: { options: DeploymentOptions; cpus: number | null }, o: VariantOverrides) {
|
||||
const { cpus, ...rest } = o;
|
||||
return { options: { ...base.options, ...rest } as DeploymentOptions, cpus: cpus !== undefined ? cpus : base.cpus };
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import "server-only";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { and, desc, eq, inArray } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { runDir } from "@/lib/benchmark-paths";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, benchmarkSweeps, deployments, modelFiles, runtimes, type SweepVariant } from "@/lib/db/schema";
|
||||
import { modelCandidates } from "@/lib/deploy-candidates";
|
||||
import { expandSweep, MAX_SWEEP_PARAMS, SweepError } from "@/lib/sweep";
|
||||
|
||||
export class SweepRequestError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "busy" | "too_many_variants",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
export const SweepBody = z.object({
|
||||
baseDeploymentId: z.string().min(1),
|
||||
label: z.string().trim().max(80).nullable().optional(),
|
||||
params: z
|
||||
.array(z.object({ key: z.string().min(1).max(40), values: z.array(z.string().max(1024)).min(1).max(16) }))
|
||||
.min(1)
|
||||
.max(MAX_SWEEP_PARAMS),
|
||||
quick: z.boolean().default(true),
|
||||
passes: z.number().int().min(1).max(200).nullable().optional(),
|
||||
phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
|
||||
/** Also run the quality eval on each variant (after its speed run). */
|
||||
quality: z.boolean().default(false),
|
||||
});
|
||||
|
||||
/** Validate against the base deployment's runtime and model files, then queue the sweep. */
|
||||
/** Requested through the API: who asked, approval, and the limits for the sweep and each of its runs. */
|
||||
export type AgentSweepRequest = { requestedBy: { tokenId: string; name: string }; pendingApproval: boolean; timeLimitS: number; runTimeLimitS: number; maxVariants: number };
|
||||
|
||||
export async function createSweep(input: z.infer<typeof SweepBody>, agent?: AgentSweepRequest) {
|
||||
const [base] = await db()
|
||||
.select({
|
||||
id: deployments.id,
|
||||
name: deployments.name,
|
||||
runtimeId: deployments.runtimeId,
|
||||
modelId: deployments.modelId,
|
||||
options: deployments.options,
|
||||
cpus: deployments.cpus,
|
||||
memoryMb: deployments.memoryMb,
|
||||
engine: runtimes.engine,
|
||||
accelerator: runtimes.accelerator,
|
||||
imageState: runtimes.imageState,
|
||||
})
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.where(eq(deployments.id, input.baseDeploymentId));
|
||||
if (!base) throw new SweepRequestError("not_found", "Base deployment not found.", 404);
|
||||
if (base.imageState !== "present") throw new SweepRequestError("invalid", "The runtime's image isn't pulled.", 409);
|
||||
const files = await db()
|
||||
.select({ path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, base.modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
|
||||
const gguf = modelCandidates(files).gguf.map((g) => g.path);
|
||||
let variants;
|
||||
try {
|
||||
variants = expandSweep(input.params, base.engine, base.accelerator, { modelFiles: gguf });
|
||||
} catch (err) {
|
||||
if (err instanceof SweepError) throw new SweepRequestError("invalid", err.message, 400);
|
||||
throw err;
|
||||
}
|
||||
if (agent && variants.length > agent.maxVariants) {
|
||||
throw new SweepRequestError("too_many_variants", `That's ${variants.length} variants; agents may run at most ${agent.maxVariants} per sweep. Vary fewer values.`, 422);
|
||||
}
|
||||
const [row] = await db()
|
||||
.insert(benchmarkSweeps)
|
||||
.values({
|
||||
label: input.label || null,
|
||||
baseDeploymentId: base.id,
|
||||
// The variants' deployments must not publish ports or require a second copy of the base's port.
|
||||
base: { name: base.name, runtimeId: base.runtimeId, modelId: base.modelId, options: base.options, cpus: base.cpus, memoryMb: base.memoryMb },
|
||||
params: input.params,
|
||||
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases, quality: input.quality },
|
||||
variants: variants.map((v): SweepVariant => ({ ...v, state: "pending" })),
|
||||
...(agent
|
||||
? {
|
||||
requestedByTokenId: agent.requestedBy.tokenId,
|
||||
requestedBy: agent.requestedBy.name,
|
||||
timeLimitS: agent.timeLimitS,
|
||||
runTimeLimitS: agent.runTimeLimitS,
|
||||
state: agent.pendingApproval ? ("pending_approval" as const) : ("queued" as const),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.returning({ id: benchmarkSweeps.id });
|
||||
return row;
|
||||
}
|
||||
|
||||
export type SweepRow = typeof benchmarkSweeps.$inferSelect;
|
||||
|
||||
export async function listSweeps(): Promise<SweepRow[]> {
|
||||
return db().select().from(benchmarkSweeps).orderBy(desc(benchmarkSweeps.createdAt));
|
||||
}
|
||||
|
||||
export async function getSweep(id: string) {
|
||||
const sweep = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
|
||||
if (!sweep) return null;
|
||||
const runIds = sweep.variants.flatMap((v) => [v.runId, v.evalRunId]).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,
|
||||
meta: benchmarkRuns.meta,
|
||||
quality: benchmarkRuns.quality,
|
||||
})
|
||||
.from(benchmarkRuns)
|
||||
.where(inArray(benchmarkRuns.id, runIds))
|
||||
: [];
|
||||
return { sweep, runs };
|
||||
}
|
||||
|
||||
export async function cancelSweep(id: string) {
|
||||
const s = await db().query.benchmarkSweeps.findFirst({ columns: { state: true }, where: eq(benchmarkSweeps.id, id) });
|
||||
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
|
||||
if (s.state === "queued" || s.state === "pending_approval") {
|
||||
await db().update(benchmarkSweeps).set({ state: "cancelled", finishedAt: new Date() }).where(eq(benchmarkSweeps.id, id));
|
||||
} else if (s.state === "running") {
|
||||
await db().update(benchmarkSweeps).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkSweeps.id, id));
|
||||
}
|
||||
}
|
||||
|
||||
/** Let a sweep an agent asked for start, or turn it down. */
|
||||
export async function decideSweep(id: string, approve: boolean) {
|
||||
const res = await db()
|
||||
.update(benchmarkSweeps)
|
||||
.set(approve ? { state: "queued" } : { state: "cancelled", finishedAt: new Date(), error: "Rejected by the user." })
|
||||
.where(and(eq(benchmarkSweeps.id, id), eq(benchmarkSweeps.state, "pending_approval")))
|
||||
.returning({ id: benchmarkSweeps.id });
|
||||
if (res.length === 0) throw new SweepRequestError("invalid", "This sweep doesn't wait for approval.", 409);
|
||||
}
|
||||
|
||||
/** Delete a finished sweep with its runs (and their files). */
|
||||
export async function deleteSweep(id: string) {
|
||||
const s = await db().query.benchmarkSweeps.findFirst({ where: eq(benchmarkSweeps.id, id) });
|
||||
if (!s) throw new SweepRequestError("not_found", "Sweep not found.", 404);
|
||||
if (s.state === "running" || s.state === "queued") throw new SweepRequestError("busy", "Cancel the sweep first.", 409);
|
||||
const runIds = s.variants.flatMap((v) => [v.runId, v.evalRunId]).filter((x): x is string => !!x);
|
||||
if (runIds.length) {
|
||||
await db().delete(benchmarkLogs).where(inArray(benchmarkLogs.runId, runIds));
|
||||
await db().delete(benchmarkRuns).where(inArray(benchmarkRuns.id, runIds));
|
||||
for (const r of runIds) await rm(runDir(r), { recursive: true, force: true });
|
||||
}
|
||||
await db().delete(benchmarkSweeps).where(eq(benchmarkSweeps.id, id));
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
// What each API token scope allows, for the settings UI. Pure, safe for the browser.
|
||||
|
||||
import type { TokenScope } from "@/lib/db/schema";
|
||||
|
||||
export const SCOPE_LABEL: Record<TokenScope, string> = {
|
||||
"models:read": "Look up Hub repos, list models, read jobs and disk space",
|
||||
"downloads:create": "Request downloads (within the guardrails)",
|
||||
"deployments:read": "List runtimes and deployments, read their state and logs",
|
||||
"deployments:write": "Create deployments and edit, start, stop or delete its own ones (within the guardrails)",
|
||||
"benchmarks:read": "Read benchmark runs, sweeps and comparisons",
|
||||
"benchmarks:run": "Start benchmark runs, A/B runs and sweeps on its own deployments (within the guardrails)",
|
||||
};
|
||||
@@ -1,34 +0,0 @@
|
||||
// `?wait=<seconds>` on /api/v1 status endpoints: instead of an agent polling (each call costs it a
|
||||
// round of context), the request blocks until the state is settled or the time is up. Pure apart
|
||||
// from the timers.
|
||||
|
||||
export const MAX_WAIT_S = 900;
|
||||
const POLL_MS = 1_000;
|
||||
|
||||
/** `?wait=` as seconds, clamped to 0–900 (absent or invalid: 0, answer right away). */
|
||||
export function parseWait(params: URLSearchParams): number {
|
||||
const n = Number(params.get("wait"));
|
||||
return Number.isFinite(n) && n > 0 ? Math.min(MAX_WAIT_S, Math.floor(n)) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads `load()` until `settled` holds, `seconds` pass or the client goes away; returns the last
|
||||
* value and how long it waited. Re-reads the database once a second (cheap with SQLite).
|
||||
*/
|
||||
export async function waitFor<T>(
|
||||
load: () => Promise<T>,
|
||||
settled: (v: T) => boolean,
|
||||
seconds: number,
|
||||
opts: { signal?: AbortSignal; pollMs?: number; now?: () => number } = {},
|
||||
): Promise<{ value: T; waitedS: number; timedOut: boolean }> {
|
||||
const now = opts.now ?? Date.now;
|
||||
const start = now();
|
||||
const deadline = start + seconds * 1000;
|
||||
let value = await load();
|
||||
while (!settled(value) && now() < deadline && !opts.signal?.aborted) {
|
||||
await new Promise((r) => setTimeout(r, Math.min(opts.pollMs ?? POLL_MS, Math.max(0, deadline - now()))));
|
||||
value = await load();
|
||||
}
|
||||
const waitedS = Math.round((now() - start) / 1000);
|
||||
return { value, waitedS, timedOut: !settled(value) && seconds > 0 };
|
||||
}
|
||||
Reference in new issue
Block a user