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:
Pascal LinxweilerandClaude Opus 5.5 committed 2026-10-06 11:31:04 +02:00
1 parent 4f7ae1fc8c
commit 8b74fa69db
32 files changed
+3824 -3

No files matched your search

+86
View File
@@ -3,6 +3,7 @@ import {
index,
integer,
primaryKey,
real,
sqliteTable,
text,
uniqueIndex,
@@ -422,3 +423,88 @@ export const localFolders = sqliteTable("local_folders", {
commit: text("commit"),
scannedAt: ts("scanned_at").notNull(),
});
// ---------------------------------------------------------------------------
// Deployments: a model served by a runtime container
// ---------------------------------------------------------------------------
/** What the worker is doing with the container. */
export const DEPLOYMENT_STATES = ["stopped", "starting", "running", "stopping", "failed"] as const;
export type DeploymentState = (typeof DEPLOYMENT_STATES)[number];
/** Launch options. Engine-specific fields are ignored by the other engine. */
export type DeploymentOptions = {
/** Model file (llama.cpp: the GGUF, first part of a split) or "" for the repo folder (vLLM). */
modelFile: string;
/** llama.cpp: multimodal projector. */
mmproj?: string | null;
/** llama.cpp: draft model (MTP head or a small draft model) for speculative decoding. */
draftFile?: string | null;
draftType?: "draft-mtp" | "draft-simple" | null;
contextSize: number;
threads?: number | null;
batchSize?: number | null;
ubatchSize?: number | null;
parallel?: number | null;
cacheTypeK?: string | null;
cacheTypeV?: string | null;
flashAttn?: "auto" | "on" | "off" | null;
/** vLLM */
dtype?: string | null;
maxNumSeqs?: number | null;
kvCacheGb?: number | null;
extraArgs: string[];
};
export type DeploymentStats = { cpuPercent: number; memoryBytes: number; memoryLimitBytes: number; at: string };
export const deployments = sqliteTable("deployments", {
id: id(),
name: text("name").notNull(),
runtimeId: text("runtime_id")
.notNull()
.references(() => runtimes.id),
modelId: text("model_id")
.notNull()
.references(() => models.id),
options: text("options", { mode: "json" }).$type<DeploymentOptions>().notNull(),
/** CPU limit in cores (fractions allowed) and memory limit; null = no limit. */
cpus: real("cpus"),
memoryMb: integer("memory_mb"),
/** Publish the API on this host port (optional; Kaname itself uses the Docker network). */
hostPort: integer("host_port"),
/** Set by the web app; the worker starts/stops the container to match. */
desiredState: text("desired_state", { enum: ["running", "stopped"] }).notNull().default("stopped"),
state: text("state", { enum: DEPLOYMENT_STATES }).notNull().default("stopped"),
/** Delete requested: the worker removes the container, then the row. */
deleteRequestedAt: ts("delete_requested_at"),
containerId: text("container_id"),
containerName: text("container_name"),
/** Command line the container was started with (for display and reproducibility). */
command: text("command", { mode: "json" }).$type<string[]>(),
imageId: text("image_id"),
startedAt: ts("started_at"),
readyAt: ts("ready_at"),
stoppedAt: ts("stopped_at"),
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
export const deploymentLogs = sqliteTable(
"deployment_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
deploymentId: text("deployment_id")
.notNull()
.references(() => deployments.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
);
+36
View File
@@ -0,0 +1,36 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { modelCandidates, servableBy } from "./deploy-candidates";
const f = (path: string, size = 10) => ({ path, size });
describe("modelCandidates", () => {
it("lists GGUF weights (split as first part), mmproj and MTP/draft files", () => {
const c = modelCandidates([
f("Qwen3.8-27B-UD-Q4_K_XL.gguf"),
f("BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf"),
f("BF16/Qwen3.8-27B-BF16-00002-of-00002.gguf"),
f("mmproj-F16.gguf"),
f("MTP/mtp-Qwen3.8-27B-Q4_0.gguf"),
f("imatrix_unsloth.gguf"),
f("config.json"),
]);
assert.deepEqual(
c.gguf.map((g) => [g.path, g.parts]),
[
["Qwen3.8-27B-UD-Q4_K_XL.gguf", 1],
["BF16/Qwen3.8-27B-BF16-00001-of-00002.gguf", 2],
],
);
assert.deepEqual(c.mmproj.map((m) => m.path), ["mmproj-F16.gguf"]);
assert.deepEqual(c.drafts.map((d) => [d.path, d.type]), [["MTP/mtp-Qwen3.8-27B-Q4_0.gguf", "draft-mtp"]]);
assert.equal(c.vllm, null);
assert.ok(servableBy(c, "llama.cpp") && !servableBy(c, "vllm"));
});
it("recognizes a safetensors repo for vLLM", () => {
const c = modelCandidates([f("config.json", 1), f("model.safetensors", 100), f("tokenizer.json", 5)]);
assert.deepEqual(c.vllm, { size: 106 });
assert.equal(c.gguf.length, 0);
});
});
+41
View File
@@ -0,0 +1,41 @@
// Which downloaded files a runtime can serve. Pure; shared by the server and the deployment form.
import type { RuntimeEngine } from "@/lib/db/schema";
import { groupSplitFiles } from "@/lib/file-groups";
import { fileRole } from "@/lib/file-roles";
export type LocalFile = { path: string; size: number };
export type CandidateFile = { path: string; size: number; parts: number };
export type DraftFile = CandidateFile & { type: "draft-mtp" | "draft-simple" };
export type ModelCandidates = {
/** llama.cpp: loadable GGUF weights (split files as their first part), plus optional extras. */
gguf: CandidateFile[];
mmproj: CandidateFile[];
drafts: DraftFile[];
/** vLLM: the repo folder has a config.json and safetensors weights. */
vllm: { size: number } | null;
};
const isGguf = (p: string) => p.toLowerCase().endsWith(".gguf");
/** `files`: the model's files that are on disk (present or verified). */
export function modelCandidates(files: LocalFile[]): ModelCandidates {
const entries = (pred: (p: string) => boolean) =>
groupSplitFiles(files.filter((f) => pred(f.path))).map((g) => ({ path: g.parts[0].path, size: g.size, parts: g.totalParts }));
const gguf = entries((p) => isGguf(p) && fileRole(p) === "model");
const mmproj = entries((p) => isGguf(p) && fileRole(p) === "vision");
const drafts: DraftFile[] = [
...entries((p) => isGguf(p) && fileRole(p) === "mtp").map((f) => ({ ...f, type: "draft-mtp" as const })),
...entries((p) => isGguf(p) && fileRole(p) === "draft").map((f) => ({ ...f, type: "draft-simple" as const })),
];
const hasConfig = files.some((f) => f.path === "config.json");
const safetensors = files.filter((f) => f.path.endsWith(".safetensors") && fileRole(f.path) === "model");
const vllm = hasConfig && safetensors.length > 0 ? { size: files.reduce((s, f) => s + f.size, 0) } : null;
return { gguf, mmproj, drafts, vllm };
}
export function servableBy(c: ModelCandidates, engine: RuntimeEngine): boolean {
return engine === "llama.cpp" ? c.gguf.length > 0 : c.vllm !== null;
}
+49
View File
@@ -0,0 +1,49 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { buildCommand, renderCommand } from "./deploy-command";
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
describe("buildCommand", () => {
it("builds llama-server arguments with mmproj and MTP draft", () => {
const cmd = buildCommand({
engine: "llama.cpp",
model,
runtime: { env: {}, extraArgs: ["--jinja"] },
options: {
modelFile: "Qwen3-0.6B-Q4_K_M.gguf",
mmproj: "mmproj-F16.gguf",
draftFile: "MTP/mtp-Q4_0.gguf",
draftType: "draft-mtp",
contextSize: 4096,
threads: 8,
parallel: 1,
cacheTypeK: "q8_0",
extraArgs: ["--temp", "0.7"],
},
});
assert.equal(cmd.port, 8080);
assert.deepEqual(cmd.args.slice(0, 2), ["-m", "/models/unsloth/Qwen3-0.6B-GGUF/Qwen3-0.6B-Q4_K_M.gguf"]);
const s = cmd.args.join(" ");
assert.match(s, /-c 4096 -t 8 -tb 8 -np 1 -ctk q8_0/);
assert.match(s, /--mmproj \/models\/unsloth\/Qwen3-0\.6B-GGUF\/mmproj-F16\.gguf/);
assert.match(s, /-md \/models\/unsloth\/Qwen3-0\.6B-GGUF\/MTP\/mtp-Q4_0\.gguf --spec-type draft-mtp/);
assert.ok(s.endsWith("--metrics --jinja --temp 0.7"));
assert.ok(!s.includes("-b "), "unset options are left out");
});
it("builds vllm serve arguments; deployment dtype and KV cache override the runtime", () => {
const cmd = buildCommand({
engine: "vllm",
model: { repoId: "HuggingFaceTB/SmolLM2-135M-Instruct", localPath: "HuggingFaceTB/SmolLM2-135M-Instruct" },
runtime: { env: { VLLM_CPU_KVCACHE_SPACE: "4" }, extraArgs: ["--dtype=bfloat16"] },
options: { modelFile: "", contextSize: 2048, maxNumSeqs: 4, dtype: "float32", kvCacheGb: 2, extraArgs: [] },
});
assert.equal(cmd.port, 8000);
assert.equal(cmd.args[0], "/models/HuggingFaceTB/SmolLM2-135M-Instruct");
assert.equal(cmd.env.VLLM_CPU_KVCACHE_SPACE, "2");
const s = cmd.args.join(" ");
assert.ok(s.indexOf("--dtype=bfloat16") < s.indexOf("--dtype float32"));
assert.match(renderCommand("vllm/vllm-openai-cpu:v0.31.0", cmd), /^docker run -e VLLM_CPU_KVCACHE_SPACE=2 /);
});
});
+93
View File
@@ -0,0 +1,93 @@
// Container command lines for deployments, per engine type. Pure: used by the worker to start
// containers and by the UI for the live preview. Flags verified against llama.cpp build 11429
// (`llama-server --help`) and vLLM v0.31.0 (`vllm serve --help=all`).
import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
/** Where the models folder is mounted inside every runtime container (read-only). */
export const CONTAINER_MODELS_DIR = "/models";
export const ENGINE_PORT: Record<RuntimeEngine, number> = { "llama.cpp": 8080, vllm: 8000 };
export type CommandInput = {
engine: RuntimeEngine;
options: DeploymentOptions;
model: { repoId: string; localPath: string };
runtime: { env: Record<string, string>; extraArgs: string[] };
};
export type ContainerCommand = { args: string[]; env: Record<string, string>; port: number };
const inModels = (localPath: string, file?: string | null) =>
[CONTAINER_MODELS_DIR, localPath, file].filter(Boolean).join("/").replace(/\/+/g, "/");
const num = (flag: string, v: number | null | undefined) => (v != null && Number.isFinite(v) ? [flag, String(v)] : []);
const str = (flag: string, v: string | null | undefined) => (v ? [flag, v] : []);
export function buildCommand({ engine, options: o, model, runtime }: CommandInput): ContainerCommand {
const port = ENGINE_PORT[engine];
if (engine === "llama.cpp") {
// The image's entrypoint is llama-server, so these are its arguments.
const args = [
"-m",
inModels(model.localPath, o.modelFile),
"--host",
"0.0.0.0",
"--port",
String(port),
"-a",
model.repoId,
...num("-c", o.contextSize),
...num("-t", o.threads),
...num("-tb", o.threads),
...num("-b", o.batchSize),
...num("-ub", o.ubatchSize),
...num("-np", o.parallel),
...str("-ctk", o.cacheTypeK),
...str("-ctv", o.cacheTypeV),
...str("-fa", o.flashAttn),
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
"--metrics",
...runtime.extraArgs,
...o.extraArgs,
];
return { args, env: { ...runtime.env }, port };
}
// vLLM: the image's entrypoint is `vllm serve`; the model is the repo folder.
const env = { ...runtime.env };
if (o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
const args = [
inModels(model.localPath, o.modelFile || null),
"--host",
"0.0.0.0",
"--port",
String(port),
"--served-model-name",
model.repoId,
...num("--max-model-len", o.contextSize),
...num("--max-num-seqs", o.maxNumSeqs),
...runtime.extraArgs,
// After the runtime's defaults, so a deployment's dtype wins (argparse keeps the last value).
...str("--dtype", o.dtype),
...o.extraArgs,
];
return { args, env, port };
}
/** Shell-style rendering for display ("docker run … image args"). */
export function renderCommand(image: string, cmd: ContainerCommand): string {
const q = (s: string) => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
const env = Object.entries(cmd.env).map(([k, v]) => `-e ${q(`${k}=${v}`)}`);
return ["docker run", ...env, `-v <models>:${CONTAINER_MODELS_DIR}:ro`, q(image), ...cmd.args.map(q)].join(" ");
}
/** Rough memory need: model files plus KV cache and runtime overhead. */
export function estimateMemoryMb(fileBytes: number, contextSize: number, engine: RuntimeEngine, kvCacheGb?: number | null): number {
const model = fileBytes / 2 ** 20;
if (engine === "vllm") return Math.ceil(model + (kvCacheGb ?? 4) * 1024 + 2048);
// llama.cpp: ~ctx/8 MiB of f16 KV cache per 4k tokens for small models is too model-specific to
// compute without the GGUF header; a margin that scales with context is a safe default.
return Math.ceil(model * 1.1 + 512 + contextSize / 16);
}
+237
View File
@@ -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,
),
);
}
+5
View File
@@ -6,6 +6,7 @@ import { jobFiles, jobs, localFolders, modelFiles, modelRevisions, models } from
import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { deploymentsUsing } from "@/lib/deployments";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
@@ -102,6 +103,10 @@ export async function deleteModel(id: string, options: { deleteFiles: boolean })
if (await hasOpenJob(id)) {
throw new ModelError("busy", "A job for this model is still queued or running. Cancel it first.", 409);
}
const using = await deploymentsUsing({ modelId: id });
if (using.length > 0) {
throw new ModelError("busy", `Deployments use this model (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
}
const [{ n }] = await d.select({ n: sql<number>`count(*)` }).from(jobs).where(eq(jobs.modelId, id));
const neverDownloaded = model.status === "pending" && n === 0;
if (!options.deleteFiles || neverDownloaded) {
+5
View File
@@ -3,6 +3,7 @@ import { asc, eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "@/lib/db/client";
import { type DockerHostInfo, runtimes, workerState } from "@/lib/db/schema";
import { deploymentsUsing } from "@/lib/deployments";
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
export type Runtime = typeof runtimes.$inferSelect;
@@ -77,6 +78,10 @@ export async function updateRuntime(id: string, input: RuntimeInput): Promise<Ru
export async function deleteRuntime(id: string): Promise<void> {
await getRuntime(id);
const using = await deploymentsUsing({ runtimeId: id });
if (using.length > 0) {
throw new RuntimeError("invalid", `Deployments use this runtime (${using.map((u) => u.name).join(", ")}). Delete them first.`, 409);
}
await db().delete(runtimes).where(eq(runtimes.id, id));
}