Release 0.13.0: agent API for deployments and benchmarks
Release / release (push) Successful in 3m0s
Release / release (push) Successful in 3m0s
Scopes deployments:read/write and benchmarks:read/run; /api/v1 endpoints for runtimes, deployments (create with dry run, edit, start, stop, delete own ones), benchmark runs, A/B, sweeps and comparisons; ?wait= on all status endpoints. Guardrails: approval, agent deployments at once, one GPU job at a time, time limits, sweep variants, runtime and argument allowlists, host port range, memory/CPU caps, protected deployments with a VRAM check. Requested-by filters, approval bars, per-token activity log, scope editing, docs/agent/SKILL-tuning.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e007a35143
commit
716bd8f2f0
62 files changed
+6091
-219
No files matched your search
@@ -0,0 +1,66 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
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;
|
||||
}
|
||||
@@ -55,9 +55,9 @@ export async function openAgentJobs(): Promise<number> {
|
||||
|
||||
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: check GET /api/v1/jobs/{jobId} every few minutes.`;
|
||||
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"}; poll GET /api/v1/jobs/{jobId} for progress.`;
|
||||
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.`;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
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, 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({
|
||||
kind: z.enum(["run", "ab"]).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(),
|
||||
})
|
||||
.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([]),
|
||||
})
|
||||
.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,
|
||||
}),
|
||||
{ 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 },
|
||||
{
|
||||
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);
|
||||
|
||||
/** Headline numbers + the setup (section 1 metadata) as key/value. */
|
||||
function compact(summary: BenchmarkSummary | null, meta: RunMeta | null) {
|
||||
const h = headline(summary);
|
||||
return {
|
||||
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.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);
|
||||
return { label: v.label, overrides: v.overrides, state: v.state, runId: v.runId ?? null, error: v.error ?? null, ...compact(run?.summary ?? null, run?.meta ?? 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[], token: TokenIdentity) {
|
||||
const runs = await getBenchmarks(ids);
|
||||
const rows = runs.map((r) => ({ id: r.id, label: r.label ?? r.snapshot.deploymentName, state: r.state, ...compact(r.summary, r.meta) }));
|
||||
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. Differences under ~2 % between separate runs are noise; use an A/B for small effects.",
|
||||
tokenName: token.name,
|
||||
};
|
||||
}
|
||||
|
||||
/** 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));
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,351 @@
|
||||
// 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(" · ");
|
||||
}
|
||||
@@ -54,6 +54,18 @@ export async function revokeToken(id: string): Promise<void> {
|
||||
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 });
|
||||
|
||||
@@ -0,0 +1,535 @@
|
||||
// /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]")));
|
||||
});
|
||||
});
|
||||
+6
-1
@@ -3,6 +3,10 @@ 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";
|
||||
@@ -31,7 +35,8 @@ const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
|
||||
|
||||
/** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */
|
||||
export function v1Catch(err: unknown) {
|
||||
if (err instanceof GuardrailError) return v1Error(err.status, err.code, err.message);
|
||||
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);
|
||||
|
||||
+38
-4
@@ -50,7 +50,10 @@ async function snapshotOf(deploymentId: string, role: string) {
|
||||
* 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.
|
||||
*/
|
||||
export async function createBenchmark(input: BenchmarkInput) {
|
||||
/** 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 ab = !!input.deploymentBId;
|
||||
const a = await snapshotOf(input.deploymentId, ab ? "Deployment A" : "The deployment");
|
||||
const b = ab ? await snapshotOf(input.deploymentBId!, "Deployment B") : null;
|
||||
@@ -79,6 +82,14 @@ export async function createBenchmark(input: BenchmarkInput) {
|
||||
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),
|
||||
}
|
||||
: {}),
|
||||
})
|
||||
.returning({ id: benchmarkRuns.id });
|
||||
return row;
|
||||
@@ -106,6 +117,9 @@ const listColumns = {
|
||||
ab: benchmarkRuns.ab,
|
||||
resources: benchmarkRuns.resources,
|
||||
sweepId: benchmarkRuns.sweepId,
|
||||
requestedBy: benchmarkRuns.requestedBy,
|
||||
requestedByTokenId: benchmarkRuns.requestedByTokenId,
|
||||
timeLimitS: benchmarkRuns.timeLimitS,
|
||||
meta: benchmarkRuns.meta,
|
||||
metaB: benchmarkRuns.metaB,
|
||||
system: benchmarkRuns.system,
|
||||
@@ -139,17 +153,37 @@ export async function getBenchmarks(ids: string[]) {
|
||||
return ids.map((id) => rows.find((r) => r.id === id)).filter((r) => r != null);
|
||||
}
|
||||
|
||||
/** Queued runs are cancelled right away; a running one is stopped by the worker. */
|
||||
/** Queued (or still unapproved) 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") {
|
||||
await db().update(benchmarkRuns).set({ state: "cancelled", finishedAt: new Date() }).where(and(eq(benchmarkRuns.id, id), eq(benchmarkRuns.state, "queued")));
|
||||
if (run.state === "queued" || run.state === "pending_approval") {
|
||||
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> = {};
|
||||
|
||||
+41
-3
@@ -601,6 +601,13 @@ export const deployments = sqliteTable("deployments", {
|
||||
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(),
|
||||
});
|
||||
@@ -637,7 +644,7 @@ export const apiKeys = sqliteTable("api_keys", {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** What a token may do. Nothing can delete, change settings or manage runtimes/tokens. */
|
||||
export const TOKEN_SCOPES = ["models:read", "downloads:create"] as const;
|
||||
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(
|
||||
@@ -657,11 +664,31 @@ export const apiTokens = sqliteTable(
|
||||
(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)],
|
||||
);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Benchmarks (BetterBench runs against a running deployment)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export const BENCHMARK_STATES = ["pending_approval", "queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
|
||||
|
||||
export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
|
||||
@@ -920,6 +947,11 @@ export const benchmarkRuns = sqliteTable(
|
||||
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
|
||||
/** 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>(),
|
||||
@@ -983,7 +1015,7 @@ export const benchmarkPublications = sqliteTable(
|
||||
// Benchmark sweeps: one base deployment, one or two settings varied, a run per variant
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const SWEEP_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
|
||||
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). */
|
||||
@@ -1016,5 +1048,11 @@ export const benchmarkSweeps = sqliteTable("benchmark_sweeps", {
|
||||
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(),
|
||||
});
|
||||
+46
-7
@@ -89,8 +89,21 @@ export async function listDeployableModels(): Promise<DeployableModel[]> {
|
||||
.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. */
|
||||
async function validate(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
|
||||
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) });
|
||||
@@ -148,8 +161,12 @@ async function validate(input: DeploymentInput, selfId?: string): Promise<Deploy
|
||||
return options;
|
||||
}
|
||||
|
||||
export async function createDeployment(input: DeploymentInput, startNow: boolean) {
|
||||
const options = await validate(input);
|
||||
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({
|
||||
@@ -160,7 +177,10 @@ export async function createDeployment(input: DeploymentInput, startNow: boolean
|
||||
cpus: input.cpus ?? null,
|
||||
memoryMb: input.memoryMb ?? null,
|
||||
hostPort: input.hostPort ?? null,
|
||||
desiredState: startNow ? "running" : "stopped",
|
||||
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;
|
||||
@@ -176,7 +196,7 @@ async function get(id: string) {
|
||||
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 validate(input, id);
|
||||
const options = await validateDeployment(input, id);
|
||||
await db()
|
||||
.update(deployments)
|
||||
.set({
|
||||
@@ -193,13 +213,27 @@ export async function updateDeployment(id: string, input: DeploymentInput) {
|
||||
|
||||
export async function setDesiredState(id: string, desired: "running" | "stopped") {
|
||||
const d = await get(id);
|
||||
if (d.desiredState === desired) return;
|
||||
if (d.desiredState === desired && !d.startRequestedAt) return;
|
||||
await db()
|
||||
.update(deployments)
|
||||
.set({ desiredState: desired, ...(desired === "running" ? { error: null } : {}) })
|
||||
// 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);
|
||||
@@ -229,6 +263,11 @@ const listColumns = {
|
||||
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,
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { 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";
|
||||
@@ -138,3 +139,32 @@ export async function saveHardwareOverrides(input: unknown): Promise<HardwareOve
|
||||
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;
|
||||
}
|
||||
+28
-3
@@ -10,7 +10,7 @@ import { expandSweep, MAX_SWEEP_PARAMS, SweepError } from "@/lib/sweep";
|
||||
|
||||
export class SweepRequestError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "busy",
|
||||
public code: "invalid" | "not_found" | "busy" | "too_many_variants",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
@@ -31,7 +31,10 @@ export const SweepBody = z.object({
|
||||
});
|
||||
|
||||
/** Validate against the base deployment's runtime and model files, then queue the sweep. */
|
||||
export async function createSweep(input: z.infer<typeof SweepBody>) {
|
||||
/** 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,
|
||||
@@ -62,6 +65,9 @@ export async function createSweep(input: z.infer<typeof SweepBody>) {
|
||||
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({
|
||||
@@ -72,6 +78,15 @@ export async function createSweep(input: z.infer<typeof SweepBody>) {
|
||||
params: input.params,
|
||||
settings: { quick: input.quick, passes: input.passes ?? null, warmup: null, phases: input.phases },
|
||||
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;
|
||||
@@ -99,13 +114,23 @@ export async function getSweep(id: string) {
|
||||
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") {
|
||||
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) });
|
||||
|
||||
@@ -5,4 +5,8 @@ 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)",
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
// `?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