Files
Kaname/src/lib/db/schema.ts
T
Pascal LinxweilerandClaude Opus 5.5 6b67c653b5
Release / release (push) Successful in 3m17s
Release 0.14.0: quality eval
A deterministic quality eval as a run type next to BetterBench: tool
calling (12 requests), coding (8 Python functions checked by unit tests
in a locked-down sandbox container) and long-context retrieval (needle at
3 depths in 3 lengths up to the context). Versioned eval set in
src/evals/v1, score stored per run, shown on the run page, in compare
views, the benchmark list and sweep tables (optional eval per variant);
API kind "eval", quality in run/sweep/compare answers; skill updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 15:24:36 +02:00

1088 lines
43 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { sql } from "drizzle-orm";
import {
index,
integer,
primaryKey,
real,
sqliteTable,
text,
uniqueIndex,
} from "drizzle-orm/sqlite-core";
import { ulid } from "ulid";
// Conventions (keep these when adding tables in later steps, they keep a Postgres port simple):
// - Primary keys are ULID strings, generated in the app, never reused.
// - Timestamps are integer milliseconds (mode "timestamp_ms").
// - Byte counts are integers (safe up to 2^53).
// - Enums are text columns with a TS-level enum, not DB enums.
// - Foreign keys are declared, but deletes cascade in app code: SQLite only enforces
// FKs per connection with PRAGMA foreign_keys=ON, which libsql's pool doesn't guarantee.
const id = () =>
text("id")
.primaryKey()
.$defaultFn(() => ulid());
const createdAt = () =>
integer("created_at", { mode: "timestamp_ms" })
.notNull()
.$defaultFn(() => new Date());
const updatedAt = () =>
integer("updated_at", { mode: "timestamp_ms" })
.notNull()
.$defaultFn(() => new Date())
.$onUpdateFn(() => new Date());
const ts = (name: string) => integer(name, { mode: "timestamp_ms" });
// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------
export const MODEL_STATUSES = [
"pending", // added, nothing downloaded yet
"downloading",
"ready", // all selected files present at pinned SHA
"incomplete", // verify found missing/broken files, or an update/repair didn't finish
"failed", // last download failed
"deleting",
] as const;
export type ModelStatus = (typeof MODEL_STATUSES)[number];
/** Is the repo (at the pinned commit) still on the Hub? Local files are never touched either way. */
export const HUB_STATES = ["available", "repo_missing", "commit_missing"] as const;
export type HubState = (typeof HUB_STATES)[number];
export type UpdateDiffFile = { path: string; size: number; oldSize?: number };
export type UpdateDiff = {
/** Commit the diff was computed against (the tracked revision's head on the Hub). */
sha: string;
changed: UpdateDiffFile[];
added: UpdateDiffFile[];
removed: UpdateDiffFile[];
checkedAt: string;
};
/** Outcome of a verify job, or extra instructions for a job (`removePaths` after an update). */
export type JobResult = {
checked?: number;
missing?: string[];
sizeMismatch?: string[];
hashMismatch?: string[];
/** Files in the model folder that aren't selected repo files. */
extra?: { path: string; size: number; inRepo: boolean }[];
/** Update jobs: files of the old revision to delete once the download succeeded. */
removePaths?: string[];
/** Delete jobs: files that were kept because they don't belong to the repo. */
kept?: string[];
/** API "add files" requests: the selection rule before, restored if the request is rejected. */
previousRule?: { include: string[]; exclude: string[] };
};
export const models = sqliteTable(
"models",
{
id: id(),
repoType: text("repo_type", { enum: ["model"] }).notNull().default("model"),
repoId: text("repo_id").notNull(), // "org/name"
trackedRevision: text("tracked_revision").notNull().default("main"),
pinnedSha: text("pinned_sha").notNull(),
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-27B-GGUF". */
localPath: text("local_path").notNull(),
/**
* Selection rule, applied to the repo's file list. Checkbox picks are stored as escaped
* exact-path globs, so the same rule can be re-applied to a newer revision.
*/
includePatterns: text("include_patterns", { mode: "json" })
.$type<string[]>()
.notNull()
.default(sql`'[]'`),
excludePatterns: text("exclude_patterns", { mode: "json" })
.$type<string[]>()
.notNull()
.default(sql`'[]'`),
status: text("status", { enum: MODEL_STATUSES }).notNull().default("pending"),
/** Latest SHA of trackedRevision seen on the Hub (update check). */
remoteSha: text("remote_sha"),
lastCheckedAt: ts("last_checked_at"),
lastCheckError: text("last_check_error"),
/** Result of the last successful Hub check; null until checked. */
hubState: text("hub_state", { enum: HUB_STATES }),
/** When the repo or pinned commit was first seen missing; cleared when it's back. */
hubMissingSince: ts("hub_missing_since"),
/** What updating to `remoteSha` would change in the selection; null when up to date. */
updateDiff: text("update_diff", { mode: "json" }).$type<UpdateDiff>(),
lastVerifiedAt: ts("last_verified_at"),
downloadedAt: ts("downloaded_at"),
// Hub metadata (for search/filters), refreshed by the worker. Null until fetched.
/** e.g. ["Qwen/Qwen3-8B"] (cardData.base_model, or base_model:* tags). */
baseModels: text("base_models", { mode: "json" }).$type<string[]>(),
/** How this model derives from its base: "quantized", "finetune", "adapter", "merge". */
baseRelation: text("base_relation"),
/** Avatar of the repo's org/user on the Hub. */
authorAvatarUrl: text("author_avatar_url"),
/** e.g. "qwen3" (gguf.architecture or config.model_type). */
architecture: text("architecture"),
pipelineTag: text("pipeline_tag"),
license: text("license"),
/** Hub tags, minus noise like arxiv:/region:/deploy:. */
hubTags: text("hub_tags", { mode: "json" }).$type<string[]>(),
metadataFetchedAt: ts("metadata_fetched_at"),
/** Added through the API: the token that asked for it, and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("models_repo_uq").on(t.repoType, t.repoId)],
);
// ---------------------------------------------------------------------------
// User tags (e.g. "roleplay", "security")
// ---------------------------------------------------------------------------
export const tags = sqliteTable(
"tags",
{
id: id(),
/** Display name as entered. */
name: text("name").notNull(),
/** Lowercased, trimmed name; unique. */
slug: text("slug").notNull(),
/** One of LABEL_COLORS; null = automatic color derived from the name. */
color: text("color"),
createdAt: createdAt(),
},
(t) => [uniqueIndex("tags_slug_uq").on(t.slug)],
);
export const modelTags = sqliteTable(
"model_tags",
{
modelId: text("model_id")
.notNull()
.references(() => models.id),
tagId: text("tag_id")
.notNull()
.references(() => tags.id),
createdAt: createdAt(),
},
(t) => [primaryKey({ columns: [t.modelId, t.tagId] }), index("model_tags_tag_idx").on(t.tagId)],
);
/** History of SHAs a model has been pinned to. */
export const modelRevisions = sqliteTable(
"model_revisions",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
sha: text("sha").notNull(),
pinnedAt: ts("pinned_at")
.notNull()
.$defaultFn(() => new Date()),
supersededAt: ts("superseded_at"),
},
(t) => [index("model_revisions_model_idx").on(t.modelId)],
);
export const MODEL_FILE_STATES = [
"pending", // not downloaded yet / not checked
"present", // exists with the expected size
"missing",
"size_mismatch",
"hash_mismatch",
"verified", // deep verify: hash matches
] as const;
export type ModelFileState = (typeof MODEL_FILE_STATES)[number];
/** All files in the repo at the pinned SHA. `selected` marks what we keep locally. */
export const modelFiles = sqliteTable(
"model_files",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
path: text("path").notNull(),
size: integer("size").notNull(),
/** Git blob SHA-1 from the Hub tree API. */
blobOid: text("blob_oid"),
/** SHA-256 for LFS/Xet files (null for small git-stored files). */
lfsSha256: text("lfs_sha256"),
selected: integer("selected", { mode: "boolean" }).notNull().default(false),
state: text("state", { enum: MODEL_FILE_STATES }).notNull().default("pending"),
checkedAt: ts("checked_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [uniqueIndex("model_files_model_path_uq").on(t.modelId, t.path)],
);
// ---------------------------------------------------------------------------
// Jobs (executed by the worker)
// ---------------------------------------------------------------------------
export const JOB_KINDS = ["download", "verify", "deep_verify", "delete"] as const;
export type JobKind = (typeof JOB_KINDS)[number];
export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as const;
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"pending_approval", // requested through the API, waits for a human to approve it
"queued",
"downloading",
"verifying",
"completed",
"failed",
"cancelled",
"interrupted",
] as const;
export type JobState = (typeof JOB_STATES)[number];
export const ACTIVE_JOB_STATES = ["downloading", "verifying"] as const satisfies JobState[];
export const JOB_ERROR_CODES = [
"auth", // invalid/missing token
"gated", // gated repo, access not granted
"repo_not_found",
"revision_not_found",
"disk_full",
"network",
"size_mismatch", // finished but files don't match expected sizes
"unknown",
] as const;
export type JobErrorCode = (typeof JOB_ERROR_CODES)[number];
export const jobs = sqliteTable(
"jobs",
{
id: id(),
modelId: text("model_id")
.notNull()
.references(() => models.id),
kind: text("kind", { enum: JOB_KINDS }).notNull(),
purpose: text("purpose", { enum: JOB_PURPOSES }),
targetSha: text("target_sha").notNull(),
state: text("state", { enum: JOB_STATES }).notNull().default("queued"),
attempt: integer("attempt").notNull().default(0),
totalBytes: integer("total_bytes").notNull().default(0),
doneBytes: integer("done_bytes").notNull().default(0),
speedBps: integer("speed_bps"),
etaSeconds: integer("eta_seconds"),
exitCode: integer("exit_code"),
errorCode: text("error_code", { enum: JOB_ERROR_CODES }),
errorMessage: text("error_message"),
result: text("result", { mode: "json" }).$type<JobResult>(),
/** Set by the web app; the worker picks it up and stops the job. */
cancelRequestedAt: ts("cancel_requested_at"),
/** Requested through the API: the token, and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
(t) => [index("jobs_state_idx").on(t.state), index("jobs_model_idx").on(t.modelId)],
);
export const JOB_FILE_STATES = ["pending", "downloading", "done", "failed"] as const;
export type JobFileState = (typeof JOB_FILE_STATES)[number];
export const jobFiles = sqliteTable(
"job_files",
{
jobId: text("job_id")
.notNull()
.references(() => jobs.id),
modelFileId: text("model_file_id")
.notNull()
.references(() => modelFiles.id),
path: text("path").notNull(),
expectedBytes: integer("expected_bytes").notNull(),
doneBytes: integer("done_bytes").notNull().default(0),
state: text("state", { enum: JOB_FILE_STATES }).notNull().default("pending"),
},
(t) => [primaryKey({ columns: [t.jobId, t.modelFileId] })],
);
export const LOG_STREAMS = ["stdout", "stderr", "system"] as const;
export type LogStream = (typeof LOG_STREAMS)[number];
export const jobLogs = sqliteTable(
"job_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
jobId: text("job_id")
.notNull()
.references(() => jobs.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("job_logs_job_idx").on(t.jobId, t.id)],
);
// ---------------------------------------------------------------------------
// App settings (key/value, edited on the Settings page)
// ---------------------------------------------------------------------------
export const settings = sqliteTable("settings", {
key: text("key").primaryKey(),
value: text("value", { mode: "json" }).notNull(),
updatedAt: updatedAt(),
});
// ---------------------------------------------------------------------------
// Worker liveness
// ---------------------------------------------------------------------------
export const workerState = sqliteTable("worker_state", {
id: text("id").primaryKey(), // "worker"
/** Random per process; the row acts as a lease so only one worker runs at a time. */
instanceId: text("instance_id"),
pid: integer("pid"),
hfVersion: text("hf_version"),
/** Free/total bytes on the filesystem holding MODELS_DIR (the web app has no access to it). */
modelsDirFreeBytes: integer("models_dir_free_bytes"),
modelsDirTotalBytes: integer("models_dir_total_bytes"),
startedAt: ts("started_at").notNull(),
heartbeatAt: ts("heartbeat_at").notNull(),
/** Set by the web app ("Rescan"); the worker scans MODELS_DIR when this is newer than its last scan. */
scanRequestedAt: ts("scan_requested_at"),
/** Docker connection and host facts, reported by the worker (null: no DOCKER_HOST). */
docker: text("docker", { mode: "json" }).$type<DockerHostInfo>(),
});
export type DockerHostInfo = {
connected: boolean;
error: string | null;
serverVersion: string | null;
os: string | null;
architecture: string | null;
cpus: number | null;
memoryBytes: number | null;
cpuModel: string | null;
/** Relevant CPU features (avx2, avx512f, avx512_bf16, amx_bf16, …). */
cpuFeatures: string[];
/** Docker network inference containers join, so the worker can reach them. */
network: string | null;
/** Where the models come from on the Docker host (bind path or volume name), mounted read-only. */
modelsSource: { type: "bind" | "volume"; source: string } | null;
/** Docker has the NVIDIA runtime / CDI devices, so GPUs can be requested. */
nvidia?: boolean;
/** GPUs found by a probe container (nvidia-smi); empty when none or not probed. */
gpus?: HostGpu[];
gpuError?: string | null;
gpuCheckedAt?: string | null;
/** Group IDs owning /dev/dri on the host (render, video); given to Intel/AMD runtime containers. */
driGroups?: number[];
/** PCIe, ReBAR, system facts from sysfs/procfs (what the worker's container sees of the host). */
hardware?: HostHardware | null;
checkedAt: string;
};
export type HostGpu = {
vendor: "nvidia";
index: number;
uuid: string;
name: string;
memoryMb: number;
driver: string;
pciAddress?: string | null;
/** PCIe link as nvidia-smi reports it (also where sysfs isn't visible, e.g. WSL2). */
linkCurrent?: PcieLink | null;
linkMax?: PcieLink | null;
};
/** A PCIe link: generation (1 = 2.5 GT/s … 6 = 64 GT/s) and lanes. */
export type PcieLink = { gen: number | null; width: number | null };
export type GpuVendor = "nvidia" | "intel" | "amd";
/** A GPU as found on the PCI bus. The link is the card's upstream link (behind on-card switches). */
export type HardwareGpu = {
vendor: GpuVendor;
pciAddress: string;
name: string | null;
vramMb: number | null;
/** Kernel driver (nvidia, xe, i915, amdgpu) and its version (the kernel's for in-tree drivers). */
driver: string | null;
driverVersion: string | null;
linkCurrent: PcieLink | null;
linkMax: PcieLink | null;
/** Largest memory BAR in MiB; Resizable BAR is on when it covers the VRAM. */
barMb: number | null;
rebar: boolean | null;
};
export type HostHardware = {
gpus: HardwareGpu[];
/** Peer-to-peer between GPUs (NVIDIA: nvidia-smi topo); null = unknown or a single GPU. */
p2p: "on" | "off" | "partial" | null;
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
kernel: string | null;
virtualization: { vm: boolean | null; hypervisor: string | null };
/** The disk holding the models folder. */
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
checkedAt: string;
};
/** Settings → Hardware: manual values where detection can't see the truth (VMs, new GPUs). */
export type HardwareOverrides = {
gpus?: Record<string, { name?: string; vramMb?: number; linkCurrent?: string; linkMax?: string; rebar?: boolean }>;
p2p?: "on" | "off" | "partial";
storage?: string;
hypervisor?: string;
gpuPassthrough?: boolean;
gpuDriver?: string;
};
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
// ---------------------------------------------------------------------------
/** How Kaname builds the command line and talks to the server. */
export const RUNTIME_ENGINES = ["llama.cpp", "vllm"] as const;
export type RuntimeEngine = (typeof RUNTIME_ENGINES)[number];
/**
* What the image computes on. nvidia: GPUs requested through Docker (NVIDIA Container Toolkit);
* dri: Intel/AMD GPUs via /dev/dri (Vulkan, SYCL, XPU); rocm: AMD via /dev/kfd + /dev/dri.
*/
export const RUNTIME_ACCELERATORS = ["cpu", "nvidia", "dri", "rocm"] as const;
export type RuntimeAccelerator = (typeof RUNTIME_ACCELERATORS)[number];
export const IMAGE_STATES = ["unknown", "missing", "pulling", "present", "failed"] as const;
export type ImageState = (typeof IMAGE_STATES)[number];
export const runtimes = sqliteTable("runtimes", {
id: id(),
name: text("name").notNull(),
engine: text("engine", { enum: RUNTIME_ENGINES }).notNull(),
accelerator: text("accelerator", { enum: RUNTIME_ACCELERATORS }).notNull().default("cpu"),
/** Full image reference, e.g. "ghcr.io/ggml-org/llama.cpp:server". */
image: text("image").notNull(),
description: text("description"),
/** Environment variables for the container. */
env: text("env", { mode: "json" }).$type<Record<string, string>>().notNull().default(sql`'{}'`),
/** Appended to the generated command line (fork-specific flags). */
extraArgs: text("extra_args", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
/** Host devices to pass through, e.g. "/dev/dri" (later: Intel GPUs). */
devices: text("devices", { mode: "json" }).$type<string[]>().notNull().default(sql`'[]'`),
shmSizeMb: integer("shm_size_mb"),
/** vLLM's NUMA optimizations: adds CAP_SYS_NICE and seccomp=unconfined. Off unless enabled. */
numaTuning: integer("numa_tuning", { mode: "boolean" }).notNull().default(false),
/** Preset this runtime was created from, if any. */
preset: text("preset"),
imageState: text("image_state", { enum: IMAGE_STATES }).notNull().default("unknown"),
imageId: text("image_id"),
imageSize: integer("image_size"),
imageCreated: text("image_created"),
/** Set by "Pull"; the worker pulls when this is newer than the last pull. */
pullRequestedAt: ts("pull_requested_at"),
pullStartedAt: ts("pull_started_at"),
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
pullError: text("pull_error"),
imageCheckedAt: ts("image_checked_at"),
/** Registry digest of the pulled image (sha256:…), from its RepoDigests. */
imageDigest: text("image_digest"),
/** Shown instead of the engine type for forks, e.g. "vllm-radiance". */
engineName: text("engine_name"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
/**
* Folders in MODELS_DIR (`<org>/<name>`, like `hf download --local-dir` layouts) that no model uses,
* found by the worker's scan. Rewritten on every scan; the web app offers them for import.
*/
export const localFolders = sqliteTable("local_folders", {
/** Relative to MODELS_DIR, e.g. "unsloth/Qwen3-8B-GGUF". */
path: text("path").primaryKey(),
/** Files in the folder (without hf's .cache), capped. */
files: text("files", { mode: "json" }).$type<{ path: string; size: number }[]>().notNull(),
fileCount: integer("file_count").notNull(),
totalBytes: integer("total_bytes").notNull(),
/** Commit from hf's download metadata, if the folder was written by `hf download`. */
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;
/** llama.cpp: serve the built-in web UI at / (llama-server's default; false passes --no-webui). */
webui?: boolean | null;
/** llama.cpp -cram: prompt cache in RAM, MiB (llama-server default 8192; 0 off, -1 unlimited). */
cacheRamMb?: number | null;
/** NVIDIA: GPU UUIDs to use (null: all). */
gpus?: string[] | null;
/** llama.cpp -ngl: "auto" (default), "all" or a number of layers. */
gpuLayers?: string | null;
/** llama.cpp -sm across several GPUs. */
splitMode?: "none" | "layer" | "row" | "tensor" | null;
/** llama.cpp -ts, e.g. "3,1". */
tensorSplit?: string | null;
/** llama.cpp: keep all MoE expert weights in RAM (-cmoe) or those of the first N layers (-ncmoe). */
cpuMoe?: boolean | null;
nCpuMoe?: number | null;
/** vLLM --tensor-parallel-size and --gpu-memory-utilization. */
tensorParallel?: number | null;
gpuMemoryUtilization?: number | null;
/** Only accept requests with one of the API keys from Settings → API keys. */
requireApiKey?: boolean | 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>(),
/** Version, slots and context the server reported once ready. */
engineInfo: text("engine_info", { mode: "json" }).$type<EngineInfo>(),
/** Temporary deployment created by a benchmark sweep (removed when its variant is done). */
sweepId: text("sweep_id"),
/** Created through the API: the token and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
/** Agents can't edit, stop, delete or benchmark it, nor start anything that would crowd it out of VRAM. */
protected: integer("protected", { mode: "boolean" }).notNull().default(false),
/** An agent asked to start it; it starts once someone approves (approval mode "approve"). */
startRequestedAt: ts("start_requested_at"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
export const deploymentLogs = sqliteTable(
"deployment_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
deploymentId: text("deployment_id")
.notNull()
.references(() => deployments.id),
ts: ts("ts")
.notNull()
.$defaultFn(() => new Date()),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("deployment_logs_idx").on(t.deploymentId, t.id)],
);
/**
* API keys that deployments with `requireApiKey` accept. Stored in plain text because the worker
* hands them to the runtime container; never logged or written into a stored command line.
*/
export const apiKeys = sqliteTable("api_keys", {
id: id(),
name: text("name").notNull(),
key: text("key").notNull().unique(),
createdAt: createdAt(),
});
// ---------------------------------------------------------------------------
// API tokens: machine clients (e.g. an AI agent) calling /api/v1 with a bearer token
// ---------------------------------------------------------------------------
/** What a token may do. Nothing can delete, change settings or manage runtimes/tokens. */
export const TOKEN_SCOPES = ["models:read", "downloads:create", "deployments:read", "deployments:write", "benchmarks:read", "benchmarks:run"] as const;
export type TokenScope = (typeof TOKEN_SCOPES)[number];
export const apiTokens = sqliteTable(
"api_tokens",
{
id: id(),
name: text("name").notNull(),
/** First characters of the token, shown in the UI to tell tokens apart. */
prefix: text("prefix").notNull(),
/** SHA-256 of the token (hex); the token itself is never stored. */
hash: text("hash").notNull().unique(),
scopes: text("scopes", { mode: "json" }).$type<TokenScope[]>().notNull(),
lastUsedAt: ts("last_used_at"),
revokedAt: ts("revoked_at"),
createdAt: createdAt(),
},
(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 = ["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;
export type BenchmarkPhase = (typeof BENCHMARK_PHASES)[number];
/** What a run measures. `passes`/`warmup` null: BetterBench's defaults (20 / 3), or 5 / 1 with quick. */
export type BenchmarkSettings = {
quick: boolean;
passes: number | null;
warmup: number | null;
phases: BenchmarkPhase[];
/** A/B: target minimum detectable effect in % (BetterBench --mde, default 1) and pair ceiling. */
mdePct?: number | null;
maxPairs?: number | null;
/** eval: which sections (empty: all). Sweeps: also run the quality eval for each variant. */
evalSections?: QualitySection[];
quality?: boolean;
};
export const QUALITY_SECTIONS = ["tools", "coding", "retrieval"] as const;
export type QualitySection = (typeof QUALITY_SECTIONS)[number];
/** A quality eval's result: pass rates per section and the overall score (their mean), 0–100. */
export type QualityResult = {
/** The eval set's version; only results of the same version are comparable. */
evalSet: string;
score: number | null;
sections: {
section: QualitySection;
passed: number;
total: number;
score: number | null;
/** Why the section couldn't run (e.g. the server doesn't do tool calls); then it doesn't count. */
unsupported?: string | null;
seconds: number;
}[];
items: { section: QualitySection; id: string; pass: boolean; detail?: string | null }[];
config: { temperature: number; seed: number; thinking: boolean; contextTokens: number | null };
};
/** run: BetterBench; ab: paired A/B; eval: Kaname's quality eval (tool calling, coding, retrieval). */
export const BENCHMARK_KINDS = ["run", "ab", "eval"] as const;
export type BenchmarkKind = (typeof BENCHMARK_KINDS)[number];
/** One side of a paired comparison, as BetterBench's paired_compare reports it. */
export type PairedResult = {
metric: string;
n_pairs: number;
mean_a: number;
mean_b: number;
mean_diff: number;
pct_diff: number;
ci_low_pct: number;
ci_high_pct: number;
conf: number;
significant: boolean;
verdict: string;
higher_is_better: boolean;
};
/** `betterbench ab` result without the endpoints (raw per-pair series kept for the chart). */
export type AbSummary = {
pairs: number;
decode_tps: PairedResult;
gap_median: PairedResult & { batched: boolean };
paired_cv: number;
pairs_needed_for_mde: number;
target_mde_pct: number;
conf: number;
maxPairs: number | null;
raw: { a_tps: number[]; b_tps: number[] };
betterbenchVersion: string;
corpusVersion: string;
timestamp: string | null;
config: { greedy?: boolean | null; temperature?: number | null; warmup?: number | null; unique_nonce?: boolean | null; ab_min_pairs?: number | null };
};
/** Resource use sampled during a run (every ~2 s), per deployment and per GPU. */
export type ResourceStats = {
samples: number;
seconds: number;
containers: {
side: "a" | "b";
cpuAvg: number | null;
cpuPeak: number | null;
memAvgBytes: number | null;
memPeakBytes: number | null;
memLimitBytes: number | null;
}[];
/** Fastest PCIe link seen per GPU (PCI address) during the run. */
links?: Record<string, PcieLink>;
/**
* Whole-GPU figures, not per process: nvidia-smi; hwmon/sysfs for AMD; hwmon plus the DRM fdinfo
* of all processes for Intel. null where a source doesn't report it.
*/
gpus: {
index: number;
name: string;
pciAddress?: string;
vramTotalMb: number | null;
vramPeakMb: number | null;
vramAvgMb: number | null;
utilAvg: number | null;
utilPeak: number | null;
powerAvgW: number | null;
powerPeakW: number | null;
tempAvgC?: number | null;
tempPeakC?: number | null;
}[];
};
/** The deployment as it was when the run started, so results stay comparable after edits. */
export type BenchmarkSnapshot = {
deploymentName: string;
repoId: string;
runtimeName: string;
engine: RuntimeEngine;
accelerator?: RuntimeAccelerator;
/** Names of the GPUs used (NVIDIA), for comparisons. */
gpuNames?: string[];
/** The Docker host when the run started. */
host?: { cpuModel: string | null; threads: number | null; memoryBytes: number | null; os: string | null };
image: string;
imageId: string | null;
options: DeploymentOptions;
cpus: number | null;
memoryMb: number | null;
/** Rendered command (API keys masked). */
command: string;
};
/** What was measured on what, recorded when a run starts (Settings → Hardware overrides applied). */
export type RunMeta = {
v: 1;
gpus: { pciAddress?: string; name: string | null; vramMb: number | null; linkCurrent: PcieLink | null; linkMax: PcieLink | null; rebar: boolean | null }[];
/**
* GPUs lower their link speed when idle: true once linkCurrent is the fastest link seen while the run
* was under load (otherwise it is what detection saw, possibly idle).
*/
linkUnderLoad?: boolean;
/** "n/a" with fewer than two GPUs; null = unknown. */
p2p: "on" | "off" | "partial" | "n/a" | null;
/** On for every GPU used; null = unknown. */
rebar: boolean | null;
runtime: { image: string; tag: string | null; digest: string | null; engine: RuntimeEngine; engineName: string; engineVersion: string | null };
model: { repoId: string; file: string | null; quant: string | null; kvCache: string | null };
contextSize: number | null;
/** Parallel slots (llama.cpp) or max sequences (vLLM); reported by the server where it can. */
concurrency: number | null;
/** Fields taken from Settings → Hardware instead of detection. */
overridden: string[];
};
/** The host, as published: nothing that identifies it (no hostname, IP, user or path). */
export type SystemSummary = {
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
os: string | null;
kernel: string | null;
gpuDrivers: string[];
virtualization: { vm: boolean | null; hypervisor: string | null; gpuPassthrough: boolean | null };
kaname: string;
};
/** What the server reported about itself once ready (llama.cpp /props, vLLM /version and /v1/models). */
export type EngineInfo = { version: string | null; slots: number | null; contextSize: number | null; at: string };
/**
* BetterBench's own report rows for a run (betterbench.report: single_rows, prefill_rows,
* concurrency_rows, combined_score, sample_gate, …), copied as computed. Nothing in Kaname derives
* or fills in a number; `null` means BetterBench didn't report it. The endpoint and host are never
* stored. `v` 2; older summaries (no `v`) are recomputed by the worker from results.json.
*/
export type BenchmarkSummary = {
v?: number;
combined: { decode: number | null; ttft_p50: number | null; itl_low1: number | null; update_p50: number | null; update_p99: number | null } | null;
single: {
category: string;
runs: number;
tokens?: number;
ttft_n?: number;
gap_n?: number;
ttft_p99_ok?: boolean;
tail_ok?: boolean;
ttft_p50: number | null;
ttft_p99: number | null;
update_p50?: number | null;
update_p99?: number | null;
tok_per_update: number | null;
batched?: boolean;
batched_runs?: number;
decode_med: number | null;
decode_iqr?: number | null;
decode_cv: number | null;
itl_low1: number | null;
itl_med?: number | null;
itl_high99?: number | null;
}[];
prefill: {
target_depth: number;
skipped: boolean;
prompt_tokens_med?: number | null;
ttft_p50?: number | null;
pp_low1?: number | null;
pp_med?: number | null;
pp_p99?: number | null;
pp_n?: number;
pp_tail_ok?: boolean;
}[];
concurrency: {
level: number;
ok: number;
requests: number;
aggregate_tps: number;
ttft_p50: number | null;
ttft_p99: number | null;
decode_med: number | null;
ttft_n?: number;
ttft_p99_ok?: boolean;
}[];
/** Thinking models: share of reasoning tokens and time to first answer token, where detectable. */
reasoning?: { category: string; runs: number; known: number; answered: number; never_answered: number; reasoning_share: number | null; ttfa_p50: number | null }[];
/** Percentiles resting on fewer samples than n · tail ≥ 5 requires (BetterBench's sample gate). */
gate?: { section: string; key: string | number; metric: string; n: number; need: number }[];
/** [runs stopped at max_tokens, ok runs] in the single-stream set. */
truncated?: [number, number];
failedSingle?: number;
phases: string[];
cacheHits: number;
betterbenchVersion: string;
corpusVersion: string;
corpusHash?: string | null;
timestamp?: string | null;
maxModelLen?: number | null;
config?: {
warmup?: number | null;
runs_per_category?: number | null;
temperature?: number | null;
top_p?: number | null;
top_k?: number | null;
greedy?: boolean | null;
unique_nonce?: boolean | null;
weights?: Record<string, number> | null;
concurrency_levels?: number[] | null;
concurrency_requests?: number | null;
prefill_runs?: number | null;
prefill_warmup?: number | null;
prefill_max_tokens?: number | null;
};
passes: number | null;
quick: boolean;
};
export const benchmarkRuns = sqliteTable(
"benchmark_runs",
{
id: id(),
/** Null once the deployment is deleted; the snapshot keeps what was measured. */
deploymentId: text("deployment_id"),
modelId: text("model_id"),
tool: text("tool").notNull().default("betterbench"),
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
snapshot: text("snapshot", { mode: "json" }).$type<BenchmarkSnapshot>().notNull(),
/** Free-form label, e.g. "q8 KV cache". */
label: text("label"),
state: text("state", { enum: BENCHMARK_STATES }).notNull().default("queued"),
phase: text("phase"),
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
error: text("error"),
summary: text("summary", { mode: "json" }).$type<BenchmarkSummary>(),
/** Files under BENCHMARKS_DIR/<id>/: results.json and results.html. */
hasReport: integer("has_report", { mode: "boolean" }).notNull().default(false),
kind: text("kind", { enum: BENCHMARK_KINDS }).notNull().default("run"),
/** A/B: the second deployment (B); `deploymentId` is A. */
deploymentBId: text("deployment_b_id"),
snapshotB: text("snapshot_b", { mode: "json" }).$type<BenchmarkSnapshot>(),
ab: text("ab", { mode: "json" }).$type<AbSummary>(),
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** kind "eval": the quality eval's result. */
quality: text("quality", { mode: "json" }).$type<QualityResult>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
/** Requested through the API: the token and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
/** Agent runs: cancelled after this many seconds of running. */
timeLimitS: integer("time_limit_s"),
/** Hardware, runtime and model facts (A, and B of an A/B), recorded at the start. */
meta: text("meta", { mode: "json" }).$type<RunMeta>(),
metaB: text("meta_b", { mode: "json" }).$type<RunMeta>(),
system: text("system", { mode: "json" }).$type<SystemSummary>(),
/** Free text by the user; passed to BetterBench and launch80 with the system summary. */
description: text("description"),
createdAt: createdAt(),
},
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
);
export const benchmarkLogs = sqliteTable(
"benchmark_logs",
{
id: integer("id").primaryKey({ autoIncrement: true }),
runId: text("run_id").notNull(),
ts: integer("ts", { mode: "timestamp_ms" }).notNull(),
stream: text("stream", { enum: LOG_STREAMS }).notNull(),
line: text("line").notNull(),
},
(t) => [index("benchmark_logs_idx").on(t.runId, t.id)],
);
// ---------------------------------------------------------------------------
// launch80 publications (double opt-in: a dry-run preview, then an explicit confirmation)
// ---------------------------------------------------------------------------
/**
* preview: the worker runs `L80 betterbench --results … --dry-run --payload-out`; previewed: the
* exact payload is ready to inspect; publish: confirmed by a user, the worker publishes it;
* published / failed.
*/
export const PUBLICATION_STATES = ["preview", "previewed", "publish", "published", "failed"] as const;
export type PublicationState = (typeof PUBLICATION_STATES)[number];
export const benchmarkPublications = sqliteTable(
"benchmark_publications",
{
id: id(),
runId: text("run_id").notNull(),
state: text("state", { enum: PUBLICATION_STATES }).notNull().default("preview"),
template: text("template").notNull().default("bench.betterbench.v1"),
title: text("title"),
summary: text("summary"),
/** Size of the exact payload from the dry run; the payload itself is a file next to the run. */
payloadBytes: integer("payload_bytes"),
previewedAt: ts("previewed_at"),
/** Who confirmed publishing (the second opt-in), and when. */
confirmedBy: text("confirmed_by"),
confirmedAt: ts("confirmed_at"),
url: text("url"),
guid: text("guid"),
publishedAt: ts("published_at"),
error: text("error"),
createdAt: createdAt(),
},
(t) => [index("benchmark_publications_run_idx").on(t.runId)],
);
// ---------------------------------------------------------------------------
// Benchmark sweeps: one base deployment, one or two settings varied, a run per variant
// ---------------------------------------------------------------------------
export const SWEEP_STATES = ["pending_approval", "queued", "running", "completed", "failed", "cancelled"] as const;
export type SweepState = (typeof SWEEP_STATES)[number];
/** A setting a sweep varies; values are strings as entered (parsed per key). */
export type SweepParam = { key: string; values: string[] };
export type SweepVariant = {
index: number;
/** Option overrides for this variant, e.g. { contextSize: 8192, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }. */
overrides: Record<string, unknown>;
label: string;
state: "pending" | "deploying" | "benchmarking" | "evaluating" | "done" | "failed" | "skipped";
deploymentId?: string | null;
runId?: string | null;
/** The quality eval run of this variant (sweeps with quality: true). */
evalRunId?: string | null;
error?: string | null;
};
export const benchmarkSweeps = sqliteTable("benchmark_sweeps", {
id: id(),
label: text("label"),
/** The deployment the variants are copied from (may be deleted later; `base` keeps it). */
baseDeploymentId: text("base_deployment_id"),
base: text("base", { mode: "json" })
.$type<{ name: string; runtimeId: string; modelId: string; options: DeploymentOptions; cpus: number | null; memoryMb: number | null }>()
.notNull(),
params: text("params", { mode: "json" }).$type<SweepParam[]>().notNull(),
settings: text("settings", { mode: "json" }).$type<BenchmarkSettings>().notNull(),
variants: text("variants", { mode: "json" }).$type<SweepVariant[]>().notNull(),
state: text("state", { enum: SWEEP_STATES }).notNull().default("queued"),
cancelRequestedAt: ts("cancel_requested_at"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
error: text("error"),
/** Requested through the API: the token and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
/** Agent sweeps: the sweep is stopped after this many seconds, each of its runs after runTimeLimitS. */
timeLimitS: integer("time_limit_s"),
runTimeLimitS: integer("run_time_limit_s"),
createdAt: createdAt(),
});