diff --git a/.env.example b/.env.example
index f5805d1..4f44187 100644
--- a/.env.example
+++ b/.env.example
@@ -19,6 +19,11 @@ OIDC_ALLOWED_GROUPS=
# (higher rate limits). Stays on the server; never sent to the browser or written to logs.
HF_TOKEN=
+# Optional: launch80.com publish token (comes with the launch80 Supporter role). Lets you publish a
+# benchmark run as a public launch80 page, after a preview and an explicit confirmation. Stays on
+# the server; never sent to the browser or written to logs.
+L80_TOKEN=
+
# ---------------------------------------------------------------------------
# Folders on the Docker host (deploy/compose.yaml); both must be owned by uid 1000
# ---------------------------------------------------------------------------
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e678ae..0c045b9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,53 @@ step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
+### Added
+
+- **Benchmarks** (new main menu entry) with [BetterBench](https://github.com/GGZ14/BetterBench)
+ (Apache-2.0, the benchmark behind launch80.com), built into the image (v0.6.1, archive pinned by
+ checksum).
+ - Start a run from a running deployment: quick (5 passes) or full (20), choose generation,
+ prompt processing (input lengths up to the context size) and parallel requests, add a label.
+ - Runs go one at a time; the run page shows the current step, the live BetterBench output, then
+ headline numbers (weighted decode t/s, time to first token, prefill t/s, peak throughput) and
+ the per-category, per-length and per-load tables, BetterBench's own HTML report (sandboxed)
+ and its `results.json`.
+ - Each run keeps a snapshot of the deployment's settings (and the CPU/GPU it ran on). Select runs
+ to **compare** them: differing settings are highlighted, numbers show the change against the
+ first run.
+ - Cancel, run again with the same settings, rename, delete.
+- **Benchmark report page** after launch80's `bench.betterbench.v1`: headline tiles (combined
+ decode, ITL 1% low or stream-update p99, TTFT p50), "Read these first" caveats with launch80's
+ rules (quick run, under-sampled percentiles marked †, runs stopped at max_tokens, batched streams,
+ failed requests, skipped prefill depths, prefix-cache hits), charts for decode by category, ITL
+ range, prefill and parallel load, the full tables, the reasoning split and a Method section. Every
+ figure comes from BetterBench's own report functions; existing runs are recomputed on start.
+- **Publish to launch80** (double opt-in, as the L80 docs describe): step 1 runs
+ `L80 betterbench --results … --dry-run --payload-out` and shows exactly what would be sent
+ (template, size, title, summary, notes; endpoint and host removed; the payload is downloadable);
+ step 2 publishes that same file with `L80 publish` only after an explicit confirmation. Needs
+ `L80_TOKEN` (launch80 Supporter) for the worker; the L80 CLI 0.4.0 ships in the image, pinned by
+ checksum. The link, who confirmed it and when it expires (5 days) are kept per run.
+- `results.json` downloads no longer contain the endpoint URL or host name.
+- **GPUs.** Runtimes have a type: CPU, NVIDIA (CUDA), Intel/AMD via `/dev/dri` (Vulkan, SYCL,
+ XPU) or AMD ROCm, with presets for the official CUDA, Vulkan, Intel and ROCm builds of
+ llama.cpp and vLLM.
+ - The worker lists NVIDIA GPUs (name, VRAM, driver) with a short-lived probe container and shows
+ them under Settings → Runtimes; the first time one shows up, a "llama.cpp (CUDA)" runtime is
+ added.
+ - Deployments on GPU runtimes pick which GPUs to use and set GPU layers (`-ngl`), split mode,
+ tensor split and MoE experts in RAM (llama.cpp) or tensor parallelism and GPU memory share
+ (vLLM).
+- llama.cpp **prompt cache in RAM** (`--cache-ram`) as a deployment option, 1 GiB for new
+ deployments.
+
+### Fixed
+
+- llama-server keeps up to 8 GiB of earlier prompts in RAM by default. Under a container memory
+ limit it grew until the limit and then slowed to a crawl (the memory-mapped model got evicted).
+ The memory estimate now counts the prompt cache and the KV cache (by context size and cache
+ type).
+
## [0.8.0] - 2026-10-06
Model testing, part two: deployments. Serve a downloaded model with a llama.cpp or vLLM runtime
diff --git a/Dockerfile b/Dockerfile
index a54672a..493964d 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,3 +1,4 @@
+# syntax=docker/dockerfile:1.7
# One image for both services; the first argument picks the role: `web` (default) or `worker`.
FROM node:24-trixie-slim AS node
@@ -22,9 +23,28 @@ COPY --from=node /usr/local/bin/node /usr/local/bin/node
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
# re-verify that before bumping.
ARG HF_HUB_VERSION=2.1.1
+# BetterBench (Apache-2.0), the benchmark run against deployments. Not on PyPI: the release
+# archive is pinned by checksum; flags used by src/worker/betterbench.ts are verified per version.
+ARG BETTERBENCH_VERSION=0.6.1
+ADD --checksum=sha256:f0a9d7fcc411c809ff87a0a22e2d76f6662b426431d2ae9fa273bc2644464db7 \
+ https://codeload.github.com/GGZ14/BetterBench/tar.gz/refs/tags/v${BETTERBENCH_VERSION} /tmp/betterbench.tar.gz
+# L80 CLI (launch80.com): publishes a BetterBench run as a shareable page. Release archives pinned
+# by checksum (from the release's checksums.txt); the per-architecture one is installed.
+ARG L80_VERSION=0.4.0
+ARG TARGETARCH
+ADD --checksum=sha256:cde6b67dfb67b0ffddd56dfd384b8b24610573199287c59597359145310d9d23 \
+ https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_amd64.tar.gz /tmp/l80/amd64.tar.gz
+ADD --checksum=sha256:bbd7c6cf35bcba2bf9a651f348581b691b36d5f7cdca9c8a11e8a1ac2fc3f5bc \
+ https://github.com/launch80/L80-Skills/releases/download/v${L80_VERSION}/L80_linux_arm64.tar.gz /tmp/l80/arm64.tar.gz
+RUN mkdir -p /opt/l80 \
+ && tar -xzf "/tmp/l80/${TARGETARCH:-amd64}.tar.gz" -C /opt/l80 L80 \
+ && chmod 0755 /opt/l80/L80 \
+ && rm -rf /tmp/l80
RUN python -m venv /opt/hf \
&& /opt/hf/bin/pip install --no-cache-dir "huggingface_hub[hf_xet]==${HF_HUB_VERSION}" \
- && rm -rf /root/.cache \
+ && python -m venv /opt/betterbench \
+ && /opt/betterbench/bin/pip install --no-cache-dir /tmp/betterbench.tar.gz \
+ && rm -rf /root/.cache /tmp/betterbench.tar.gz \
&& useradd --uid 1000 --create-home --shell /usr/sbin/nologin app \
&& mkdir -p /data /models \
&& chown app:app /data /models
@@ -38,7 +58,9 @@ ENV PATH=/opt/hf/bin:$PATH \
HOSTNAME=0.0.0.0 \
DATABASE_URL=file:/data/app.db \
MODELS_DIR=/models \
- HF_HOME=/data/hf-home
+ HF_HOME=/data/hf-home \
+ BETTERBENCH_BIN=/opt/betterbench/bin/betterbench \
+ L80_BIN=/opt/l80/L80
WORKDIR /app
COPY --from=build --chown=app:app /app/package.json /app/next.config.ts ./
diff --git a/drizzle/0013_benchmarks.sql b/drizzle/0013_benchmarks.sql
new file mode 100644
index 0000000..bae8956
--- /dev/null
+++ b/drizzle/0013_benchmarks.sql
@@ -0,0 +1,29 @@
+CREATE TABLE `benchmark_logs` (
+ `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
+ `run_id` text NOT NULL,
+ `ts` integer NOT NULL,
+ `stream` text NOT NULL,
+ `line` text NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `benchmark_logs_idx` ON `benchmark_logs` (`run_id`,`id`);--> statement-breakpoint
+CREATE TABLE `benchmark_runs` (
+ `id` text PRIMARY KEY NOT NULL,
+ `deployment_id` text,
+ `model_id` text,
+ `tool` text DEFAULT 'betterbench' NOT NULL,
+ `settings` text NOT NULL,
+ `snapshot` text NOT NULL,
+ `label` text,
+ `state` text DEFAULT 'queued' NOT NULL,
+ `phase` text,
+ `cancel_requested_at` integer,
+ `started_at` integer,
+ `finished_at` integer,
+ `error` text,
+ `summary` text,
+ `has_report` integer DEFAULT false NOT NULL,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `benchmark_runs_created_idx` ON `benchmark_runs` (`created_at`);
\ No newline at end of file
diff --git a/drizzle/0014_runtime_accelerator.sql b/drizzle/0014_runtime_accelerator.sql
new file mode 100644
index 0000000..9514547
--- /dev/null
+++ b/drizzle/0014_runtime_accelerator.sql
@@ -0,0 +1 @@
+ALTER TABLE `runtimes` ADD `accelerator` text DEFAULT 'cpu' NOT NULL;
\ No newline at end of file
diff --git a/drizzle/0015_benchmark_publications.sql b/drizzle/0015_benchmark_publications.sql
new file mode 100644
index 0000000..400a147
--- /dev/null
+++ b/drizzle/0015_benchmark_publications.sql
@@ -0,0 +1,19 @@
+CREATE TABLE `benchmark_publications` (
+ `id` text PRIMARY KEY NOT NULL,
+ `run_id` text NOT NULL,
+ `state` text DEFAULT 'preview' NOT NULL,
+ `template` text DEFAULT 'bench.betterbench.v1' NOT NULL,
+ `title` text,
+ `summary` text,
+ `payload_bytes` integer,
+ `previewed_at` integer,
+ `confirmed_by` text,
+ `confirmed_at` integer,
+ `url` text,
+ `guid` text,
+ `published_at` integer,
+ `error` text,
+ `created_at` integer NOT NULL
+);
+--> statement-breakpoint
+CREATE INDEX `benchmark_publications_run_idx` ON `benchmark_publications` (`run_id`);
\ No newline at end of file
diff --git a/drizzle/meta/0013_snapshot.json b/drizzle/meta/0013_snapshot.json
new file mode 100644
index 0000000..2e408ed
--- /dev/null
+++ b/drizzle/meta/0013_snapshot.json
@@ -0,0 +1,1710 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "664d5f18-eefb-49f1-acb6-296226115906",
+ "prevId": "0d459c4f-2846-4f48-a248-25ef06279cb6",
+ "tables": {
+ "api_keys": {
+ "name": "api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "api_keys_key_unique": {
+ "name": "api_keys_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_logs": {
+ "name": "benchmark_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_logs_idx": {
+ "name": "benchmark_logs_idx",
+ "columns": [
+ "run_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_runs": {
+ "name": "benchmark_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "deployment_id": {
+ "name": "deployment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'betterbench'"
+ },
+ "settings": {
+ "name": "settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "phase": {
+ "name": "phase",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_requested_at": {
+ "name": "cancel_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "has_report": {
+ "name": "has_report",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_runs_created_idx": {
+ "name": "benchmark_runs_created_idx",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "deployment_logs": {
+ "name": "deployment_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "deployment_id": {
+ "name": "deployment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "deployment_logs_idx": {
+ "name": "deployment_logs_idx",
+ "columns": [
+ "deployment_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "deployment_logs_deployment_id_deployments_id_fk": {
+ "name": "deployment_logs_deployment_id_deployments_id_fk",
+ "tableFrom": "deployment_logs",
+ "tableTo": "deployments",
+ "columnsFrom": [
+ "deployment_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "deployments": {
+ "name": "deployments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtime_id": {
+ "name": "runtime_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cpus": {
+ "name": "cpus",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "memory_mb": {
+ "name": "memory_mb",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_port": {
+ "name": "host_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "desired_state": {
+ "name": "desired_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'stopped'"
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'stopped'"
+ },
+ "delete_requested_at": {
+ "name": "delete_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container_id": {
+ "name": "container_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container_name": {
+ "name": "container_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_id": {
+ "name": "image_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ready_at": {
+ "name": "ready_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stopped_at": {
+ "name": "stopped_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stats": {
+ "name": "stats",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "deployments_runtime_id_runtimes_id_fk": {
+ "name": "deployments_runtime_id_runtimes_id_fk",
+ "tableFrom": "deployments",
+ "tableTo": "runtimes",
+ "columnsFrom": [
+ "runtime_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "deployments_model_id_models_id_fk": {
+ "name": "deployments_model_id_models_id_fk",
+ "tableFrom": "deployments",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "job_files": {
+ "name": "job_files",
+ "columns": {
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_file_id": {
+ "name": "model_file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expected_bytes": {
+ "name": "expected_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "done_bytes": {
+ "name": "done_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "job_files_job_id_jobs_id_fk": {
+ "name": "job_files_job_id_jobs_id_fk",
+ "tableFrom": "job_files",
+ "tableTo": "jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "job_files_model_file_id_model_files_id_fk": {
+ "name": "job_files_model_file_id_model_files_id_fk",
+ "tableFrom": "job_files",
+ "tableTo": "model_files",
+ "columnsFrom": [
+ "model_file_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "job_files_job_id_model_file_id_pk": {
+ "columns": [
+ "job_id",
+ "model_file_id"
+ ],
+ "name": "job_files_job_id_model_file_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "job_logs": {
+ "name": "job_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "job_logs_job_idx": {
+ "name": "job_logs_job_idx",
+ "columns": [
+ "job_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "job_logs_job_id_jobs_id_fk": {
+ "name": "job_logs_job_id_jobs_id_fk",
+ "tableFrom": "job_logs",
+ "tableTo": "jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "jobs": {
+ "name": "jobs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "target_sha": {
+ "name": "target_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "attempt": {
+ "name": "attempt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_bytes": {
+ "name": "total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "done_bytes": {
+ "name": "done_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "speed_bps": {
+ "name": "speed_bps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "eta_seconds": {
+ "name": "eta_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_requested_at": {
+ "name": "cancel_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "jobs_state_idx": {
+ "name": "jobs_state_idx",
+ "columns": [
+ "state"
+ ],
+ "isUnique": false
+ },
+ "jobs_model_idx": {
+ "name": "jobs_model_idx",
+ "columns": [
+ "model_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "jobs_model_id_models_id_fk": {
+ "name": "jobs_model_id_models_id_fk",
+ "tableFrom": "jobs",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_folders": {
+ "name": "local_folders",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "files": {
+ "name": "files",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_count": {
+ "name": "file_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total_bytes": {
+ "name": "total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "commit": {
+ "name": "commit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scanned_at": {
+ "name": "scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_files": {
+ "name": "model_files",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blob_oid": {
+ "name": "blob_oid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lfs_sha256": {
+ "name": "lfs_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "selected": {
+ "name": "selected",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_files_model_path_uq": {
+ "name": "model_files_model_path_uq",
+ "columns": [
+ "model_id",
+ "path"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "model_files_model_id_models_id_fk": {
+ "name": "model_files_model_id_models_id_fk",
+ "tableFrom": "model_files",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_revisions": {
+ "name": "model_revisions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "superseded_at": {
+ "name": "superseded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_revisions_model_idx": {
+ "name": "model_revisions_model_idx",
+ "columns": [
+ "model_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "model_revisions_model_id_models_id_fk": {
+ "name": "model_revisions_model_id_models_id_fk",
+ "tableFrom": "model_revisions",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_tags": {
+ "name": "model_tags",
+ "columns": {
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_tags_tag_idx": {
+ "name": "model_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "model_tags_model_id_models_id_fk": {
+ "name": "model_tags_model_id_models_id_fk",
+ "tableFrom": "model_tags",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "model_tags_tag_id_tags_id_fk": {
+ "name": "model_tags_tag_id_tags_id_fk",
+ "tableFrom": "model_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "model_tags_model_id_tag_id_pk": {
+ "columns": [
+ "model_id",
+ "tag_id"
+ ],
+ "name": "model_tags_model_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "models": {
+ "name": "models",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo_type": {
+ "name": "repo_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'model'"
+ },
+ "repo_id": {
+ "name": "repo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracked_revision": {
+ "name": "tracked_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "pinned_sha": {
+ "name": "pinned_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "local_path": {
+ "name": "local_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "include_patterns": {
+ "name": "include_patterns",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "exclude_patterns": {
+ "name": "exclude_patterns",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "remote_sha": {
+ "name": "remote_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_checked_at": {
+ "name": "last_checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_check_error": {
+ "name": "last_check_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_state": {
+ "name": "hub_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_missing_since": {
+ "name": "hub_missing_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "update_diff": {
+ "name": "update_diff",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_verified_at": {
+ "name": "last_verified_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "downloaded_at": {
+ "name": "downloaded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "base_models": {
+ "name": "base_models",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "base_relation": {
+ "name": "base_relation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_avatar_url": {
+ "name": "author_avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "architecture": {
+ "name": "architecture",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pipeline_tag": {
+ "name": "pipeline_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "license": {
+ "name": "license",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_tags": {
+ "name": "hub_tags",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata_fetched_at": {
+ "name": "metadata_fetched_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "models_repo_uq": {
+ "name": "models_repo_uq",
+ "columns": [
+ "repo_type",
+ "repo_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "engine": {
+ "name": "engine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "extra_args": {
+ "name": "extra_args",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "devices": {
+ "name": "devices",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "shm_size_mb": {
+ "name": "shm_size_mb",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "numa_tuning": {
+ "name": "numa_tuning",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "preset": {
+ "name": "preset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_state": {
+ "name": "image_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "image_id": {
+ "name": "image_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_size": {
+ "name": "image_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_created": {
+ "name": "image_created",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_requested_at": {
+ "name": "pull_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_started_at": {
+ "name": "pull_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_progress": {
+ "name": "pull_progress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_error": {
+ "name": "pull_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_checked_at": {
+ "name": "image_checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tags": {
+ "name": "tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tags_slug_uq": {
+ "name": "tags_slug_uq",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "worker_state": {
+ "name": "worker_state",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pid": {
+ "name": "pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hf_version": {
+ "name": "hf_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "models_dir_free_bytes": {
+ "name": "models_dir_free_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "models_dir_total_bytes": {
+ "name": "models_dir_total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scan_requested_at": {
+ "name": "scan_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "docker": {
+ "name": "docker",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/0014_snapshot.json b/drizzle/meta/0014_snapshot.json
new file mode 100644
index 0000000..ea2f5d8
--- /dev/null
+++ b/drizzle/meta/0014_snapshot.json
@@ -0,0 +1,1718 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "5e6c0bf9-4e45-4f01-b460-bc0cbbdbe1ab",
+ "prevId": "664d5f18-eefb-49f1-acb6-296226115906",
+ "tables": {
+ "api_keys": {
+ "name": "api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "api_keys_key_unique": {
+ "name": "api_keys_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_logs": {
+ "name": "benchmark_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_logs_idx": {
+ "name": "benchmark_logs_idx",
+ "columns": [
+ "run_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_runs": {
+ "name": "benchmark_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "deployment_id": {
+ "name": "deployment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'betterbench'"
+ },
+ "settings": {
+ "name": "settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "phase": {
+ "name": "phase",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_requested_at": {
+ "name": "cancel_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "has_report": {
+ "name": "has_report",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_runs_created_idx": {
+ "name": "benchmark_runs_created_idx",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "deployment_logs": {
+ "name": "deployment_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "deployment_id": {
+ "name": "deployment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "deployment_logs_idx": {
+ "name": "deployment_logs_idx",
+ "columns": [
+ "deployment_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "deployment_logs_deployment_id_deployments_id_fk": {
+ "name": "deployment_logs_deployment_id_deployments_id_fk",
+ "tableFrom": "deployment_logs",
+ "tableTo": "deployments",
+ "columnsFrom": [
+ "deployment_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "deployments": {
+ "name": "deployments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtime_id": {
+ "name": "runtime_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cpus": {
+ "name": "cpus",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "memory_mb": {
+ "name": "memory_mb",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_port": {
+ "name": "host_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "desired_state": {
+ "name": "desired_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'stopped'"
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'stopped'"
+ },
+ "delete_requested_at": {
+ "name": "delete_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container_id": {
+ "name": "container_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container_name": {
+ "name": "container_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_id": {
+ "name": "image_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ready_at": {
+ "name": "ready_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stopped_at": {
+ "name": "stopped_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stats": {
+ "name": "stats",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "deployments_runtime_id_runtimes_id_fk": {
+ "name": "deployments_runtime_id_runtimes_id_fk",
+ "tableFrom": "deployments",
+ "tableTo": "runtimes",
+ "columnsFrom": [
+ "runtime_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "deployments_model_id_models_id_fk": {
+ "name": "deployments_model_id_models_id_fk",
+ "tableFrom": "deployments",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "job_files": {
+ "name": "job_files",
+ "columns": {
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_file_id": {
+ "name": "model_file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expected_bytes": {
+ "name": "expected_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "done_bytes": {
+ "name": "done_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "job_files_job_id_jobs_id_fk": {
+ "name": "job_files_job_id_jobs_id_fk",
+ "tableFrom": "job_files",
+ "tableTo": "jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "job_files_model_file_id_model_files_id_fk": {
+ "name": "job_files_model_file_id_model_files_id_fk",
+ "tableFrom": "job_files",
+ "tableTo": "model_files",
+ "columnsFrom": [
+ "model_file_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "job_files_job_id_model_file_id_pk": {
+ "columns": [
+ "job_id",
+ "model_file_id"
+ ],
+ "name": "job_files_job_id_model_file_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "job_logs": {
+ "name": "job_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "job_logs_job_idx": {
+ "name": "job_logs_job_idx",
+ "columns": [
+ "job_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "job_logs_job_id_jobs_id_fk": {
+ "name": "job_logs_job_id_jobs_id_fk",
+ "tableFrom": "job_logs",
+ "tableTo": "jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "jobs": {
+ "name": "jobs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "target_sha": {
+ "name": "target_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "attempt": {
+ "name": "attempt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_bytes": {
+ "name": "total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "done_bytes": {
+ "name": "done_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "speed_bps": {
+ "name": "speed_bps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "eta_seconds": {
+ "name": "eta_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_requested_at": {
+ "name": "cancel_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "jobs_state_idx": {
+ "name": "jobs_state_idx",
+ "columns": [
+ "state"
+ ],
+ "isUnique": false
+ },
+ "jobs_model_idx": {
+ "name": "jobs_model_idx",
+ "columns": [
+ "model_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "jobs_model_id_models_id_fk": {
+ "name": "jobs_model_id_models_id_fk",
+ "tableFrom": "jobs",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_folders": {
+ "name": "local_folders",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "files": {
+ "name": "files",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_count": {
+ "name": "file_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total_bytes": {
+ "name": "total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "commit": {
+ "name": "commit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scanned_at": {
+ "name": "scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_files": {
+ "name": "model_files",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blob_oid": {
+ "name": "blob_oid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lfs_sha256": {
+ "name": "lfs_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "selected": {
+ "name": "selected",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_files_model_path_uq": {
+ "name": "model_files_model_path_uq",
+ "columns": [
+ "model_id",
+ "path"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "model_files_model_id_models_id_fk": {
+ "name": "model_files_model_id_models_id_fk",
+ "tableFrom": "model_files",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_revisions": {
+ "name": "model_revisions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "superseded_at": {
+ "name": "superseded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_revisions_model_idx": {
+ "name": "model_revisions_model_idx",
+ "columns": [
+ "model_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "model_revisions_model_id_models_id_fk": {
+ "name": "model_revisions_model_id_models_id_fk",
+ "tableFrom": "model_revisions",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_tags": {
+ "name": "model_tags",
+ "columns": {
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_tags_tag_idx": {
+ "name": "model_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "model_tags_model_id_models_id_fk": {
+ "name": "model_tags_model_id_models_id_fk",
+ "tableFrom": "model_tags",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "model_tags_tag_id_tags_id_fk": {
+ "name": "model_tags_tag_id_tags_id_fk",
+ "tableFrom": "model_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "model_tags_model_id_tag_id_pk": {
+ "columns": [
+ "model_id",
+ "tag_id"
+ ],
+ "name": "model_tags_model_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "models": {
+ "name": "models",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo_type": {
+ "name": "repo_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'model'"
+ },
+ "repo_id": {
+ "name": "repo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracked_revision": {
+ "name": "tracked_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "pinned_sha": {
+ "name": "pinned_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "local_path": {
+ "name": "local_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "include_patterns": {
+ "name": "include_patterns",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "exclude_patterns": {
+ "name": "exclude_patterns",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "remote_sha": {
+ "name": "remote_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_checked_at": {
+ "name": "last_checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_check_error": {
+ "name": "last_check_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_state": {
+ "name": "hub_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_missing_since": {
+ "name": "hub_missing_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "update_diff": {
+ "name": "update_diff",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_verified_at": {
+ "name": "last_verified_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "downloaded_at": {
+ "name": "downloaded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "base_models": {
+ "name": "base_models",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "base_relation": {
+ "name": "base_relation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_avatar_url": {
+ "name": "author_avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "architecture": {
+ "name": "architecture",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pipeline_tag": {
+ "name": "pipeline_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "license": {
+ "name": "license",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_tags": {
+ "name": "hub_tags",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata_fetched_at": {
+ "name": "metadata_fetched_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "models_repo_uq": {
+ "name": "models_repo_uq",
+ "columns": [
+ "repo_type",
+ "repo_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "engine": {
+ "name": "engine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accelerator": {
+ "name": "accelerator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cpu'"
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "extra_args": {
+ "name": "extra_args",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "devices": {
+ "name": "devices",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "shm_size_mb": {
+ "name": "shm_size_mb",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "numa_tuning": {
+ "name": "numa_tuning",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "preset": {
+ "name": "preset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_state": {
+ "name": "image_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "image_id": {
+ "name": "image_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_size": {
+ "name": "image_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_created": {
+ "name": "image_created",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_requested_at": {
+ "name": "pull_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_started_at": {
+ "name": "pull_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_progress": {
+ "name": "pull_progress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_error": {
+ "name": "pull_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_checked_at": {
+ "name": "image_checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tags": {
+ "name": "tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tags_slug_uq": {
+ "name": "tags_slug_uq",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "worker_state": {
+ "name": "worker_state",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pid": {
+ "name": "pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hf_version": {
+ "name": "hf_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "models_dir_free_bytes": {
+ "name": "models_dir_free_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "models_dir_total_bytes": {
+ "name": "models_dir_total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scan_requested_at": {
+ "name": "scan_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "docker": {
+ "name": "docker",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/0015_snapshot.json b/drizzle/meta/0015_snapshot.json
new file mode 100644
index 0000000..f5c7bfb
--- /dev/null
+++ b/drizzle/meta/0015_snapshot.json
@@ -0,0 +1,1843 @@
+{
+ "version": "6",
+ "dialect": "sqlite",
+ "id": "b794cf33-c3fd-4dc8-9a8c-8320abc1a056",
+ "prevId": "5e6c0bf9-4e45-4f01-b460-bc0cbbdbe1ab",
+ "tables": {
+ "api_keys": {
+ "name": "api_keys",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "api_keys_key_unique": {
+ "name": "api_keys_key_unique",
+ "columns": [
+ "key"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_logs": {
+ "name": "benchmark_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_logs_idx": {
+ "name": "benchmark_logs_idx",
+ "columns": [
+ "run_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_publications": {
+ "name": "benchmark_publications",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "run_id": {
+ "name": "run_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'preview'"
+ },
+ "template": {
+ "name": "template",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'bench.betterbench.v1'"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "payload_bytes": {
+ "name": "payload_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "previewed_at": {
+ "name": "previewed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "confirmed_by": {
+ "name": "confirmed_by",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "confirmed_at": {
+ "name": "confirmed_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "url": {
+ "name": "url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "guid": {
+ "name": "guid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "published_at": {
+ "name": "published_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_publications_run_idx": {
+ "name": "benchmark_publications_run_idx",
+ "columns": [
+ "run_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "benchmark_runs": {
+ "name": "benchmark_runs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "deployment_id": {
+ "name": "deployment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "tool": {
+ "name": "tool",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'betterbench'"
+ },
+ "settings": {
+ "name": "settings",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "snapshot": {
+ "name": "snapshot",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "label": {
+ "name": "label",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "phase": {
+ "name": "phase",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_requested_at": {
+ "name": "cancel_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "summary": {
+ "name": "summary",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "has_report": {
+ "name": "has_report",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "benchmark_runs_created_idx": {
+ "name": "benchmark_runs_created_idx",
+ "columns": [
+ "created_at"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "deployment_logs": {
+ "name": "deployment_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "deployment_id": {
+ "name": "deployment_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "deployment_logs_idx": {
+ "name": "deployment_logs_idx",
+ "columns": [
+ "deployment_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "deployment_logs_deployment_id_deployments_id_fk": {
+ "name": "deployment_logs_deployment_id_deployments_id_fk",
+ "tableFrom": "deployment_logs",
+ "tableTo": "deployments",
+ "columnsFrom": [
+ "deployment_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "deployments": {
+ "name": "deployments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "runtime_id": {
+ "name": "runtime_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "options": {
+ "name": "options",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "cpus": {
+ "name": "cpus",
+ "type": "real",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "memory_mb": {
+ "name": "memory_mb",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "host_port": {
+ "name": "host_port",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "desired_state": {
+ "name": "desired_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'stopped'"
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'stopped'"
+ },
+ "delete_requested_at": {
+ "name": "delete_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container_id": {
+ "name": "container_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "container_name": {
+ "name": "container_name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "command": {
+ "name": "command",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_id": {
+ "name": "image_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "ready_at": {
+ "name": "ready_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stopped_at": {
+ "name": "stopped_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error": {
+ "name": "error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stats": {
+ "name": "stats",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "deployments_runtime_id_runtimes_id_fk": {
+ "name": "deployments_runtime_id_runtimes_id_fk",
+ "tableFrom": "deployments",
+ "tableTo": "runtimes",
+ "columnsFrom": [
+ "runtime_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "deployments_model_id_models_id_fk": {
+ "name": "deployments_model_id_models_id_fk",
+ "tableFrom": "deployments",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "job_files": {
+ "name": "job_files",
+ "columns": {
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_file_id": {
+ "name": "model_file_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expected_bytes": {
+ "name": "expected_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "done_bytes": {
+ "name": "done_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {
+ "job_files_job_id_jobs_id_fk": {
+ "name": "job_files_job_id_jobs_id_fk",
+ "tableFrom": "job_files",
+ "tableTo": "jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "job_files_model_file_id_model_files_id_fk": {
+ "name": "job_files_model_file_id_model_files_id_fk",
+ "tableFrom": "job_files",
+ "tableTo": "model_files",
+ "columnsFrom": [
+ "model_file_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "job_files_job_id_model_file_id_pk": {
+ "columns": [
+ "job_id",
+ "model_file_id"
+ ],
+ "name": "job_files_job_id_model_file_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "job_logs": {
+ "name": "job_logs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "integer",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": true
+ },
+ "job_id": {
+ "name": "job_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ts": {
+ "name": "ts",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "stream": {
+ "name": "stream",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "line": {
+ "name": "line",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "job_logs_job_idx": {
+ "name": "job_logs_job_idx",
+ "columns": [
+ "job_id",
+ "id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "job_logs_job_id_jobs_id_fk": {
+ "name": "job_logs_job_id_jobs_id_fk",
+ "tableFrom": "job_logs",
+ "tableTo": "jobs",
+ "columnsFrom": [
+ "job_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "jobs": {
+ "name": "jobs",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "kind": {
+ "name": "kind",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "purpose": {
+ "name": "purpose",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "target_sha": {
+ "name": "target_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'queued'"
+ },
+ "attempt": {
+ "name": "attempt",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "total_bytes": {
+ "name": "total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "done_bytes": {
+ "name": "done_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 0
+ },
+ "speed_bps": {
+ "name": "speed_bps",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "eta_seconds": {
+ "name": "eta_seconds",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "exit_code": {
+ "name": "exit_code",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_code": {
+ "name": "error_code",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "error_message": {
+ "name": "error_message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "result": {
+ "name": "result",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "cancel_requested_at": {
+ "name": "cancel_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "finished_at": {
+ "name": "finished_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "jobs_state_idx": {
+ "name": "jobs_state_idx",
+ "columns": [
+ "state"
+ ],
+ "isUnique": false
+ },
+ "jobs_model_idx": {
+ "name": "jobs_model_idx",
+ "columns": [
+ "model_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "jobs_model_id_models_id_fk": {
+ "name": "jobs_model_id_models_id_fk",
+ "tableFrom": "jobs",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "local_folders": {
+ "name": "local_folders",
+ "columns": {
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "files": {
+ "name": "files",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "file_count": {
+ "name": "file_count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "total_bytes": {
+ "name": "total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "commit": {
+ "name": "commit",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scanned_at": {
+ "name": "scanned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_files": {
+ "name": "model_files",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "path": {
+ "name": "path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "blob_oid": {
+ "name": "blob_oid",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lfs_sha256": {
+ "name": "lfs_sha256",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "selected": {
+ "name": "selected",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "state": {
+ "name": "state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "checked_at": {
+ "name": "checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_files_model_path_uq": {
+ "name": "model_files_model_path_uq",
+ "columns": [
+ "model_id",
+ "path"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {
+ "model_files_model_id_models_id_fk": {
+ "name": "model_files_model_id_models_id_fk",
+ "tableFrom": "model_files",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_revisions": {
+ "name": "model_revisions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sha": {
+ "name": "sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "pinned_at": {
+ "name": "pinned_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "superseded_at": {
+ "name": "superseded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_revisions_model_idx": {
+ "name": "model_revisions_model_idx",
+ "columns": [
+ "model_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "model_revisions_model_id_models_id_fk": {
+ "name": "model_revisions_model_id_models_id_fk",
+ "tableFrom": "model_revisions",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "model_tags": {
+ "name": "model_tags",
+ "columns": {
+ "model_id": {
+ "name": "model_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tag_id": {
+ "name": "tag_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "model_tags_tag_idx": {
+ "name": "model_tags_tag_idx",
+ "columns": [
+ "tag_id"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {
+ "model_tags_model_id_models_id_fk": {
+ "name": "model_tags_model_id_models_id_fk",
+ "tableFrom": "model_tags",
+ "tableTo": "models",
+ "columnsFrom": [
+ "model_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ },
+ "model_tags_tag_id_tags_id_fk": {
+ "name": "model_tags_tag_id_tags_id_fk",
+ "tableFrom": "model_tags",
+ "tableTo": "tags",
+ "columnsFrom": [
+ "tag_id"
+ ],
+ "columnsTo": [
+ "id"
+ ],
+ "onDelete": "no action",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {
+ "model_tags_model_id_tag_id_pk": {
+ "columns": [
+ "model_id",
+ "tag_id"
+ ],
+ "name": "model_tags_model_id_tag_id_pk"
+ }
+ },
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "models": {
+ "name": "models",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "repo_type": {
+ "name": "repo_type",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'model'"
+ },
+ "repo_id": {
+ "name": "repo_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "tracked_revision": {
+ "name": "tracked_revision",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'main'"
+ },
+ "pinned_sha": {
+ "name": "pinned_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "local_path": {
+ "name": "local_path",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "include_patterns": {
+ "name": "include_patterns",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "exclude_patterns": {
+ "name": "exclude_patterns",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "status": {
+ "name": "status",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "remote_sha": {
+ "name": "remote_sha",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_checked_at": {
+ "name": "last_checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_check_error": {
+ "name": "last_check_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_state": {
+ "name": "hub_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_missing_since": {
+ "name": "hub_missing_since",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "update_diff": {
+ "name": "update_diff",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "last_verified_at": {
+ "name": "last_verified_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "downloaded_at": {
+ "name": "downloaded_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "base_models": {
+ "name": "base_models",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "base_relation": {
+ "name": "base_relation",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "author_avatar_url": {
+ "name": "author_avatar_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "architecture": {
+ "name": "architecture",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pipeline_tag": {
+ "name": "pipeline_tag",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "license": {
+ "name": "license",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hub_tags": {
+ "name": "hub_tags",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata_fetched_at": {
+ "name": "metadata_fetched_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "models_repo_uq": {
+ "name": "models_repo_uq",
+ "columns": [
+ "repo_type",
+ "repo_id"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "runtimes": {
+ "name": "runtimes",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "engine": {
+ "name": "engine",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accelerator": {
+ "name": "accelerator",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'cpu'"
+ },
+ "image": {
+ "name": "image",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "description": {
+ "name": "description",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "env": {
+ "name": "env",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'{}'"
+ },
+ "extra_args": {
+ "name": "extra_args",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "devices": {
+ "name": "devices",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'[]'"
+ },
+ "shm_size_mb": {
+ "name": "shm_size_mb",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "numa_tuning": {
+ "name": "numa_tuning",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "preset": {
+ "name": "preset",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_state": {
+ "name": "image_state",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'unknown'"
+ },
+ "image_id": {
+ "name": "image_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_size": {
+ "name": "image_size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_created": {
+ "name": "image_created",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_requested_at": {
+ "name": "pull_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_started_at": {
+ "name": "pull_started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_progress": {
+ "name": "pull_progress",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pull_error": {
+ "name": "pull_error",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image_checked_at": {
+ "name": "image_checked_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "settings": {
+ "name": "settings",
+ "columns": {
+ "key": {
+ "name": "key",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "value": {
+ "name": "value",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "tags": {
+ "name": "tags",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "slug": {
+ "name": "slug",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "color": {
+ "name": "color",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "tags_slug_uq": {
+ "name": "tags_slug_uq",
+ "columns": [
+ "slug"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ },
+ "worker_state": {
+ "name": "worker_state",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "text",
+ "primaryKey": true,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "instance_id": {
+ "name": "instance_id",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "pid": {
+ "name": "pid",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "hf_version": {
+ "name": "hf_version",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "models_dir_free_bytes": {
+ "name": "models_dir_free_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "models_dir_total_bytes": {
+ "name": "models_dir_total_bytes",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "started_at": {
+ "name": "started_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "heartbeat_at": {
+ "name": "heartbeat_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "scan_requested_at": {
+ "name": "scan_requested_at",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "docker": {
+ "name": "docker",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "checkConstraints": {}
+ }
+ },
+ "views": {},
+ "enums": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ },
+ "internal": {
+ "indexes": {}
+ }
+}
\ No newline at end of file
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index fc21ded..a0aa61f 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -92,6 +92,27 @@
"when": 1791281615301,
"tag": "0012_api_keys",
"breakpoints": true
+ },
+ {
+ "idx": 13,
+ "version": "6",
+ "when": 1791654372298,
+ "tag": "0013_benchmarks",
+ "breakpoints": true
+ },
+ {
+ "idx": 14,
+ "version": "6",
+ "when": 1791655909335,
+ "tag": "0014_runtime_accelerator",
+ "breakpoints": true
+ },
+ {
+ "idx": 15,
+ "version": "6",
+ "when": 1791657884019,
+ "tag": "0015_benchmark_publications",
+ "breakpoints": true
}
]
}
\ No newline at end of file
diff --git a/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx
new file mode 100644
index 0000000..001232c
--- /dev/null
+++ b/src/app/(app)/benchmarks/[id]/benchmark-detail.tsx
@@ -0,0 +1,232 @@
+"use client";
+
+import { DownloadIcon, ExternalLinkIcon, RotateCcwIcon, SquareIcon, Trash2Icon, TriangleAlertIcon } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { BenchmarkStateBadge } from "@/components/benchmark-state";
+import { CopyButton } from "@/components/copy-button";
+import { LiveLog } from "@/components/live-log";
+import { LocalTime } from "@/components/local-time";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from "@/components/ui/alert-dialog";
+import { Button, buttonVariants } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Input } from "@/components/ui/input";
+import { reportSummary, weightsLabel } from "@/lib/benchmark-report";
+import { CONFIG_ROWS, describeSettings } from "@/lib/benchmark-view";
+import type { ListRow } from "../benchmark-list";
+import { cancelBenchmark, deleteBenchmark, renameBenchmark } from "../actions";
+import { BenchmarkReport } from "./benchmark-report";
+import { PublishCard } from "./publish-card";
+
+function duration(a: string | null, b: string | null, now: number) {
+ if (!a) return null;
+ const s = Math.max(0, ((b ? new Date(b).getTime() : now) - new Date(a).getTime()) / 1000);
+ const h = Math.floor(s / 3600);
+ const m = Math.floor((s % 3600) / 60);
+ return h ? `${h} h ${m} min` : m ? `${m} min ${Math.round(s % 60)} s` : `${Math.round(s)} s`;
+}
+
+export function BenchmarkDetail({ initial }: { initial: ListRow }) {
+ const router = useRouter();
+ const [r, setR] = useState(initial);
+ const [now, setNow] = useState(() => Date.now());
+ const [label, setLabel] = useState(initial.label ?? "");
+ const active = r.state === "queued" || r.state === "running";
+
+ useEffect(() => {
+ if (!active) return;
+ const t = setInterval(async () => {
+ setNow(Date.now());
+ const res = await fetch(`/api/benchmarks/${r.id}`, { cache: "no-store" }).catch(() => null);
+ if (res?.ok) setR(await res.json());
+ }, 2_000);
+ return () => clearInterval(t);
+ }, [active, r.id]);
+
+ async function again() {
+ if (!r.deploymentId) return;
+ const res = await fetch("/api/benchmarks", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ deploymentId: r.deploymentId, label: r.label, ...r.settings }),
+ });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
+ router.push(`/benchmarks/${json.id}`);
+ }
+
+ const s = r.snapshot;
+ const sum = r.summary;
+ const took = duration(r.startedAt, r.finishedAt, now);
+
+ return (
+
+
+
+
+
+
{r.label ?? s.deploymentName}
+
+
+
+ {r.deploymentId ? (
+
+ {s.deploymentName}
+
+ ) : (
+ `${s.deploymentName} (deleted)`
+ )}{" "}
+ ·{" "}
+ {r.modelId ? (
+
+ {s.repoId}
+
+ ) : (
+ s.repoId
+ )}{" "}
+ · {s.runtimeName}
+
+
+ BetterBench · {describeSettings(r.settings)} · created
+ {took && ` · ${r.state === "running" ? "running for" : "took"} ${took}`}
+
+
+
+ {r.hasReport && (
+
+
+ Full report
+
+ )}
+ {r.state === "completed" && (
+
+
+ results.json
+
+ )}
+ {active ? (
+
(await cancelBenchmark(r.id)) && router.refresh()}>
+
+ Cancel
+
+ ) : (
+ r.deploymentId && (
+
+
+ Run again
+
+ )
+ )}
+
+ }
+ >
+
+ Delete
+
+
+
+ Delete this benchmark?
+ Its numbers, log, results.json and HTML report are removed.
+
+
+ Cancel
+ {
+ if (await deleteBenchmark(r.id)) {
+ router.push("/benchmarks");
+ router.refresh();
+ }
+ }}
+ >
+ Delete
+
+
+
+
+
+
+
+
+ {r.error && (
+
+ )}
+ {r.state === "queued" &&
Waiting: benchmarks run one at a time.
}
+ {r.state === "running" && r.phase &&
Now: {r.phase}
}
+
+
+
+
+
+
+
+
+ {r.state === "completed" && r.summary && (
+
+ )}
+
+
+ Label
+
+
+ setLabel(e.target.value)}
+ onBlur={async () => label !== (r.label ?? "") && (await renameBenchmark(r.id, label || null)) && setR({ ...r, label: label.trim() || null })}
+ onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
+ />
+
+
+
+
+ Settings measured
+
+
+
+ {CONFIG_ROWS.map((row) => {
+ const v = row.value(s);
+ return v == null ? null : (
+
+
{row.label}
+ {v}
+
+ );
+ })}
+
+
+
+ Command
+
+
+
{s.command}
+
+ {sum && (
+
+ BetterBench {sum.betterbenchVersion} · corpus v{sum.corpusVersion} · phases: {sum.phases.join(", ") || "–"}
+
+ )}
+
+
+
+
+
+ );
+}
diff --git a/src/app/(app)/benchmarks/[id]/benchmark-report.tsx b/src/app/(app)/benchmarks/[id]/benchmark-report.tsx
new file mode 100644
index 0000000..2c948cb
--- /dev/null
+++ b/src/app/(app)/benchmarks/[id]/benchmark-report.tsx
@@ -0,0 +1,382 @@
+"use client";
+
+import { TriangleAlertIcon } from "lucide-react";
+import { BarChart } from "@/components/bar-chart";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { f0, f1, isBatched, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled, weightsLabel } from "@/lib/benchmark-report";
+import { configChips } from "@/lib/benchmark-view";
+import type { BenchmarkSummary } from "@/lib/db/schema";
+import { cn } from "@/lib/utils";
+import type { ListRow } from "../benchmark-list";
+
+function Tile({ label, value, unit, note }: { label: string; value: string; unit: string; note: string }) {
+ return (
+
+ {label}
+
+ {value}
+ {unit}
+
+ {note}
+
+ );
+}
+
+function Section({ title, intro, children }: { title: string; intro?: string; children: React.ReactNode }) {
+ return (
+
+
+
{title}
+ {intro &&
{intro}
}
+
+ {children}
+
+ );
+}
+
+/** A percentile cell, daggered when it fails BetterBench's sample gate. */
+function Gated({ v, sum, section, k, metric, fmt = f1 }: { v: number | null | undefined; sum: BenchmarkSummary; section: string; k: string | number; metric: string; fmt?: (v: number | null | undefined) => string }) {
+ const gated = v != null && undersampled(sum, section, k, metric);
+ return (
+
+ {fmt(v)}
+ {gated && "†"}
+
+ );
+}
+
+const date = (iso: string | null | undefined) =>
+ iso
+ ? new Date(iso.replace(/([+-]\d\d)(\d\d)$/, "$1:$2"))
+ .toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" })
+ .toUpperCase()
+ .replace(",", " ·")
+ : "";
+
+/** The run's report, after launch80's bench.betterbench.v1 page; every figure is one BetterBench reported. */
+export function BenchmarkReport({ run }: { run: ListRow }) {
+ const sum = run.summary;
+ if (!sum) return null;
+ const s = run.snapshot;
+ const batched = isBatched(sum);
+ const caveats = reportCaveats(run);
+ const c = sum.combined;
+ const peak = sum.concurrency.length ? sum.concurrency.reduce((a, b) => (b.aggregate_tps > a.aggregate_tps ? b : a)) : null;
+ const cfg = sum.config ?? {};
+ const chips = [
+ sum.corpusVersion && `corpus v${sum.corpusVersion}`,
+ sum.single.length && sum.passes ? `${sum.passes} passes/cat` : null,
+ cfg.greedy ? "greedy" : cfg.temperature != null ? `temp ${cfg.temperature}` : null,
+ cfg.unique_nonce === false ? "warm prefix cache" : "cold prefix cache (nonce)",
+ `phases: ${sum.phases.join(", ")}`,
+ ].filter(Boolean) as string[];
+
+ return (
+
+
+
+ {c && (
+
+
+ {batched ? (
+
+ ) : (
+
+ )}
+
+
+ )}
+
+ {caveats.length > 0 && (
+
+
+
+
Read these first
+ {caveats.map((x) => (
+
+ {x}
+
+ ))}
+
+
+ )}
+
+ {sum.single.length > 0 && (
+
+ ({
+ label: r.category,
+ value: r.decode_med,
+ valueLabel: f1(r.decode_med),
+ details: [
+ `decode ${f1(r.decode_med)} t/s`,
+ r.decode_iqr != null ? `IQR ${f1(r.decode_iqr)}` : "",
+ r.decode_cv != null ? `CV ${(r.decode_cv * 100).toFixed(1)}%` : "",
+ `${r.runs} passes`,
+ ].filter(Boolean),
+ }))}
+ />
+ Hover a bar for its IQR and coefficient of variation. A high CV means the category's passes disagree, so read small differences there with care.
+
+ )}
+
+ {sum.single.length > 0 && !batched && sum.single.some((r) => r.itl_low1 != null && r.itl_high99 != null) && (
+
+ ({
+ label: r.category,
+ value: r.itl_med ?? null,
+ range: r.itl_low1 != null && r.itl_high99 != null ? [r.itl_low1, r.itl_high99] : null,
+ valueLabel: r.itl_low1 != null ? `${f1(r.itl_low1)} – ${f1(r.itl_high99)}${undersampled(sum, "single_stream", r.category, "itl_high99") ? "†" : ""}` : undefined,
+ details: [`1% low ${f1(r.itl_low1)} t/s`, `median ${f1(r.itl_med)} t/s`, `99% high ${f1(r.itl_high99)} t/s`],
+ }))}
+ />
+
+ )}
+
+ {sum.prefill.some((p) => !p.skipped) && (
+
+ !p.skipped)
+ .map((p) => ({
+ label: `~${p.target_depth.toLocaleString("en-US")} tok`,
+ value: p.pp_med ?? null,
+ valueLabel: f0(p.pp_med),
+ details: [`prompt ${f0(p.prompt_tokens_med)} tokens`, `TTFT ${f0(p.ttft_p50)} ms`, `1% low ${f0(p.pp_low1)} · 99% high ${f0(p.pp_p99)} t/s`, `${p.pp_n ?? "?"} runs`],
+ }))}
+ />
+
+ )}
+
+ {sum.concurrency.length > 0 && (
+
+ ({
+ label: `${x.level} parallel`,
+ value: x.aggregate_tps,
+ valueLabel: f1(x.aggregate_tps),
+ details: [`per request ${f1(x.decode_med)} t/s`, `TTFT p50 ${f0(x.ttft_p50)} ms · p99 ${f0(x.ttft_p99)} ms`, `${x.ok}/${x.requests} requests ok`],
+ }))}
+ />
+
+ )}
+
+
+ {sum.single.length > 0 && (
+
+
+
+
+ Category
+ Passes
+ TTFT p50
+ TTFT p99
+ {batched ? (
+ <>
+ Update p50
+ Update p99
+ Tok/update
+ >
+ ) : (
+ <>
+ ITL 1% low
+ ITL med
+ ITL 99% high
+ >
+ )}
+ Decode med
+ ±IQR
+ CV
+
+
+
+ {sum.single.map((r) => (
+
+ {r.category}
+ {r.runs}
+ {f1(r.ttft_p50)}
+
+
+
+ {batched ? (
+ <>
+ {f1(r.update_p50)}
+
+
+
+ {r.tok_per_update != null ? r.tok_per_update.toFixed(2) : "—"}
+ >
+ ) : (
+ <>
+ {f1(r.itl_low1)}
+ {f1(r.itl_med)}
+
+
+
+ >
+ )}
+ {f1(r.decode_med)}
+ {f1(r.decode_iqr)}
+ {r.decode_cv != null ? `${(r.decode_cv * 100).toFixed(1)}%` : "—"}
+
+ ))}
+
+
+
+ )}
+
+ {sum.concurrency.length > 0 && (
+
+
+
+
+ Concurrency
+ OK
+ Aggregate t/s
+ Decode med
+ TTFT p50
+ TTFT p99
+
+
+
+ {sum.concurrency.map((x) => (
+
+ {x.level}
+
+ {x.ok}/{x.requests}
+
+ {f1(x.aggregate_tps)}
+ {f1(x.decode_med)}
+ {f1(x.ttft_p50)}
+
+
+
+
+ ))}
+
+
+
+ )}
+ {sum.prefill.length > 0 && (
+
+
+
+
+ Depth
+ Prompt tok
+ TTFT p50
+ PP 1% low
+ PP med
+ PP 99%
+
+
+
+ {sum.prefill.map((p) => (
+
+ ~{p.target_depth.toLocaleString("en-US")}
+ {p.skipped ? (
+
+ skipped
+
+ ) : (
+ <>
+ {f0(p.prompt_tokens_med)}
+ {f1(p.ttft_p50)}
+ {f1(p.pp_low1)}
+ {f1(p.pp_med)}
+
+
+
+ >
+ )}
+
+ ))}
+
+
+
+ )}
+
+ {sum.reasoning && sum.reasoning.length > 0 && (
+
+
+
+
+ Category
+ Split known
+ Reasoning share
+ Never answered
+ Time to first answer p50
+
+
+
+ {sum.reasoning.map((x) => (
+
+ {x.category}
+
+ {x.known}/{x.runs}
+
+ {x.reasoning_share != null ? `${Math.round(x.reasoning_share * 100)}%` : "unknown"}
+ {x.never_answered}
+ {x.ttfa_p50 != null ? `${f0(x.ttfa_p50)} ms` : "unknown"}
+
+ ))}
+
+
+
+ )}
+
+
+
+
+ {reportMethod(sum).map((p) => (
+
{p}
+ ))}
+
+
+
+
+ Generated by Kaname from a BetterBench {sum.betterbenchVersion} run{sum.corpusVersion ? ` on corpus v${sum.corpusVersion}` : ""}
+ {sum.corpusHash ? ` (corpus hash ${sum.corpusHash})` : ""}. Results are only comparable within a corpus version. Every figure comes from BetterBench's own report
+ functions; Kaname adds none.
+
+
+ );
+}
diff --git a/src/app/(app)/benchmarks/[id]/page.tsx b/src/app/(app)/benchmarks/[id]/page.tsx
new file mode 100644
index 0000000..96290c0
--- /dev/null
+++ b/src/app/(app)/benchmarks/[id]/page.tsx
@@ -0,0 +1,17 @@
+import type { Metadata } from "next";
+import { notFound } from "next/navigation";
+import { getBenchmark } from "@/lib/benchmarks";
+import { BenchmarkDetail } from "./benchmark-detail";
+
+export const dynamic = "force-dynamic";
+
+export async function generateMetadata({ params }: PageProps<"/benchmarks/[id]">): Promise {
+ const run = await getBenchmark((await params).id);
+ return { title: run ? `${run.label ?? run.snapshot.deploymentName} · Benchmark` : "Benchmark" };
+}
+
+export default async function BenchmarkPage({ params }: PageProps<"/benchmarks/[id]">) {
+ const run = await getBenchmark((await params).id);
+ if (!run) notFound();
+ return ;
+}
diff --git a/src/app/(app)/benchmarks/[id]/publish-card.tsx b/src/app/(app)/benchmarks/[id]/publish-card.tsx
new file mode 100644
index 0000000..74c4aa2
--- /dev/null
+++ b/src/app/(app)/benchmarks/[id]/publish-card.tsx
@@ -0,0 +1,257 @@
+"use client";
+
+import { CheckIcon, DownloadIcon, ExternalLinkIcon, EyeIcon, LoaderCircleIcon, SendIcon, Trash2Icon } from "lucide-react";
+import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
+import { CopyButton } from "@/components/copy-button";
+import { LocalTime } from "@/components/local-time";
+import { Button, buttonVariants } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import type { L80Status, PayloadPreview, PublicationRow } from "@/lib/publications";
+
+type Pub = Omit & {
+ createdAt: string;
+ previewedAt: string | null;
+ confirmedAt: string | null;
+ publishedAt: string | null;
+};
+
+const RETENTION_DAYS = 5;
+const textareaClass =
+ "min-h-24 w-full rounded-lg border border-input bg-transparent px-2.5 py-2 text-sm outline-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 dark:bg-input/30";
+
+async function send(url: string, method: string, body?: unknown) {
+ const res = await fetch(url, { method, ...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) toast.error(json.error?.message ?? `Request failed (${res.status})`);
+ return res.ok ? json : null;
+}
+
+/**
+ * Publish to launch80 as a double opt-in, the way the L80 docs describe it: first a dry run that
+ * builds the exact payload (nothing is sent), then an explicit confirmation that publishes that file.
+ */
+export function PublishCard({ runId, defaultTitle, defaultSummary }: { runId: string; defaultTitle: string; defaultSummary: string }) {
+ const [status, setStatus] = useState(null);
+ const [pubs, setPubs] = useState(null);
+ const [title, setTitle] = useState(defaultTitle.slice(0, 120));
+ const [summary, setSummary] = useState(defaultSummary.slice(0, 600));
+ const [preview, setPreview] = useState<{ id: string; data: PayloadPreview | null } | null>(null);
+ const [ack, setAck] = useState(false);
+ const [busy, setBusy] = useState(false);
+
+ const load = useCallback(async () => {
+ const res = await fetch(`/api/benchmarks/${runId}/publications`, { cache: "no-store" }).catch(() => null);
+ if (!res?.ok) return;
+ const json = (await res.json()) as { status: L80Status; publications: Pub[] };
+ setStatus(json.status);
+ setPubs(json.publications);
+ }, [runId]);
+
+ const current = pubs?.find((p) => p.state !== "published") ?? null;
+ const pending = !!pubs?.some((p) => p.state === "preview" || p.state === "publish");
+ useEffect(() => {
+ const first = setTimeout(load, 0);
+ const t = setInterval(load, pending ? 1_500 : 20_000);
+ return () => {
+ clearTimeout(first);
+ clearInterval(t);
+ };
+ }, [load, pending]);
+
+ // Load what the previewed payload contains once its preview is ready.
+ const previewId = current?.state === "previewed" ? current.id : null;
+ useEffect(() => {
+ if (!previewId || preview?.id === previewId) return;
+ let stop = false;
+ void fetch(`/api/benchmarks/${runId}/publications/${previewId}`, { cache: "no-store" })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => !stop && setPreview({ id: previewId, data: j?.preview ?? null }));
+ return () => {
+ stop = true;
+ };
+ }, [previewId, preview?.id, runId]);
+
+ async function prepare() {
+ setBusy(true);
+ setAck(false);
+ try {
+ if (await send(`/api/benchmarks/${runId}/publications`, "POST", { title: title.trim() || null, summary: summary.trim() || null })) await load();
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function publish(id: string) {
+ setBusy(true);
+ try {
+ if (await send(`/api/benchmarks/${runId}/publications/${id}`, "POST", { confirm: true })) await load();
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function discard(id: string) {
+ const res = await fetch(`/api/benchmarks/${runId}/publications/${id}`, { method: "DELETE" });
+ if (!res.ok) toast.error(`Could not discard (${res.status})`);
+ setPreview(null);
+ setAck(false);
+ await load();
+ }
+
+ const published = pubs?.filter((p) => p.state === "published") ?? [];
+ const p = preview?.id === current?.id ? preview?.data : null;
+
+ return (
+
+
+
+
+ Publish to launch80
+
+
+
+ {pubs === null ? (
+ Loading…
+ ) : !status?.version ? (
+ The L80 CLI isn't available in this installation, so runs can't be published.
+ ) : (
+ <>
+ {published.map((x) => (
+
+
+
+ Published
+
+
+
+ {x.url}
+
+
+
+
+ Public until about
+ {x.confirmedBy && ` · confirmed by ${x.confirmedBy}`}
+
+
+ ))}
+
+ {!current && (
+ <>
+
+ Step 1 of 2: prepare a preview. The L80 CLI builds the exact page payload from this run's results.json (endpoint and host removed). Nothing is sent yet.
+
+
+ Page title
+ setTitle(e.target.value)} maxLength={120} />
+
+
+ Summary
+
+
+
+ Prepare preview
+
+ >
+ )}
+
+ {current?.state === "preview" && (
+
+
+ Building the payload (dry run)…
+
+ )}
+
+ {current?.state === "previewed" && (
+
+
Step 2 of 2: check what would be published.
+ {p ? (
+
+ Template
+ {p.template}
+ Size
+ {(p.bytes / 1024).toFixed(1)} KB
+ Title
+ {p.title ?? model name }
+ Summary
+ {p.summary ?? none }
+ Model
+ {p.model}
+ Notes
+
+ {Object.entries(p.notes).map(([k, v]) => (
+
+ {k}={v}
+
+ ))}
+
+ Data
+ {p.phases.join(", ")} · every raw sample
+ Removed
+ {p.hostRemoved ? "endpoint URL and host name" : "endpoint or host still present!"}
+
+ ) : (
+
Reading the payload…
+ )}
+
+
+ Exact payload (JSON)
+
+
+ Public: anyone with the link can read it.
+ Immutable: to change it, publish again.
+ Unindexed, self-contained, marked “self-reported, not verified by launch80”.
+ Removed after {RETENTION_DAYS} days. Counts against your token's 10 publishes per day.
+
+ {!status.tokenSet && (
+
No launch80 token: set L80_TOKEN (launch80 Supporter) for the worker to publish.
+ )}
+
+ setAck(v === true)} className="mt-0.5" disabled={!status.tokenSet || !p?.hostRemoved} />
+ I want this run published as a public page on launch80.com, exactly as previewed.
+
+
+ publish(current.id)} disabled={!ack || busy || !status.tokenSet || !p?.hostRemoved}>
+
+ Publish
+
+ discard(current.id)} disabled={busy}>
+
+ Discard
+
+
+
+ )}
+
+ {current?.state === "publish" && (
+
+
+ Publishing…
+
+ )}
+
+ {current?.state === "failed" && (
+
+
{current.error}
+
discard(current.id)}>
+ Start over
+
+
+ )}
+
+ {published.length > 0 && !current && (
+
+ launch80.com
+
+ )}
+ >
+ )}
+
+
+ );
+}
diff --git a/src/app/(app)/benchmarks/actions.ts b/src/app/(app)/benchmarks/actions.ts
new file mode 100644
index 0000000..15af8c9
--- /dev/null
+++ b/src/app/(app)/benchmarks/actions.ts
@@ -0,0 +1,15 @@
+"use client";
+
+import { toast } from "sonner";
+
+async function call(url: string, method: string, body?: unknown): Promise {
+ const res = await fetch(url, { method, ...(body ? { headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) } : {}) });
+ if (res.ok) return true;
+ const json = await res.json().catch(() => ({}));
+ toast.error(json.error?.message ?? `Request failed (${res.status})`);
+ return false;
+}
+
+export const cancelBenchmark = (id: string) => call(`/api/benchmarks/${id}/cancel`, "POST");
+export const deleteBenchmark = (id: string) => call(`/api/benchmarks/${id}`, "DELETE");
+export const renameBenchmark = (id: string, label: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { label });
diff --git a/src/app/(app)/benchmarks/benchmark-list.tsx b/src/app/(app)/benchmarks/benchmark-list.tsx
new file mode 100644
index 0000000..59b14f7
--- /dev/null
+++ b/src/app/(app)/benchmarks/benchmark-list.tsx
@@ -0,0 +1,151 @@
+"use client";
+
+import { GaugeIcon, GitCompareIcon } from "lucide-react";
+import Link from "next/link";
+import { useEffect, useState } from "react";
+import { BenchmarkStateBadge } from "@/components/benchmark-state";
+import { LocalTime } from "@/components/local-time";
+import { buttonVariants } from "@/components/ui/button";
+import { Card } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import type { BenchmarkRow } from "@/lib/benchmarks";
+import { configChips, describeSettings, headline } from "@/lib/benchmark-view";
+import { cn } from "@/lib/utils";
+
+export type ListRow = Omit & {
+ createdAt: string;
+ startedAt: string | null;
+ finishedAt: string | null;
+ cancelRequestedAt: string | null;
+};
+
+const MAX_COMPARE = 6;
+const fmt = (v: number | null | undefined, digits = 1) => (v == null ? "–" : v.toFixed(digits));
+
+/** All runs with their headline numbers; polls while something is queued or running. */
+export function BenchmarkList({ rows: initial, compact }: { rows: ListRow[]; compact?: boolean }) {
+ const [rows, setRows] = useState(initial);
+ const [selected, setSelected] = useState([]);
+ const busy = rows.some((r) => r.state === "queued" || r.state === "running");
+
+ useEffect(() => {
+ if (!busy || compact) return;
+ const t = setInterval(async () => {
+ const res = await fetch("/api/benchmarks", { cache: "no-store" }).catch(() => null);
+ if (res?.ok) setRows(await res.json());
+ }, 3_000);
+ return () => clearInterval(t);
+ }, [busy, compact]);
+
+ if (rows.length === 0) {
+ return (
+
+
+
+ No benchmarks yet. Open a running{" "}
+
+ deployment
+ {" "}
+ and start one there.
+
+
+ );
+ }
+
+ const toggle = (id: string) => setSelected((s) => (s.includes(id) ? s.filter((x) => x !== id) : s.length < MAX_COMPARE ? [...s, id] : s));
+ const comparable = rows.filter((r) => r.state === "completed");
+
+ return (
+
+ {!compact && comparable.length > 1 && (
+
+ {selected.length === 0 ? "Select completed runs to compare them." : `${selected.length} selected (up to ${MAX_COMPARE}).`}
+
+
+ Compare
+
+
+ )}
+
+
+
+
+ {!compact && }
+ Run
+ Settings
+
+ Decode t/s
+
+
+ TTFT
+
+
+ Prefill t/s
+
+
+ Peak t/s
+
+ State
+
+
+
+ {rows.map((r) => {
+ const h = headline(r.summary);
+ const s = r.snapshot;
+ return (
+
+ {!compact && (
+
+ toggle(r.id)}
+ aria-label={`Select ${r.label ?? s.deploymentName} for comparison`}
+ />
+
+ )}
+
+
+ {r.label ?? s.deploymentName}
+
+
+ {r.label && `${s.deploymentName} · `}
+ {s.repoId} ·
+
+
+
+
+ {s.runtimeName}
+ {configChips(s).map((c) => (
+
+ {c}
+
+ ))}
+
+ {describeSettings(r.settings)}
+
+ {fmt(h.decode)}
+ {h.ttftMs != null ? `${Math.round(h.ttftMs)} ms` : "–"}
+
+ {fmt(h.prefill?.tps, 0)}
+
+
+ {fmt(h.peak?.tps)}
+
+
+
+
+
+ );
+ })}
+
+
+
+
+ );
+}
diff --git a/src/app/(app)/benchmarks/compare/page.tsx b/src/app/(app)/benchmarks/compare/page.tsx
new file mode 100644
index 0000000..84ee800
--- /dev/null
+++ b/src/app/(app)/benchmarks/compare/page.tsx
@@ -0,0 +1,187 @@
+import type { Metadata } from "next";
+import Link from "next/link";
+import { BenchmarkStateBadge } from "@/components/benchmark-state";
+import { Card } from "@/components/ui/card";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
+import { getBenchmarks } from "@/lib/benchmarks";
+import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
+import type { BenchmarkSummary } from "@/lib/db/schema";
+import { cn } from "@/lib/utils";
+
+export const dynamic = "force-dynamic";
+export const metadata: Metadata = { title: "Compare benchmarks" };
+
+type Metric = { label: string; unit: string; higherIsBetter: boolean; digits: number; get: (s: BenchmarkSummary | null) => number | null };
+
+/** Differences smaller than this are shown without color: below what a single run can resolve. */
+const NOISE_PCT = 2;
+
+function Delta({ v, base, higherIsBetter }: { v: number | null; base: number | null; higherIsBetter: boolean }) {
+ const d = deltaPct(v, base);
+ if (d == null) return null;
+ const good = higherIsBetter ? d > 0 : d < 0;
+ return (
+
+ {d > 0 ? "+" : ""}
+ {d.toFixed(1)}%
+
+ );
+}
+
+export default async function ComparePage({ searchParams }: PageProps<"/benchmarks/compare">) {
+ const { ids } = await searchParams;
+ const runs = await getBenchmarks(
+ String(ids ?? "")
+ .split(",")
+ .filter(Boolean)
+ .slice(0, 6),
+ );
+ if (runs.length < 2) {
+ return (
+
+ Pick at least two completed runs on the{" "}
+
+ Benchmarks
+ {" "}
+ page.
+
+ );
+ }
+
+ const sums = runs.map((r) => r.summary);
+ const depths = [...new Set(sums.flatMap((s) => s?.prefill.filter((p) => !p.skipped).map((p) => p.target_depth) ?? []))].sort((a, b) => a - b);
+ const levels = [...new Set(sums.flatMap((s) => s?.concurrency.map((c) => c.level) ?? []))].sort((a, b) => a - b);
+ const categories = [...new Set(sums.flatMap((s) => s?.single.map((c) => c.category) ?? []))];
+
+ const groups: { group: string; rows: Metric[] }[] = [
+ {
+ group: "Headline",
+ rows: [
+ { label: "Decode (weighted)", unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => headline(s).decode },
+ { label: "Time to first token", unit: "ms", higherIsBetter: false, digits: 0, get: (s) => headline(s).ttftMs },
+ ],
+ },
+ {
+ group: "Decode per category",
+ rows: categories.map((c) => ({ label: c, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.single.find((x) => x.category === c)?.decode_med ?? null })),
+ },
+ {
+ group: "Prompt processing",
+ rows: depths.map((d) => ({
+ label: `${d.toLocaleString()} tokens`,
+ unit: "t/s",
+ higherIsBetter: true,
+ digits: 0,
+ get: (s) => s?.prefill.find((p) => p.target_depth === d && !p.skipped)?.pp_med ?? null,
+ })),
+ },
+ {
+ group: "Parallel requests (total)",
+ rows: levels.map((l) => ({ label: `${l} parallel`, unit: "t/s", higherIsBetter: true, digits: 1, get: (s) => s?.concurrency.find((c) => c.level === l)?.aggregate_tps ?? null })),
+ },
+ ];
+ const metrics = groups.filter((g) => g.rows.length > 0);
+
+ const configRows = CONFIG_ROWS.map((row) => ({ row, values: runs.map((r) => row.value(r.snapshot)) })).filter((x) => x.values.some((v) => v != null));
+ const corpora = new Set(sums.map((s) => s?.corpusVersion).filter(Boolean));
+ const anyQuick = runs.some((r) => r.summary?.quick);
+
+ return (
+
+
+
Compare benchmarks
+
+ Differences are against the first run. Separate runs aren't paired in time, so differences below ~{NOISE_PCT}% are within normal noise.
+
+ {corpora.size > 1 &&
These runs used different prompt sets (corpus versions), so their numbers aren't comparable.
}
+ {anyQuick &&
Some runs are quick runs (5 passes); their numbers are rough.
}
+
+
+
+
+
+
+
+ {runs.map((r, i) => (
+
+
+ {r.label ?? r.snapshot.deploymentName}
+
+
+ {i === 0 && baseline }
+
+
+ {describeSettings(r.settings)}
+
+ ))}
+
+
+
+
+
+ Settings
+
+
+ {configRows.map(({ row, values }) => {
+ const differs = new Set(values.map((v) => v ?? "")).size > 1;
+ return (
+
+ {row.label}
+ {values.map((v, i) => (
+ 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
+ {v ?? default }
+
+ ))}
+
+ );
+ })}
+ {metrics.map((g) => (
+
+ ))}
+
+
+
+
+ );
+}
+
+function MetricGroup({ group, rows, sums, cols }: { group: string; rows: Metric[]; sums: (BenchmarkSummary | null)[]; cols: number }) {
+ return (
+ <>
+
+
+ {group}
+
+
+ {rows.map((m) => {
+ const vals = sums.map((s) => m.get(s));
+ const present = vals.filter((v): v is number => v != null);
+ const best = present.length > 1 ? (m.higherIsBetter ? Math.max(...present) : Math.min(...present)) : null;
+ return (
+
+ {m.label}
+ {vals.map((v, i) => (
+
+ {v == null ? (
+ –
+ ) : (
+ <>
+
+ {v.toFixed(m.digits)} {m.unit}
+
+ {i > 0 && }
+ >
+ )}
+
+ ))}
+
+ );
+ })}
+ >
+ );
+}
diff --git a/src/app/(app)/benchmarks/page.tsx b/src/app/(app)/benchmarks/page.tsx
new file mode 100644
index 0000000..de3aeee
--- /dev/null
+++ b/src/app/(app)/benchmarks/page.tsx
@@ -0,0 +1,21 @@
+import type { Metadata } from "next";
+import { listBenchmarks } from "@/lib/benchmarks";
+import { BenchmarkList } from "./benchmark-list";
+
+export const dynamic = "force-dynamic";
+export const metadata: Metadata = { title: "Benchmarks" };
+
+export default async function BenchmarksPage() {
+ const rows = await listBenchmarks();
+ return (
+
+
+
Benchmarks
+
+ BetterBench runs against your deployments. Start one from a running deployment; select runs to compare their settings and numbers.
+
+
+
+
+ );
+}
diff --git a/src/app/(app)/deployments/[id]/benchmark-card.tsx b/src/app/(app)/deployments/[id]/benchmark-card.tsx
new file mode 100644
index 0000000..36c3d8a
--- /dev/null
+++ b/src/app/(app)/deployments/[id]/benchmark-card.tsx
@@ -0,0 +1,134 @@
+"use client";
+
+import { GaugeIcon } from "lucide-react";
+import Link from "next/link";
+import { useRouter } from "next/navigation";
+import { useEffect, useState } from "react";
+import { toast } from "sonner";
+import { BenchmarkStateBadge } from "@/components/benchmark-state";
+import { Button } from "@/components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Checkbox } from "@/components/ui/checkbox";
+import { Input } from "@/components/ui/input";
+import { NativeSelect } from "@/components/ui/native-select";
+import { headline } from "@/lib/benchmark-view";
+import type { BenchmarkPhase } from "@/lib/db/schema";
+import type { ListRow } from "../../benchmarks/benchmark-list";
+
+const PHASES: { id: BenchmarkPhase; label: string; hint: string }[] = [
+ { id: "decode", label: "Generation", hint: "single request, 8 prompt categories" },
+ { id: "prefill", label: "Prompt processing", hint: "growing input lengths, up to the context size" },
+ { id: "concurrency", label: "Parallel requests", hint: "1, 2, 4 and 8 at once" },
+];
+
+/** Start a BetterBench run against this deployment and list its recent runs. */
+export function BenchmarkCard({ deploymentId, running, initial }: { deploymentId: string; running: boolean; initial: ListRow[] }) {
+ const router = useRouter();
+ const [mode, setMode] = useState("quick");
+ const [passes, setPasses] = useState("10");
+ const [phases, setPhases] = useState(["decode", "prefill", "concurrency"]);
+ const [label, setLabel] = useState("");
+ const [busy, setBusy] = useState(false);
+ const [runs, setRuns] = useState(initial);
+
+ const active = runs.some((r) => r.state === "queued" || r.state === "running");
+ useEffect(() => {
+ const t = setInterval(
+ async () => {
+ const res = await fetch(`/api/benchmarks?deployment=${deploymentId}`, { cache: "no-store" }).catch(() => null);
+ if (res?.ok) setRuns(await res.json());
+ },
+ active ? 3_000 : 15_000,
+ );
+ return () => clearInterval(t);
+ }, [deploymentId, active]);
+
+ async function start() {
+ setBusy(true);
+ try {
+ const res = await fetch("/api/benchmarks", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ deploymentId,
+ label: label.trim() || null,
+ quick: mode === "quick",
+ passes: mode === "custom" ? Number(passes) || 10 : null,
+ // All three selected means "everything" (BetterBench's default).
+ phases: phases.length === PHASES.length ? [] : phases,
+ }),
+ });
+ const json = await res.json().catch(() => ({}));
+ if (!res.ok) return toast.error(json.error?.message ?? `Could not start (${res.status})`);
+ router.push(`/benchmarks/${json.id}`);
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+
+
+
+
+ Benchmark
+
+
+
+
+ setMode(e.target.value)} aria-label="Run length">
+ Quick: 5 passes (smoke test)
+ Full: 20 passes (comparable)
+ Custom number of passes
+
+ {mode === "custom" && (
+ setPasses(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-16" aria-label="Passes per category" />
+ )}
+
+
+ {PHASES.map((p) => (
+
+ setPhases((cur) => (v ? [...cur, p.id] : cur.filter((x) => x !== p.id)))}
+ className="mt-0.5"
+ />
+
+ {p.label}
+ {p.hint}
+
+
+ ))}
+
+ setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
+
+
+ Run benchmark
+
+
+ {running ? "On a CPU a full run can take hours. Avoid other load on the server while it runs." : "Start the deployment to benchmark it."}
+
+
+ {runs.length > 0 && (
+
+ {runs.slice(0, 5).map((r) => {
+ const h = headline(r.summary);
+ return (
+
+ {r.label ?? new Date(r.createdAt).toLocaleString()}
+
+ {h.decode != null && `${h.decode.toFixed(1)} t/s`}
+
+
+
+ );
+ })}
+
+ All benchmarks →
+
+
+ )}
+
+
+ );
+}
diff --git a/src/app/(app)/deployments/[id]/deployment-detail.tsx b/src/app/(app)/deployments/[id]/deployment-detail.tsx
index 4fb51ab..58b4dd0 100644
--- a/src/app/(app)/deployments/[id]/deployment-detail.tsx
+++ b/src/app/(app)/deployments/[id]/deployment-detail.tsx
@@ -3,9 +3,10 @@
import { ExternalLinkIcon, PencilIcon, PlayIcon, SendIcon, SquareIcon, Trash2Icon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useState } from "react";
import { CopyButton } from "@/components/copy-button";
import { DeploymentStateBadge } from "@/components/deployment-state";
+import { LiveLog } from "@/components/live-log";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
@@ -23,11 +24,14 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Progress } from "@/components/ui/progress";
import { useHostname, webUiUrl } from "@/hooks/use-hostname";
import { ENGINE_PORT } from "@/lib/deploy-command";
+import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
import type { DeploymentRow } from "@/lib/deployments";
import { formatBytes, percent } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
import { deleteDeployment, startDeployment, stopDeployment } from "../actions";
+import type { ListRow } from "../../benchmarks/benchmark-list";
+import { BenchmarkCard } from "./benchmark-card";
type Deployment = Omit & {
startedAt: string | null;
@@ -35,7 +39,6 @@ type Deployment = Omit Date.now());
@@ -186,11 +189,12 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
-
+
+
Endpoint
@@ -234,6 +238,11 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
Container
{d.containerName ?? "–"}
+ Runs on
+
+ {ACCELERATOR_LABEL[d.accelerator]}
+ {d.accelerator === "nvidia" && ` · ${d.options.gpus?.length ? `${d.options.gpus.length} selected GPU${d.options.gpus.length === 1 ? "" : "s"}` : "all GPUs"}`}
+
Started
@@ -261,63 +270,6 @@ export function DeploymentDetail({ initial }: { initial: Deployment }) {
}
/** Live container log (polls new lines every 1.5 s). */
-function Logs({ id }: { id: string }) {
- const [lines, setLines] = useState([]);
- const box = useRef(null);
- const stick = useRef(true);
-
- useEffect(() => {
- let last = 0;
- let stopped = false;
- const load = async () => {
- const res = await fetch(`/api/deployments/${id}/logs?after=${last}`, { cache: "no-store" }).catch(() => null);
- if (!res?.ok || stopped) return;
- const next: LogLine[] = await res.json();
- if (next.length === 0) return;
- last = next[next.length - 1].id;
- setLines((prev) => [...prev, ...next].slice(-2000));
- };
- void load();
- const t = setInterval(load, 1_500);
- return () => {
- stopped = true;
- clearInterval(t);
- };
- }, [id]);
-
- useEffect(() => {
- if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
- }, [lines]);
-
- return (
-
-
- Log
-
-
- {
- const el = e.currentTarget;
- stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
- }}
- className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
- >
- {lines.length === 0 ? (
-
No output yet.
- ) : (
- lines.map((l) => (
-
- {l.line}
-
- ))
- )}
-
-
-
- );
-}
-
/** Smoke test over the OpenAI API: streams the answer and measures time to first token and speed. */
function Chat({ id, running }: { id: string; running: boolean }) {
const [prompt, setPrompt] = useState("Write one sentence about the sea.");
diff --git a/src/app/(app)/deployments/[id]/page.tsx b/src/app/(app)/deployments/[id]/page.tsx
index 77c4325..91c2450 100644
--- a/src/app/(app)/deployments/[id]/page.tsx
+++ b/src/app/(app)/deployments/[id]/page.tsx
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { notFound } from "next/navigation";
+import { listBenchmarks } from "@/lib/benchmarks";
import { getDeployment } from "@/lib/deployments";
import { DeploymentDetail } from "./deployment-detail";
@@ -11,7 +12,8 @@ export async function generateMetadata({ params }: PageProps<"/deployments/[id]"
}
export default async function DeploymentPage({ params }: PageProps<"/deployments/[id]">) {
- const d = await getDeployment((await params).id);
+ const { id } = await params;
+ const [d, runs] = await Promise.all([getDeployment(id), listBenchmarks({ deploymentId: id })]);
if (!d) notFound();
- return ;
+ return ;
}
diff --git a/src/app/(app)/deployments/deployment-form.tsx b/src/app/(app)/deployments/deployment-form.tsx
index 6a591db..8f7a666 100644
--- a/src/app/(app)/deployments/deployment-form.tsx
+++ b/src/app/(app)/deployments/deployment-form.tsx
@@ -9,15 +9,33 @@ import { ArgsEditor } from "@/components/args-editor";
import { CopyButton } from "@/components/copy-button";
import { FileRoleBadge } from "@/components/labels";
import { Button } from "@/components/ui/button";
-import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
+import {
+ Card,
+ CardContent,
+ CardDescription,
+ CardHeader,
+ CardTitle,
+} from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
-import type { DeploymentOptions, RuntimeEngine } from "@/lib/db/schema";
+import type {
+ DeploymentOptions,
+ HostGpu,
+ RuntimeAccelerator,
+ RuntimeEngine,
+} from "@/lib/db/schema";
import type { ModelCandidates } from "@/lib/deploy-candidates";
-import { API_KEY_PLACEHOLDER, buildCommand, ENGINE_PORT, estimateMemoryMb, renderCommand } from "@/lib/deploy-command";
+import {
+ API_KEY_PLACEHOLDER,
+ buildCommand,
+ ENGINE_PORT,
+ estimateMemoryMb,
+ renderCommand,
+} from "@/lib/deploy-command";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
+import { ACCELERATOR_LABEL } from "@/lib/runtimes-shared";
import { formatBytes } from "@/lib/format";
import { quantGroup } from "@/lib/selection";
import { cn } from "@/lib/utils";
@@ -30,9 +48,21 @@ export type FormRuntime = {
imageState: string;
env: Record;
extraArgs: string[];
+ accelerator: RuntimeAccelerator;
};
-export type FormModel = { id: string; repoId: string; localPath: string; candidates: ModelCandidates };
-export type FormHost = { cpus: number | null; memoryBytes: number | null; cpuFeatures: string[] } | null;
+export type FormModel = {
+ id: string;
+ repoId: string;
+ localPath: string;
+ candidates: ModelCandidates;
+};
+export type FormHost = {
+ cpus: number | null;
+ memoryBytes: number | null;
+ cpuFeatures: string[];
+ nvidia: boolean;
+ gpus: HostGpu[];
+} | null;
export type FormInitial = {
id?: string;
name: string;
@@ -47,15 +77,33 @@ export type FormInitial = {
const CONTEXT_PRESETS = [2048, 4096, 8192, 16384, 32768];
const KV_TYPES = ["f16", "q8_0", "q4_0"];
-const intOrNull = (s: string) => (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
+const intOrNull = (s: string) =>
+ (s.trim() === "" ? null : Math.max(0, Math.round(Number(s)))) || null;
+/** Like intOrNull, but 0 and -1 are meaningful (e.g. --cache-ram 0 = off). */
+const intOrNullSigned = (s: string) =>
+ s.trim() === "" || !Number.isFinite(Number(s)) ? null : Math.round(Number(s));
+/** Default prompt cache for new llama.cpp deployments (llama-server's own default is 8 GiB). */
+const DEFAULT_CACHE_RAM_MB = 1024;
const numOrNull = (s: string) => (s.trim() === "" ? null : Number(s)) || null;
-function Section({ step, title, description, children }: { step: number; title: string; description?: string; children: React.ReactNode }) {
+function Section({
+ step,
+ title,
+ description,
+ children,
+}: {
+ step: number;
+ title: string;
+ description?: string;
+ children: React.ReactNode;
+}) {
return (
- {step}
+
+ {step}
+
{title}
{description && {description} }
@@ -66,12 +114,22 @@ function Section({ step, title, description, children }: { step: number; title:
}
/** A titled block of related options inside the launch options card. */
-function Group({ title, description, children }: { title: string; description?: string; children: React.ReactNode }) {
+function Group({
+ title,
+ description,
+ children,
+}: {
+ title: string;
+ description?: string;
+ children: React.ReactNode;
+}) {
return (
{title}
- {description &&
{description}
}
+ {description && (
+
{description}
+ )}
{children}
@@ -98,7 +156,11 @@ function Field({
{label}
- {flag && {flag}}
+ {flag && (
+
+ {flag}
+
+ )}
{children}
{hint &&
{hint}
}
@@ -122,14 +184,24 @@ export function DeploymentForm({
}) {
const router = useRouter();
const editing = !!initial?.id;
- const [runtimeId, setRuntimeId] = useState(initial?.runtimeId ?? runtimes.find((r) => r.imageState === "present")?.id ?? "");
+ const [runtimeId, setRuntimeId] = useState(
+ initial?.runtimeId ??
+ runtimes.find((r) => r.imageState === "present")?.id ??
+ "",
+ );
const runtime = runtimes.find((r) => r.id === runtimeId) ?? null;
const engine = runtime?.engine ?? "llama.cpp";
+ const accelerator: RuntimeAccelerator = runtime?.accelerator ?? "cpu";
+ const gpu = accelerator !== "cpu";
const [query, setQuery] = useState("");
const [modelId, setModelId] = useState(initial?.modelId ?? "");
- const servable = models.filter((m) => (engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm));
- const shown = servable.filter((m) => m.repoId.toLowerCase().includes(query.trim().toLowerCase()));
+ const servable = models.filter((m) =>
+ engine === "llama.cpp" ? m.candidates.gguf.length > 0 : m.candidates.vllm,
+ );
+ const shown = servable.filter((m) =>
+ m.repoId.toLowerCase().includes(query.trim().toLowerCase()),
+ );
const model = servable.find((m) => m.id === modelId) ?? null;
const o = initial?.options;
@@ -137,24 +209,65 @@ export function DeploymentForm({
const [mmproj, setMmproj] = useState(o?.mmproj ?? "");
const [draftFile, setDraftFile] = useState(o?.draftFile ?? "");
const [name, setName] = useState(initial?.name ?? "");
- const [contextSize, setContextSize] = useState(String(o?.contextSize ?? 4096));
- const [threads, setThreads] = useState(o?.threads != null ? String(o.threads) : "");
- const [parallel, setParallel] = useState(o?.parallel != null ? String(o.parallel) : "1");
+ const [contextSize, setContextSize] = useState(
+ String(o?.contextSize ?? 4096),
+ );
+ const [threads, setThreads] = useState(
+ o?.threads != null ? String(o.threads) : "",
+ );
+ const [parallel, setParallel] = useState(
+ o?.parallel != null ? String(o.parallel) : "1",
+ );
const [cacheTypeK, setCacheTypeK] = useState(o?.cacheTypeK ?? "");
const [cacheTypeV, setCacheTypeV] = useState(o?.cacheTypeV ?? "");
const [flashAttn, setFlashAttn] = useState(o?.flashAttn ?? "");
const [webui, setWebui] = useState(o?.webui !== false);
const [requireApiKey, setRequireApiKey] = useState(!!o?.requireApiKey);
- const [batchSize, setBatchSize] = useState(o?.batchSize != null ? String(o.batchSize) : "");
- const [ubatchSize, setUbatchSize] = useState(o?.ubatchSize != null ? String(o.ubatchSize) : "");
+ const [batchSize, setBatchSize] = useState(
+ o?.batchSize != null ? String(o.batchSize) : "",
+ );
+ const [ubatchSize, setUbatchSize] = useState(
+ o?.ubatchSize != null ? String(o.ubatchSize) : "",
+ );
const [dtype, setDtype] = useState(o?.dtype ?? "");
- const [maxNumSeqs, setMaxNumSeqs] = useState(o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "");
- const [kvCacheGb, setKvCacheGb] = useState(o?.kvCacheGb != null ? String(o.kvCacheGb) : "");
+ const [maxNumSeqs, setMaxNumSeqs] = useState(
+ o?.maxNumSeqs != null ? String(o.maxNumSeqs) : "",
+ );
+ const [kvCacheGb, setKvCacheGb] = useState(
+ o?.kvCacheGb != null ? String(o.kvCacheGb) : "",
+ );
+ const [cacheRam, setCacheRam] = useState(
+ o
+ ? o.cacheRamMb != null
+ ? String(o.cacheRamMb)
+ : ""
+ : String(DEFAULT_CACHE_RAM_MB),
+ );
+ const [gpuIds, setGpuIds] = useState
(o?.gpus ?? []);
+ const [gpuLayers, setGpuLayers] = useState(o?.gpuLayers ?? "auto");
+ const [splitMode, setSplitMode] = useState(o?.splitMode ?? "");
+ const [tensorSplit, setTensorSplit] = useState(o?.tensorSplit ?? "");
+ const [cpuMoe, setCpuMoe] = useState(!!o?.cpuMoe);
+ const [nCpuMoe, setNCpuMoe] = useState(
+ o?.nCpuMoe != null ? String(o.nCpuMoe) : "",
+ );
+ const [tensorParallel, setTensorParallel] = useState(
+ o?.tensorParallel != null ? String(o.tensorParallel) : "",
+ );
+ const [gpuMemUtil, setGpuMemUtil] = useState(
+ o?.gpuMemoryUtilization != null ? String(o.gpuMemoryUtilization) : "",
+ );
const [argRows, setArgRows] = useState(() => argsToRows(o?.extraArgs ?? []));
- const [cpus, setCpus] = useState(initial?.cpus != null ? String(initial.cpus) : "");
- const [memoryMb, setMemoryMb] = useState(initial?.memoryMb != null ? String(initial.memoryMb) : "");
+ const [cpus, setCpus] = useState(
+ initial?.cpus != null ? String(initial.cpus) : "",
+ );
+ const [memoryMb, setMemoryMb] = useState(
+ initial?.memoryMb != null ? String(initial.memoryMb) : "",
+ );
const [memoryTouched, setMemoryTouched] = useState(!!initial?.memoryMb);
- const [hostPort, setHostPort] = useState(initial?.hostPort != null ? String(initial.hostPort) : "");
+ const [hostPort, setHostPort] = useState(
+ initial?.hostPort != null ? String(initial.hostPort) : "",
+ );
const [saving, setSaving] = useState(false);
function pickModel(m: FormModel) {
@@ -163,14 +276,18 @@ export function DeploymentForm({
setModelFile(engine === "llama.cpp" ? (first?.path ?? "") : "");
setMmproj(m.candidates.mmproj[0]?.path ?? "");
setDraftFile("");
- if (!editing) setName(`${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim());
+ if (!editing)
+ setName(
+ `${m.repoId.split("/")[1]}${first && engine === "llama.cpp" ? ` ${quantGroup(first.path) ?? ""}` : ""}`.trim(),
+ );
}
const options: DeploymentOptions = {
modelFile: engine === "llama.cpp" ? modelFile : "",
mmproj: engine === "llama.cpp" && mmproj ? mmproj : null,
draftFile: engine === "llama.cpp" && draftFile ? draftFile : null,
- draftType: model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
+ draftType:
+ model?.candidates.drafts.find((d) => d.path === draftFile)?.type ?? null,
contextSize: intOrNull(contextSize) ?? 4096,
threads: intOrNull(threads),
parallel: intOrNull(parallel),
@@ -178,12 +295,33 @@ export function DeploymentForm({
ubatchSize: engine === "llama.cpp" ? intOrNull(ubatchSize) : null,
cacheTypeK: engine === "llama.cpp" && cacheTypeK ? cacheTypeK : null,
cacheTypeV: engine === "llama.cpp" && cacheTypeV ? cacheTypeV : null,
- flashAttn: engine === "llama.cpp" && flashAttn ? (flashAttn as "auto" | "on" | "off") : null,
+ flashAttn:
+ engine === "llama.cpp" && flashAttn
+ ? (flashAttn as "auto" | "on" | "off")
+ : null,
webui: engine === "llama.cpp" ? webui : null,
requireApiKey,
dtype: engine === "vllm" && dtype ? dtype : null,
maxNumSeqs: engine === "vllm" ? intOrNull(maxNumSeqs) : null,
- kvCacheGb: engine === "vllm" ? numOrNull(kvCacheGb) : null,
+ kvCacheGb: engine === "vllm" && !gpu ? numOrNull(kvCacheGb) : null,
+ cacheRamMb: engine === "llama.cpp" ? intOrNullSigned(cacheRam) : null,
+ gpus: accelerator === "nvidia" && gpuIds.length ? gpuIds : null,
+ gpuLayers:
+ gpu && engine === "llama.cpp" && gpuLayers !== "auto" ? gpuLayers : null,
+ splitMode:
+ gpu && engine === "llama.cpp" && splitMode
+ ? (splitMode as "none" | "layer" | "row" | "tensor")
+ : null,
+ tensorSplit:
+ gpu && engine === "llama.cpp" && tensorSplit.trim()
+ ? tensorSplit.trim()
+ : null,
+ cpuMoe: gpu && engine === "llama.cpp" ? cpuMoe : null,
+ nCpuMoe:
+ gpu && engine === "llama.cpp" && !cpuMoe ? intOrNull(nCpuMoe) : null,
+ tensorParallel: gpu && engine === "vllm" ? intOrNull(tensorParallel) : null,
+ gpuMemoryUtilization:
+ gpu && engine === "vllm" ? numOrNull(gpuMemUtil) : null,
extraArgs: rowsToArgs(argRows),
};
@@ -194,16 +332,38 @@ export function DeploymentForm({
(model.candidates.drafts.find((g) => g.path === draftFile)?.size ?? 0)
: (model.candidates.vllm?.size ?? 0)
: 0;
- const estimate = model ? estimateMemoryMb(fileBytes, options.contextSize, engine, options.kvCacheGb) : null;
+ const estimate = model
+ ? estimateMemoryMb(fileBytes, options.contextSize, engine, {
+ ...options,
+ accelerator,
+ })
+ : null;
+ const hostGpus = host?.gpus ?? [];
+ const chosenGpus = gpuIds.length
+ ? hostGpus.filter((g) => gpuIds.includes(g.uuid))
+ : hostGpus;
+ const vramMb = chosenGpus.reduce((s, g) => s + g.memoryMb, 0);
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
- runtime && model ? renderCommand(runtime.image, buildCommand({
+ runtime && model
+ ? renderCommand(
+ runtime.image,
+ buildCommand({
engine,
options,
model,
- runtime: { env: runtime.env, extraArgs: runtime.extraArgs },
- apiKeys: Array.from({ length: apiKeyCount }, () => API_KEY_PLACEHOLDER),
- })) : null;
+ runtime: {
+ env: runtime.env,
+ extraArgs: runtime.extraArgs,
+ accelerator,
+ },
+ apiKeys: Array.from(
+ { length: apiKeyCount },
+ () => API_KEY_PLACEHOLDER,
+ ),
+ }),
+ )
+ : null;
const noBf16 = host && !host.cpuFeatures.includes("avx512_bf16");
async function submit(start: boolean) {
@@ -220,18 +380,22 @@ export function DeploymentForm({
hostPort: intOrNull(hostPort),
start,
};
- const res = await fetch(editing ? `/api/deployments/${initial!.id}` : "/api/deployments", {
- method: editing ? "PUT" : "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(body),
- });
+ const res = await fetch(
+ editing ? `/api/deployments/${initial!.id}` : "/api/deployments",
+ {
+ method: editing ? "PUT" : "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(body),
+ },
+ );
const json = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(json.error?.message ?? `Could not save (${res.status})`);
return;
}
const id = editing ? initial!.id : json.id;
- if (editing && start) await fetch(`/api/deployments/${id}/start`, { method: "POST" });
+ if (editing && start)
+ await fetch(`/api/deployments/${id}/start`, { method: "POST" });
toast.success(start ? "Deployment starting" : "Deployment saved");
router.push(`/deployments/${id}`);
router.refresh();
@@ -242,7 +406,11 @@ export function DeploymentForm({
return (
-
+
{runtimes.length === 0 ? (
No runtimes yet.{" "}
@@ -266,7 +434,9 @@ export function DeploymentForm({
}}
className={cn(
"flex flex-col items-start gap-1 rounded-lg border px-3 py-2.5 text-left transition-colors disabled:cursor-not-allowed disabled:opacity-50",
- runtimeId === r.id ? "border-primary bg-primary/5 ring-1 ring-primary" : "hover:bg-muted/50",
+ runtimeId === r.id
+ ? "border-primary bg-primary/5 ring-1 ring-primary"
+ : "hover:bg-muted/50",
)}
>
@@ -274,11 +444,17 @@ export function DeploymentForm({
{r.name}
- {runtimeId === r.id && }
+ {runtimeId === r.id && (
+
+ )}
- {r.image}
+
+ {r.image}
+
- {r.engine === "vllm" ? "vLLM · safetensors" : "llama.cpp · GGUF"}
+ {r.engine === "vllm"
+ ? "vLLM · safetensors"
+ : "llama.cpp · GGUF"}
{!ready && " · image not pulled"}
@@ -301,7 +477,11 @@ export function DeploymentForm({
{servable.length === 0 ? (
@@ -309,14 +489,21 @@ export function DeploymentForm({
Add one in the library
- {engine === "vllm" ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)." : "."}
+ {engine === "vllm"
+ ? " (a safetensors repo, e.g. HuggingFaceTB/SmolLM2-135M-Instruct)."
+ : "."}
) : (
<>
{servable.length > 6 && (
- setQuery(e.target.value)} placeholder="Search models…" className="pl-8" />
+ setQuery(e.target.value)}
+ placeholder="Search models…"
+ className="pl-8"
+ />
)}
@@ -325,10 +512,17 @@ export function DeploymentForm({
key={m.id}
type="button"
onClick={() => pickModel(m)}
- className={cn("flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50", modelId === m.id && "bg-primary/5")}
+ className={cn(
+ "flex items-center justify-between gap-3 px-3 py-2 text-left text-sm hover:bg-muted/50",
+ modelId === m.id && "bg-primary/5",
+ )}
>
- {modelId === m.id ? : }
+ {modelId === m.id ? (
+
+ ) : (
+
+ )}
{m.repoId}
@@ -345,18 +539,48 @@ export function DeploymentForm({
{model.candidates.gguf.map((g) => (
-
- setModelFile(g.path)} className="accent-primary" />
-
+
+ setModelFile(g.path)}
+ className="accent-primary"
+ />
+
{quantGroup(g.path) ?? g.path}
- {formatBytes(g.size)}
+
+ {formatBytes(g.size)}
+
))}
-
- setMmproj(e.target.value)} disabled={model.candidates.mmproj.length === 0}>
+
+ setMmproj(e.target.value)}
+ disabled={model.candidates.mmproj.length === 0}
+ >
None
{model.candidates.mmproj.map((m) => (
@@ -368,9 +592,17 @@ export function DeploymentForm({
- setDraftFile(e.target.value)} disabled={model.candidates.drafts.length === 0}>
+ setDraftFile(e.target.value)}
+ disabled={model.candidates.drafts.length === 0}
+ >
Off
{model.candidates.drafts.map((d) => (
@@ -398,16 +630,43 @@ export function DeploymentForm({
)}
{runtime && model && (
-
-
+
+
- setName(e.target.value)} maxLength={80} />
+ setName(e.target.value)}
+ maxLength={80}
+ />
-
- setHostPort(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="not published" />
+
+ setHostPort(e.target.value.replace(/\D/g, ""))}
+ inputMode="numeric"
+ placeholder="not published"
+ />
- setRequireApiKey(v === true)} className="mt-0.5" disabled={apiKeyCount === 0 && !requireApiKey} />
+ setRequireApiKey(v === true)}
+ className="mt-0.5"
+ disabled={apiKeyCount === 0 && !requireApiKey}
+ />
Require an API key
@@ -421,11 +680,14 @@ export function DeploymentForm({
>
) : (
<>
- Accepts any of the {apiKeyCount} key{apiKeyCount === 1 ? "" : "s"} from{" "}
+ Accepts any of the {apiKeyCount} key
+ {apiKeyCount === 1 ? "" : "s"} from{" "}
Settings → API keys
{" "}
- as Authorization: Bearer.{engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
+ as{" "}
+ Authorization: Bearer.
+ {engine === "vllm" ? " vLLM only checks /v1 paths." : ""}
>
)}
@@ -433,7 +695,11 @@ export function DeploymentForm({
{engine === "llama.cpp" && (
- setWebui(v === true)} className="mt-0.5" />
+ setWebui(v === true)}
+ className="mt-0.5"
+ />
Serve the llama.cpp web UI
@@ -448,56 +714,355 @@ export function DeploymentForm({
)}
-
-
+
+
- setContextSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" className="w-28" />
+
+ setContextSize(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ className="w-28"
+ />
{CONTEXT_PRESETS.map((c) => (
- setContextSize(String(c))}>
+ setContextSize(String(c))}
+ >
{c / 1024}k
))}
{engine === "vllm" ? (
-
- setMaxNumSeqs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="default" />
+
+
+ setMaxNumSeqs(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ placeholder="default"
+ />
) : (
-
- setParallel(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
+
+
+ setParallel(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ placeholder="auto"
+ />
)}
+ {gpu && (
+
+ {accelerator === "nvidia" && (
+
+
GPUs
+ {!host?.nvidia ? (
+
+ Docker on this host has no NVIDIA runtime. Install the
+ NVIDIA Container Toolkit, then restart the worker.
+
+ ) : hostGpus.length === 0 ? (
+
+ No GPUs detected yet; the deployment gets all of them.
+
+ ) : (
+
+ {hostGpus.map((g) => (
+
+ {
+ const all = hostGpus.map((x) => x.uuid);
+ const cur = gpuIds.length ? gpuIds : all;
+ const next = v
+ ? [...new Set([...cur, g.uuid])]
+ : cur.filter((x) => x !== g.uuid);
+ setGpuIds(next.length === all.length ? [] : next);
+ }}
+ />
+
+ {g.index}: {g.name}
+
+
+ {formatBytes(g.memoryMb * 2 ** 20)}
+
+
+ ))}
+
+ {gpuIds.length === 0
+ ? "All GPUs"
+ : `${gpuIds.length} of ${hostGpus.length}`}{" "}
+ · {formatBytes(vramMb * 2 ** 20)} VRAM
+ {fileBytes > 0 &&
+ ` · model files ${formatBytes(fileBytes)}`}
+
+
+ )}
+
+ )}
+ {engine === "llama.cpp" ? (
+ <>
+
+
+
+ setGpuLayers(
+ e.target.value === "n" ? "20" : e.target.value,
+ )
+ }
+ >
+ auto
+ all
+ number…
+
+ {gpuLayers !== "auto" && gpuLayers !== "all" && (
+
+ setGpuLayers(
+ e.target.value.replace(/\D/g, "") || "0",
+ )
+ }
+ inputMode="numeric"
+ className="w-20"
+ aria-label="Number of GPU layers"
+ />
+ )}
+
+
+
+ setSplitMode(e.target.value)}
+ >
+ default (layer)
+ none (one GPU)
+ layer
+ row
+ tensor
+
+
+
+
+ setTensorSplit(e.target.value.replace(/[^\d.,]/g, ""))
+ }
+ placeholder="even"
+ />
+
+
+
+ {
+ setCpuMoe(e.target.value === "all");
+ if (e.target.value === "") setNCpuMoe("");
+ if (e.target.value === "n" && !nCpuMoe)
+ setNCpuMoe("10");
+ }}
+ >
+ none
+ all experts
+ first N layers…
+
+ {!cpuMoe && nCpuMoe !== "" && (
+
+ setNCpuMoe(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ className="w-20"
+ aria-label="Layers with MoE experts in RAM"
+ />
+ )}
+
+
+ >
+ ) : (
+ <>
+
+
+ setTensorParallel(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ placeholder={String(Math.max(1, chosenGpus.length))}
+ />
+
+
+
+ setGpuMemUtil(e.target.value.replace(/[^\d.]/g, ""))
+ }
+ inputMode="decimal"
+ placeholder="0.9"
+ />
+
+ >
+ )}
+
+ )}
+
{engine === "llama.cpp" ? (
-
-
- setThreads(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="auto" />
+
+
+
+ setThreads(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ placeholder="auto"
+ />
- setFlashAttn(e.target.value)}>
+ setFlashAttn(e.target.value)}
+ >
auto
on
off
- setBatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="2048" />
+
+ setBatchSize(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ placeholder="2048"
+ />
- setUbatchSize(e.target.value.replace(/\D/g, ""))} inputMode="numeric" placeholder="512" />
+
+ setUbatchSize(e.target.value.replace(/\D/g, ""))
+ }
+ inputMode="numeric"
+ placeholder="512"
+ />
) : (
-
+
- setDtype(e.target.value)}>
+ setDtype(e.target.value)}
+ >
runtime default
bfloat16
float32
@@ -508,11 +1073,23 @@ export function DeploymentForm({
)}
-
+
{engine === "llama.cpp" ? (
<>
-
- setCacheTypeK(e.target.value)}>
+
+ setCacheTypeK(e.target.value)}
+ >
f16 (default)
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
@@ -522,7 +1099,11 @@ export function DeploymentForm({
- setCacheTypeV(e.target.value)}>
+ setCacheTypeV(e.target.value)}
+ >
f16 (default)
{KV_TYPES.filter((t) => t !== "f16").map((t) => (
@@ -531,27 +1112,82 @@ export function DeploymentForm({
))}
+
+
+ setCacheRam(e.target.value.replace(/[^\d-]/g, ""))
+ }
+ inputMode="numeric"
+ placeholder="8192"
+ />
+
>
+ ) : gpu ? (
+
+ On a GPU, vLLM sizes the KV cache from the GPU memory share
+ above.
+
) : (
-
- setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"} />
+
+
+ setKvCacheGb(e.target.value.replace(/[^\d.]/g, ""))
+ }
+ inputMode="decimal"
+ placeholder={runtime.env.VLLM_CPU_KVCACHE_SPACE ?? "4"}
+ />
)}
-
- setCpus(e.target.value.replace(/[^\d.]/g, ""))} inputMode="decimal" placeholder="no limit" />
+
+ setCpus(e.target.value.replace(/[^\d.]/g, ""))}
+ inputMode="decimal"
+ placeholder="no limit"
+ />
- Estimate: {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
- {host?.memoryBytes ? ` · host: ${formatBytes(host.memoryBytes)}` : ""}
+ Estimate:{" "}
+ {estimate != null ? formatBytes(estimate * 2 ** 20) : "–"}
+ {host?.memoryBytes
+ ? ` · host: ${formatBytes(host.memoryBytes)}`
+ : ""}
{memoryTouched && (
- setMemoryTouched(false)}>
+ setMemoryTouched(false)}
+ >
use estimate
)}
@@ -575,14 +1211,26 @@ export function DeploymentForm({
description={`Any other ${engine === "vllm" ? "vllm serve" : "llama-server"} flag. Added after the runtime's own arguments.`}
>
)}
{runtime && model && (
-
+
{preview && (
@@ -598,10 +1246,19 @@ export function DeploymentForm({
router.back()}>
Cancel
- submit(false)}>
+ submit(false)}
+ >
{editing ? "Save" : "Create"}
- submit(true)}>
+ submit(true)}
+ >
{editing ? "Save & start" : "Create & start"}
diff --git a/src/app/(app)/deployments/form-data.ts b/src/app/(app)/deployments/form-data.ts
index 6de1078..e9bf59b 100644
--- a/src/app/(app)/deployments/form-data.ts
+++ b/src/app/(app)/deployments/form-data.ts
@@ -8,9 +8,9 @@ import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
export async function formData(): Promise<{ runtimes: FormRuntime[]; models: FormModel[]; host: FormHost; apiKeyCount: number }> {
const [runtimes, models, docker, keys] = await Promise.all([listRuntimes(), listDeployableModels(), getDockerInfo(), listApiKeys()]);
return {
- runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs })),
+ runtimes: runtimes.map((r) => ({ id: r.id, name: r.name, engine: r.engine, image: r.image, imageState: r.imageState, env: r.env, extraArgs: r.extraArgs, accelerator: r.accelerator })),
models,
- host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures } : null,
+ host: docker ? { cpus: docker.cpus, memoryBytes: docker.memoryBytes, cpuFeatures: docker.cpuFeatures, nvidia: !!docker.nvidia, gpus: docker.gpus ?? [] } : null,
apiKeyCount: keys.length,
};
}
diff --git a/src/app/(app)/settings/runtimes/runtime-form.tsx b/src/app/(app)/settings/runtimes/runtime-form.tsx
index 6090081..21bbfe8 100644
--- a/src/app/(app)/settings/runtimes/runtime-form.tsx
+++ b/src/app/(app)/settings/runtimes/runtime-form.tsx
@@ -6,9 +6,10 @@ import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
-import type { RuntimeEngine } from "@/lib/db/schema";
+import { NativeSelect } from "@/components/ui/native-select";
+import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
-import { formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
+import { ACCELERATOR_DEVICES, ACCELERATOR_LABEL, formatEnvLines, parseEnvLines, type RuntimeInput, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
const ENGINES: { id: RuntimeEngine; label: string; hint: string }[] = [
@@ -33,6 +34,7 @@ export function RuntimeForm({
}) {
const [name, setName] = useState(initial.name);
const [engine, setEngine] = useState(initial.engine);
+ const [accelerator, setAccelerator] = useState(initial.accelerator ?? "cpu");
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
@@ -50,6 +52,7 @@ export function RuntimeForm({
value = validateRuntime({
name,
engine,
+ accelerator,
image,
description,
env: parseEnvLines(envText),
@@ -114,6 +117,35 @@ export function RuntimeForm({
+
+
Runs on
+
{
+ const next = e.target.value as RuntimeAccelerator;
+ setAccelerator(next);
+ // Suggest the device nodes the accelerator needs.
+ if (!devicesText.trim()) setDevicesText(ACCELERATOR_DEVICES[next].join(", "));
+ }}
+ >
+ {RUNTIME_ACCELERATORS.map((a) => (
+
+ {ACCELERATOR_LABEL[a]}
+
+ ))}
+
+
+ {accelerator === "nvidia"
+ ? "GPUs are requested from Docker (NVIDIA Container Toolkit on the host); each deployment picks which ones."
+ : accelerator === "dri"
+ ? "Intel and AMD GPUs are passed in as /dev/dri (Vulkan, Intel SYCL, vLLM XPU). The image must be built for it."
+ : accelerator === "rocm"
+ ? "AMD GPUs with ROCm: /dev/kfd and /dev/dri are passed in."
+ : "CPU and RAM only."}
+
+
+
Description
setDescription(e.target.value)} maxLength={2000} />
@@ -150,7 +182,7 @@ export function RuntimeForm({
onChange={(e) => setDevicesText(e.target.value)}
spellCheck={false}
className="font-mono text-xs"
- placeholder="/dev/dri (Intel/AMD GPUs, later)"
+ placeholder="/dev/dri, /dev/kfd"
/>
diff --git a/src/app/(app)/settings/runtimes/runtimes-view.tsx b/src/app/(app)/settings/runtimes/runtimes-view.tsx
index f3883b0..f706576 100644
--- a/src/app/(app)/settings/runtimes/runtimes-view.tsx
+++ b/src/app/(app)/settings/runtimes/runtimes-view.tsx
@@ -30,7 +30,7 @@ import {
import { Progress } from "@/components/ui/progress";
import type { DockerHostInfo, runtimes } from "@/lib/db/schema";
import { formatBytes, percent } from "@/lib/format";
-import { RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
+import { ACCELERATOR_LABEL, RUNTIME_PRESETS, type RuntimeInput } from "@/lib/runtimes-shared";
import { cn } from "@/lib/utils";
import { RuntimeForm } from "./runtime-form";
@@ -63,6 +63,7 @@ async function send(url: string, method: string, body?: unknown): Promise ({
name: r.name,
engine: r.engine,
+ accelerator: r.accelerator,
image: r.image,
description: r.description,
env: r.env,
@@ -218,6 +219,24 @@ function HostCard({ docker, workerOnline }: { docker: DockerHostInfo | null; wor
Memory
{docker.memoryBytes != null ? formatBytes(docker.memoryBytes) : "unknown"}
+ GPUs
+
+ {docker.gpus && docker.gpus.length > 0 ? (
+ docker.gpus.map((g) => (
+
+ {g.index}: {g.name} · {formatBytes(g.memoryMb * 2 ** 20)} · driver {g.driver}
+
+ ))
+ ) : docker.nvidia ? (
+
+ {docker.gpuError ? `NVIDIA runtime found, but listing GPUs failed: ${docker.gpuError}` : "NVIDIA runtime found, no GPUs listed."}
+
+ ) : (
+
+ No NVIDIA GPUs (no NVIDIA runtime in Docker). Intel/AMD GPUs aren't listed; pass /dev/dri to a runtime to use them.
+
+ )}
+
Network
{docker.network ?? "not detected (set KANAME_DOCKER_NETWORK)"}
@@ -290,6 +309,9 @@ function RuntimeRow({
{r.name}
{r.engine === "vllm" ? "vLLM" : "llama.cpp"}
+ {r.accelerator !== "cpu" && (
+ {ACCELERATOR_LABEL[r.accelerator]}
+ )}
{r.numaTuning && NUMA tuning }
{r.image}
diff --git a/src/app/api/benchmarks/[id]/cancel/route.ts b/src/app/api/benchmarks/[id]/cancel/route.ts
new file mode 100644
index 0000000..5118b90
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/cancel/route.ts
@@ -0,0 +1,14 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { BenchmarkError, cancelBenchmark } from "@/lib/benchmarks";
+
+export const POST = withAuth>(async (_req, { params }) => {
+ try {
+ await cancelBenchmark((await params).id);
+ return new NextResponse(null, { status: 202 });
+ } catch (err) {
+ if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/benchmarks/[id]/logs/route.ts b/src/app/api/benchmarks/[id]/logs/route.ts
new file mode 100644
index 0000000..e82f80f
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/logs/route.ts
@@ -0,0 +1,11 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { listBenchmarkLogs } from "@/lib/benchmarks";
+
+export const dynamic = "force-dynamic";
+
+/** Log lines after `?after=` (first call: the last 500). */
+export const GET = withAuth>(async (req, { params }) => {
+ const after = Number(new URL(req.url).searchParams.get("after") ?? 0) || 0;
+ return NextResponse.json(await listBenchmarkLogs((await params).id, after));
+});
diff --git a/src/app/api/benchmarks/[id]/publications/[pubId]/payload/route.ts b/src/app/api/benchmarks/[id]/publications/[pubId]/payload/route.ts
new file mode 100644
index 0000000..0e6301e
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/publications/[pubId]/payload/route.ts
@@ -0,0 +1,20 @@
+import { readFile } from "node:fs/promises";
+import { withAuth } from "@/lib/api-auth";
+import { apiError } from "@/lib/api-errors";
+import { payloadFile } from "@/lib/publications";
+
+export const dynamic = "force-dynamic";
+
+/** The exact payload the preview built, byte for byte what would be sent to launch80. */
+export const GET = withAuth>(async (_req, { params }) => {
+ const { id, pubId } = await params;
+ let path: string;
+ try {
+ path = payloadFile(id, pubId);
+ } catch {
+ return apiError(404, "not_found", "No payload for this preview.");
+ }
+ const body = await readFile(path).catch(() => null);
+ if (!body) return apiError(404, "not_found", "No payload for this preview.");
+ return new Response(body, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="launch80-payload-${pubId.slice(-6).toLowerCase()}.json"` } });
+});
diff --git a/src/app/api/benchmarks/[id]/publications/[pubId]/route.ts b/src/app/api/benchmarks/[id]/publications/[pubId]/route.ts
new file mode 100644
index 0000000..9597035
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/publications/[pubId]/route.ts
@@ -0,0 +1,45 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { confirmPublication, discardPublication, PublicationError, readPayloadPreview } from "@/lib/publications";
+
+export const dynamic = "force-dynamic";
+
+/** What the previewed payload contains (read from the exact file that would be sent). */
+export const GET = withAuth>(async (_req, { params }) => {
+ try {
+ const { id, pubId } = await params;
+ return NextResponse.json({ preview: await readPayloadPreview(id, pubId) });
+ } catch (err) {
+ if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
+
+const Confirm = z.object({ confirm: z.literal(true) });
+
+/** Opt-in 2: publish the previewed payload. Requires `{ "confirm": true }`. */
+export const POST = withAuth>(async (req, { params, session }) => {
+ try {
+ const { id, pubId } = await params;
+ Confirm.parse(await req.json());
+ await confirmPublication(id, pubId, session.user.email ?? session.user.name ?? null);
+ return new NextResponse(null, { status: 202 });
+ } catch (err) {
+ if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
+
+/** Discard a preview. */
+export const DELETE = withAuth>(async (_req, { params }) => {
+ try {
+ const { id, pubId } = await params;
+ await discardPublication(id, pubId);
+ return new NextResponse(null, { status: 204 });
+ } catch (err) {
+ if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/benchmarks/[id]/publications/route.ts b/src/app/api/benchmarks/[id]/publications/route.ts
new file mode 100644
index 0000000..0dadfc6
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/publications/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { getL80Status, listPublications, PreviewBody, PublicationError, requestPreview } from "@/lib/publications";
+
+export const dynamic = "force-dynamic";
+
+/** This run's launch80 publications and whether publishing is available (never the token). */
+export const GET = withAuth>(async (_req, { params }) => {
+ const { id } = await params;
+ const [status, publications] = await Promise.all([getL80Status(), listPublications(id)]);
+ return NextResponse.json({ status, publications });
+});
+
+/** Opt-in 1: prepare a preview (L80 dry run). Nothing is sent to launch80. */
+export const POST = withAuth>(async (req, { params }) => {
+ try {
+ const { id } = await params;
+ return NextResponse.json(await requestPreview(id, PreviewBody.parse(await req.json())), { status: 201 });
+ } catch (err) {
+ if (err instanceof PublicationError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/benchmarks/[id]/report/route.ts b/src/app/api/benchmarks/[id]/report/route.ts
new file mode 100644
index 0000000..fa03682
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/report/route.ts
@@ -0,0 +1,27 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { withAuth } from "@/lib/api-auth";
+import { apiError } from "@/lib/api-errors";
+import { REPORT_FILE, runDir } from "@/lib/benchmark-paths";
+import { getBenchmark } from "@/lib/benchmarks";
+
+export const dynamic = "force-dynamic";
+
+/**
+ * BetterBench's self-contained HTML report. Served sandboxed (opaque origin, no network): it is
+ * generated content and must not run with access to Kaname's session.
+ */
+export const GET = withAuth>(async (_req, { params }) => {
+ const run = await getBenchmark((await params).id);
+ if (!run?.hasReport) return apiError(404, "not_found", "This run has no report.");
+ const html = await readFile(join(runDir(run.id), REPORT_FILE)).catch(() => null);
+ if (!html) return apiError(404, "not_found", "The report file is missing.");
+ return new Response(html, {
+ headers: {
+ "Content-Type": "text/html; charset=utf-8",
+ "Content-Security-Policy": "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; font-src data:",
+ "X-Content-Type-Options": "nosniff",
+ "Cache-Control": "private, max-age=300",
+ },
+ });
+});
diff --git a/src/app/api/benchmarks/[id]/results/route.ts b/src/app/api/benchmarks/[id]/results/route.ts
new file mode 100644
index 0000000..ab85bc5
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/results/route.ts
@@ -0,0 +1,25 @@
+import { readFile } from "node:fs/promises";
+import { join } from "node:path";
+import { withAuth } from "@/lib/api-auth";
+import { apiError } from "@/lib/api-errors";
+import { RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
+import { getBenchmark } from "@/lib/benchmarks";
+
+export const dynamic = "force-dynamic";
+
+/** BetterBench's results.json without endpoint and host, as a download (works with `betterbench report/compare` and `L80 betterbench --results`). */
+export const GET = withAuth>(async (_req, { params }) => {
+ const run = await getBenchmark((await params).id);
+ if (!run) return apiError(404, "not_found", "Benchmark not found.");
+ const raw = await readFile(join(runDir(run.id), RESULTS_FILE), "utf8").catch(() => null);
+ if (!raw) return apiError(404, "not_found", "This run has no results file.");
+ // Like launch80's L80 CLI: the endpoint URL and host name never leave the machine.
+ const data = JSON.parse(raw) as { env?: Record };
+ if (data.env) {
+ delete data.env.endpoint;
+ delete data.env.host;
+ }
+ const json = JSON.stringify(data, null, 2);
+ const name = `betterbench-${run.snapshot.deploymentName.replace(/[^\w.-]+/g, "-")}-${run.id.slice(-6).toLowerCase()}.json`;
+ return new Response(json, { headers: { "Content-Type": "application/json", "Content-Disposition": `attachment; filename="${name}"` } });
+});
diff --git a/src/app/api/benchmarks/[id]/route.ts b/src/app/api/benchmarks/[id]/route.ts
new file mode 100644
index 0000000..3712bc2
--- /dev/null
+++ b/src/app/api/benchmarks/[id]/route.ts
@@ -0,0 +1,36 @@
+import { NextResponse } from "next/server";
+import { z } from "zod";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { BenchmarkError, deleteBenchmark, getBenchmark, updateBenchmarkLabel } from "@/lib/benchmarks";
+
+export const dynamic = "force-dynamic";
+
+export const GET = withAuth>(async (_req, { params }) => {
+ const run = await getBenchmark((await params).id);
+ return run ? NextResponse.json(run) : apiError(404, "not_found", "Benchmark not found.");
+});
+
+const Patch = z.object({ label: z.string().max(120).nullable() });
+
+/** Rename (label) a run. */
+export const PATCH = withAuth>(async (req, { params }) => {
+ try {
+ await updateBenchmarkLabel((await params).id, Patch.parse(await req.json()).label);
+ return new NextResponse(null, { status: 204 });
+ } catch (err) {
+ if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
+
+/** Delete a run with its log and files. */
+export const DELETE = withAuth>(async (_req, { params }) => {
+ try {
+ await deleteBenchmark((await params).id);
+ return new NextResponse(null, { status: 204 });
+ } catch (err) {
+ if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/api/benchmarks/route.ts b/src/app/api/benchmarks/route.ts
new file mode 100644
index 0000000..ed6a874
--- /dev/null
+++ b/src/app/api/benchmarks/route.ts
@@ -0,0 +1,22 @@
+import { NextResponse } from "next/server";
+import { withAuth } from "@/lib/api-auth";
+import { apiError, handleApiError } from "@/lib/api-errors";
+import { BenchmarkBody, BenchmarkError, createBenchmark, listBenchmarks } from "@/lib/benchmarks";
+
+export const dynamic = "force-dynamic";
+
+/** All runs, newest first; `?deployment=` or `?model=` narrows them. */
+export const GET = withAuth(async (req) => {
+ const sp = new URL(req.url).searchParams;
+ return NextResponse.json(await listBenchmarks({ deploymentId: sp.get("deployment") ?? undefined, modelId: sp.get("model") ?? undefined }));
+});
+
+/** Queue a BetterBench run against a running deployment. */
+export const POST = withAuth(async (req) => {
+ try {
+ return NextResponse.json(await createBenchmark(BenchmarkBody.parse(await req.json())), { status: 201 });
+ } catch (err) {
+ if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
+ return handleApiError(err);
+ }
+});
diff --git a/src/app/globals.css b/src/app/globals.css
index 88ffb65..c3aa146 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -21,6 +21,7 @@
--color-chart-3: var(--chart-3);
--color-chart-2: var(--chart-2);
--color-chart-1: var(--chart-1);
+ --color-series: var(--series);
--color-ring: var(--ring);
--color-input: var(--input);
--color-border: var(--border);
@@ -68,6 +69,8 @@
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.87 0 0);
+ /* Single-series data color (benchmark charts); validated reference blue, light surface. */
+ --series: #2a78d6;
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
@@ -103,6 +106,7 @@
--input: oklch(1 0 0 / 15%);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.87 0 0);
+ --series: #3987e5;
--chart-2: oklch(0.556 0 0);
--chart-3: oklch(0.439 0 0);
--chart-4: oklch(0.371 0 0);
diff --git a/src/components/app-nav.tsx b/src/components/app-nav.tsx
index 1b7ecf9..5f6b277 100644
--- a/src/components/app-nav.tsx
+++ b/src/components/app-nav.tsx
@@ -1,6 +1,6 @@
"use client";
-import { LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
+import { GaugeIcon, LibraryIcon, RocketIcon, SettingsIcon } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { cn } from "@/lib/utils";
@@ -10,9 +10,10 @@ const LINKS = [
href: "/",
label: "Library",
icon: LibraryIcon,
- active: (p: string) => !p.startsWith("/settings") && !p.startsWith("/deployments"),
+ active: (p: string) => !["/settings", "/deployments", "/benchmarks"].some((x) => p.startsWith(x)),
},
{ href: "/deployments", label: "Deployments", icon: RocketIcon, active: (p: string) => p.startsWith("/deployments") },
+ { href: "/benchmarks", label: "Benchmarks", icon: GaugeIcon, active: (p: string) => p.startsWith("/benchmarks") },
{ href: "/settings", label: "Settings", icon: SettingsIcon, active: (p: string) => p.startsWith("/settings") },
];
diff --git a/src/components/bar-chart.tsx b/src/components/bar-chart.tsx
new file mode 100644
index 0000000..73a2eed
--- /dev/null
+++ b/src/components/bar-chart.tsx
@@ -0,0 +1,125 @@
+"use client";
+
+import { useState } from "react";
+import { cn } from "@/lib/utils";
+
+export type BarRow = {
+ label: string;
+ /** Bar length (mode "bar") or median tick (mode "range"). */
+ value: number | null;
+ /** Mode "range": the span, e.g. 1% low → 99% high. */
+ range?: [number, number] | null;
+ /** Text at the bar tip. */
+ valueLabel?: string;
+ /** Tooltip lines. */
+ details?: string[];
+};
+
+/** Clean axis maximum and ticks (0 / 25 / 50 / 75 / 100 style). */
+function niceTicks(max: number): number[] {
+ if (!(max > 0)) return [0, 1];
+ const raw = max / 4;
+ const mag = 10 ** Math.floor(Math.log10(raw));
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw) ?? 10 * mag;
+ const ticks: number[] = [];
+ for (let t = 0; t <= max + step * 0.001; t += step) ticks.push(Number(t.toPrecision(6)));
+ if (ticks[ticks.length - 1] < max) ticks.push(Number((ticks[ticks.length - 1] + step).toPrecision(6)));
+ return ticks;
+}
+
+const fmtTick = (v: number) => (v >= 1000 ? v.toLocaleString("en-US", { maximumFractionDigits: 0 }) : v.toLocaleString("en-US", { maximumFractionDigits: 2 }));
+
+/**
+ * Horizontal single-series bars (one hue), value at the tip, a hover tooltip per row, an optional
+ * reference line (e.g. the weighted combined score). Mode "range" draws a span with a median tick.
+ */
+export function BarChart({
+ rows,
+ axisLabel,
+ reference,
+ mode = "bar",
+ className,
+}: {
+ rows: BarRow[];
+ axisLabel: string;
+ reference?: { value: number; label: string } | null;
+ mode?: "bar" | "range";
+ className?: string;
+}) {
+ const [hover, setHover] = useState(null);
+ const max = Math.max(...rows.map((r) => (mode === "range" ? (r.range?.[1] ?? r.value ?? 0) : (r.value ?? 0))), reference?.value ?? 0);
+ const ticks = niceTicks(max);
+ const top = ticks[ticks.length - 1] || 1;
+ const pct = (v: number) => `${Math.max(0, Math.min(100, (v / top) * 100))}%`;
+
+ return (
+ r.label).join(", ")}`}>
+
+ {/* gridlines + reference line span the plot column */}
+
+
+
+ {ticks.map((t) => (
+
+ ))}
+ {reference && (
+
+ {reference.label}
+
+ )}
+
+
+ {rows.map((r, i) => (
+
setHover(i)} onMouseLeave={() => setHover((h) => (h === i ? null : h))}>
+
+ {r.label}
+
+
+ {mode === "bar" && r.value != null && (
+
+ )}
+ {mode === "range" && r.range && (
+ <>
+
+ {r.value != null &&
}
+ >
+ )}
+ {r.valueLabel && (
+
+ {r.valueLabel}
+
+ )}
+ {hover === i && r.details && r.details.length > 0 && (
+
+
{r.label}
+ {r.details.map((d) => (
+
+ {d}
+
+ ))}
+
+ )}
+
+
+ ))}
+ {/* axis */}
+
+
+ {ticks.map((t) => (
+
+ {fmtTick(t)}
+
+ ))}
+
+
+
{axisLabel}
+
+
+ );
+}
diff --git a/src/components/benchmark-state.tsx b/src/components/benchmark-state.tsx
new file mode 100644
index 0000000..1c6a6e2
--- /dev/null
+++ b/src/components/benchmark-state.tsx
@@ -0,0 +1,20 @@
+import { LoaderCircleIcon } from "lucide-react";
+import { cn } from "@/lib/utils";
+
+const STYLE: Record = {
+ queued: "border-foreground/15 text-muted-foreground",
+ running: "border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-300",
+ completed: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300",
+ failed: "border-destructive/30 bg-destructive/10 text-destructive",
+ cancelled: "border-foreground/15 text-muted-foreground",
+};
+
+export function BenchmarkStateBadge({ state, cancelling, className }: { state: string; cancelling?: boolean; className?: string }) {
+ const label = state === "running" && cancelling ? "cancelling" : state;
+ return (
+
+ {state === "running" && }
+ {label}
+
+ );
+}
diff --git a/src/components/live-log.tsx b/src/components/live-log.tsx
new file mode 100644
index 0000000..910aeff
--- /dev/null
+++ b/src/components/live-log.tsx
@@ -0,0 +1,66 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { cn } from "@/lib/utils";
+
+type LogLine = { id: number; ts: number; stream: string; line: string };
+
+/** Polls `url?after=` for new lines and keeps the view pinned to the bottom unless scrolled up. */
+export function LiveLog({ url, title = "Log", live = true, className }: { url: string; title?: string; live?: boolean; className?: string }) {
+ const [lines, setLines] = useState([]);
+ const box = useRef(null);
+ const stick = useRef(true);
+
+ useEffect(() => {
+ let last = 0;
+ let stopped = false;
+ const load = async () => {
+ const res = await fetch(`${url}?after=${last}`, { cache: "no-store" }).catch(() => null);
+ if (!res?.ok || stopped) return;
+ const next: LogLine[] = await res.json();
+ if (next.length === 0) return;
+ last = next[next.length - 1].id;
+ setLines((prev) => [...prev, ...next].slice(-2000));
+ };
+ void load();
+ if (!live) return () => void (stopped = true);
+ const t = setInterval(load, 1_500);
+ return () => {
+ stopped = true;
+ clearInterval(t);
+ };
+ }, [url, live]);
+
+ useEffect(() => {
+ if (stick.current && box.current) box.current.scrollTop = box.current.scrollHeight;
+ }, [lines]);
+
+ return (
+
+
+ {title}
+
+
+ {
+ const el = e.currentTarget;
+ stick.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
+ }}
+ className="h-96 overflow-auto rounded-lg bg-muted/50 px-3 py-2 font-mono text-[11px] leading-relaxed"
+ >
+ {lines.length === 0 ? (
+
No output yet.
+ ) : (
+ lines.map((l) => (
+
+ {l.line}
+
+ ))
+ )}
+
+
+
+ );
+}
diff --git a/src/lib/benchmark-paths.ts b/src/lib/benchmark-paths.ts
new file mode 100644
index 0000000..ee83783
--- /dev/null
+++ b/src/lib/benchmark-paths.ts
@@ -0,0 +1,23 @@
+// Where benchmark files live. Shared by the worker (writes) and the web app (serves reports).
+
+import { dirname, join, resolve } from "node:path";
+import { coreEnv } from "@/lib/env";
+
+/** BENCHMARKS_DIR, or "benchmarks" next to the SQLite file (e.g. /data/benchmarks). */
+export function benchmarksDir(): string {
+ const env = coreEnv();
+ if (env.BENCHMARKS_DIR) return resolve(env.BENCHMARKS_DIR);
+ const db = env.DATABASE_URL.replace(/^file:/, "");
+ return resolve(dirname(db), "benchmarks");
+}
+
+/** Run ids are ULIDs; anything else never becomes a path. */
+const RUN_ID_RE = /^[0-9A-HJKMNP-TV-Z]{26}$/;
+
+export function runDir(runId: string): string {
+ if (!RUN_ID_RE.test(runId)) throw new Error("invalid run id");
+ return join(benchmarksDir(), runId);
+}
+
+export const RESULTS_FILE = "results.json";
+export const REPORT_FILE = "results.html";
diff --git a/src/lib/benchmark-report.test.ts b/src/lib/benchmark-report.test.ts
new file mode 100644
index 0000000..6a8cdaa
--- /dev/null
+++ b/src/lib/benchmark-report.test.ts
@@ -0,0 +1,83 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+import { describeHardware, reportCaveats, reportMethod, reportSubtitle, reportSummary, undersampled } from "./benchmark-report";
+import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
+
+const snap = {
+ deploymentName: "bench test",
+ repoId: "unsloth/Qwen3-0.6B-GGUF",
+ runtimeName: "llama.cpp (CPU)",
+ engine: "llama.cpp",
+ image: "ghcr.io/ggml-org/llama.cpp:server",
+ imageId: null,
+ options: { modelFile: "Qwen3-0.6B-Q4_K_M.gguf", contextSize: 4096, extraArgs: [] },
+ cpus: 4,
+ memoryMb: 2640,
+ command: "",
+ host: { cpuModel: "AMD Ryzen 7 9850X3D 8-Core Processor", threads: 16, memoryBytes: 32e9, os: null },
+} as BenchmarkSnapshot;
+
+const summary: BenchmarkSummary = {
+ v: 2,
+ combined: { decode: 97.25, ttft_p50: 140, itl_low1: 48.03, update_p50: 10.1, update_p99: 17.5 },
+ single: [
+ { category: "chat", runs: 5, ttft_p50: 150.3, ttft_p99: 165.5, decode_med: 102.8, decode_cv: 0.05, itl_low1: 51.1, tok_per_update: 1.01, batched: false, batched_runs: 0 },
+ { category: "code", runs: 5, ttft_p50: 135.7, ttft_p99: 165.7, decode_med: 89.1, decode_cv: 0.1, itl_low1: 40.8, tok_per_update: 1.0, batched: false, batched_runs: 0 },
+ ],
+ prefill: [
+ { target_depth: 2000, skipped: false, pp_med: 600 },
+ { target_depth: 8000, skipped: true },
+ ],
+ concurrency: [
+ { level: 1, ok: 48, requests: 48, aggregate_tps: 95, ttft_p50: 100, ttft_p99: 200, decode_med: 95 },
+ { level: 4, ok: 46, requests: 48, aggregate_tps: 210, ttft_p50: 300, ttft_p99: 900, decode_med: 52 },
+ ],
+ gate: [
+ { section: "single_stream", key: "chat", metric: "ttft_p99", n: 5, need: 500 },
+ { section: "concurrency", key: 4, metric: "ttft_p99", n: 46, need: 500 },
+ ],
+ truncated: [3, 10],
+ failedSingle: 0,
+ phases: ["decode", "prefill", "concurrency"],
+ cacheHits: 0,
+ betterbenchVersion: "0.6.1",
+ corpusVersion: "1.0",
+ maxModelLen: 4096,
+ config: { warmup: 1, runs_per_category: 5, temperature: 0.7, top_p: 0.95, top_k: 20, unique_nonce: true, weights: { code: 0.3, chat: 0 }, concurrency_requests: 48, prefill_runs: 8, prefill_warmup: 2, prefill_max_tokens: 16 },
+ passes: 5,
+ quick: true,
+};
+
+const run = { label: null, snapshot: snap, settings: { quick: true, passes: null, warmup: null, phases: [] }, summary };
+
+describe("benchmark report (launch80 conventions)", () => {
+ it("describes hardware, subtitle and summary", () => {
+ assert.equal(describeHardware(snap), "4 CPU cores of an AMD Ryzen 7 9850X3D");
+ assert.equal(describeHardware({ ...snap, gpuNames: ["NVIDIA GeForce RTX 3080", "NVIDIA GeForce RTX 3080"] }), "2× NVIDIA GeForce RTX 3080");
+ assert.equal(reportSubtitle(run), "4 CPU cores of an AMD Ryzen 7 9850X3D · 5 passes per category · temp 0.7 · quick smoke run");
+ const s = reportSummary(run);
+ assert.match(s, /^Quick smoke run, not a publishable measurement\. unsloth\/Qwen3-0\.6B-GGUF \(Q4_K_M, 4,096-token context\)/);
+ assert.match(s, /5 measured passes per category over 2 categories\. Combined decode 97\.3 t\/s \(weighted median\), TTFT p50 140 ms, ITL 1% low 48\.0 t\/s\./);
+ assert.match(s, /peaked at 210\.0 t\/s at concurrency 4\. Prefill reached 600 t\/s at ~2,000 prompt tokens\.$/);
+ });
+
+ it("lists caveats in launch80's order", () => {
+ const c = reportCaveats(run);
+ assert.match(c[0], /^Quick smoke run: 5 passes per category after 1 warmup/);
+ assert.match(c[1], /^Under-sampled: TTFT p99 in chat, c4 \(n ≤ 46\)\. A p99 needs 500 samples/);
+ assert.match(c[2], /^3 of 10 runs stopped at max_tokens \(30%\)/);
+ assert.match(c[3], /^Concurrency requests failed at level 4: 46\/48 ok/);
+ assert.match(c[4], /^Prefill depths skipped: 8,000 tokens \(exceed the model context of 4,096\)/);
+ assert.equal(c.length, 5);
+ });
+
+ it("writes the method from the config and flags gated cells", () => {
+ const m = reportMethod(summary).join("\n");
+ assert.match(m, /Single stream: 1 warmup then 5 measured passes per category, temperature 0\.7, top_p 0\.95, top_k 20, prefix cache cold/);
+ assert.match(m, /Concurrency sweep: 48 requests at levels 1, 4\./);
+ assert.match(m, /weighted by category: chat 0, code 0\.3/);
+ assert.ok(undersampled(summary, "single_stream", "chat", "ttft_p99"));
+ assert.ok(undersampled(summary, "concurrency", 4, "ttft_p99"));
+ assert.ok(!undersampled(summary, "single_stream", "code", "ttft_p99"));
+ });
+});
diff --git a/src/lib/benchmark-report.ts b/src/lib/benchmark-report.ts
new file mode 100644
index 0000000..4702b8a
--- /dev/null
+++ b/src/lib/benchmark-report.ts
@@ -0,0 +1,169 @@
+// Text for a benchmark's report page, following launch80's bench.betterbench.v1 conventions
+// (L80 CLI, internal/betterbench/payload.go): every figure is one BetterBench reported, quick runs
+// say so first, under-sampled percentiles are flagged, truncated and batched runs are called out,
+// and no endpoint or host name appears. Pure, for tests.
+
+import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
+import { quantGroup } from "@/lib/selection";
+
+type Run = { label: string | null; snapshot: BenchmarkSnapshot; settings: BenchmarkSettings; summary: BenchmarkSummary | null };
+
+export const f1 = (v: number | null | undefined) => (v == null ? "—" : v.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 }));
+export const f0 = (v: number | null | undefined) => (v == null ? "—" : Math.round(v).toLocaleString("en-US"));
+const int = (v: number) => v.toLocaleString("en-US");
+
+/** launch80's quick rule: a single-stream run with ≤ 5 passes per category. */
+export function isQuick(sum: BenchmarkSummary | null): boolean {
+ if (!sum) return false;
+ return sum.quick || (sum.single.length > 0 && sum.passes != null && sum.passes > 0 && sum.passes <= 5);
+}
+
+/** Did the server stream several tokens per update (speculative/batched decoding)? */
+export function isBatched(sum: BenchmarkSummary | null): boolean {
+ return !!sum?.single.some((r) => r.batched);
+}
+
+/** "RTX 3080" / "4 CPU cores of an AMD Ryzen 7 9850X3D" / "an AMD EPYC 7282 (16 threads)". */
+export function describeHardware(s: BenchmarkSnapshot): string {
+ if (s.gpuNames?.length) {
+ const names = [...new Set(s.gpuNames)];
+ return s.gpuNames.length > 1 && names.length === 1 ? `${s.gpuNames.length}× ${names[0]}` : names.join(" + ");
+ }
+ const cpu = s.host?.cpuModel
+ ?.replace(/\s+\d+-Core Processor$/i, "")
+ .replace(/\(R\)|\(TM\)/g, "")
+ .trim();
+ if (s.cpus) return `${s.cpus} CPU core${s.cpus === 1 ? "" : "s"}${cpu ? ` of an ${cpu}` : ""}`;
+ return cpu ? `an ${cpu}${s.host?.threads ? ` (${s.host.threads} threads)` : ""}` : "CPU";
+}
+
+export function weightsLabel(s: BenchmarkSnapshot): string {
+ return s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors";
+}
+
+/** hardware · N passes per category · temp 0.7 · quick smoke run */
+export function reportSubtitle(run: Run): string {
+ const sum = run.summary;
+ const parts = [describeHardware(run.snapshot)];
+ if (sum?.single.length && sum.passes) parts.push(`${sum.passes} passes per category`);
+ const cfg = sum?.config;
+ if (cfg?.greedy) parts.push("greedy");
+ else if (cfg?.temperature != null) parts.push(`temp ${cfg.temperature}`);
+ if (isQuick(sum)) parts.push("quick smoke run");
+ return parts.join(" · ");
+}
+
+export function reportSummary(run: Run): string {
+ const s = run.snapshot;
+ const sum = run.summary;
+ const out: string[] = [];
+ if (isQuick(sum)) out.push("Quick smoke run, not a publishable measurement.");
+ out.push(
+ `${s.repoId} (${weightsLabel(s)}, ${int(s.options.contextSize)}-token context) on ${s.runtimeName}, ${describeHardware(s)}, measured with BetterBench ${sum?.betterbenchVersion ?? ""}${
+ sum?.single.length ? `: ${sum.passes} measured passes per category over ${sum.single.length} categories` : ""
+ }.`.replace(" ,", ","),
+ );
+ const c = sum?.combined;
+ if (c) {
+ const bits: string[] = [];
+ if (c.decode != null) bits.push(`combined decode ${f1(c.decode)} t/s (weighted median)`);
+ if (c.ttft_p50 != null) bits.push(`TTFT p50 ${f0(c.ttft_p50)} ms`);
+ if (isBatched(sum) && c.update_p99 != null) bits.push(`stream-update p99 ${f1(c.update_p99)} ms`);
+ else if (c.itl_low1 != null) bits.push(`ITL 1% low ${f1(c.itl_low1)} t/s`);
+ if (bits.length) out.push(bits.join(", ").replace(/^./, (x) => x.toUpperCase()) + ".");
+ }
+ const peak = sum?.concurrency.length ? sum.concurrency.reduce((a, b) => (b.aggregate_tps > a.aggregate_tps ? b : a)) : null;
+ if (peak) out.push(`Aggregate throughput peaked at ${f1(peak.aggregate_tps)} t/s at concurrency ${peak.level}.`);
+ const pre = sum?.prefill.filter((p) => !p.skipped && p.pp_med != null) ?? [];
+ const best = pre.length ? pre.reduce((a, b) => (b.pp_med! > a.pp_med! ? b : a)) : null;
+ if (best) out.push(`Prefill reached ${f0(best.pp_med)} t/s at ~${int(best.target_depth)} prompt tokens.`);
+ return out.join(" ");
+}
+
+/** The Method section: how BetterBench measured, from the run's own config. */
+export function reportMethod(sum: BenchmarkSummary): string[] {
+ const p: string[] = [];
+ const cfg = sum.config ?? {};
+ const cats = sum.single.map((r) => r.category);
+ p.push(`BetterBench ${sum.betterbenchVersion}${sum.corpusVersion ? `, corpus v${sum.corpusVersion}` : ""}${cats.length ? ` (${cats.length} categories: ${cats.join(", ")})` : ""}.`);
+ if (sum.single.length) {
+ let s = `Single stream: ${cfg.warmup ?? "?"} warmup then ${cfg.runs_per_category ?? sum.passes} measured passes per category`;
+ if (cfg.greedy) s += ", greedy sampling";
+ else if (cfg.temperature != null) s += `, temperature ${cfg.temperature}${cfg.top_p != null ? `, top_p ${cfg.top_p}` : ""}${cfg.top_k != null ? `, top_k ${cfg.top_k}` : ""}`;
+ s += cfg.unique_nonce === false ? ", prefix cache warm" : ", prefix cache cold (unique nonce per request)";
+ p.push(`${s}.`);
+ }
+ if (sum.concurrency.length) {
+ const n = cfg.concurrency_requests ?? sum.concurrency[0].requests;
+ p.push(`Concurrency sweep: ${n} requests at levels ${sum.concurrency.map((c) => c.level).join(", ")}.`);
+ }
+ if (sum.prefill.length) {
+ let s = `Prefill sweep at target depths ${sum.prefill.map((d) => d.target_depth).join(", ")} tokens`;
+ if (cfg.prefill_runs) s += `, ${cfg.prefill_runs} runs after ${cfg.prefill_warmup ?? 0} warmup`;
+ if (cfg.prefill_max_tokens) s += `, ${cfg.prefill_max_tokens}-token decode`;
+ p.push(`${s}, cold prefix cache. Prefill throughput is prompt tokens divided by TTFT.`);
+ }
+ p.push(
+ isBatched(sum)
+ ? "Units: TTFT in ms; decode and prefill throughput in tokens per second; update p50/p99 is the wall-clock gap between stream updates in ms, and tok/update how many tokens each update carried."
+ : "Units: TTFT in ms; decode, ITL and prefill throughput in tokens per second; ITL columns are instantaneous tokens per second (1% low = slowest tokens, 99% high = fastest).",
+ );
+ const w = cfg.weights;
+ if (w && Object.keys(w).length && sum.single.length) {
+ const ws = sum.single.filter((r) => w[r.category] != null).map((r) => `${r.category} ${w[r.category]}`);
+ if (ws.length) p.push(`Combined figures are weighted by category: ${ws.join(", ")}. Categories without a weight are excluded from the combined figures.`);
+ } else if (sum.single.length > 1) {
+ p.push("Combined figures weight every category equally.");
+ }
+ p.push("Undersampled cells (†) carry a percentile that rests on fewer samples than n · tail ≥ 5 requires; read them as roughly the worst observed, not as percentiles.");
+ return p;
+}
+
+const METRIC_LABEL: Record = {
+ ttft_p99: "TTFT p99",
+ itl_high99: "ITL 99% high",
+ update_p99: "update p99",
+ pp_p99: "prefill p99",
+};
+
+/** "Read these first": the same rules as launch80's buildCaveats, plus prefix-cache hits. */
+export function reportCaveats(run: Run): string[] {
+ const sum = run.summary;
+ if (!sum) return [];
+ const out: string[] = [];
+ if (isQuick(sum)) {
+ out.push(`Quick smoke run: ${sum.passes ?? 5} passes per category after ${sum.config?.warmup ?? 1} warmup. Too few passes for any percentile to hold; treat every figure as indicative, not as a result.`);
+ }
+ const gate = sum.gate ?? [];
+ if (gate.length) {
+ const by = new Map();
+ for (const g of gate) {
+ const label = `${METRIC_LABEL[g.metric] ?? g.metric}`;
+ by.set(label, [...(by.get(label) ?? []), String(g.section === "prefill" ? `${int(Number(g.key))} tok` : g.section === "concurrency" ? `c${g.key}` : g.key)]);
+ }
+ const list = [...by].map(([m, keys]) => `${m} in ${keys.slice(0, 4).join(", ")}${keys.length > 4 ? ` +${keys.length - 4}` : ""}`).join("; ");
+ const need = Math.max(...gate.map((g) => g.need));
+ out.push(`Under-sampled: ${list} (n ≤ ${Math.max(...gate.map((g) => g.n))}). A p99 needs ${int(need)} samples; the daggered cells are roughly the worst observed, not percentiles.`);
+ }
+ const [trunc, tot] = sum.truncated ?? [0, 0];
+ if (tot > 0 && trunc > 0) {
+ out.push(`${trunc} of ${tot} runs stopped at max_tokens (${Math.round((trunc / tot) * 100)}%). On a thinking model a truncated run measures the thinking phase, not a complete answer.`);
+ }
+ const batchedRuns = sum.single.reduce((s, r) => s + (r.batched_runs ?? 0), 0);
+ if (batchedRuns > 0) {
+ const runs = sum.single.reduce((s, r) => s + r.runs, 0);
+ out.push(`${batchedRuns} of ${runs} runs streamed several tokens per update (speculative or batched decoding), so per-token ITL is not reported; update p50/p99 and tok/update are shown instead.`);
+ }
+ if (sum.failedSingle) out.push(`${sum.failedSingle} single-stream request(s) failed and are excluded from every figure.`);
+ const concFail = sum.concurrency.filter((c) => c.ok < c.requests).map((c) => `level ${c.level}: ${c.ok}/${c.requests} ok`);
+ if (concFail.length) out.push(`Concurrency requests failed at ${concFail.join("; ")}. Aggregate throughput counts only completed requests.`);
+ const skipped = sum.prefill.filter((p) => p.skipped).map((p) => int(p.target_depth));
+ if (skipped.length) out.push(`Prefill depths skipped: ${skipped.join(", ")} tokens (exceed the model context of ${int(sum.maxModelLen ?? run.snapshot.options.contextSize)}).`);
+ if (sum.cacheHits > 0) out.push(`${sum.cacheHits} request(s) were partly served from the server's prefix cache although the run asked for a cold cache; those prefill figures may be cache lookups.`);
+ return out.slice(0, 8);
+}
+
+/** Did this percentile cell fail the sample gate? */
+export function undersampled(sum: BenchmarkSummary, section: string, key: string | number, metric: string): boolean {
+ return !!sum.gate?.some((g) => g.section === section && String(g.key) === String(key) && g.metric === metric);
+}
diff --git a/src/lib/benchmark-view.test.ts b/src/lib/benchmark-view.test.ts
new file mode 100644
index 0000000..49807c9
--- /dev/null
+++ b/src/lib/benchmark-view.test.ts
@@ -0,0 +1,48 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+import { configChips, deltaPct, describeSettings, headline } from "./benchmark-view";
+import type { BenchmarkSnapshot, BenchmarkSummary } from "./db/schema";
+
+const summary: BenchmarkSummary = {
+ combined: { decode: 42.5, ttft_p50: 180, itl_low1: null, update_p50: null, update_p99: null },
+ single: [],
+ prefill: [
+ { target_depth: 2048, skipped: false, pp_med: 900 },
+ { target_depth: 8192, skipped: false, pp_med: 700 },
+ { target_depth: 65536, skipped: true },
+ ],
+ concurrency: [
+ { level: 1, ok: 48, requests: 48, aggregate_tps: 40, ttft_p50: 100, ttft_p99: 200, decode_med: 40 },
+ { level: 4, ok: 48, requests: 48, aggregate_tps: 95, ttft_p50: 300, ttft_p99: 900, decode_med: 25 },
+ { level: 8, ok: 48, requests: 48, aggregate_tps: 90, ttft_p50: 700, ttft_p99: 2000, decode_med: 12 },
+ ],
+ phases: ["decode", "prefill", "concurrency"],
+ cacheHits: 0,
+ betterbenchVersion: "0.6.1",
+ corpusVersion: "1.0",
+ passes: 20,
+ quick: false,
+};
+
+describe("benchmark view", () => {
+ it("picks the headline numbers", () => {
+ assert.deepEqual(headline(summary), { decode: 42.5, ttftMs: 180, prefill: { tps: 700, depth: 8192 }, peak: { tps: 95, level: 4 } });
+ assert.deepEqual(headline(null), { decode: null, ttftMs: null, prefill: null, peak: null });
+ });
+
+ it("lists set options as chips", () => {
+ const snap = {
+ options: { modelFile: "Qwen3-0.6B-Q4_K_M.gguf", contextSize: 4096, threads: 8, cacheTypeK: "q8_0", extraArgs: [] },
+ cpus: 8,
+ memoryMb: null,
+ } as unknown as BenchmarkSnapshot;
+ assert.deepEqual(configChips(snap), ["Q4_K_M", "context 4096", "threads 8", "kv cache k / v q8_0 / f16", "cpu limit 8 cores"]);
+ });
+
+ it("describes settings and deltas", () => {
+ assert.equal(describeSettings({ quick: true, passes: null, warmup: null, phases: [] }), "quick, 5 passes · all phases");
+ assert.equal(describeSettings({ quick: false, passes: 10, warmup: null, phases: ["decode"] }), "10 passes · decode");
+ assert.equal(deltaPct(110, 100), 10);
+ assert.equal(deltaPct(null, 100), null);
+ });
+});
diff --git a/src/lib/benchmark-view.ts b/src/lib/benchmark-view.ts
new file mode 100644
index 0000000..320c02b
--- /dev/null
+++ b/src/lib/benchmark-view.ts
@@ -0,0 +1,81 @@
+// Display helpers for benchmark runs. Pure; shared by list, detail and compare pages.
+
+import type { BenchmarkSettings, BenchmarkSnapshot, BenchmarkSummary } from "@/lib/db/schema";
+import { quantGroup } from "@/lib/selection";
+
+export type Headline = {
+ /** Weighted single-stream decode t/s (BetterBench's combined score). */
+ decode: number | null;
+ ttftMs: number | null;
+ /** Prefill t/s at the deepest measured depth. */
+ prefill: { tps: number; depth: number } | null;
+ /** Highest aggregate t/s in the concurrency sweep. */
+ peak: { tps: number; level: number } | null;
+};
+
+export function headline(s: BenchmarkSummary | null): Headline {
+ if (!s) return { decode: null, ttftMs: null, prefill: null, peak: null };
+ const pre = s.prefill.filter((p) => !p.skipped && p.pp_med != null).sort((a, b) => b.target_depth - a.target_depth)[0];
+ const peak = [...s.concurrency].sort((a, b) => b.aggregate_tps - a.aggregate_tps)[0];
+ return {
+ decode: s.combined?.decode ?? null,
+ ttftMs: s.combined?.ttft_p50 ?? null,
+ prefill: pre ? { tps: pre.pp_med!, depth: pre.target_depth } : null,
+ peak: peak ? { tps: peak.aggregate_tps, level: peak.level } : null,
+ };
+}
+
+export type ConfigRow = { key: string; label: string; value: (s: BenchmarkSnapshot) => string | null };
+
+const n = (v: number | null | undefined, unit = "") => (v != null ? `${v}${unit}` : null);
+
+/** Launch settings worth comparing between runs, in display order. */
+export const CONFIG_ROWS: ConfigRow[] = [
+ { key: "runtime", label: "Runtime", value: (s) => s.runtimeName },
+ { key: "image", label: "Image", value: (s) => s.image },
+ { key: "accel", label: "Runs on", value: (s) => (s.accelerator && s.accelerator !== "cpu" ? s.accelerator : null) },
+ { key: "gpus", label: "GPUs", value: (s) => (s.gpuNames?.length ? s.gpuNames.join(", ") : null) },
+ { key: "ngl", label: "GPU layers", value: (s) => s.options.gpuLayers ?? null },
+ { key: "sm", label: "Split mode", value: (s) => s.options.splitMode ?? null },
+ { key: "ts", label: "Tensor split", value: (s) => s.options.tensorSplit ?? null },
+ { key: "moe", label: "MoE experts in RAM", value: (s) => (s.options.cpuMoe ? "all" : s.options.nCpuMoe != null ? `first ${s.options.nCpuMoe} layers` : null) },
+ { key: "tp", label: "Tensor parallel", value: (s) => n(s.options.tensorParallel) },
+ { key: "gmu", label: "GPU memory share", value: (s) => n(s.options.gpuMemoryUtilization) },
+ { key: "cram", label: "Prompt cache (MiB)", value: (s) => n(s.options.cacheRamMb) },
+ { key: "file", label: "Weights", value: (s) => (s.options.modelFile ? (quantGroup(s.options.modelFile) ?? s.options.modelFile) : "safetensors") },
+ { key: "ctx", label: "Context", value: (s) => n(s.options.contextSize) },
+ { key: "threads", label: "Threads", value: (s) => n(s.options.threads) },
+ { key: "parallel", label: "Parallel slots", value: (s) => n(s.options.parallel) },
+ { key: "batch", label: "Batch / micro-batch", value: (s) => (s.options.batchSize || s.options.ubatchSize ? `${s.options.batchSize ?? "–"} / ${s.options.ubatchSize ?? "–"}` : null) },
+ { key: "kv", label: "KV cache K / V", value: (s) => (s.options.cacheTypeK || s.options.cacheTypeV ? `${s.options.cacheTypeK ?? "f16"} / ${s.options.cacheTypeV ?? "f16"}` : null) },
+ { key: "fa", label: "Flash attention", value: (s) => s.options.flashAttn ?? null },
+ { key: "draft", label: "Speculative", value: (s) => (s.options.draftFile ? `${s.options.draftType === "draft-mtp" ? "MTP" : "draft"}: ${s.options.draftFile}` : null) },
+ { key: "dtype", label: "Data type", value: (s) => s.options.dtype ?? null },
+ { key: "seqs", label: "Max sequences", value: (s) => n(s.options.maxNumSeqs) },
+ { key: "kvgb", label: "KV cache (GiB)", value: (s) => n(s.options.kvCacheGb) },
+ { key: "cpus", label: "CPU limit", value: (s) => n(s.cpus, " cores") },
+ { key: "mem", label: "Memory limit", value: (s) => (s.memoryMb ? `${Math.round(s.memoryMb / 102.4) / 10} GiB` : null) },
+ { key: "args", label: "Extra arguments", value: (s) => (s.options.extraArgs.length ? s.options.extraArgs.join(" ") : null) },
+];
+
+/** Short chips for a list row: the settings that are set. */
+export function configChips(s: BenchmarkSnapshot): string[] {
+ const skip = new Set(["runtime", "image", "args"]);
+ return CONFIG_ROWS.filter((r) => !skip.has(r.key))
+ .map((r) => {
+ const v = r.value(s);
+ return v == null ? null : r.key === "file" ? v : `${r.label.toLowerCase()} ${v}`;
+ })
+ .filter((v): v is string => v != null);
+}
+
+export function describeSettings(st: BenchmarkSettings): string {
+ const passes = st.passes ?? (st.quick ? 5 : 20);
+ const phases = st.phases.length ? st.phases.join(", ") : "all phases";
+ return `${st.quick && st.passes == null ? "quick, " : ""}${passes} passes · ${phases}`;
+}
+
+/** Relative difference of `v` against `base` in percent (null if either is missing). */
+export function deltaPct(v: number | null | undefined, base: number | null | undefined): number | null {
+ return v != null && base != null && base !== 0 ? ((v - base) / base) * 100 : null;
+}
diff --git a/src/lib/benchmarks.ts b/src/lib/benchmarks.ts
new file mode 100644
index 0000000..ea114e6
--- /dev/null
+++ b/src/lib/benchmarks.ts
@@ -0,0 +1,176 @@
+import "server-only";
+import { rm } from "node:fs/promises";
+import { and, asc, desc, eq, gt, inArray, isNull } from "drizzle-orm";
+import { z } from "zod";
+import { runDir } from "@/lib/benchmark-paths";
+import { db } from "@/lib/db/client";
+import { BENCHMARK_PHASES, benchmarkLogs, benchmarkRuns, type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
+
+export class BenchmarkError extends Error {
+ constructor(
+ public code: "invalid" | "not_found" | "busy",
+ message: string,
+ public status: number,
+ ) {
+ super(message);
+ }
+}
+
+export const BenchmarkBody = z.object({
+ deploymentId: z.string().min(1),
+ label: z.string().trim().max(120).nullable().optional(),
+ quick: z.boolean().default(false),
+ passes: z.number().int().min(1).max(200).nullable().optional(),
+ warmup: z.number().int().min(0).max(50).nullable().optional(),
+ /** Empty: all phases. */
+ phases: z.array(z.enum(BENCHMARK_PHASES)).max(3).default([]),
+});
+export type BenchmarkInput = z.infer;
+
+/** Names of the GPUs a deployment uses (all detected ones when none are picked). */
+async function hostFacts(uuids: string[] | null, nvidia: boolean) {
+ const ws = await db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") });
+ const h = ws?.docker;
+ const gpus = h?.gpus ?? [];
+ return {
+ gpuNames: nvidia ? (uuids ? gpus.filter((g) => uuids.includes(g.uuid)) : gpus).map((g) => g.name) : [],
+ host: { cpuModel: h?.cpuModel ?? null, threads: h?.cpus ?? null, memoryBytes: h?.memoryBytes ?? null, os: h?.os ?? null },
+ };
+}
+
+/** Queue a run against a running deployment; the worker runs one benchmark at a time. */
+export async function createBenchmark(input: BenchmarkInput) {
+ const [d] = await db()
+ .select({
+ id: deployments.id,
+ name: deployments.name,
+ state: deployments.state,
+ options: deployments.options,
+ cpus: deployments.cpus,
+ memoryMb: deployments.memoryMb,
+ command: deployments.command,
+ imageId: deployments.imageId,
+ modelId: deployments.modelId,
+ repoId: models.repoId,
+ runtimeName: runtimes.name,
+ engine: runtimes.engine,
+ accelerator: runtimes.accelerator,
+ image: runtimes.image,
+ })
+ .from(deployments)
+ .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
+ .innerJoin(models, eq(models.id, deployments.modelId))
+ .where(and(eq(deployments.id, input.deploymentId), isNull(deployments.deleteRequestedAt)));
+ if (!d) throw new BenchmarkError("not_found", "Deployment not found.", 404);
+ if (d.state !== "running") throw new BenchmarkError("invalid", "Start the deployment first; benchmarks run against a running server.", 409);
+
+ const snapshot: BenchmarkSnapshot = {
+ deploymentName: d.name,
+ repoId: d.repoId,
+ runtimeName: d.runtimeName,
+ engine: d.engine,
+ accelerator: d.accelerator,
+ ...(await hostFacts(d.options.gpus ?? null, d.accelerator === "nvidia")),
+ image: d.image,
+ imageId: d.imageId,
+ options: d.options,
+ cpus: d.cpus,
+ memoryMb: d.memoryMb,
+ command: [d.image, ...(d.command ?? [])].join(" "),
+ };
+ const [row] = await db()
+ .insert(benchmarkRuns)
+ .values({
+ deploymentId: d.id,
+ modelId: d.modelId,
+ label: input.label || null,
+ settings: { quick: input.quick, passes: input.passes ?? null, warmup: input.warmup ?? null, phases: input.phases },
+ snapshot,
+ })
+ .returning({ id: benchmarkRuns.id });
+ return row;
+}
+
+const listColumns = {
+ id: benchmarkRuns.id,
+ deploymentId: benchmarkRuns.deploymentId,
+ modelId: benchmarkRuns.modelId,
+ tool: benchmarkRuns.tool,
+ label: benchmarkRuns.label,
+ settings: benchmarkRuns.settings,
+ snapshot: benchmarkRuns.snapshot,
+ state: benchmarkRuns.state,
+ phase: benchmarkRuns.phase,
+ cancelRequestedAt: benchmarkRuns.cancelRequestedAt,
+ startedAt: benchmarkRuns.startedAt,
+ finishedAt: benchmarkRuns.finishedAt,
+ error: benchmarkRuns.error,
+ summary: benchmarkRuns.summary,
+ hasReport: benchmarkRuns.hasReport,
+ createdAt: benchmarkRuns.createdAt,
+};
+
+export type BenchmarkRow = Awaited>[number];
+
+export async function listBenchmarks(filter: { deploymentId?: string; modelId?: string } = {}) {
+ return db()
+ .select(listColumns)
+ .from(benchmarkRuns)
+ .where(
+ and(
+ filter.deploymentId ? eq(benchmarkRuns.deploymentId, filter.deploymentId) : undefined,
+ filter.modelId ? eq(benchmarkRuns.modelId, filter.modelId) : undefined,
+ ),
+ )
+ .orderBy(desc(benchmarkRuns.createdAt));
+}
+
+export async function getBenchmark(id: string) {
+ const [row] = await db().select(listColumns).from(benchmarkRuns).where(eq(benchmarkRuns.id, id));
+ return row ?? null;
+}
+
+export async function getBenchmarks(ids: string[]) {
+ if (ids.length === 0) return [];
+ const rows = await db().select(listColumns).from(benchmarkRuns).where(inArray(benchmarkRuns.id, ids));
+ 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. */
+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")));
+ } else if (run.state === "running") {
+ await db().update(benchmarkRuns).set({ cancelRequestedAt: new Date() }).where(eq(benchmarkRuns.id, id));
+ }
+}
+
+export async function updateBenchmarkLabel(id: string, label: string | null) {
+ const res = await db().update(benchmarkRuns).set({ label: label?.trim() || null }).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
+ if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
+}
+
+/** Deletes the run, its log and its files. Cancel a running one first. */
+export async function deleteBenchmark(id: string) {
+ const run = await getBenchmark(id);
+ if (!run) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
+ if (run.state === "running") throw new BenchmarkError("busy", "Cancel the run before deleting it.", 409);
+ await db().delete(benchmarkLogs).where(eq(benchmarkLogs.runId, id));
+ await db().delete(benchmarkRuns).where(eq(benchmarkRuns.id, id));
+ await rm(runDir(id), { recursive: true, force: true });
+}
+
+export async function listBenchmarkLogs(id: string, afterId: number, tail = 500) {
+ const rows =
+ afterId > 0
+ ? await db()
+ .select()
+ .from(benchmarkLogs)
+ .where(and(eq(benchmarkLogs.runId, id), gt(benchmarkLogs.id, afterId)))
+ .orderBy(asc(benchmarkLogs.id))
+ .limit(2000)
+ : (await db().select().from(benchmarkLogs).where(eq(benchmarkLogs.runId, id)).orderBy(desc(benchmarkLogs.id)).limit(tail)).reverse();
+ return rows.map((r) => ({ id: r.id, ts: r.ts.getTime(), stream: r.stream, line: r.line }));
+}
diff --git a/src/lib/db/schema.ts b/src/lib/db/schema.ts
index 0b8f047..64b3d91 100644
--- a/src/lib/db/schema.ts
+++ b/src/lib/db/schema.ts
@@ -362,9 +362,17 @@ export type DockerHostInfo = {
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;
checkedAt: string;
};
+export type HostGpu = { vendor: "nvidia"; index: number; uuid: string; name: string; memoryMb: number; driver: string };
+
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
// ---------------------------------------------------------------------------
@@ -373,6 +381,13 @@ export type DockerHostInfo = {
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];
@@ -380,6 +395,7 @@ 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"),
@@ -451,6 +467,22 @@ export type DeploymentOptions = {
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 */
@@ -523,3 +555,201 @@ export const apiKeys = sqliteTable("api_keys", {
key: text("key").notNull().unique(),
createdAt: createdAt(),
});
+
+// ---------------------------------------------------------------------------
+// Benchmarks (BetterBench runs against a running deployment)
+// ---------------------------------------------------------------------------
+
+export const BENCHMARK_STATES = ["queued", "running", "completed", "failed", "cancelled"] as const;
+export type BenchmarkState = (typeof BENCHMARK_STATES)[number];
+
+export const BENCHMARK_PHASES = ["decode", "prefill", "concurrency"] as const;
+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[];
+};
+
+/** 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;
+};
+
+/**
+ * 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 | 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().notNull(),
+ snapshot: text("snapshot", { mode: "json" }).$type().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(),
+ /** Files under BENCHMARKS_DIR//: results.json and results.html. */
+ hasReport: integer("has_report", { mode: "boolean" }).notNull().default(false),
+ 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)],
+);
diff --git a/src/lib/deploy-command.test.ts b/src/lib/deploy-command.test.ts
index 9a31288..6577122 100644
--- a/src/lib/deploy-command.test.ts
+++ b/src/lib/deploy-command.test.ts
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
-import { buildCommand, redactCommand, renderCommand } from "./deploy-command";
+import { buildCommand, estimateMemoryMb, redactCommand, renderCommand } from "./deploy-command";
const model = { repoId: "unsloth/Qwen3-0.6B-GGUF", localPath: "unsloth/Qwen3-0.6B-GGUF" };
@@ -83,4 +83,34 @@ describe("buildCommand", () => {
const off = buildCommand({ ...base, engine: "llama.cpp", options: { ...opts, requireApiKey: false }, apiKeys: ["sk-one-1234567890"] });
assert.equal(off.env.LLAMA_API_KEY, undefined);
});
+
+ it("adds GPU flags only on GPU runtimes", () => {
+ const model = { repoId: "a/b", localPath: "a/b" };
+ const options = { modelFile: "m.gguf", contextSize: 4096, gpuLayers: "all", splitMode: "layer" as const, nCpuMoe: 8, cacheRamMb: 1024, extraArgs: [] };
+ const gpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } }).args.join(" ");
+ assert.match(gpu, /-cram 1024 -ngl all -sm layer -ncmoe 8 --metrics/);
+ const cpu = buildCommand({ engine: "llama.cpp", model, options, runtime: { env: {}, extraArgs: [] } }).args.join(" ");
+ assert.ok(cpu.includes("-cram 1024") && !cpu.includes("-ngl") && !cpu.includes("-ncmoe"));
+ const auto = buildCommand({ engine: "llama.cpp", model, options: { ...options, gpuLayers: "auto" }, runtime: { env: {}, extraArgs: [], accelerator: "nvidia" } });
+ assert.ok(!auto.args.includes("-ngl"));
+
+ const vllm = buildCommand({
+ engine: "vllm",
+ model,
+ options: { modelFile: "", contextSize: 4096, tensorParallel: 2, gpuMemoryUtilization: 0.85, kvCacheGb: 4, extraArgs: [] },
+ runtime: { env: {}, extraArgs: [], accelerator: "nvidia" },
+ });
+ assert.match(vllm.args.join(" "), /--tensor-parallel-size 2 --gpu-memory-utilization 0.85/);
+ assert.equal(vllm.env.VLLM_CPU_KVCACHE_SPACE, undefined);
+ });
+
+ it("counts the prompt cache and KV cache in the llama.cpp memory estimate", () => {
+ const file = 400 * 2 ** 20;
+ const small = estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024 });
+ const unset = estimateMemoryMb(file, 4096, "llama.cpp", {});
+ assert.ok(small > 2048 && small < 3072, String(small));
+ assert.equal(unset - small, 8192 - 1024);
+ assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, cacheTypeK: "q8_0", cacheTypeV: "q8_0" }) < small);
+ assert.ok(estimateMemoryMb(file, 4096, "llama.cpp", { cacheRamMb: 1024, accelerator: "nvidia" }) < small);
+ });
});
diff --git a/src/lib/deploy-command.ts b/src/lib/deploy-command.ts
index 680e371..4dc49bd 100644
--- a/src/lib/deploy-command.ts
+++ b/src/lib/deploy-command.ts
@@ -2,7 +2,7 @@
// 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";
+import type { DeploymentOptions, RuntimeAccelerator, RuntimeEngine } from "@/lib/db/schema";
/** Where the models folder is mounted inside every runtime container (read-only). */
export const CONTAINER_MODELS_DIR = "/models";
@@ -13,7 +13,8 @@ export type CommandInput = {
engine: RuntimeEngine;
options: DeploymentOptions;
model: { repoId: string; localPath: string };
- runtime: { env: Record; extraArgs: string[] };
+ /** `accelerator` unset: CPU. */
+ runtime: { env: Record; extraArgs: string[]; accelerator?: RuntimeAccelerator };
/** Keys from Settings → API keys; used when `options.requireApiKey` is set. */
apiKeys?: string[];
};
@@ -42,6 +43,7 @@ function withoutFlag(args: string[], flag: string): string[] {
export function buildCommand({ engine, options: o, model, runtime, apiKeys = [] }: CommandInput): ContainerCommand {
const port = ENGINE_PORT[engine];
const keys = o.requireApiKey ? apiKeys : [];
+ const gpu = !!runtime.accelerator && runtime.accelerator !== "cpu";
if (engine === "llama.cpp") {
// The image's entrypoint is llama-server, so these are its arguments.
const args = [
@@ -62,9 +64,16 @@ export function buildCommand({ engine, options: o, model, runtime, apiKeys = []
...str("-ctk", o.cacheTypeK),
...str("-ctv", o.cacheTypeV),
...str("-fa", o.flashAttn),
+ ...num("-cram", o.cacheRamMb),
...(o.mmproj ? ["--mmproj", inModels(model.localPath, o.mmproj)] : []),
...(o.draftFile ? ["-md", inModels(model.localPath, o.draftFile), "--spec-type", o.draftType ?? "draft-simple"] : []),
...(o.webui === false ? ["--no-webui"] : []),
+ // GPU offload (-ngl defaults to "auto", which fits layers into free VRAM).
+ ...(gpu ? str("-ngl", o.gpuLayers && o.gpuLayers !== "auto" ? o.gpuLayers : null) : []),
+ ...(gpu ? str("-sm", o.splitMode) : []),
+ ...(gpu ? str("-ts", o.tensorSplit) : []),
+ ...(gpu && o.cpuMoe ? ["-cmoe"] : []),
+ ...(gpu && !o.cpuMoe ? num("-ncmoe", o.nCpuMoe) : []),
"--metrics",
...runtime.extraArgs,
...o.extraArgs,
@@ -76,7 +85,7 @@ export function buildCommand({ engine, options: o, model, runtime, apiKeys = []
// 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);
+ if (!gpu && o.kvCacheGb != null) env.VLLM_CPU_KVCACHE_SPACE = String(o.kvCacheGb);
// VLLM_API_KEY holds a single key; more than one needs --api-key.
if (keys.length === 1) env.VLLM_API_KEY = keys[0];
const args = [
@@ -89,6 +98,8 @@ export function buildCommand({ engine, options: o, model, runtime, apiKeys = []
model.repoId,
...num("--max-model-len", o.contextSize),
...num("--max-num-seqs", o.maxNumSeqs),
+ ...(gpu ? num("--tensor-parallel-size", o.tensorParallel) : []),
+ ...(gpu ? num("--gpu-memory-utilization", o.gpuMemoryUtilization) : []),
...(keys.length > 1 ? ["--api-key", ...keys] : []),
// A deployment's dtype replaces the runtime's default instead of repeating the flag.
...(o.dtype ? withoutFlag(runtime.extraArgs, "--dtype") : runtime.extraArgs),
@@ -112,11 +123,31 @@ export function renderCommand(image: string, cmd: ContainerCommand): string {
}
/** Rough memory need: model files plus KV cache and runtime overhead. */
-export function estimateMemoryMb(fileBytes: number, contextSize: number, engine: RuntimeEngine, kvCacheGb?: number | null): number {
+/** llama-server's default --cache-ram (MiB): prompts kept in RAM for reuse. */
+export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192;
+
+const KV_TYPE_FACTOR: Record = { f32: 2, f16: 1, bf16: 1, q8_0: 0.53, q5_0: 0.34, q5_1: 0.38, q4_0: 0.28, q4_1: 0.31, iq4_nl: 0.28 };
+
+/**
+ * Rough RAM need of a deployment in MiB, for the memory limit. Without the GGUF header the KV size
+ * per token is a heuristic: ~110 KiB (f16) for sub-1B models up to ~250 KiB around 70B with GQA.
+ * Measured (llama.cpp b11429, Qwen3-0.6B Q4_K_M, ctx 4096): ~1.2 GiB without the prompt cache.
+ */
+export function estimateMemoryMb(
+ fileBytes: number,
+ contextSize: number,
+ engine: RuntimeEngine,
+ o: Pick & { accelerator?: RuntimeAccelerator } = {},
+): number {
const model = fileBytes / 2 ** 20;
+ const gpu = !!o.accelerator && o.accelerator !== "cpu";
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
- if (engine === "vllm") return Math.ceil(model + (kvCacheGb ?? 4) * 1024 + 3072);
- // 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);
+ // On a GPU the weights and KV cache live in VRAM; RAM holds the processes.
+ if (engine === "vllm") return Math.ceil(gpu ? 6144 : model + (o.kvCacheGb ?? 4) * 1024 + 3072);
+ const perTokenKiB = 96 + 24 * Math.sqrt(model / 1024);
+ const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
+ const kv = (contextSize * perTokenKiB * kvFactor) / 1024;
+ const cache = o.cacheRamMb == null ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb < 0 ? LLAMA_DEFAULT_CACHE_RAM_MB : o.cacheRamMb;
+ // The memory-mapped model counts against the container's limit (page cache), even when offloaded.
+ return Math.ceil(model + (gpu ? 0 : kv) + cache + 768);
}
diff --git a/src/lib/deployments.ts b/src/lib/deployments.ts
index 6d40d45..a7bcdfc 100644
--- a/src/lib/deployments.ts
+++ b/src/lib/deployments.ts
@@ -37,6 +37,23 @@ export const DeploymentBody = z.object({
flashAttn: z.enum(["auto", "on", "off"]).nullable().optional(),
webui: z.boolean().nullable().optional(),
requireApiKey: z.boolean().nullable().optional(),
+ cacheRamMb: int(-1, 1_048_576).nullable().optional(),
+ gpus: z.array(z.string().regex(/^GPU-[0-9a-f-]{36}$/i, "a GPU UUID")).max(64).nullable().optional(),
+ gpuLayers: z
+ .string()
+ .regex(/^(auto|all|\d{1,4})$/, "auto, all or a number")
+ .nullable()
+ .optional(),
+ splitMode: z.enum(["none", "layer", "row", "tensor"]).nullable().optional(),
+ tensorSplit: z
+ .string()
+ .regex(/^\d+(\.\d+)?(,\d+(\.\d+)?)*$/, "proportions like 3,1")
+ .nullable()
+ .optional(),
+ cpuMoe: z.boolean().nullable().optional(),
+ nCpuMoe: int(0, 1000).nullable().optional(),
+ tensorParallel: int(1, 64).nullable().optional(),
+ gpuMemoryUtilization: z.number().min(0.05).max(1).nullable().optional(),
dtype: z.enum(["auto", "bfloat16", "float16", "float32"]).nullable().optional(),
maxNumSeqs: int(1, 1024).nullable().optional(),
kvCacheGb: z.number().min(0.25).max(1024).nullable().optional(),
@@ -90,9 +107,33 @@ async function validate(input: DeploymentInput, selfId?: string): Promise 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 });
+ Object.assign(options, { dtype: null, maxNumSeqs: null, kvCacheGb: null, tensorParallel: null, gpuMemoryUtilization: null });
} else {
- Object.assign(options, { modelFile: "", mmproj: null, draftFile: null, draftType: null, batchSize: null, ubatchSize: null, cacheTypeK: null, cacheTypeV: null, flashAttn: null, webui: null });
+ Object.assign(options, {
+ modelFile: "",
+ mmproj: null,
+ draftFile: null,
+ draftType: null,
+ batchSize: null,
+ ubatchSize: null,
+ cacheTypeK: null,
+ cacheTypeV: null,
+ flashAttn: null,
+ webui: null,
+ cacheRamMb: null,
+ gpuLayers: null,
+ splitMode: null,
+ tensorSplit: null,
+ cpuMoe: null,
+ nCpuMoe: null,
+ });
+ }
+ // GPU settings only mean something on a GPU runtime; GPU picking only on NVIDIA.
+ if (runtime.accelerator === "cpu") {
+ Object.assign(options, { gpus: null, gpuLayers: null, splitMode: null, tensorSplit: null, cpuMoe: null, nCpuMoe: null, tensorParallel: null, gpuMemoryUtilization: null });
+ } else {
+ if (runtime.accelerator !== "nvidia") options.gpus = null;
+ options.kvCacheGb = null;
}
if (o.requireApiKey && (await db().select({ id: apiKeys.id }).from(apiKeys).limit(1)).length === 0) {
throw new DeploymentError("invalid", "Add an API key under Settings → API keys first.", 400);
@@ -186,6 +227,7 @@ const listColumns = {
runtimeId: deployments.runtimeId,
runtimeName: runtimes.name,
runtimeImage: runtimes.image,
+ accelerator: runtimes.accelerator,
engine: runtimes.engine,
modelId: deployments.modelId,
repoId: models.repoId,
diff --git a/src/lib/env.ts b/src/lib/env.ts
index aa2d457..c4edf65 100644
--- a/src/lib/env.ts
+++ b/src/lib/env.ts
@@ -30,6 +30,15 @@ const coreSchema = z.object({
/** Override the auto-detected Docker network / models source (needed when the worker isn't a container). */
KANAME_DOCKER_NETWORK: z.preprocess(emptyToUndefined, z.string().optional()),
KANAME_MODELS_SOURCE: z.preprocess(emptyToUndefined, z.string().optional()),
+ /** BetterBench results and HTML reports. Default: "benchmarks" next to the SQLite database. */
+ BENCHMARKS_DIR: z.preprocess(emptyToUndefined, z.string().optional()),
+ /** The betterbench executable (the image ships one). Unset and not on PATH: benchmarks are disabled. */
+ BETTERBENCH_BIN: z.preprocess(emptyToUndefined, z.string().default("betterbench")),
+ /** launch80 publish token (worker only; passed to the L80 CLI via its environment, never shown or logged). */
+ L80_TOKEN: z.preprocess(emptyToUndefined, z.string().optional()),
+ L80_API_BASE: z.preprocess(emptyToUndefined, z.url().optional()),
+ /** The L80 CLI (the image ships one). */
+ L80_BIN: z.preprocess(emptyToUndefined, z.string().default("L80")),
});
const authSchema = z.object({
diff --git a/src/lib/publications.ts b/src/lib/publications.ts
new file mode 100644
index 0000000..c995c78
--- /dev/null
+++ b/src/lib/publications.ts
@@ -0,0 +1,127 @@
+import "server-only";
+import { readFile, rm } from "node:fs/promises";
+import { join } from "node:path";
+import { and, desc, eq } from "drizzle-orm";
+import { z } from "zod";
+import { runDir } from "@/lib/benchmark-paths";
+import { db } from "@/lib/db/client";
+import { benchmarkPublications, benchmarkRuns, settings } from "@/lib/db/schema";
+
+export class PublicationError extends Error {
+ constructor(
+ public code: "invalid" | "not_found" | "busy",
+ message: string,
+ public status: number,
+ ) {
+ super(message);
+ }
+}
+
+/** Limits of the L80 CLI (internal/betterbench: maxTitle, maxSummary). */
+export const PreviewBody = z.object({
+ title: z.string().trim().max(120).nullable().optional(),
+ summary: z.string().trim().max(600).nullable().optional(),
+});
+
+export type L80Status = { version: string | null; tokenSet: boolean; apiBase: string; checkedAt: string } | null;
+
+export async function getL80Status(): Promise {
+ const row = await db().query.settings.findFirst({ where: eq(settings.key, "l80.status") });
+ return (row?.value as L80Status) ?? null;
+}
+
+export type PublicationRow = typeof benchmarkPublications.$inferSelect;
+
+export async function listPublications(runId: string): Promise {
+ return db().select().from(benchmarkPublications).where(eq(benchmarkPublications.runId, runId)).orderBy(desc(benchmarkPublications.createdAt));
+}
+
+async function getPublication(runId: string, pubId: string) {
+ const p = await db().query.benchmarkPublications.findFirst({ where: and(eq(benchmarkPublications.id, pubId), eq(benchmarkPublications.runId, runId)) });
+ if (!p) throw new PublicationError("not_found", "Publication not found.", 404);
+ return p;
+}
+
+/** Opt-in 1: build the exact payload with a dry run (nothing leaves the machine). */
+export async function requestPreview(runId: string, input: z.infer) {
+ const run = await db().query.benchmarkRuns.findFirst({ columns: { state: true }, where: eq(benchmarkRuns.id, runId) });
+ if (!run) throw new PublicationError("not_found", "Benchmark not found.", 404);
+ if (run.state !== "completed") throw new PublicationError("invalid", "Only completed runs can be published.", 409);
+ const status = await getL80Status();
+ if (!status?.version) throw new PublicationError("invalid", "The L80 CLI isn't available in this installation.", 409);
+ const [row] = await db()
+ .insert(benchmarkPublications)
+ .values({ runId, title: input.title || null, summary: input.summary || null })
+ .returning({ id: benchmarkPublications.id });
+ return row;
+}
+
+/** Opt-in 2: an explicit confirmation of a previewed payload. */
+export async function confirmPublication(runId: string, pubId: string, by: string | null) {
+ const p = await getPublication(runId, pubId);
+ if (p.state !== "previewed") throw new PublicationError("invalid", "Only a finished preview can be published.", 409);
+ const status = await getL80Status();
+ if (!status?.tokenSet) throw new PublicationError("invalid", "No launch80 token is configured (L80_TOKEN).", 409);
+ await db()
+ .update(benchmarkPublications)
+ .set({ state: "publish", confirmedBy: by, confirmedAt: new Date() })
+ .where(and(eq(benchmarkPublications.id, pubId), eq(benchmarkPublications.state, "previewed")));
+}
+
+/** Throw away a preview (published ones stay as a record). */
+export async function discardPublication(runId: string, pubId: string) {
+ const p = await getPublication(runId, pubId);
+ if (p.state === "published" || p.state === "publish") throw new PublicationError("busy", "Published pages can't be withdrawn from here; they expire after 5 days.", 409);
+ await db().delete(benchmarkPublications).where(eq(benchmarkPublications.id, pubId));
+ await rm(payloadFile(runId, pubId), { force: true });
+}
+
+export function payloadFile(runId: string, pubId: string): string {
+ // Ids come from the URL; only ULIDs become a path.
+ if (!/^[0-9A-HJKMNP-TV-Z]{26}$/.test(pubId)) throw new PublicationError("not_found", "Publication not found.", 404);
+ return join(runDir(runId), "publications", `${pubId}.json`);
+}
+
+export type PayloadPreview = {
+ template: string;
+ bytes: number;
+ title: string | null;
+ summary: string | null;
+ model: string | null;
+ notes: Record;
+ /** Top-level keys that will be sent, and env keys (endpoint/host must be absent). */
+ keys: string[];
+ envKeys: string[];
+ hostRemoved: boolean;
+ categories: string[];
+ phases: string[];
+};
+
+/** What the dry-run payload contains, read from the exact file that would be sent. */
+export async function readPayloadPreview(runId: string, pubId: string): Promise {
+ const p = await getPublication(runId, pubId);
+ const raw = await readFile(payloadFile(runId, p.id), "utf8").catch(() => null);
+ if (!raw) return null;
+ const data = JSON.parse(raw) as Record & {
+ $template?: string;
+ env?: Record;
+ l80?: { title?: string; summary?: string };
+ single_stream?: Record;
+ prefill?: unknown[];
+ concurrency?: unknown[];
+ };
+ const env = data.env ?? {};
+ return {
+ template: data.$template ?? p.template,
+ bytes: Buffer.byteLength(raw),
+ title: data.l80?.title ?? null,
+ summary: data.l80?.summary ?? null,
+ model: typeof env.model === "string" ? env.model : null,
+ notes: (env.notes as Record) ?? {},
+ keys: Object.keys(data),
+ envKeys: Object.keys(env),
+ hostRemoved: !("endpoint" in env) && !("host" in env),
+ categories: Object.keys(data.single_stream ?? {}),
+ phases: [data.single_stream ? "decode" : null, data.prefill?.length ? "prefill" : null, data.concurrency?.length ? "concurrency" : null].filter(Boolean) as string[],
+ };
+}
diff --git a/src/lib/runtimes-shared.ts b/src/lib/runtimes-shared.ts
index 9cabdd0..991bbd6 100644
--- a/src/lib/runtimes-shared.ts
+++ b/src/lib/runtimes-shared.ts
@@ -1,10 +1,21 @@
// Runtime presets and validation. Pure (no DB), shared by the web app, the worker and tests.
-import type { RuntimeEngine } from "@/lib/db/schema";
+import { RUNTIME_ACCELERATORS, type RuntimeAccelerator, type RuntimeEngine } from "@/lib/db/schema";
+
+export const ACCELERATOR_LABEL: Record = {
+ cpu: "CPU",
+ nvidia: "NVIDIA (CUDA)",
+ dri: "Intel / AMD via /dev/dri",
+ rocm: "AMD ROCm",
+};
+
+/** Device nodes an accelerator needs passed through (NVIDIA GPUs are requested from Docker instead). */
+export const ACCELERATOR_DEVICES: Record = { cpu: [], nvidia: [], dri: ["/dev/dri"], rocm: ["/dev/kfd", "/dev/dri"] };
export type RuntimeInput = {
name: string;
engine: RuntimeEngine;
+ accelerator?: RuntimeAccelerator;
image: string;
description?: string | null;
env?: Record;
@@ -16,7 +27,7 @@ export type RuntimeInput = {
export type RuntimePreset = RuntimeInput & { id: string; summary: string };
-/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0). */
+/** Starting points; verified against the images (llama.cpp build 11429, vLLM v0.31.0; all tags exist). */
export const RUNTIME_PRESETS: RuntimePreset[] = [
{
id: "llama.cpp-cpu",
@@ -37,6 +48,77 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
extraArgs: ["--dtype=bfloat16"],
shmSizeMb: 4096,
},
+ {
+ id: "llama.cpp-cuda",
+ name: "llama.cpp (CUDA)",
+ engine: "llama.cpp",
+ accelerator: "nvidia",
+ image: "ghcr.io/ggml-org/llama.cpp:server-cuda",
+ summary: "llama-server for NVIDIA GPUs. Needs the NVIDIA Container Toolkit on the Docker host.",
+ description: "Official llama.cpp server, CUDA build. Layers go to the GPU automatically (-ngl auto); set GPU layers per deployment.",
+ },
+ {
+ id: "vllm-cuda",
+ name: "vLLM (CUDA)",
+ engine: "vllm",
+ accelerator: "nvidia",
+ image: "vllm/vllm-openai:v0.31.0",
+ summary: "Official vLLM image for NVIDIA GPUs (large download). Needs the NVIDIA Container Toolkit.",
+ description: "Official vLLM, CUDA build. vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU up front.",
+ shmSizeMb: 8192,
+ },
+ {
+ id: "llama.cpp-vulkan",
+ name: "llama.cpp (Vulkan)",
+ engine: "llama.cpp",
+ accelerator: "dri",
+ image: "ghcr.io/ggml-org/llama.cpp:server-vulkan",
+ summary: "llama-server over Vulkan: Intel Arc and AMD GPUs via /dev/dri.",
+ description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri.",
+ devices: ["/dev/dri"],
+ },
+ {
+ id: "llama.cpp-intel",
+ name: "llama.cpp (Intel SYCL)",
+ engine: "llama.cpp",
+ accelerator: "dri",
+ image: "ghcr.io/ggml-org/llama.cpp:server-intel",
+ summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs.",
+ description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri).",
+ devices: ["/dev/dri"],
+ },
+ {
+ id: "llama.cpp-rocm",
+ name: "llama.cpp (ROCm)",
+ engine: "llama.cpp",
+ accelerator: "rocm",
+ image: "ghcr.io/ggml-org/llama.cpp:server-rocm",
+ summary: "llama-server for AMD GPUs with ROCm (/dev/kfd, /dev/dri).",
+ description: "Official llama.cpp server, ROCm build for AMD GPUs.",
+ devices: ["/dev/kfd", "/dev/dri"],
+ },
+ {
+ id: "vllm-xpu",
+ name: "vLLM (Intel XPU)",
+ engine: "vllm",
+ accelerator: "dri",
+ image: "vllm/vllm-openai-xpu:v0.31.0",
+ summary: "Official vLLM image for Intel GPUs (Arc, Data Center GPU Max) via /dev/dri.",
+ description: "Official vLLM, XPU build for Intel GPUs.",
+ devices: ["/dev/dri"],
+ shmSizeMb: 8192,
+ },
+ {
+ id: "vllm-rocm",
+ name: "vLLM (ROCm)",
+ engine: "vllm",
+ accelerator: "rocm",
+ image: "vllm/vllm-openai-rocm:v0.31.0",
+ summary: "Official vLLM image for AMD GPUs with ROCm.",
+ description: "Official vLLM, ROCm build for AMD GPUs.",
+ devices: ["/dev/kfd", "/dev/dri"],
+ shmSizeMb: 8192,
+ },
];
export const RUNTIME_NAME_MAX = 60;
@@ -54,6 +136,8 @@ export function validateRuntime(input: RuntimeInput): Required {
const name = input.name.trim().replace(/\s+/g, " ");
if (!name || name.length > RUNTIME_NAME_MAX) throw new RuntimeValidationError(`Name must be 1–${RUNTIME_NAME_MAX} characters.`);
if (input.engine !== "llama.cpp" && input.engine !== "vllm") throw new RuntimeValidationError("Unknown engine type.");
+ const accelerator = input.accelerator ?? "cpu";
+ if (!RUNTIME_ACCELERATORS.includes(accelerator)) throw new RuntimeValidationError("Unknown accelerator.");
const image = input.image.trim();
if (!IMAGE_RE.test(image)) throw new RuntimeValidationError(`"${image}" is not a valid image reference (e.g. ghcr.io/org/image:tag).`);
@@ -76,6 +160,7 @@ export function validateRuntime(input: RuntimeInput): Required {
return {
name,
engine: input.engine,
+ accelerator,
image,
description: input.description?.trim() || null,
env,
diff --git a/src/lib/runtimes.ts b/src/lib/runtimes.ts
index f0da94b..95829c9 100644
--- a/src/lib/runtimes.ts
+++ b/src/lib/runtimes.ts
@@ -2,7 +2,7 @@ import "server-only";
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 { type DockerHostInfo, RUNTIME_ACCELERATORS, runtimes, workerState } from "@/lib/db/schema";
import { deploymentsUsing } from "@/lib/deployments";
import { type RuntimeInput, RUNTIME_PRESETS, RuntimeValidationError, validateRuntime } from "@/lib/runtimes-shared";
@@ -12,6 +12,7 @@ export type Runtime = typeof runtimes.$inferSelect;
export const RuntimeBody = z.object({
name: z.string().max(200),
engine: z.enum(["llama.cpp", "vllm"]),
+ accelerator: z.enum(RUNTIME_ACCELERATORS).optional(),
image: z.string().max(512),
description: z.string().max(2000).nullable().optional(),
env: z.record(z.string(), z.string().max(4000)).optional(),
diff --git a/src/worker/benchmarks.ts b/src/worker/benchmarks.ts
new file mode 100644
index 0000000..10793ff
--- /dev/null
+++ b/src/worker/benchmarks.ts
@@ -0,0 +1,262 @@
+// Runs BetterBench against running deployments, one benchmark at a time (two at once would
+// measure each other).
+
+import { type ChildProcess, execFile, spawn } from "node:child_process";
+import { access, mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { asc, eq } from "drizzle-orm";
+import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
+import { db } from "@/lib/db/client";
+import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
+import { ENGINE_PORT } from "@/lib/deploy-command";
+import { coreEnv } from "@/lib/env";
+import { betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
+import { sanitizeLine } from "./job-log";
+import { log } from "./log";
+import { errorCauses } from "./log-causes";
+
+type Current = { runId: string; deploymentId: string | null; child: ChildProcess; cancelled: boolean; lost: string | null; secrets: string[] };
+
+let current: Current | null = null;
+let starting = false;
+const pending: { runId: string; stream: LogStream; line: string; ts: Date }[] = [];
+const partial = new Map();
+const tails = new Map();
+
+const message = (err: unknown) => (err instanceof Error ? err.message : String(err));
+
+function addLog(runId: string, stream: LogStream, line: string, secrets: string[] = []) {
+ const clean = sanitizeLine(line, [coreEnv().HF_TOKEN ?? "", ...secrets]).slice(0, 4000);
+ pending.push({ runId, stream, line: clean, ts: new Date() });
+ const tail = tails.get(runId) ?? [];
+ tail.push(clean);
+ if (tail.length > 400) tail.shift();
+ tails.set(runId, tail);
+}
+
+/** Split a stream into lines (keeps the unfinished rest per run and stream). */
+function chunk(runId: string, stream: "stdout" | "stderr", data: Buffer, secrets: string[]) {
+ const key = `${runId}:${stream}`;
+ const parts = ((partial.get(key) ?? "") + data.toString("utf8")).split(/\r?\n|\r/);
+ partial.set(key, parts.pop() ?? "");
+ for (const p of parts) {
+ if (!p.trim()) continue;
+ addLog(runId, stream, p, secrets);
+ const step = stepOf(p);
+ if (step) void db().update(benchmarkRuns).set({ phase: step }).where(eq(benchmarkRuns.id, runId)).then(() => {}, () => {});
+ }
+}
+
+/** BetterBench's progress lines ("[single] chat: …", "[prefill] depth ~2000 tok: …") as a short step label. */
+export function stepOf(line: string): string | null {
+ const m = line.match(/^\[(single|prefill|concurrency)\]\s*([^:]*)/);
+ if (!m) return null;
+ const what = m[2].trim();
+ const name = m[1] === "single" ? "Generation" : m[1] === "prefill" ? "Prompt processing" : "Parallel requests";
+ return what ? `${name}: ${what}` : name;
+}
+
+export async function flushBenchmarkLogs(): Promise {
+ if (pending.length === 0) return;
+ const batch = pending.splice(0, pending.length);
+ for (let i = 0; i < batch.length; i += 500) await db().insert(benchmarkLogs).values(batch.slice(i, i + 500));
+}
+
+async function finish(runId: string, set: Partial) {
+ await db()
+ .update(benchmarkRuns)
+ .set({ finishedAt: new Date(), ...set })
+ .where(eq(benchmarkRuns.id, runId));
+}
+
+/** Runs left "running" by a previous worker can't be resumed. */
+export async function recoverBenchmarks(): Promise {
+ const res = await db()
+ .update(benchmarkRuns)
+ .set({ state: "failed", error: "Interrupted: the worker restarted during the run.", finishedAt: new Date() })
+ .where(eq(benchmarkRuns.state, "running"))
+ .returning({ id: benchmarkRuns.id });
+ if (res.length) log.info(`marked ${res.length} interrupted benchmark(s) as failed`);
+}
+
+async function exists(path: string) {
+ return access(path).then(
+ () => true,
+ () => false,
+ );
+}
+
+/** Completed runs whose stored summary predates SUMMARY_VERSION: recompute from results.json. */
+export async function refreshSummaries(): Promise {
+ const rows = await db()
+ .select({ id: benchmarkRuns.id, summary: benchmarkRuns.summary, settings: benchmarkRuns.settings })
+ .from(benchmarkRuns)
+ .where(eq(benchmarkRuns.state, "completed"));
+ let n = 0;
+ for (const r of rows) {
+ if (r.summary?.v === SUMMARY_VERSION) continue;
+ const results = join(runDir(r.id), RESULTS_FILE);
+ if (!(await exists(results))) continue;
+ try {
+ const summary = { ...(await summarize(results)), quick: !!r.settings.quick };
+ await db().update(benchmarkRuns).set({ summary }).where(eq(benchmarkRuns.id, r.id));
+ n++;
+ } catch (err) {
+ log.warn(`benchmark ${r.id}: summary refresh failed: ${message(err)}`);
+ }
+ }
+ if (n) log.info(`refreshed ${n} benchmark summar${n === 1 ? "y" : "ies"}`);
+}
+
+async function summarize(results: string): Promise {
+ const { stdout } = await promisify(execFile)(betterbenchPython(), ["-c", SUMMARY_SCRIPT, results], { timeout: 120_000, maxBuffer: 16 * 2 ** 20 });
+ return JSON.parse(stdout) as BenchmarkSummary;
+}
+
+async function start(run: typeof benchmarkRuns.$inferSelect) {
+ const fail = (error: string) => finish(run.id, { state: "failed", error });
+ const [d] = run.deploymentId
+ ? await db()
+ .select({ state: deployments.state, containerName: deployments.containerName, engine: runtimes.engine })
+ .from(deployments)
+ .innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
+ .where(eq(deployments.id, run.deploymentId))
+ : [];
+ if (!d || d.state !== "running" || !d.containerName) return fail("The deployment isn't running anymore.");
+
+ const dir = runDir(run.id);
+ await mkdir(dir, { recursive: true });
+ const keys = run.snapshot.options.requireApiKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
+ const s = run.snapshot;
+ const args = runArgs({
+ endpoint: `http://${d.containerName}:${ENGINE_PORT[d.engine]}/v1`,
+ model: s.repoId,
+ out: join(dir, RESULTS_FILE),
+ settings: run.settings,
+ maxModelLen: s.options.contextSize ?? null,
+ notes: {
+ deployment: s.deploymentName,
+ runtime: s.runtimeName,
+ image: s.image,
+ ...(s.options.modelFile ? { file: s.options.modelFile } : {}),
+ ctx: String(s.options.contextSize),
+ ...(run.label ? { label: run.label } : {}),
+ },
+ });
+ // Only what BetterBench needs: no HF_TOKEN or other worker secrets.
+ const env: Record = {
+ PATH: process.env.PATH,
+ HOME: process.env.HOME,
+ LANG: "C.UTF-8",
+ PYTHONUNBUFFERED: "1",
+ NO_COLOR: "1",
+ BETTERBENCH_HOME: dir,
+ BETTERBENCH_NO_UPDATE_CHECK: "1",
+ ...(keys[0] ? { BETTERBENCH_API_KEY: keys[0] } : {}),
+ };
+
+ addLog(run.id, "system", `Benchmarking ${s.deploymentName} (${s.repoId} on ${s.runtimeName}) with BetterBench`);
+ addLog(run.id, "system", `$ betterbench ${args.join(" ")}`, keys);
+ await db().update(benchmarkRuns).set({ state: "running", startedAt: new Date(), error: null, phase: null }).where(eq(benchmarkRuns.id, run.id));
+
+ const child = spawn(betterbenchBin(), args, { env: env as NodeJS.ProcessEnv, cwd: dir, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
+ const cur: Current = { runId: run.id, deploymentId: run.deploymentId, child, cancelled: false, lost: null, secrets: keys };
+ current = cur;
+ child.stdout.on("data", (b: Buffer) => chunk(run.id, "stdout", b, keys));
+ child.stderr.on("data", (b: Buffer) => chunk(run.id, "stderr", b, keys));
+ child.on("error", (err: NodeJS.ErrnoException) => {
+ addLog(run.id, "system", err.code === "ENOENT" ? `BetterBench was not found (${betterbenchBin()}).` : `Could not start BetterBench: ${err.message}`);
+ });
+ child.on("close", (code, signal) => void done(cur, code, signal).catch((err) => log.error(`benchmark ${run.id}`, err)));
+ log.info(`benchmark ${run.id}: started for ${s.deploymentName}`);
+}
+
+async function done(cur: Current, code: number | null, signal: NodeJS.Signals | null) {
+ const id = cur.runId;
+ for (const stream of ["stdout", "stderr"] as const) {
+ const rest = partial.get(`${id}:${stream}`);
+ if (rest?.trim()) addLog(id, stream, rest, cur.secrets);
+ partial.delete(`${id}:${stream}`);
+ }
+ if (current === cur) current = null;
+ const dir = runDir(id);
+ const results = join(dir, RESULTS_FILE);
+ const hasReport = await exists(join(dir, REPORT_FILE));
+
+ if (cur.cancelled) {
+ addLog(id, "system", "Cancelled.");
+ await finish(id, { state: "cancelled", hasReport });
+ } else if (cur.lost) {
+ addLog(id, "system", cur.lost);
+ await finish(id, { state: "failed", error: cur.lost, hasReport });
+ } else if (code === 0 && (await exists(results))) {
+ try {
+ const summary = { ...(await summarize(results)), quick: false };
+ const run = await db().query.benchmarkRuns.findFirst({ columns: { settings: true }, where: eq(benchmarkRuns.id, id) });
+ summary.quick = !!run?.settings.quick;
+ addLog(id, "system", "Done.");
+ await finish(id, { state: "completed", summary, hasReport });
+ } catch (err) {
+ await finish(id, { state: "failed", error: `The run finished, but its results couldn't be read: ${message(err)}`, hasReport });
+ }
+ } else {
+ const lines = tails.get(id) ?? [];
+ const causes = errorCauses(lines);
+ const why = signal ? `stopped by ${signal}` : `exit code ${code ?? "?"}`;
+ const last = lines.slice(-12).join("\n");
+ await finish(id, {
+ state: "failed",
+ error: [`BetterBench failed (${why}).`, causes.join("\n"), last && `Last output:\n${last}`].filter(Boolean).join("\n\n"),
+ hasReport,
+ });
+ }
+ tails.delete(id);
+ await flushBenchmarkLogs().catch(() => {});
+ log.info(`benchmark ${id}: ${cur.cancelled ? "cancelled" : cur.lost ? "failed (deployment gone)" : code === 0 ? "completed" : "failed"}`);
+}
+
+function stop(cur: Current) {
+ if (cur.child.exitCode !== null) return;
+ cur.child.kill("SIGTERM");
+ setTimeout(() => cur.child.exitCode === null && cur.child.kill("SIGKILL"), 10_000).unref();
+}
+
+/** Start the next queued run, stop the current one on cancel or when its deployment goes away. */
+export async function tickBenchmarks(): Promise {
+ if (starting) return;
+ if (current) {
+ const cur = current;
+ const [run] = await db().select({ cancel: benchmarkRuns.cancelRequestedAt }).from(benchmarkRuns).where(eq(benchmarkRuns.id, cur.runId));
+ if (!run || run.cancel) {
+ cur.cancelled = true;
+ stop(cur);
+ return;
+ }
+ if (cur.deploymentId) {
+ const [d] = await db().select({ state: deployments.state }).from(deployments).where(eq(deployments.id, cur.deploymentId));
+ if (!d || d.state !== "running") {
+ cur.lost = "The deployment stopped during the run.";
+ stop(cur);
+ }
+ }
+ return;
+ }
+ starting = true;
+ try {
+ const next = await db().query.benchmarkRuns.findFirst({ where: eq(benchmarkRuns.state, "queued"), orderBy: asc(benchmarkRuns.createdAt) });
+ if (next) await start(next).catch((err) => finish(next.id, { state: "failed", error: `Could not start: ${message(err)}` }));
+ } finally {
+ starting = false;
+ }
+}
+
+/** Worker shutdown: a run can't continue in another process. */
+export async function stopBenchmarks(): Promise {
+ const cur = current;
+ if (!cur) return;
+ cur.lost = "Interrupted: the worker stopped during the run.";
+ stop(cur);
+ const deadline = Date.now() + 5_000;
+ while (current === cur && Date.now() < deadline) await new Promise((r) => setTimeout(r, 100));
+}
diff --git a/src/worker/betterbench.test.ts b/src/worker/betterbench.test.ts
new file mode 100644
index 0000000..3d7e856
--- /dev/null
+++ b/src/worker/betterbench.test.ts
@@ -0,0 +1,54 @@
+import assert from "node:assert/strict";
+import { describe, it } from "node:test";
+import { runArgs } from "./betterbench";
+import { stepOf } from "./benchmarks";
+
+describe("betterbench runArgs", () => {
+ const base = { endpoint: "http://kaname-x-abc123:8080/v1", model: "unsloth/Qwen3-0.6B-GGUF", out: "/data/benchmarks/R/results.json", maxModelLen: 4096 };
+
+ it("builds a quick run with phases and notes, never checking for updates", () => {
+ const args = runArgs({ ...base, settings: { quick: true, passes: null, warmup: null, phases: ["decode", "prefill"] }, notes: { ctx: "4096", label: "q8 kv" } });
+ assert.deepEqual(args, [
+ "run",
+ "--endpoint",
+ "http://kaname-x-abc123:8080/v1",
+ "--model",
+ "unsloth/Qwen3-0.6B-GGUF",
+ "--out",
+ "/data/benchmarks/R/results.json",
+ "--max-model-len",
+ "4096",
+ "--quick",
+ "--decode",
+ "--prefill",
+ "--note",
+ "ctx=4096",
+ "--note",
+ "label=q8 kv",
+ "--no-update-check",
+ ]);
+ });
+
+ it("passes explicit passes and warmup, and no phase flags for a full run", () => {
+ const args = runArgs({ ...base, maxModelLen: null, settings: { quick: false, passes: 10, warmup: 2, phases: [] }, notes: {} });
+ assert.ok(args.includes("--passes") && args[args.indexOf("--passes") + 1] === "10");
+ assert.ok(args.includes("--warmup") && args[args.indexOf("--warmup") + 1] === "2");
+ assert.ok(!args.includes("--quick") && !args.includes("--decode") && !args.includes("--max-model-len"));
+ });
+
+ it("turns progress lines into steps", () => {
+ assert.equal(stepOf("[single] chat: warmup 1 + 5 runs"), "Generation: chat");
+ assert.equal(stepOf("[prefill] depth ~2000 tok: warmup 2 + 8"), "Prompt processing: depth ~2000 tok");
+ assert.equal(stepOf("model max context: 4096 tokens"), null);
+ });
+});
+
+describe("parseNvidiaSmi", () => {
+ it("reads nvidia-smi CSV", async () => {
+ const { parseNvidiaSmi } = await import("./runtimes");
+ assert.deepEqual(parseNvidiaSmi("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14\n"), [
+ { vendor: "nvidia", index: 0, uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14" },
+ ]);
+ assert.deepEqual(parseNvidiaSmi("NVIDIA-SMI has failed"), []);
+ });
+});
diff --git a/src/worker/betterbench.ts b/src/worker/betterbench.ts
new file mode 100644
index 0000000..f8e7a59
--- /dev/null
+++ b/src/worker/betterbench.ts
@@ -0,0 +1,101 @@
+// BetterBench (https://github.com/GGZ14/BetterBench, Apache-2.0): the benchmark Kaname runs
+// against deployments. Flags verified against v0.6.1 (`betterbench run --help`, betterbench/cli.py).
+
+import { dirname, join } from "node:path";
+import type { BenchmarkSettings } from "@/lib/db/schema";
+import { coreEnv } from "@/lib/env";
+
+export function betterbenchBin(): string {
+ return coreEnv().BETTERBENCH_BIN;
+}
+
+/** The Python of BetterBench's own venv (it imports `betterbench`). */
+export function betterbenchPython(): string {
+ const bin = betterbenchBin();
+ return bin.includes("/") ? join(dirname(bin), "python") : "python3";
+}
+
+export function runArgs(o: {
+ endpoint: string;
+ model: string;
+ out: string;
+ settings: BenchmarkSettings;
+ maxModelLen: number | null;
+ notes: Record;
+}): string[] {
+ const s = o.settings;
+ return [
+ "run",
+ "--endpoint",
+ o.endpoint,
+ "--model",
+ o.model,
+ "--out",
+ o.out,
+ // Kaname knows the context window; llama-server's /v1/models doesn't report it.
+ ...(o.maxModelLen ? ["--max-model-len", String(o.maxModelLen)] : []),
+ ...(s.quick ? ["--quick"] : []),
+ ...(s.passes != null ? ["--passes", String(s.passes)] : []),
+ ...(s.warmup != null ? ["--warmup", String(s.warmup)] : []),
+ ...s.phases.map((p) => `--${p}`),
+ ...Object.entries(o.notes).flatMap(([k, v]) => ["--note", `${k}=${v}`]),
+ "--no-update-check",
+ ];
+}
+
+/**
+ * Prints Kaname's BenchmarkSummary for a results.json, using BetterBench's own report functions
+ * so the numbers match its HTML report.
+ */
+export const SUMMARY_SCRIPT = `
+import json, math, sys
+from betterbench import report as r
+res = json.load(open(sys.argv[1]))
+def clean(v):
+ if isinstance(v, dict):
+ return {str(k): clean(x) for k, x in v.items()}
+ if isinstance(v, (list, tuple)):
+ return [clean(x) for x in v]
+ if isinstance(v, (bool, str)) or v is None:
+ return v
+ try:
+ f = float(v)
+ except (TypeError, ValueError):
+ return None
+ if math.isnan(f) or math.isinf(f):
+ return None
+ return int(f) if float(f).is_integer() and not isinstance(v, float) else f
+rows = r.single_rows(res)
+cfg = res.get("config", {})
+env = res.get("env", {})
+reasoning = r.reasoning_rows(res)
+gate = res.get("sample_gate") or r.sample_gate(res)
+trunc, ok_runs = r.truncation_summary(res)
+failed = sum(1 for recs in res.get("single_stream", {}).values() for x in recs if not x.get("ok"))
+keep_cfg = ("warmup", "runs_per_category", "temperature", "top_p", "top_k", "greedy", "unique_nonce", "weights",
+ "concurrency_levels", "concurrency_requests", "prefill_runs", "prefill_warmup", "prefill_max_tokens")
+out = {
+ "v": 2,
+ "combined": r.combined_score(res, rows),
+ "single": rows,
+ "prefill": r.prefill_rows(res),
+ "concurrency": r.concurrency_rows(res),
+ "reasoning": reasoning if r.has_reasoning_evidence(reasoning) else [],
+ "gate": gate.get("under_sampled", []),
+ "truncated": [trunc, ok_runs],
+ "failedSingle": failed,
+ "phases": r.phases_present(res),
+ "cacheHits": r.cache_hits(res),
+ "betterbenchVersion": res.get("betterbench_version", ""),
+ "corpusVersion": res.get("corpus_version", ""),
+ "corpusHash": env.get("corpus_hash"),
+ "timestamp": env.get("timestamp"),
+ "maxModelLen": env.get("max_model_len"),
+ "config": {k: cfg.get(k) for k in keep_cfg},
+ "passes": cfg.get("runs_per_category"),
+}
+print(json.dumps(clean(out)))
+`;
+
+/** Version of the summary shape above; older stored summaries are recomputed from results.json. */
+export const SUMMARY_VERSION = 2;
diff --git a/src/worker/deployments.ts b/src/worker/deployments.ts
index 4da8718..fc00b0e 100644
--- a/src/worker/deployments.ts
+++ b/src/worker/deployments.ts
@@ -8,6 +8,7 @@ import { and, asc, desc, eq, inArray, lt } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { apiKeys, deploymentLogs, deployments, type LogStream, models, runtimes, workerState } from "@/lib/db/schema";
import { buildCommand, CONTAINER_MODELS_DIR, ENGINE_PORT, redactCommand, renderCommand } from "@/lib/deploy-command";
+import { ACCELERATOR_DEVICES } from "@/lib/runtimes-shared";
import { coreEnv } from "@/lib/env";
import { formatBytes } from "@/lib/format";
import { sanitizeLine } from "./job-log";
@@ -136,6 +137,17 @@ async function start(c: DockerClient, d: Deployment) {
}
}
+ // GPUs: NVIDIA ones are requested from Docker (all, or the selected UUIDs); Intel/AMD come in as /dev nodes.
+ let deviceRequests: unknown[] = [];
+ if (runtime.accelerator === "nvidia") {
+ if (!host.nvidia) return fail(d, "This runtime needs NVIDIA GPUs, but Docker has no NVIDIA runtime (install the NVIDIA Container Toolkit on the Docker host).");
+ const wanted = d.options.gpus?.length ? d.options.gpus : null;
+ const missing = wanted?.filter((u) => !(host.gpus ?? []).some((g) => g.uuid === u)) ?? [];
+ if (missing.length && (host.gpus ?? []).length) return fail(d, `Selected GPU not found: ${missing.join(", ")}. Pick the GPUs again in the deployment.`);
+ deviceRequests = [{ Driver: "", Count: wanted ? 0 : -1, DeviceIDs: wanted ?? undefined, Capabilities: [["gpu"]] }];
+ }
+ const devices = runtime.accelerator === "dri" || runtime.accelerator === "rocm" ? [...new Set([...runtime.devices, ...ACCELERATOR_DEVICES[runtime.accelerator]])] : runtime.devices;
+
const keys = d.options.requireApiKey ? await loadApiKeys() : [];
if (d.options.requireApiKey && keys.length === 0) return fail(d, "This deployment requires an API key, but there are none. Add one under Settings → API keys.");
const cmd = buildCommand({ engine: runtime.engine, options: d.options, model, runtime, apiKeys: keys });
@@ -154,7 +166,8 @@ async function start(c: DockerClient, d: Deployment) {
NanoCpus: d.cpus ? Math.round(d.cpus * 1e9) : 0,
Memory: d.memoryMb ? d.memoryMb * 2 ** 20 : 0,
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
- Devices: runtime.devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
+ Devices: devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
+ DeviceRequests: deviceRequests,
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
diff --git a/src/worker/docker/client.ts b/src/worker/docker/client.ts
index b68e28c..9b34bcf 100644
--- a/src/worker/docker/client.ts
+++ b/src/worker/docker/client.ts
@@ -71,7 +71,15 @@ export class DockerClient {
}
info() {
- return this.json<{ NCPU: number; MemTotal: number; OperatingSystem: string; Architecture: string; ServerVersion: string }>(
+ return this.json<{
+ NCPU: number;
+ MemTotal: number;
+ OperatingSystem: string;
+ Architecture: string;
+ ServerVersion: string;
+ Runtimes?: Record;
+ DiscoveredDevices?: { Source: string; ID: string }[];
+ }>(
"GET",
"/info",
);
@@ -83,6 +91,7 @@ export class DockerClient {
return await this.json<{
Id: string;
Name: string;
+ Image: string;
Mounts: { Type: string; Source: string; Destination: string; Name?: string }[];
NetworkSettings: { Networks: Record };
}>("GET", `/containers/${encodeURIComponent(id)}/json`);
diff --git a/src/worker/index.ts b/src/worker/index.ts
index b329b9e..b1cb971 100644
--- a/src/worker/index.ts
+++ b/src/worker/index.ts
@@ -12,6 +12,8 @@ import { coreEnv } from "@/lib/env";
import { checkHub, modelsDueForHubCheck } from "@/lib/hub/availability";
import { backfillMetadata } from "@/lib/hub/refresh";
import { DeleteRunner } from "./delete";
+import { flushBenchmarkLogs, recoverBenchmarks, refreshSummaries, stopBenchmarks, tickBenchmarks } from "./benchmarks";
+import { reportL80Status, tickPublications } from "./publish";
import { adoptContainers, flushDeploymentLogs, LOG_FLUSH_INTERVAL_MS, reconcileDeployments, stopFollowingLogs } from "./deployments";
import { DownloadRunner } from "./download";
import { log } from "./log";
@@ -34,6 +36,7 @@ const DOCKER_INFO_MS = 5 * 60_000;
const IMAGE_SYNC_MS = 60_000;
const PULL_CHECK_MS = 3_000;
const DEPLOYMENT_TICK_MS = 2_000;
+const BENCHMARK_TICK_MS = 2_000;
/** Touched on every heartbeat; the Docker healthcheck checks its age. */
const HEALTH_FILE = join(tmpdir(), "kaname-worker-alive");
@@ -348,6 +351,8 @@ async function shutdown(reason: string, code = 0) {
// Deployment containers keep running; the next worker re-attaches to them.
stopFollowingLogs();
await flushDeploymentLogs().catch(() => {});
+ await stopBenchmarks().catch(() => {});
+ await flushBenchmarkLogs().catch(() => {});
if (runners.size > 0) {
for (const r of runners.values()) r.interrupt();
const deadline = Date.now() + SHUTDOWN_GRACE_MS;
@@ -404,6 +409,13 @@ async function main() {
await adoptContainers();
timers.push(setInterval(() => void reconcileDeployments().catch((err) => log.error("deployments failed", err)), DEPLOYMENT_TICK_MS));
timers.push(setInterval(() => void flushDeploymentLogs().catch((err) => log.error("deployment logs failed", err)), LOG_FLUSH_INTERVAL_MS));
+ // Benchmarks: one BetterBench run at a time against a running deployment.
+ await recoverBenchmarks();
+ void refreshSummaries();
+ void reportL80Status();
+ timers.push(setInterval(() => void tickPublications().catch((err) => log.error("publications failed", err)), BENCHMARK_TICK_MS));
+ timers.push(setInterval(() => void tickBenchmarks().catch((err) => log.error("benchmarks failed", err)), BENCHMARK_TICK_MS));
+ timers.push(setInterval(() => void flushBenchmarkLogs().catch((err) => log.error("benchmark logs failed", err)), LOG_FLUSH_INTERVAL_MS));
void scanFolders();
void tick();
setTimeout(() => void checkHubDue(), 15_000);
diff --git a/src/worker/publish.ts b/src/worker/publish.ts
new file mode 100644
index 0000000..73bdc49
--- /dev/null
+++ b/src/worker/publish.ts
@@ -0,0 +1,123 @@
+// Publishing benchmark runs to launch80 with the L80 CLI (https://launch80.com/skills), as a double
+// opt-in: (1) `L80 betterbench --results … --dry-run --payload-out` builds the exact payload, which the
+// user inspects; (2) only after an explicit confirmation is that same file sent with `L80 publish`.
+// The token (L80_TOKEN) is only ever in the CLI's environment for step 2.
+
+import { execFile } from "node:child_process";
+import { access, mkdir } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { asc, eq, inArray } from "drizzle-orm";
+import { benchmarksDir, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
+import { db } from "@/lib/db/client";
+import { benchmarkPublications, settings } from "@/lib/db/schema";
+import { coreEnv } from "@/lib/env";
+import { log } from "./log";
+
+export const L80_STATUS_KEY = "l80.status";
+export const RAW_TEMPLATE = "bench.betterbench.v1";
+
+const run = promisify(execFile);
+let busy = false;
+
+export const payloadPath = (runId: string, pubId: string) => join(runDir(runId), "publications", `${pubId}.json`);
+
+/** Only what the CLI needs; the token only when publishing. */
+function cliEnv(withToken: boolean): NodeJS.ProcessEnv {
+ const env = coreEnv();
+ return {
+ PATH: process.env.PATH,
+ HOME: process.env.HOME,
+ // The CLI's local publish history lives next to Kaname's data.
+ XDG_CONFIG_HOME: join(benchmarksDir(), ".l80"),
+ NO_COLOR: "1",
+ ...(env.L80_API_BASE ? { L80_API_BASE: env.L80_API_BASE } : {}),
+ ...(withToken && env.L80_TOKEN ? { L80_TOKEN: env.L80_TOKEN } : {}),
+ } as unknown as NodeJS.ProcessEnv;
+}
+
+/** "error: E_X …" plus the remedy line, without anything that could echo a token. */
+function cliError(err: unknown): string {
+ const e = err as { stderr?: string; stdout?: string; message?: string; code?: string | number };
+ if (e.code === "ENOENT") return `The L80 CLI was not found (${coreEnv().L80_BIN}).`;
+ const text = `${e.stderr ?? ""}\n${e.stdout ?? ""}`.trim() || e.message || String(err);
+ const token = coreEnv().L80_TOKEN;
+ return (token ? text.split(token).join("***") : text).slice(0, 2000);
+}
+
+/** CLI version and whether a token is configured, for the UI (never the token itself). */
+export async function reportL80Status(): Promise {
+ const env = coreEnv();
+ let version: string | null = null;
+ try {
+ const { stdout } = await run(env.L80_BIN, ["version"], { env: cliEnv(false), timeout: 15_000 });
+ version = stdout.trim().split(/\s+/).find((w) => /^v?\d+\.\d+/.test(w)) ?? (stdout.trim() || null);
+ } catch {
+ version = null;
+ }
+ const value = { version, tokenSet: !!env.L80_TOKEN, apiBase: env.L80_API_BASE ?? "https://launch80.com", checkedAt: new Date().toISOString() };
+ await db().insert(settings).values({ key: L80_STATUS_KEY, value }).onConflictDoUpdate({ target: settings.key, set: { value } });
+ log.info(version ? `L80 CLI ${version}, publish token ${value.tokenSet ? "set" : "not set"}` : "L80 CLI not found; publishing to launch80 is unavailable");
+}
+
+async function exists(p: string) {
+ return access(p).then(
+ () => true,
+ () => false,
+ );
+}
+
+/** One step at a time: build a preview (dry run) or publish a confirmed one. */
+export async function tickPublications(): Promise {
+ if (busy) return;
+ busy = true;
+ try {
+ const p = await db().query.benchmarkPublications.findFirst({
+ where: inArray(benchmarkPublications.state, ["preview", "publish"]),
+ orderBy: asc(benchmarkPublications.createdAt),
+ });
+ if (!p) return;
+ const fail = (error: string) => db().update(benchmarkPublications).set({ state: "failed", error }).where(eq(benchmarkPublications.id, p.id));
+ const env = coreEnv();
+ const results = join(runDir(p.runId), RESULTS_FILE);
+ const payload = payloadPath(p.runId, p.id);
+
+ if (p.state === "preview") {
+ if (!(await exists(results))) return void (await fail("The run has no results.json to publish."));
+ await mkdir(join(runDir(p.runId), "publications"), { recursive: true });
+ const args = ["betterbench", "--results", results, "--dry-run", "--payload-out", payload, "--json"];
+ if (p.title) args.push("--title", p.title);
+ if (p.summary) args.push("--summary", p.summary);
+ try {
+ const { stdout } = await run(env.L80_BIN, args, { env: cliEnv(false), timeout: 60_000, maxBuffer: 8 * 2 ** 20 });
+ const out = JSON.parse(stdout) as { byte_size?: number; template?: string };
+ await db()
+ .update(benchmarkPublications)
+ .set({ state: "previewed", payloadBytes: out.byte_size ?? null, template: out.template ?? RAW_TEMPLATE, previewedAt: new Date(), error: null })
+ .where(eq(benchmarkPublications.id, p.id));
+ log.info(`publication ${p.id}: preview ready (${out.byte_size ?? "?"} bytes)`);
+ } catch (err) {
+ await fail(`Preview failed: ${cliError(err)}`);
+ }
+ return;
+ }
+
+ // state "publish": confirmed by a user; send exactly the previewed payload.
+ if (!env.L80_TOKEN) return void (await fail("No launch80 token: set L80_TOKEN for the worker (see .env.example)."));
+ if (!(await exists(payload))) return void (await fail("The previewed payload is gone; prepare a new preview."));
+ try {
+ const { stdout } = await run(env.L80_BIN, ["publish", payload, "--template", p.template, "--json"], { env: cliEnv(true), timeout: 120_000, maxBuffer: 8 * 2 ** 20 });
+ const a = JSON.parse(stdout) as { url?: string; guid?: string; created_at?: string };
+ if (!a.url) throw new Error(`no URL in the CLI's answer: ${stdout.slice(0, 300)}`);
+ await db()
+ .update(benchmarkPublications)
+ .set({ state: "published", url: a.url, guid: a.guid ?? null, publishedAt: a.created_at ? new Date(a.created_at) : new Date(), error: null })
+ .where(eq(benchmarkPublications.id, p.id));
+ log.info(`publication ${p.id}: published ${a.url}`);
+ } catch (err) {
+ await fail(`Publishing failed: ${cliError(err)}`);
+ }
+ } finally {
+ busy = false;
+ }
+}
diff --git a/src/worker/runtimes.ts b/src/worker/runtimes.ts
index 3018d34..c42c941 100644
--- a/src/worker/runtimes.ts
+++ b/src/worker/runtimes.ts
@@ -6,7 +6,7 @@ import { hostname } from "node:os";
import { resolve } from "node:path";
import { and, eq, isNotNull, ne } from "drizzle-orm";
import { db } from "@/lib/db/client";
-import { type DockerHostInfo, runtimes, settings, workerState } from "@/lib/db/schema";
+import { type DockerHostInfo, type HostGpu, runtimes, settings, workerState } from "@/lib/db/schema";
import { coreEnv } from "@/lib/env";
import { RUNTIME_PRESETS } from "@/lib/runtimes-shared";
import { DockerClient, DockerError } from "./docker/client";
@@ -40,14 +40,14 @@ async function cpuFacts(): Promise<{ model: string | null; features: string[] }>
}
/** Find our own container to learn the network and where MODELS_DIR comes from on the host. */
-async function selfDetect(c: DockerClient): Promise> {
+async function selfDetect(c: DockerClient): Promise & { image: string | null }> {
const env = coreEnv();
let network: string | null = env.KANAME_DOCKER_NETWORK ?? null;
let modelsSource: DockerHostInfo["modelsSource"] = env.KANAME_MODELS_SOURCE
? { type: env.KANAME_MODELS_SOURCE.startsWith("/") ? "bind" : "volume", source: env.KANAME_MODELS_SOURCE }
: null;
- if (network && modelsSource) return { network, modelsSource };
+ // Always inspected: the worker's own image also serves as the GPU probe image.
const self = await c.inspectContainer(hostname()).catch(() => null);
if (self) {
network ??= Object.keys(self.NetworkSettings.Networks).find((n) => !["bridge", "host", "none"].includes(n)) ?? null;
@@ -56,7 +56,80 @@ async function selfDetect(c: DockerClient): Promise l.split(",").map((p) => p.trim()))
+ .filter((p) => p.length >= 5 && /^\d+$/.test(p[0]))
+ .map(([index, uuid, name, mem, driver]) => ({ vendor: "nvidia" as const, index: Number(index), uuid, name, memoryMb: Number(mem) || 0, driver }));
+}
+
+/**
+ * Lists the GPUs containers get from Docker: a short-lived container (our own image) requests all
+ * GPUs and runs nvidia-smi, which the NVIDIA Container Toolkit injects.
+ */
+async function probeNvidia(c: DockerClient, image: string): Promise {
+ const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, {
+ Image: image,
+ Entrypoint: ["nvidia-smi"],
+ Cmd: ["--query-gpu=index,uuid,name,memory.total,driver_version", "--format=csv,noheader,nounits"],
+ Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
+ Labels: { "kaname.managed": "true", "kaname.probe": "gpu" },
+ HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false },
+ });
+ try {
+ const lines: string[] = [];
+ await c.startContainer(created.Id);
+ await c.followLogs(created.Id, (_s, line) => lines.push(line), { tail: "all", signal: AbortSignal.timeout(30_000) });
+ const st = await c.containerState(created.Id);
+ if (st && st.ExitCode !== 0) throw new Error(`nvidia-smi exited with ${st.ExitCode}: ${lines.slice(-3).join(" ")}`);
+ return parseNvidiaSmi(lines.join("\n"));
+ } finally {
+ await c.removeContainer(created.Id).catch(() => {});
+ }
+}
+
+async function gpuFacts(c: DockerClient, info: Awaited>, selfImage: string | null) {
+ const nvidia = !!info.Runtimes?.nvidia || !!info.DiscoveredDevices?.some((d) => d.ID.startsWith("nvidia.com/gpu"));
+ if (!nvidia) return { nvidia, gpus: [], gpuError: null, gpuCheckedAt: null };
+ if (!gpuCache || Date.now() - gpuCache.at > GPU_PROBE_MS) {
+ try {
+ if (!selfImage) throw new Error("Kaname's own image is unknown (the worker isn't running in a container), so GPUs can't be probed.");
+ const gpus = await probeNvidia(c, selfImage);
+ gpuCache = { at: Date.now(), gpus, error: null };
+ if (gpus.length) {
+ log.info(`GPUs: ${gpus.map((g) => `${g.index}: ${g.name} (${Math.round(g.memoryMb / 1024)} GiB)`).join(", ")}`);
+ await seedGpuPresets();
+ }
+ } catch (err) {
+ gpuCache = { at: Date.now(), gpus: [], error: message(err) };
+ log.warn(`GPU probe failed: ${message(err)}`);
+ }
+ }
+ return { nvidia, gpus: gpuCache.gpus, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
+}
+
+const CUDA_SEEDED_KEY = "runtimes.cudaPresetSeeded";
+
+/** The first time NVIDIA GPUs show up, add the llama.cpp CUDA runtime (once). */
+async function seedGpuPresets() {
+ const d = db();
+ if (await d.query.settings.findFirst({ where: eq(settings.key, CUDA_SEEDED_KEY) })) return;
+ const p = RUNTIME_PRESETS.find((x) => x.id === "llama.cpp-cuda");
+ if (p) {
+ await d.insert(runtimes).values({ name: p.name, engine: p.engine, accelerator: "nvidia", image: p.image, description: p.description ?? null, preset: p.id });
+ log.info(`NVIDIA GPU found: added the "${p.name}" runtime`);
+ }
+ await d.insert(settings).values({ key: CUDA_SEEDED_KEY, value: true }).onConflictDoNothing();
}
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
@@ -72,6 +145,7 @@ export async function refreshDockerInfo(instanceId: string): Promise {
};
try {
const [v, i] = await Promise.all([c.version(), c.info()]);
+ const self = await selfDetect(c);
info = {
connected: true,
error: null,
@@ -81,7 +155,9 @@ export async function refreshDockerInfo(instanceId: string): Promise {
cpus: i.NCPU,
memoryBytes: i.MemTotal,
...base,
- ...(await selfDetect(c)),
+ network: self.network,
+ modelsSource: self.modelsSource,
+ ...(await gpuFacts(c, i, self.image)),
};
} catch (err) {
info = {
@@ -110,10 +186,13 @@ export async function seedRuntimePresets(): Promise {
if (seeded) return;
const existing = await d.select({ id: runtimes.id }).from(runtimes).limit(1);
if (existing.length === 0) {
+ // CPU presets only; GPU ones are added from Settings (or automatically when an NVIDIA GPU shows up).
+ const presets = RUNTIME_PRESETS.filter((p) => (p.accelerator ?? "cpu") === "cpu");
await d.insert(runtimes).values(
- RUNTIME_PRESETS.map((p) => ({
+ presets.map((p) => ({
name: p.name,
engine: p.engine,
+ accelerator: p.accelerator ?? "cpu",
image: p.image,
description: p.description ?? null,
env: p.env ?? {},
@@ -124,7 +203,7 @@ export async function seedRuntimePresets(): Promise {
preset: p.id,
})),
);
- log.info(`created ${RUNTIME_PRESETS.length} preset runtime(s)`);
+ log.info(`created ${presets.length} preset runtime(s)`);
}
await d.insert(settings).values({ key: SEEDED_KEY, value: true }).onConflictDoNothing();
}