Deployments: serve a model with a runtime container
- deployments + deployment_logs tables; desired/actual state reconciled by the worker (create/start/stop/remove via the socket proxy, /health wait, log follower, stats, memory guard, adopt/remove containers on restart). - Pure command builder for llama-server and vllm serve (mmproj, MTP draft, KV cache types, dtype, KV cache size) with tests; file candidates per engine with tests. - New main menu entry Deployments: list, new/edit form (runtime -> model and files -> launch options, live command preview), detail page with stats, log, endpoint and a streaming chat smoke test. Not yet tested end-to-end against real containers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
4f7ae1fc8c
commit
8b74fa69db
32 files changed
+3824
-3
No files matched your search
@@ -0,0 +1,237 @@
|
||||
import "server-only";
|
||||
import { and, asc, desc, eq, gt, inArray, isNull, ne } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "@/lib/db/client";
|
||||
import { deploymentLogs, deployments, type DeploymentOptions, modelFiles, models, runtimes } from "@/lib/db/schema";
|
||||
import { type ModelCandidates, modelCandidates, servableBy } from "@/lib/deploy-candidates";
|
||||
|
||||
export class DeploymentError extends Error {
|
||||
constructor(
|
||||
public code: "invalid" | "not_found" | "busy",
|
||||
message: string,
|
||||
public status: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
const int = (min: number, max: number) => z.number().int().min(min).max(max);
|
||||
|
||||
export const DeploymentBody = z.object({
|
||||
name: z.string().trim().min(1).max(80),
|
||||
runtimeId: z.string().min(1),
|
||||
modelId: z.string().min(1),
|
||||
options: z.object({
|
||||
modelFile: z.string().max(1024),
|
||||
mmproj: z.string().max(1024).nullable().optional(),
|
||||
draftFile: z.string().max(1024).nullable().optional(),
|
||||
draftType: z.enum(["draft-mtp", "draft-simple"]).nullable().optional(),
|
||||
contextSize: int(128, 1_048_576),
|
||||
threads: int(1, 1024).nullable().optional(),
|
||||
batchSize: int(1, 65_536).nullable().optional(),
|
||||
ubatchSize: int(1, 65_536).nullable().optional(),
|
||||
parallel: int(1, 256).nullable().optional(),
|
||||
cacheTypeK: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
|
||||
cacheTypeV: z.enum(["f32", "f16", "bf16", "q8_0", "q4_0", "q4_1", "iq4_nl", "q5_0", "q5_1"]).nullable().optional(),
|
||||
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
|
||||
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
|
||||
maxNumSeqs: int(1, 1024).nullable().optional(),
|
||||
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
|
||||
extraArgs: z.array(z.string().max(4000).refine((a) => !/[\r\n\0]/.test(a), "single line")).max(100),
|
||||
}),
|
||||
cpus: z.number().min(0.1).max(1024).nullable().optional(),
|
||||
memoryMb: int(256, 4_194_304).nullable().optional(),
|
||||
hostPort: int(1024, 65_535).nullable().optional(),
|
||||
});
|
||||
export type DeploymentInput = z.infer<typeof DeploymentBody>;
|
||||
|
||||
/** Downloaded files of a model (selected and on disk). */
|
||||
async function localFiles(modelId: string) {
|
||||
return db()
|
||||
.select({ path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.modelId, modelId), eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
|
||||
}
|
||||
|
||||
export type DeployableModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
|
||||
|
||||
/** Library models with something a runtime can serve. */
|
||||
export async function listDeployableModels(): Promise<DeployableModel[]> {
|
||||
const rows = await db().select({ id: models.id, repoId: models.repoId, localPath: models.localPath }).from(models).orderBy(asc(models.repoId));
|
||||
const files = await db()
|
||||
.select({ modelId: modelFiles.modelId, path: modelFiles.path, size: modelFiles.size })
|
||||
.from(modelFiles)
|
||||
.where(and(eq(modelFiles.selected, true), inArray(modelFiles.state, ["present", "verified"])));
|
||||
const byModel = new Map<string, { path: string; size: number }[]>();
|
||||
for (const f of files) byModel.set(f.modelId, [...(byModel.get(f.modelId) ?? []), f]);
|
||||
return rows
|
||||
.map((m) => ({ ...m, candidates: modelCandidates(byModel.get(m.id) ?? []) }))
|
||||
.filter((m) => m.candidates.gguf.length > 0 || m.candidates.vllm);
|
||||
}
|
||||
|
||||
/** Check that runtime, model and files fit together; returns normalized options. */
|
||||
async function validate(input: DeploymentInput, selfId?: string): Promise<DeploymentOptions> {
|
||||
const runtime = await db().query.runtimes.findFirst({ where: eq(runtimes.id, input.runtimeId) });
|
||||
if (!runtime) throw new DeploymentError("invalid", "Runtime not found.", 400);
|
||||
const model = await db().query.models.findFirst({ where: eq(models.id, input.modelId) });
|
||||
if (!model) throw new DeploymentError("invalid", "Model not found.", 400);
|
||||
const c = modelCandidates(await localFiles(model.id));
|
||||
if (!servableBy(c, runtime.engine)) {
|
||||
throw new DeploymentError("invalid", `${model.repoId} has no downloaded files ${runtime.name} can serve.`, 400);
|
||||
}
|
||||
const o = input.options;
|
||||
const options: DeploymentOptions = { ...o, extraArgs: o.extraArgs.map((a) => a.trim()).filter(Boolean) };
|
||||
if (runtime.engine === "llama.cpp") {
|
||||
if (!c.gguf.some((g) => g.path === o.modelFile)) throw new DeploymentError("invalid", "Pick one of the model's downloaded GGUF files.", 400);
|
||||
if (o.mmproj && !c.mmproj.some((m) => m.path === o.mmproj)) throw new DeploymentError("invalid", "Unknown mmproj file.", 400);
|
||||
const draft = o.draftFile ? c.drafts.find((d) => d.path === o.draftFile) : null;
|
||||
if (o.draftFile && !draft) throw new DeploymentError("invalid", "Unknown draft/MTP file.", 400);
|
||||
options.draftType = draft?.type ?? null;
|
||||
Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null });
|
||||
} else {
|
||||
Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null });
|
||||
}
|
||||
if (input.hostPort) {
|
||||
const clash = await db().query.deployments.findFirst({
|
||||
columns: { name: true },
|
||||
where: and(eq(deployments.hostPort, input.hostPort), selfId ? ne(deployments.id, selfId) : undefined, isNull(deployments.deleteRequestedAt)),
|
||||
});
|
||||
if (clash) throw new DeploymentError("invalid", `Port ${input.hostPort} is already used by "${clash.name}".`, 409);
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
export async function createDeployment(input: DeploymentInput, startNow: boolean) {
|
||||
const options = await validate(input);
|
||||
const [row] = await db()
|
||||
.insert(deployments)
|
||||
.values({
|
||||
name: input.name,
|
||||
runtimeId: input.runtimeId,
|
||||
modelId: input.modelId,
|
||||
options,
|
||||
cpus: input.cpus ?? null,
|
||||
memoryMb: input.memoryMb ?? null,
|
||||
hostPort: input.hostPort ?? null,
|
||||
desiredState: startNow ? "running" : "stopped",
|
||||
})
|
||||
.returning({ id: deployments.id });
|
||||
return row;
|
||||
}
|
||||
|
||||
async function get(id: string) {
|
||||
const d = await db().query.deployments.findFirst({ where: and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)) });
|
||||
if (!d) throw new DeploymentError("not_found", "Deployment not found.", 404);
|
||||
return d;
|
||||
}
|
||||
|
||||
/** Change launch options; only while stopped (a running container keeps its command). */
|
||||
export async function updateDeployment(id: string, input: DeploymentInput) {
|
||||
const d = await get(id);
|
||||
if (d.state !== "stopped" && d.state !== "failed") throw new DeploymentError("busy", "Stop the deployment before changing it.", 409);
|
||||
const options = await validate(input, id);
|
||||
await db()
|
||||
.update(deployments)
|
||||
.set({
|
||||
name: input.name,
|
||||
runtimeId: input.runtimeId,
|
||||
modelId: input.modelId,
|
||||
options,
|
||||
cpus: input.cpus ?? null,
|
||||
memoryMb: input.memoryMb ?? null,
|
||||
hostPort: input.hostPort ?? null,
|
||||
})
|
||||
.where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
export async function setDesiredState(id: string, desired: "running" | "stopped") {
|
||||
const d = await get(id);
|
||||
if (d.desiredState === desired) return;
|
||||
await db()
|
||||
.update(deployments)
|
||||
.set({ desiredState: desired, ...(desired === "running" ? { error: null } : {}) })
|
||||
.where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
/** The worker stops the container and deletes the row. */
|
||||
export async function requestDelete(id: string) {
|
||||
await get(id);
|
||||
await db().update(deployments).set({ deleteRequestedAt: new Date(), desiredState: "stopped" }).where(eq(deployments.id, id));
|
||||
}
|
||||
|
||||
const listColumns = {
|
||||
id: deployments.id,
|
||||
name: deployments.name,
|
||||
state: deployments.state,
|
||||
desiredState: deployments.desiredState,
|
||||
options: deployments.options,
|
||||
cpus: deployments.cpus,
|
||||
memoryMb: deployments.memoryMb,
|
||||
hostPort: deployments.hostPort,
|
||||
containerName: deployments.containerName,
|
||||
command: deployments.command,
|
||||
startedAt: deployments.startedAt,
|
||||
readyAt: deployments.readyAt,
|
||||
stoppedAt: deployments.stoppedAt,
|
||||
exitCode: deployments.exitCode,
|
||||
error: deployments.error,
|
||||
stats: deployments.stats,
|
||||
createdAt: deployments.createdAt,
|
||||
runtimeId: deployments.runtimeId,
|
||||
runtimeName: runtimes.name,
|
||||
runtimeImage: runtimes.image,
|
||||
engine: runtimes.engine,
|
||||
modelId: deployments.modelId,
|
||||
repoId: models.repoId,
|
||||
};
|
||||
|
||||
export type DeploymentRow = Awaited<ReturnType<typeof listDeployments>>[number];
|
||||
|
||||
export async function listDeployments() {
|
||||
return db()
|
||||
.select(listColumns)
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.innerJoin(models, eq(models.id, deployments.modelId))
|
||||
.where(isNull(deployments.deleteRequestedAt))
|
||||
.orderBy(desc(deployments.createdAt));
|
||||
}
|
||||
|
||||
export async function getDeployment(id: string) {
|
||||
const [row] = await db()
|
||||
.select(listColumns)
|
||||
.from(deployments)
|
||||
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
|
||||
.innerJoin(models, eq(models.id, deployments.modelId))
|
||||
.where(and(eq(deployments.id, id), isNull(deployments.deleteRequestedAt)));
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
export async function listDeploymentLogs(id: string, afterId: number, tail = 500) {
|
||||
const rows =
|
||||
afterId > 0
|
||||
? await db()
|
||||
.select()
|
||||
.from(deploymentLogs)
|
||||
.where(and(eq(deploymentLogs.deploymentId, id), gt(deploymentLogs.id, afterId)))
|
||||
.orderBy(asc(deploymentLogs.id))
|
||||
.limit(2000)
|
||||
: (
|
||||
await db().select().from(deploymentLogs).where(eq(deploymentLogs.deploymentId, id)).orderBy(desc(deploymentLogs.id)).limit(tail)
|
||||
).reverse();
|
||||
return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
|
||||
}
|
||||
|
||||
/** Deployments that use a model or runtime (deleting those is refused while any exist). */
|
||||
export async function deploymentsUsing(by: { modelId?: string; runtimeId?: string }) {
|
||||
return db()
|
||||
.select({ id: deployments.id, name: deployments.name })
|
||||
.from(deployments)
|
||||
.where(
|
||||
and(
|
||||
isNull(deployments.deleteRequestedAt),
|
||||
by.modelId ? eq(deployments.modelId, by.modelId) : undefined,
|
||||
by.runtimeId ? eq(deployments.runtimeId, by.runtimeId) : undefined,
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user