Compare commits

..
5 Commits
Author SHA1 Message Date
Pascal LinxweilerandClaude Opus 5.5 e007a35143 Release 0.12.0: Intel GPU support
Release / release (push) Successful in 3m40s
Intel/AMD GPU telemetry in benchmark runs (hwmon power/temperature,
amdgpu sysfs, Intel VRAM/utilization from DRM fdinfo via a minimal
host-PID probe container), temperature for all GPUs, VRAM estimate for
NVIDIA and Intel/AMD in the deployment form, /dev/dri group IDs added to
Intel/AMD runtime containers, Intel llama.cpp presets seeded on first
detection, ZES_ENABLE_SYSMAN=1 for the SYCL preset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 14:47:00 +02:00
Pascal LinxweilerandClaude Opus 5.5 ee6c623e2a Release 0.11.0: benchmark metadata and system info
Release / release (push) Successful in 3m25s
Every run records GPUs (PCIe link under load and maximum, ReBAR, P2P),
runtime image/tag/digest and the engine version the server reports,
model, quant, KV cache, context and concurrency, plus a whitelisted
system summary and a description. Shown on the run page, compare and
sweep views; passed to BetterBench as notes and to the launch80 preview
as sections. Settings -> Hardware for manual values.

Also: scripts/intel-probe.sh (read-only diagnostics for Intel hosts),
and --quick is no longer passed together with --passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 19:07:04 +02:00
Pascal LinxweilerandClaude Opus 5.5 981c4170fc Agent skill: kaname helper script, declared env vars, less polling
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:24:51 +02:00
Pascal LinxweilerandClaude Opus 5.5 93edb198d8 Release 0.10.0: API for agents
Release / release (push) Successful in 3m14s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:14:45 +02:00
Pascal LinxweilerandClaude Opus 5.5 7b1c8070b3 API for agents: tokens, /api/v1, guardrails, approval
- Scoped bearer tokens (models:read, downloads:create), stored as SHA-256, managed in
  Settings -> API tokens. Only /api/v1 accepts them; the rest stays OIDC-only.
- /api/v1: Hub lookup, library list with the search filters, download requests through the
  existing add-model/queue path (idempotent), compact job status, disk space.
- Guardrails: approval mode (default approve), max size per request, minimum free space incl.
  reserved bytes, max open agent jobs, author allowlist. Approve/reject in the UI; "requested by"
  shown and filterable.
- docs/api.md (incl. Traefik forward-auth bypass), docs/agent/SKILL.md, DB-backed API tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 16:14:45 +02:00
98 changed files with 10031 additions and 160 deletions

No files matched your search

+129 -1
View File
@@ -4,7 +4,135 @@ All notable changes to this project are documented here.
The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); each milestone of
step 1 (Hugging Face downloader) is released as a minor version.
## [Unreleased]
## [0.12.0] - 2026-10-21
Intel GPU support (Arc A- and B-series, Arc Pro): telemetry during benchmarks, presets, render group
handling and a VRAM estimate for NVIDIA and Intel alike. Host prerequisites are on the wiki page
"Intel GPUs".
No changes to `compose.yaml` or `.env`.
### Added
- **GPU telemetry for Intel and AMD** in benchmark runs, A/B and sweeps, with the same fields as
NVIDIA (VRAM in use, utilization, power, temperature):
- power and temperature from the GPU's hwmon sensors (energy counter or power reading);
- AMD: VRAM in use and busy percent from sysfs;
- Intel: VRAM in use and utilization summed from every process's DRM fdinfo (the only place the
`xe`/`i915` drivers report them), read by a probe container that runs only during the run: host
PID namespace, `SYS_PTRACE` and `DAC_READ_SEARCH` only, no network, read-only, removed at the
end. Utilization is the busiest engine class, like `intel_gpu_top`.
- **Temperature** for every GPU (NVIDIA too), shown in the run's resources and, with GPU power, as
sweep table columns.
- **VRAM estimate** in the deployment form for NVIDIA and Intel/AMD: weights, KV cache and compute
buffers for llama.cpp with all layers on the GPU, the reserved share for vLLM, against the GPUs'
VRAM, with a hint when it doesn't fit.
- **Render group handling**: the worker reads the group IDs of the host's `/dev/dri` nodes (render,
video) and adds them to Intel/AMD runtime containers, so images that don't run as root can use the
GPU.
- The llama.cpp **Intel SYCL and Vulkan runtimes are added** the first time an Intel GPU is detected.
### Changed
- The llama.cpp Intel (SYCL) preset sets `ZES_ENABLE_SYSMAN=1`, so llama.cpp sees free VRAM (needed
by `-ngl auto`). Preset descriptions mention the B-series.
- GPU figures a source doesn't report are now shown as "—" instead of 0.
## [0.11.0] - 2026-10-20
Every benchmark run now records what it ran on: GPUs with their PCIe link and Resizable BAR, the
runtime image and the engine version the server reports, model, quant and KV cache type, context and
concurrency, plus a system summary and your own description. All of it is shown on the run page, in
compare views and sweep tables, and goes to BetterBench and the launch80 preview.
No changes to `compose.yaml` or `.env`. The new columns are added on start.
### Added
- **Run metadata**, recorded when a run starts (single runs, A/B and sweep variants):
- GPU count, name and VRAM; PCIe link, current and maximum (e.g. "Gen4 x8 of Gen5 x16"), read
from sysfs at the card's upstream port (behind on-card switches like Intel's Arc B-series) or
from `nvidia-smi`; peer-to-peer between GPUs (`nvidia-smi topo -p2p`, "n/a" with one GPU);
Resizable BAR (on when a BAR covers the VRAM).
- GPUs slow their link down when idle, so the current link is sampled during the run and the
fastest one seen under load is recorded ("at idle" when it couldn't be sampled).
- Runtime image, tag and registry digest, and the engine version the server reports once it's
ready (llama.cpp `/props` build, vLLM `/version`, falling back to the startup log). Runtimes have
an optional **engine name** for forks (e.g. `vllm-radiance`).
- Model, quant and KV cache type (e.g. "Q4_K_M with q8_0 KV cache"), context length and
concurrency (llama.cpp slots as reported by the server, vLLM max sequences).
- **System summary** per run: CPU model, cores and threads, RAM, the disk holding the models
folder, OS and kernel, GPU driver versions, VM or bare metal with GPU passthrough, Kaname version.
Only these whitelisted facts; never the hostname, IP addresses, users or paths.
- **Description** per run: set it when starting a run or edit it on the run page.
- Everything goes to BetterBench as `--note`s (in `results.json` and its report) and into the
launch80 dry-run preview as page sections (description, hardware and runtime, system), visible in
the preview before anything is sent.
- **Settings → Hardware**: what was detected, with manual values for what detection can't see (in a
VM the PCIe link is the one the VM sees; new GPUs missing from the PCI ID list). New runs use them.
- The run page shows the metadata; compare views get a "Hardware & runtime" section and a prefill
row in the headline; sweep tables list the setup shared by all variants and show what differs as
columns.
- `scripts/intel-probe.sh`: read-only diagnostics for Intel GPU hosts (link, BARs, hwmon, DRM
fdinfo, `/dev/dri` groups), for the upcoming Intel GPU support.
### Changed
- The image includes the PCI ID database (`pci.ids`) for GPU names.
### Fixed
- A run or sweep with both "quick" and an explicit number of passes failed (BetterBench refuses
`--quick` with `--passes`); the passes now win.
- Agent skill (`docs/agent/SKILL.md`) works with how Hermes Agent runs commands: a `kaname` helper
script (`docs/agent/kaname`) instead of a shell function that didn't survive between commands,
`KANAME_URL`/`KANAME_TOKEN` declared in the frontmatter, and far less polling (none while a
request waits for approval, one check around the ETA while downloading).
## [0.10.0] - 2026-10-20
An API for AI agents: a token-authenticated `/api/v1` lets a program look up models, request
downloads and follow them, within guardrails you set and, by default, only after you approve each
request.
No changes to `compose.yaml` or `.env`. If Kaname is behind a forward-auth proxy, let `/api/v1/`
through without forward auth (example in [docs/api.md](docs/api.md)). The new table is created on
start.
### Added
- **API tokens** (Settings → API tokens): create (shown once; only a SHA-256 hash is stored), name,
scopes `models:read` and `downloads:create`, last used, revoke. Sent as
`Authorization: Bearer kn_…`; only `/api/v1` accepts them, and it accepts nothing else (the rest of
Kaname stays OIDC-only). No token can delete models or files, change settings, or manage runtimes
or tokens.
- **`/api/v1`**, compact JSON with actionable error messages ([docs/api.md](docs/api.md)):
- `GET /api/v1`: the token's name, scopes and the guardrails.
- `GET /api/v1/hub/lookup?repo=`: commit SHA, quants and files with sizes (the Add model lookup).
- `GET /api/v1/models`: the library with its search and filters (author, family, quant, tag,
status, requested by) and the size on disk; `GET /api/v1/models/{id}`.
- `POST /api/v1/downloads`: repo + pinned commit + a quant (weights plus the recommended companion
files, as in Add model) or include globs, optional tags. Uses the same add-model and queue code
as the UI. Repeating a request returns the existing model and job instead of queueing a
duplicate; for a model already in the library it adds the missing files.
- `GET /api/v1/jobs/{id}`: state, per-file progress, error; the `hf` log only with `?log=N`.
- `GET /api/v1/disk`: free, used and reserved space on the models folder.
- **Guardrails for API downloads** (Settings → API tokens): approval mode (default: requests wait
as *pending approval* until you approve or reject them on the model or job page), max size per
request (60 GB), free space that must remain after the download, counting what other open
downloads still need (100 GB), API jobs at once (2), and an optional author allowlist. Rejecting a
request removes a model it added, or restores the previous file selection.
- Everything requested with a token shows **requested by &lt;token name&gt;** in the library, on the
model and job pages, with a "Requested by" filter (and "awaiting approval" under Status).
- **Agent skill** for Hermes Agent and similar ([docs/agent/SKILL.md](docs/agent/SKILL.md)): how to
search, look up, request and monitor a download with `curl`, the guardrails, and to wait for
approval instead of retrying.
### Changed
- Settings → API keys is now **Runtime API keys** (the keys deployments require), to keep it apart
from API tokens.
- Tests can now use the database: `npm test` runs with `--conditions=react-server`.
## [0.9.0] - 2026-10-13
+4 -1
View File
@@ -16,9 +16,12 @@ RUN npm run build \
# --- runtime -----------------------------------------------------------------
# Python base (provides the official `hf` CLI) plus the Node binary. The Python image already
# has CA certificates and libstdc++, so no apt is needed.
# has CA certificates and libstdc++; apt only adds the PCI ID database (GPU names for benchmarks).
FROM python:3.13-slim-trixie AS runtime
COPY --from=node /usr/local/bin/node /usr/local/bin/node
RUN apt-get update \
&& apt-get install -y --no-install-recommends pci.ids \
&& rm -rf /var/lib/apt/lists/*
# Pinned: the worker relies on the CLI's on-disk layout (see src/worker/hf-layout.ts);
# re-verify that before bumping.
+4
View File
@@ -86,6 +86,10 @@ More guides are in the [wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname
(groundwork for testing model configs). See the
[wiki](https://git.linxweiler.xyz/pascallinxweiler/Kaname/wiki/Runtimes).
- **Jobs:** each download has a page with per-file progress and the full `hf` log.
- **API for agents:** create a token in Settings → API tokens and let a program or AI agent look up
repos, list models and request downloads at `/api/v1`, within guardrails you set (approval, max
size, free space, jobs at once, allowed authors). See [docs/api.md](docs/api.md) (also how to let
`/api/v1/` past a forward-auth proxy) and the agent skill [docs/agent/SKILL.md](docs/agent/SKILL.md).
## How it works
+128
View File
@@ -0,0 +1,128 @@
---
name: kaname-models
description: Find, request and track downloads of local LLMs (Hugging Face models, GGUF quants) on the user's Kaname server. Use when the user asks to get, download, add or check a model, or asks which models are available locally or how much disk space is left.
required_environment_variables:
- name: KANAME_URL
prompt: Kaname base URL (no trailing slash)
- name: KANAME_TOKEN
prompt: Kaname API token (kn_…)
---
# Kaname: local model downloads
Kaname manages the user's local LLM library. You can look up Hugging Face repos, see what is
already downloaded, request a download and follow it. You **cannot** delete anything, change
settings, or start models: tell the user when they need one of those.
Every call needs two environment variables:
- `KANAME_URL`: e.g. `https://models.example.com` (no trailing slash)
- `KANAME_TOKEN`: the API token (`kn_…`). Never print it or put it in a URL.
## Setup
The examples use `kaname`, a small wrapper around `curl` that adds the token and JSON headers. The
user installs it once:
```bash
mkdir -p ~/.local/bin && curl -fsSL https://git.linxweiler.xyz/pascallinxweiler/Kaname/raw/branch/main/docs/agent/kaname -o ~/.local/bin/kaname && chmod +x ~/.local/bin/kaname
```
If `kaname` is not found, write out the full command in each call instead:
`curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" …`
(every command runs in a fresh shell, so don't define a shell function for it).
All responses are JSON. Errors are `{"error": {"code", "message"}}`; the message says what to do.
## 0. Know your limits
```bash
kaname "$KANAME_URL/api/v1"
```
Shows your token name, scopes and the guardrails. The defaults:
- **approvalMode `approve`**: your requests wait until the user approves them. That's normal.
- **maxRequestSize** (60 GB): one request may download at most this much.
- **minFreeSize** (100 GB): this much must stay free on disk after the download.
- **maxOpenAgentJobs** (2): at most this many of your requests pending or running at once.
- **allowedAuthors**: if not empty, only repos from these Hugging Face authors.
## 1. Is it already here?
```bash
kaname "$KANAME_URL/api/v1/models?q=qwen3%208b"
kaname "$KANAME_URL/api/v1/models?author=unsloth&quant=Q4_K_M&status=ready"
```
Filters: `q`, `author`, `family`, `quant`, `tag`, `status`, `requested_by` (comma-separate values).
If the model is there with `status: ready`, you're done. Don't request it again.
## 2. Look up the repo
```bash
kaname "$KANAME_URL/api/v1/hub/lookup?repo=unsloth/Qwen3-8B-GGUF"
```
Note `sha` (the commit) and pick a quant from `quants` (each has a `size`). Choose one that fits the
user's request and the limits: check `size` against `maxRequestSize`, and check space with:
```bash
kaname "$KANAME_URL/api/v1/disk" # availableForRequests = what a request may still use
```
If `gated` is not `false`, the download only works if the user's Hugging Face account has access.
## 3. Request the download
```bash
kaname -X POST "$KANAME_URL/api/v1/downloads" \
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"<sha from lookup>","quant":"Q4_K_M"}'
```
For repos without GGUF quants (safetensors), use `"include": ["*.safetensors", "*.json"]` instead
of `quant`. Optional: `"tags": ["…"]`.
Answer:
- `201`, `state: pending_approval`: **waiting for the user.** Tell them what you requested and that
it needs their approval in Kaname. **Do not retry or re-request.**
- `201`, `state: queued`: it will start on its own.
- `200`, `created: false`: you (or someone) already requested exactly this; you get the existing
job. Don't request it again.
## 4. Follow it
```bash
kaname "$KANAME_URL/api/v1/jobs/<jobId>"
```
`state`: `pending_approval` → `queued` → `downloading` → `verifying` → `completed`. Every check
costs a full round of your context, so check rarely:
- **`pending_approval`:** do **not** poll. Tell the user what you requested and that it awaits
their approval in Kaname, then stop. Check again only when the user says it's approved, or, if
the user asks for it, schedule a single one-off check later with your cron/scheduling tool.
- **`queued` / `downloading` / `verifying`:** check at most once, around the reported
`etaSeconds`; if there is no ETA, once after about 10 minutes. Never loop in short intervals.
- **`completed`:** tell the user it's ready.
- **`cancelled`:** the user rejected or cancelled it. Don't ask again unless the user says so.
- **`failed`:** report `error.message` to the user. Don't loop on retries.
Add `?log=20` only when you need to explain a failure.
## When a request is refused
| `error.code` | What to do |
| --- | --- |
| `too_large` | Pick a smaller quant (or fewer files) that fits `maxRequestSize`. |
| `disk_space` | Pick a smaller quant, or tell the user the disk is full. |
| `too_many_jobs` | Don't wait in a loop: tell the user your earlier downloads are still pending or running, and stop. Request again later when the user asks. |
| `author_not_allowed` | Find the model from an allowed author, or ask the user. |
| `already_exists` | The repo is in the library at another commit; the user updates it in Kaname. |
| `busy` | That model has a download in progress; tell the user and stop. |
| `gated_no_access`, `gated_no_token` | The user must accept the model's terms on Hugging Face. |
| `disk_unknown` | Kaname's worker is offline; tell the user and stop. |
| `unauthorized`, `forbidden` | Your token is wrong, revoked or lacks a scope: tell the user. |
Never try to work around a guardrail (e.g. by splitting one big download into several requests).
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env bash
exec curl -sS -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" "$@"
+248
View File
@@ -0,0 +1,248 @@
# Kaname API (`/api/v1`)
A small JSON API for programs and AI agents: look up Hugging Face repos, list the local library,
request downloads and follow them. Everything an agent can do here is bounded by
[guardrails](#guardrails); it can't delete models or files, change settings, or manage runtimes or
tokens.
The rest of Kaname (the web UI and its internal `/api/*` routes) stays behind your OIDC login. Only
`/api/v1` accepts tokens, and it accepts *only* tokens (a browser session doesn't work there).
- [Authentication](#authentication)
- [Errors](#errors)
- [Endpoints](#endpoints)
- [Guardrails](#guardrails)
- [Behind a forward-auth proxy (Traefik)](#behind-a-forward-auth-proxy-traefik)
## Authentication
Create a token in **Settings → API tokens**. It is shown once; Kaname stores only its SHA-256.
Send it with every request:
```
Authorization: Bearer kn_…
```
| Scope | Allows |
| --- | --- |
| `models:read` | Hub lookup, list models, read jobs (and their log), disk space |
| `downloads:create` | `POST /api/v1/downloads`, within the guardrails |
A missing, unknown or revoked token gets `401`; a token without the needed scope gets `403`. The
settings page shows when each token was last used; **Revoke** stops it immediately.
Everything a token requests is marked with its name ("requested by hermes") on the model and job
pages and in the library, where you can filter by it.
## Errors
Errors are JSON with a message meant to be read and acted on:
```json
{ "error": { "code": "too_large", "message": "exceeds max size per request 60.0 GB: requested 74.2 GB. Pick a smaller quant or fewer files." } }
```
| Status | Codes |
| --- | --- |
| 400 | `invalid_request`, `invalid_json`, `empty_selection` (quant or globs match nothing), `invalid_repo_id` |
| 401 / 403 | `unauthorized`, `forbidden` (scope), `author_not_allowed`, `gated_no_token`, `gated_no_access` |
| 404 | `not_found`, `repo_not_found`, `revision_not_found` |
| 409 | `already_exists` (repo is in the library at another commit), `busy` (the model has an open job) |
| 422 | `too_large` |
| 429 | `too_many_jobs`, `rate_limited` (Hugging Face) |
| 503 / 507 | `disk_unknown` (worker offline), `disk_space` |
Sizes appear as bytes plus a readable `"… GB"` field (decimal GB, like the Hub).
## Endpoints
### `GET /api/v1`
Any valid token. Who you are, your scopes, the current guardrails and the endpoint list.
```bash
curl -s -H "Authorization: Bearer $KANAME_TOKEN" "$KANAME_URL/api/v1"
```
```json
{
"token": { "name": "hermes", "scopes": ["models:read", "downloads:create"] },
"guardrails": { "approvalMode": "approve", "maxRequestBytes": 60000000000, "maxRequestSize": "60.0 GB",
"minFreeBytes": 100000000000, "minFreeSize": "100.0 GB", "maxOpenAgentJobs": 2, "allowedAuthors": [] },
"endpoints": ["…"]
}
```
### `GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]`
`models:read`. Resolves the revision to a commit SHA and lists quants and files, the same data as
the Add model dialog. `repo` may also be a Hub URL. Up to 200 files are listed unless `files=all`.
```json
{
"repoId": "unsloth/Qwen3-8B-GGUF", "revision": "main", "sha": "9e6855bc…", "gated": false,
"lastModified": "2026-05-01T10:00:00.000Z",
"inLibrary": null,
"quants": [{ "quant": "Q4_K_M", "files": 1, "bytes": 5027783488, "size": "5.0 GB" }, "…"],
"fileCount": 31, "totalBytes": 104000000000,
"files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "bytes": 5027783488 }, "…"],
"filesTruncated": false
}
```
`inLibrary` is `{ modelId, pinnedSha, status }` when the repo is already in Kaname.
### `GET /api/v1/models`
`models:read`. The library, filtered like the library page:
| Parameter | Meaning |
| --- | --- |
| `q` | Search text; every word must match (repo, author, family, quant, tags, …) |
| `author`, `family`, `quant`, `tag` | Facets; repeat or comma-separate values (OR within a facet, AND across) |
| `status` | `pending`, `downloading`, `ready`, `incomplete`, `failed`, `deleting`, `pending_approval`, `update_available`, `repo_missing`, `commit_missing` |
| `requested_by` | Token name |
```json
{ "count": 1, "models": [{ "id": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "status": "ready", "pendingApproval": false,
"pinnedSha": "9e68…", "quants": ["Q4_K_M"], "tags": ["agent"], "selectedFiles": 1, "selectedBytes": 5027783488,
"onDiskBytes": 5027783488, "onDisk": "5.0 GB", "updateAvailable": false, "hubState": "available",
"requestedBy": "hermes", "createdAt": "…", "downloadedAt": "…" }] }
```
### `GET /api/v1/models/{id}`
`models:read`. One model with its selected files (path, bytes, state) and latest job.
### `POST /api/v1/downloads`
`downloads:create`. Request a download of a repo **at a pinned commit**: take `sha` from the lookup.
| Field | |
| --- | --- |
| `repoId` | `"org/name"` |
| `sha` | Full 40-character commit SHA |
| `quant` | e.g. `"Q4_K_M"`: that quant's weight files (all split parts) plus the companion files ticked in Settings → Downloads (chat template, mmproj, …), as in the Add model dialog |
| `include` | Instead of `quant`: glob patterns, e.g. `["*.safetensors", "*.json"]` |
| `tags` | Optional user tags for the model |
| `revision` | Optional branch to track for update checks (default `main`) |
```bash
curl -s -X POST -H "Authorization: Bearer $KANAME_TOKEN" -H "Content-Type: application/json" \
-d '{"repoId":"unsloth/Qwen3-8B-GGUF","sha":"9e6855bc…","quant":"Q4_K_M"}' \
"$KANAME_URL/api/v1/downloads"
```
```json
{ "created": true, "modelId": "01M…", "jobId": "01M…", "state": "pending_approval",
"requestedBytes": 5027783488, "requestedSize": "5.0 GB", "files": ["Qwen3-8B-Q4_K_M.gguf"],
"message": "Requested; waiting for the user to approve it in Kaname. Do not retry: check GET /api/v1/jobs/01M… every few minutes." }
```
- **201**: a new job, `state` `pending_approval` (approval mode `approve`) or `queued` (`auto`).
- **200** with `"created": false`: the same repo, commit and files were requested before; you get the
existing model and its latest job. Nothing is queued twice.
- If the repo is already in the library at the same commit, the request adds the files that are
missing from its selection (only the added bytes count against the guardrails). At another commit
it is refused: updating a model is done in the UI.
It uses the same code path as the Add model dialog (the file list is fetched again from the Hub at
that commit; the client's list isn't trusted).
### `GET /api/v1/jobs/{id}[?log=N]`
`models:read`. Compact job state:
```json
{ "id": "01M…", "modelId": "01M…", "repoId": "unsloth/Qwen3-8B-GGUF", "kind": "download", "purpose": "initial",
"state": "downloading", "cancelRequested": false, "requestedBy": "hermes",
"progress": { "doneBytes": 3000000000, "totalBytes": 5027783488, "percent": 59.7, "done": "3.0 GB", "total": "5.0 GB",
"speedBytesPerSecond": 52000000, "etaSeconds": 39 },
"error": null,
"files": [{ "path": "Qwen3-8B-Q4_K_M.gguf", "state": "downloading", "doneBytes": 3000000000, "totalBytes": 5027783488 }],
"createdAt": "…", "startedAt": "…", "finishedAt": null,
"next": "Downloading; check again in a minute." }
```
States: `pending_approval`, `queued`, `downloading`, `verifying`, `completed`, `failed`, `cancelled`
(also when the user rejected the request), `interrupted`. The `hf` log is only included with
`?log=N` (the last N lines, at most 200).
### `GET /api/v1/disk`
`models:read`. Space on the models folder, as reported by the worker every few seconds:
```json
{ "workerOnline": true, "freeBytes": 945600000000, "totalBytes": 2000000000000, "usedBytes": 1054400000000,
"reservedBytes": 105454144, "minFreeBytes": 100000000000, "availableForRequestsBytes": 845494545856,
"free": "945.6 GB", "total": "2000.0 GB", "availableForRequests": "845.5 GB" }
```
`reservedBytes` is what open downloads still have to fetch; `availableForRequests` is what a request
may use before hitting the minimum-free guardrail.
## Guardrails
Settings → API tokens → **Guardrails for API downloads**. They apply to every token together;
downloads started in the UI aren't affected.
| Setting | Default | Rejection |
| --- | --- | --- |
| Approval | **Ask me**: requests wait as *pending approval* until you approve or reject them on the model or job page | (not an error; `state: pending_approval`) |
| Max size per request | 60 GB | `422 too_large` |
| Keep free on the models folder | 100 GB, after the download and after what other open downloads still need | `507 disk_space` (`503 disk_unknown` if the worker is offline) |
| Agent jobs at once | 2 (pending approval, queued or running) | `429 too_many_jobs` |
| Allowed authors | empty = any; e.g. `unsloth, ggml-org, Qwen` (case-insensitive) | `403 author_not_allowed` |
Rejecting a request cancels its job. A model that only that request added leaves the library again;
for a request that added files to an existing model, the previous selection is restored.
## Behind a forward-auth proxy (Traefik)
If Kaname sits behind forward auth (e.g. Traefik with Tinyauth or Pocket ID), the proxy would answer
API calls with a login redirect. Let `/api/v1/` through without forward auth; Kaname checks the
bearer token itself there. Everything else keeps forward auth.
Two routers for the same host, the API one with a higher priority and no auth middleware:
```yaml
# docker compose labels on the kaname "web" service
labels:
- traefik.enable=true
- traefik.http.services.kaname.loadbalancer.server.port=3000
# UI and internal API: forward auth as before
- traefik.http.routers.kaname.rule=Host(`models.example.com`)
- traefik.http.routers.kaname.entrypoints=websecure
- traefik.http.routers.kaname.tls=true
- traefik.http.routers.kaname.middlewares=tinyauth
- traefik.http.routers.kaname.service=kaname
# Token API: no forward auth (bearer tokens are checked by Kaname)
- traefik.http.routers.kaname-api.rule=Host(`models.example.com`) && PathPrefix(`/api/v1/`)
- traefik.http.routers.kaname-api.entrypoints=websecure
- traefik.http.routers.kaname-api.tls=true
- traefik.http.routers.kaname-api.priority=100
- traefik.http.routers.kaname-api.service=kaname
```
The same in a file provider:
```yaml
http:
routers:
kaname-api:
rule: Host(`models.example.com`) && PathPrefix(`/api/v1/`)
entryPoints: [websecure]
tls: {}
priority: 100
service: kaname
```
Notes:
- Use `PathPrefix(`/api/v1/`)` with the trailing slash, so nothing else that starts with `/api/v1`
slips past forward auth. Kaname's own login gate also excludes exactly `/api/v1` and `/api/v1/…`.
- Don't exempt `/api` as a whole: the internal routes rely on the login session.
- Agents on the same network can also call Kaname directly (`http://<host>:3000/api/v1/…`) without
going through the proxy.
+17
View File
@@ -0,0 +1,17 @@
CREATE TABLE `api_tokens` (
`id` text PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`prefix` text NOT NULL,
`hash` text NOT NULL,
`scopes` text NOT NULL,
`last_used_at` integer,
`revoked_at` integer,
`created_at` integer NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `api_tokens_hash_unique` ON `api_tokens` (`hash`);--> statement-breakpoint
CREATE UNIQUE INDEX `api_tokens_name_uq` ON `api_tokens` (`name`);--> statement-breakpoint
ALTER TABLE `jobs` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `jobs` ADD `requested_by` text;--> statement-breakpoint
ALTER TABLE `models` ADD `requested_by_token_id` text;--> statement-breakpoint
ALTER TABLE `models` ADD `requested_by` text;
+7
View File
@@ -0,0 +1,7 @@
ALTER TABLE `benchmark_runs` ADD `meta` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `meta_b` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `system` text;--> statement-breakpoint
ALTER TABLE `benchmark_runs` ADD `description` text;--> statement-breakpoint
ALTER TABLE `deployments` ADD `engine_info` text;--> statement-breakpoint
ALTER TABLE `runtimes` ADD `image_digest` text;--> statement-breakpoint
ALTER TABLE `runtimes` ADD `engine_name` text;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+14
View File
@@ -120,6 +120,20 @@
"when": 1791658947930,
"tag": "0016_ab_resources_sweeps",
"breakpoints": true
},
{
"idx": 17,
"version": "6",
"when": 1792504668583,
"tag": "0017_api_tokens",
"breakpoints": true
},
{
"idx": 18,
"version": "6",
"when": 1792513935880,
"tag": "0018_benchmark_metadata",
"breakpoints": true
}
]
}
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "kaname",
"version": "0.9.0",
"version": "0.12.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "kaname",
"version": "0.9.0",
"version": "0.12.0",
"dependencies": {
"@base-ui/react": "^1.8.0",
"@libsql/client": "^0.18.0",
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "kaname",
"version": "0.9.0",
"version": "0.12.0",
"private": true,
"scripts": {
"dev": "concurrently -k -n web,worker -c blue,magenta \"npm:dev:web\" \"npm:dev:worker\"",
@@ -13,7 +13,7 @@
"typecheck": "next typegen && tsc --noEmit",
"db:generate": "drizzle-kit generate",
"db:migrate": "dotenv -e .env -- tsx src/lib/db/migrate-cli.ts",
"test": "tsx --test \"src/**/*.test.ts\"",
"test": "tsx --conditions=react-server --test \"src/**/*.test.ts\"",
"build:worker": "esbuild src/worker/index.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/worker.mjs && esbuild src/lib/db/migrate-cli.ts --bundle --platform=node --target=node24 --format=esm --packages=external --outfile=dist/migrate.mjs"
},
"dependencies": {
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env bash
# Read-only diagnostics for Intel GPU support (Arc / Arc Pro B-series) on a Kaname host.
# Shows which telemetry sources this kernel and driver offer, so Kaname uses ones that exist.
# Changes nothing. Run it on the Docker host (or VM) that has the GPU:
#
# bash scripts/intel-probe.sh # as your user: what an unprivileged container can see
# sudo bash scripts/intel-probe.sh # adds lspci's link/ReBAR capability details
#
# Paste the output back. It contains no hostname, IP addresses or user names.
set -u
section() { printf '\n=== %s ===\n' "$1"; }
show() { [ -e "$1" ] && printf '%s: %s\n' "$1" "$(tr '\n' ' ' < "$1" 2>/dev/null || echo '(not readable)')"; }
section "System"
echo "kernel: $(uname -r)"
grep -E '^(PRETTY_NAME|VERSION_ID)=' /etc/os-release 2>/dev/null
command -v systemd-detect-virt >/dev/null && echo "virt: $(systemd-detect-virt 2>/dev/null)"
show /sys/class/dmi/id/sys_vendor
show /sys/class/dmi/id/product_name
echo "running as uid $(id -u)"
section "Intel display devices"
gpus=()
for d in /sys/bus/pci/devices/*; do
[ "$(cat "$d/vendor" 2>/dev/null)" = "0x8086" ] || continue
case "$(cat "$d/class" 2>/dev/null)" in 0x03*) gpus+=("$(basename "$d")") ;; esac
done
[ ${#gpus[@]} -eq 0 ] && echo "no Intel GPU found on the PCI bus"
for a in "${gpus[@]}"; do
d=$(readlink -f "/sys/bus/pci/devices/$a")
section "GPU $a"
echo "sysfs path: $d"
show "$d/device"
show "$d/subsystem_device"
echo "driver: $(basename "$(readlink "$d/driver" 2>/dev/null)" 2>/dev/null)"
command -v lspci >/dev/null && lspci -nn -s "$a"
echo "-- link per level (GPU up to the root port):"
p=$d
while [[ $(basename "$p") =~ ^[0-9a-f]{4}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$ ]]; do
printf '%s vendor=%s cur=%s x%s max=%s x%s\n' "$(basename "$p")" "$(cat "$p/vendor" 2>/dev/null)" \
"$(cat "$p/current_link_speed" 2>/dev/null)" "$(cat "$p/current_link_width" 2>/dev/null)" \
"$(cat "$p/max_link_speed" 2>/dev/null)" "$(cat "$p/max_link_width" 2>/dev/null)"
p=$(dirname "$p")
done
echo "-- BARs (start end flags):"
head -6 "$d/resource" 2>/dev/null
echo "-- VRAM / memory files:"
find "$d" -maxdepth 3 \( -iname '*vram*' -o -iname '*lmem*' -o -iname '*mem_info*' \) 2>/dev/null | while read -r f; do
[ -f "$f" ] && show "$f"
done
ls "$d/tile0" 2>/dev/null | head -30
echo "-- hwmon:"
for h in "$d"/hwmon/hwmon*; do
[ -d "$h" ] || continue
show "$h/name"
for f in "$h"/*_input "$h"/*_label "$h"/*_crit "$h"/power*_max; do [ -f "$f" ] && show "$f"; done
done
if [ "$(id -u)" = 0 ] && command -v lspci >/dev/null; then
echo "-- lspci capabilities:"
lspci -vvv -s "$a" | grep -E 'LnkCap:|LnkSta:|Resizable BAR|BAR [0-9]: current size|Region'
fi
done
section "/dev/dri"
ls -ln /dev/dri 2>/dev/null
for n in /dev/dri/renderD*; do [ -e "$n" ] && echo "$n gid=$(stat -c %g "$n") group=$(stat -c %G "$n")"; done
getent group render video | cut -d: -f1,3
section "DRM fdinfo (per-process VRAM / engine time)"
found=0
for f in /proc/[0-9]*/fdinfo/*; do
grep -q '^drm-driver:' "$f" 2>/dev/null || continue
found=1
echo "readable example: $f"
grep -E '^drm-(driver|client-id|engine-|cycles-|total-cycles-|memory-|total-|resident-)' "$f" | head -25
break
done
[ $found = 0 ] && echo "no readable DRM fdinfo (no GPU process running, or not permitted for this user)"
section "Tools"
for t in xpu-smi intel_gpu_top clinfo sycl-ls vulkaninfo docker; do
printf '%s: %s\n' "$t" "$(command -v "$t" || echo missing)"
done
command -v docker >/dev/null && docker version --format 'docker server {{.Server.Version}}' 2>/dev/null
+12 -5
View File
@@ -2,7 +2,9 @@
import { DownloadIcon, ShieldCheckIcon, WrenchIcon } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { ApprovalBar } from "@/components/approval-bar";
import { cancelJob, startDownload, startRepair, startVerify } from "@/components/job-actions";
import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { Button } from "@/components/ui/button";
@@ -33,6 +35,8 @@ export function DownloadCard({
const jobs = snapshot?.jobs ?? [];
const latest = jobs[0];
const open = latest && OPEN.includes(latest.state) ? latest : undefined;
const pending = latest?.state === "pending_approval" ? latest : undefined;
const router = useRouter();
const files = open ? groupJobFiles(snapshot?.files ?? []) : [];
// The newest verify, unless a download ran after it (its result would be stale).
const lastCheck = jobs.find((j) => VERIFY_KINDS.includes(j.kind) || j.kind === "download");
@@ -58,12 +62,13 @@ export function DownloadCard({
: latest?.state === "failed" && latest.kind === "download"
? "Retry"
: "Download missing";
const canDownload = !open && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
const canVerify = !open && !neverRan && status !== "deleting" && !!snapshot;
const needsRepair = !open && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
const canDownload = !open && !pending && !hubMissing && status !== "ready" && status !== "deleting" && !!snapshot;
const canVerify = !open && !pending && !neverRan && status !== "deleting" && !!snapshot;
const needsRepair = !open && !pending && !hubMissing && status !== "deleting" && (verifyProblems > 0 || status === "incomplete");
let hint = "Downloads the selected files at the pinned commit.";
if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
if (pending) hint = "Requested through the API; waits for your approval.";
else if (open?.state === "queued") hint = snapshot?.worker.online ? "Waiting for a free slot." : "Queued, but the worker is offline.";
else if (open) hint = "Runs in the background; you can close this page.";
else if (status === "deleting") hint = "Deleting…";
else if (hubMissing && status !== "ready") hint = "Can't download: no longer available on Hugging Face. Local files are kept.";
@@ -83,7 +88,9 @@ export function DownloadCard({
</div>
<p className="text-xs text-muted-foreground">{hint}</p>
{showProgress && <JobProgress job={latest} compact />}
{pending && <ApprovalBar job={pending} onRemoved={() => router.push("/")} />}
{showProgress && !pending && <JobProgress job={latest} compact />}
{latest?.state === "failed" && latest.errorMessage && (
<pre className="max-h-40 overflow-auto rounded-md bg-destructive/10 px-2.5 py-2 text-xs whitespace-pre-wrap text-destructive">
+2
View File
@@ -23,6 +23,7 @@ import { DeploymentStateBadge } from "@/components/deployment-state";
import { HubStateBadge } from "@/components/hub-state-badge";
import { LocalTime } from "@/components/local-time";
import { ModelStatusBadge } from "@/components/model-status-badge";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { formatBytes, shortSha } from "@/lib/format";
@@ -145,6 +146,7 @@ export default async function ModelPage({ params, searchParams }: PageProps<"/[o
<CopyButton value={model.repoId} label="Copy repo ID" />
<ModelStatusBadge status={model.status} />
<HubStateBadge state={model.hubState} />
<RequestedByBadge name={model.requestedBy} />
{update && (
<span className="inline-flex h-5 items-center rounded-4xl border border-sky-500/30 bg-sky-500/10 px-2 text-xs font-medium text-sky-700 dark:text-sky-300">
update available
@@ -33,7 +33,8 @@ 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 { RunMetaCard } from "@/components/run-meta";
import { cancelBenchmark, deleteBenchmark, describeBenchmark, renameBenchmark } from "../actions";
import { AbReport } from "./ab-report";
import { BenchmarkReport } from "./benchmark-report";
import { PublishCard } from "./publish-card";
@@ -58,6 +59,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
const [r, setR] = useState(initial);
const [now, setNow] = useState(() => Date.now());
const [label, setLabel] = useState(initial.label ?? "");
const [description, setDescription] = useState(initial.description ?? "");
const active = r.state === "queued" || r.state === "running";
useEffect(() => {
@@ -81,6 +83,7 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
deploymentId: r.deploymentId,
deploymentBId: r.kind === "ab" ? r.deploymentBId : null,
label: r.label,
description: r.description,
...r.settings,
}),
});
@@ -318,6 +321,30 @@ export function BenchmarkDetail({ initial }: { initial: ListRow }) {
/>
</CardContent>
</Card>
<Card size="sm">
<CardHeader>
<CardTitle>Description</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-1.5">
<textarea
value={description}
maxLength={4000}
rows={3}
placeholder="What this run tries out, e.g. q8_0 KV cache to fit 64k context"
className="w-full rounded-md border bg-transparent px-2.5 py-1.5 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
onChange={(e) => setDescription(e.target.value)}
onBlur={async () =>
description !== (r.description ?? "") &&
(await describeBenchmark(r.id, description || null)) &&
setR({ ...r, description: description.trim() || null })
}
/>
<p className="text-[11px] text-muted-foreground">
Passed to BetterBench (when set before the run starts) and to the launch80 preview, together with the system summary.
</p>
</CardContent>
</Card>
<RunMetaCard meta={r.meta} metaB={r.metaB} system={r.system} />
{r.kind === "run" && (
<Card size="sm">
<CardHeader>
@@ -190,6 +190,12 @@ export function PublishCard({ runId, defaultTitle, defaultSummary }: { runId: st
</span>
))}
</dd>
{p.sections.map((s) => (
<div key={s.heading} className="contents">
<dt className="text-muted-foreground">{s.heading}</dt>
<dd className="whitespace-pre-line">{s.body}</dd>
</div>
))}
<dt className="text-muted-foreground">Data</dt>
<dd>{p.phases.join(", ")} · every raw sample</dd>
<dt className="text-muted-foreground">Removed</dt>
+1
View File
@@ -13,3 +13,4 @@ async function call(url: string, method: string, body?: unknown): Promise<boolea
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 });
export const describeBenchmark = (id: string, description: string | null) => call(`/api/benchmarks/${id}`, "PATCH", { description });
+28
View File
@@ -4,6 +4,7 @@ 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 { metaRows } from "@/lib/benchmark-meta";
import { CONFIG_ROWS, deltaPct, describeSettings, headline } from "@/lib/benchmark-view";
import type { BenchmarkSummary } from "@/lib/db/schema";
import { cn } from "@/lib/utils";
@@ -62,6 +63,7 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
{
group: "Headline",
rows: [
{ label: "Prefill (deepest prompt)", unit: "t/s", higherIsBetter: true, digits: 0, get: (s) => headline(s).prefill?.tps ?? null },
{ 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 },
],
@@ -87,6 +89,10 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
];
const metrics = groups.filter((g) => g.rows.length > 0);
// Hardware, runtime version, model/quant/KV, context and concurrency as recorded at the start of each run.
const metaByRun = runs.map((r) => (r.meta ? metaRows(r.meta) : null));
const metaKeys = [...new Map(metaByRun.flatMap((rows) => rows ?? []).map((x) => [x.key, x.label])).entries()];
const metaTable = metaKeys.map(([key, label]) => ({ key, label, values: metaByRun.map((rows) => (rows ? (rows.find((x) => x.key === key)?.value ?? null) : null)) }));
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);
@@ -122,6 +128,28 @@ export default async function ComparePage({ searchParams }: PageProps<"/benchmar
</TableRow>
</TableHeader>
<TableBody>
{metaTable.length > 0 && (
<>
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Hardware &amp; runtime
</TableCell>
</TableRow>
{metaTable.map(({ key, label, values }) => {
const differs = new Set(values.map((v) => v ?? "")).size > 1;
return (
<TableRow key={`meta-${key}`} className={cn(differs && "bg-amber-500/5")}>
<TableCell className={cn("text-xs", differs ? "font-medium" : "text-muted-foreground")}>{label}</TableCell>
{values.map((v, i) => (
<TableCell key={i} className={cn("font-mono text-xs break-all whitespace-normal", differs && i > 0 && v !== values[0] && "text-amber-700 dark:text-amber-300")}>
{v ?? <span className="text-muted-foreground">not recorded</span>}
</TableCell>
))}
</TableRow>
);
})}
</>
)}
<TableRow className="bg-muted/40 hover:bg-muted/40">
<TableCell colSpan={runs.length + 1} className="text-xs font-medium tracking-wide text-muted-foreground uppercase">
Settings
@@ -9,13 +9,14 @@ import { BarChart } from "@/components/bar-chart";
import { BenchmarkStateBadge } from "@/components/benchmark-state";
import { Button, buttonVariants } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { metaRows } from "@/lib/benchmark-meta";
import { describeSettings, headline } from "@/lib/benchmark-view";
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, SweepVariant } from "@/lib/db/schema";
import type { benchmarkSweeps, BenchmarkSummary, ResourceStats, RunMeta, SweepVariant } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { cn } from "@/lib/utils";
type Sweep = typeof benchmarkSweeps.$inferSelect;
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null };
type Run = { id: string; state: string; summary: BenchmarkSummary | null; resources: ResourceStats | null; phase: string | null; error: string | null; meta: RunMeta | null };
export type SweepData = { sweep: Sweep; runs: Run[] };
const VARIANT_STATE: Record<SweepVariant["state"], string> = {
@@ -37,6 +38,8 @@ type Row = {
cpu: number | null;
ram: number | null;
vram: number | null;
power: number | null;
temp: number | null;
};
function rowsOf(data: SweepData): Row[] {
@@ -54,11 +57,27 @@ function rowsOf(data: SweepData): Row[] {
peak: h.peak?.tps ?? null,
cpu: c?.cpuAvg ?? null,
ram: c?.memPeakBytes ?? null,
vram: g.length ? g.reduce((s, x) => s + x.vramPeakMb, 0) : null,
vram: g.some((x) => x.vramPeakMb != null) ? g.reduce((s, x) => s + (x.vramPeakMb ?? 0), 0) : null,
power: g.some((x) => x.powerAvgW != null) ? g.reduce((s, x) => s + (x.powerAvgW ?? 0), 0) : null,
temp: g.some((x) => x.tempPeakC != null) ? Math.max(...g.map((x) => x.tempPeakC ?? -Infinity)) : null,
};
});
}
/**
* Recorded setup (GPU, PCIe, engine version, quant, KV cache, context, concurrency): values shared by
* every variant go above the table, the ones that differ become columns.
*/
function setupOf(rows: Row[]) {
const per = rows.map((r) => (r.run?.meta ? metaRows(r.run.meta).filter((x) => x.key !== "image" && x.key !== "digest") : null));
const keys = [...new Map(per.flatMap((x) => x ?? []).map((x) => [x.key, x.label])).entries()];
const recorded = per.filter((x) => x != null);
const value = (i: number, key: string) => per[i]?.find((x) => x.key === key)?.value ?? null;
const differs = keys.filter(([key]) => new Set(recorded.map((x) => x.find((y) => y.key === key)?.value ?? "")).size > 1);
const shared = keys.filter((k) => !differs.includes(k)).map(([key, label]) => ({ label, value: recorded[0]?.find((y) => y.key === key)?.value ?? null }));
return { shared: recorded.length ? shared : [], columns: differs.map(([key, label]) => ({ key, label })), value };
}
/** Best value per column (higher or lower is better), to set it in bold. */
function best(rows: Row[], key: keyof Row, higher: boolean): number | null {
const vals = rows.map((r) => r[key]).filter((x): x is number => typeof x === "number");
@@ -95,6 +114,7 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
}
const rows = rowsOf(data);
const setup = setupOf(rows);
const finished = rows.filter((r) => r.decode != null);
const runIds = rows.map((r) => r.v.runId).filter((x): x is string => !!x && rows.some((r) => r.run?.id === x && r.run.state === "completed"));
const bestOf = {
@@ -105,6 +125,8 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
cpu: best(rows, "cpu", false),
ram: best(rows, "ram", false),
vram: best(rows, "vram", false),
power: best(rows, "power", false),
temp: best(rows, "temp", false),
};
const cell = (v: number | null, b: number | null, fmt: (x: number) => string) => (
<td className={cn("px-3 py-2 text-right tabular-nums", v != null && v === b && "font-semibold")}>{v != null ? fmt(v) : "—"}</td>
@@ -183,6 +205,14 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
<CardHeader>
<CardTitle>Variants</CardTitle>
<CardDescription>Best value per column in bold. Resource figures are averages/peaks over the run.</CardDescription>
{setup.shared.length > 0 && (
<p className="text-xs text-muted-foreground">
{setup.shared
.filter((x) => x.value)
.map((x) => `${x.label}: ${x.value}`)
.join(" · ")}
</p>
)}
</CardHeader>
<CardContent className="overflow-x-auto px-0">
<table className="w-full text-sm">
@@ -190,6 +220,11 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
<tr className="border-b">
<th className="px-3 py-2 text-left font-medium">Variant</th>
<th className="px-3 py-2 text-left font-medium">State</th>
{setup.columns.map((c) => (
<th key={c.key} className="px-3 py-2 text-left font-medium">
{c.label}
</th>
))}
<th className="px-3 py-2 text-right font-medium">Decode t/s</th>
<th className="px-3 py-2 text-right font-medium">TTFT ms</th>
<th className="px-3 py-2 text-right font-medium">Prefill t/s</th>
@@ -197,10 +232,12 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
<th className="px-3 py-2 text-right font-medium">CPU cores</th>
<th className="px-3 py-2 text-right font-medium">Peak RAM</th>
<th className="px-3 py-2 text-right font-medium">Peak VRAM</th>
<th className="px-3 py-2 text-right font-medium">GPU power</th>
<th className="px-3 py-2 text-right font-medium">Peak temp</th>
</tr>
</thead>
<tbody>
{rows.map((r) => (
{rows.map((r, i) => (
<tr key={r.v.index} className="border-b last:border-0">
<td className="px-3 py-2 font-mono text-xs">
{r.v.runId ? (
@@ -216,6 +253,11 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
{r.v.state === "benchmarking" && r.run?.phase ? ` · ${r.run.phase}` : ""}
{(r.v.error || r.run?.error) && r.v.state === "failed" ? ` · ${(r.v.error ?? r.run?.error ?? "").slice(0, 60)}` : ""}
</td>
{setup.columns.map((c) => (
<td key={c.key} className="px-3 py-2 font-mono text-xs">
{setup.value(i, c.key) ?? "–"}
</td>
))}
{cell(r.decode, bestOf.decode, (x) => x.toFixed(1))}
{cell(r.ttft, bestOf.ttft, (x) => x.toFixed(0))}
{cell(r.prefill, bestOf.prefill, (x) => x.toFixed(0))}
@@ -223,6 +265,8 @@ export function SweepDetail({ initial }: { initial: SweepData }) {
{cell(r.cpu, bestOf.cpu, (x) => x.toFixed(2))}
{cell(r.ram, bestOf.ram, (x) => formatBytes(x))}
{cell(r.vram, bestOf.vram, (x) => `${(x / 1024).toFixed(1)} GiB`)}
{cell(r.power, bestOf.power, (x) => `${Math.round(x)} W`)}
{cell(r.temp, bestOf.temp, (x) => `${Math.round(x)} °C`)}
</tr>
))}
</tbody>
@@ -34,6 +34,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
const [passes, setPasses] = useState("10");
const [phases, setPhases] = useState<BenchmarkPhase[]>(["decode", "prefill", "concurrency"]);
const [label, setLabel] = useState("");
const [description, setDescription] = useState("");
const [busy, setBusy] = useState(false);
const [runs, setRuns] = useState(initial);
const [peers, setPeers] = useState<Peer[] | null>(null);
@@ -73,7 +74,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
async function start(body: Record<string, unknown>) {
setBusy(true);
try {
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, ...body }) });
const res = await fetch("/api/benchmarks", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ deploymentId, label: label.trim() || null, description: description.trim() || null, ...body }) });
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}`);
@@ -138,6 +139,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
))}
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. q8_0 KV cache (optional)" />
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
<Button
onClick={() =>
start({ quick: mode === "quick", passes: mode === "custom" ? Number(passes) || 10 : null, phases: phases.length === PHASES.length ? [] : phases })
@@ -195,6 +197,7 @@ export function BenchmarkCard({ deploymentId, modelId, running, initial }: { dep
</label>
</div>
<Input value={label} onChange={(e) => setLabel(e.target.value)} maxLength={120} placeholder="Label, e.g. f16 vs q8_0 KV (optional)" />
<Input value={description} onChange={(e) => setDescription(e.target.value)} maxLength={4000} placeholder="Description: what this run tries out (optional, published with it)" />
<Button
onClick={() => start({ deploymentBId: peerId, mdePct: Number(mde) || 1, maxPairs: Math.max(12, Number(maxPairs) || 200) })}
disabled={!running || busy || !peer || peer.state !== "running"}
+23 -1
View File
@@ -22,6 +22,7 @@ import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type {
DeploymentOptions,
HardwareGpu,
HostGpu,
RuntimeAccelerator,
RuntimeEngine,
@@ -32,6 +33,7 @@ import {
buildCommand,
ENGINE_PORT,
estimateMemoryMb,
estimateVramMb,
renderCommand,
} from "@/lib/deploy-command";
import { argsToRows, rowsToArgs } from "@/lib/extra-args";
@@ -62,6 +64,8 @@ export type FormHost = {
cpuFeatures: string[];
nvidia: boolean;
gpus: HostGpu[];
/** All GPUs on the host with Settings → Hardware applied (Intel/AMD VRAM for the estimate). */
hardwareGpus: HardwareGpu[];
} | null;
export type FormInitial = {
id?: string;
@@ -343,6 +347,10 @@ export function DeploymentForm({
? hostGpus.filter((g) => gpuIds.includes(g.uuid))
: hostGpus;
const vramMb = chosenGpus.reduce((s, g) => s + g.memoryMb, 0);
// Intel/AMD GPUs come in as /dev/dri: all of them, VRAM as detected (or set in Settings → Hardware).
const driGpus = (host?.hardwareGpus ?? []).filter((g) => (accelerator === "rocm" ? g.vendor === "amd" : g.vendor === "intel" || g.vendor === "amd"));
const gpuVramMb = accelerator === "nvidia" ? vramMb || null : driGpus.some((g) => g.vramMb) ? driGpus.reduce((s, g) => s + (g.vramMb ?? 0), 0) : null;
const vramEstimate = model && gpu ? estimateVramMb(fileBytes, options.contextSize, engine, options, gpuVramMb) : null;
const memory = memoryTouched ? intOrNull(memoryMb) : estimate;
const preview =
runtime && model
@@ -683,7 +691,7 @@ export function DeploymentForm({
Accepts any of the {apiKeyCount} key
{apiKeyCount === 1 ? "" : "s"} from{" "}
<Link href="/settings/api-keys" className="underline">
Settings → API keys
Settings → Runtime API keys
</Link>{" "}
as{" "}
<code className="font-mono">Authorization: Bearer</code>.
@@ -840,6 +848,20 @@ export function DeploymentForm({
)}
</div>
)}
{accelerator !== "nvidia" && driGpus.length > 0 && (
<p className="text-xs text-muted-foreground sm:col-span-2">
{driGpus.map((g) => `${g.name ?? "GPU"}${g.vramMb ? ` (${formatBytes(g.vramMb * 2 ** 20)})` : ""}`).join(", ")} via /dev/dri
</p>
)}
{model && (
<p className={`text-xs sm:col-span-2 ${vramEstimate != null && gpuVramMb != null && vramEstimate > gpuVramMb ? "text-amber-700 dark:text-amber-300" : "text-muted-foreground"}`}>
{vramEstimate == null
? "VRAM need: depends on how many layers/experts go to the GPU."
: `VRAM need, roughly: ${formatBytes(vramEstimate * 2 ** 20)}${gpuVramMb ? ` of ${formatBytes(gpuVramMb * 2 ** 20)}` : ""}${
engine === "vllm" ? " (vLLM reserves its GPU memory share up front)" : " (weights, KV cache, compute buffers)"
}${gpuVramMb != null && vramEstimate > gpuVramMb ? ". Doesn't fit: lower the context, quantize the KV cache or offload fewer layers." : ""}`}
</p>
)}
{engine === "llama.cpp" ? (
<>
<Field
+35 -4
View File
@@ -1,16 +1,47 @@
import "server-only";
import { listApiKeys } from "@/lib/api-keys";
import { listDeployableModels } from "@/lib/deployments";
import { applyOverrides } from "@/lib/hardware";
import { getDockerInfo, listRuntimes } from "@/lib/runtimes";
import { getHardwareOverrides } from "@/lib/settings";
import type { FormHost, FormModel, FormRuntime } from "./deployment-form";
/** Everything the deployment form needs: runtimes, servable models, host facts, API key count. */
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()]);
export async function formData(): Promise<{
runtimes: FormRuntime[];
models: FormModel[];
host: FormHost;
apiKeyCount: number;
}> {
const [runtimes, models, docker, keys, overrides] = await Promise.all([
listRuntimes(),
listDeployableModels(),
getDockerInfo(),
listApiKeys(),
getHardwareOverrides(),
]);
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, accelerator: r.accelerator })),
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, nvidia: !!docker.nvidia, gpus: docker.gpus ?? [] } : null,
host: docker
? {
cpus: docker.cpus,
memoryBytes: docker.memoryBytes,
cpuFeatures: docker.cpuFeatures,
nvidia: !!docker.nvidia,
gpus: docker.gpus ?? [],
hardwareGpus: applyOverrides(docker.hardware, overrides)?.gpus ?? [],
}
: null,
apiKeyCount: keys.length,
};
}
+13
View File
@@ -1,10 +1,13 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { ApprovalBar } from "@/components/approval-bar";
import { cancelJob } from "@/components/job-actions";
import { JobFilesTable } from "@/components/job-files-table";
import { JobProgress } from "@/components/job-progress";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { useLive } from "@/hooks/use-live";
@@ -21,6 +24,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
const files = snapshot?.files ?? [];
const open = OPEN.includes(job.state);
const [busy, setBusy] = useState(false);
const router = useRouter();
const logRef = useRef<HTMLDivElement>(null);
const [follow, setFollow] = useState(true);
@@ -46,6 +50,7 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
{job.repoId}
</Link>
</h1>
<RequestedByBadge name={job.requestedBy} />
{open && (
<Button
className="ml-auto"
@@ -63,12 +68,20 @@ export function JobLive({ initial }: { initial: JobSnapshot }) {
)}
</div>
{job.state === "pending_approval" && <ApprovalBar job={job} onRemoved={() => router.push("/")} />}
<Card>
<CardContent className="flex flex-col gap-3">
<JobProgress job={job} />
<dl className="grid grid-cols-[max-content_1fr] gap-x-6 gap-y-1 text-sm">
<dt className="text-muted-foreground">Created</dt>
<dd><LocalTime value={job.createdAt} /></dd>
{job.requestedBy && (
<>
<dt className="text-muted-foreground">Requested by</dt>
<dd>{job.requestedBy} (API token)</dd>
</>
)}
<dt className="text-muted-foreground">Started</dt>
<dd>
<LocalTime value={job.startedAt} />
+9 -3
View File
@@ -8,6 +8,7 @@ import { JobProgress, JobStateBadge } from "@/components/job-progress";
import { LocalTime } from "@/components/local-time";
import { HUB_STATE_LABEL, HubStateBadge } from "@/components/hub-state-badge";
import { MODEL_STATUS, ModelStatusBadge } from "@/components/model-status-badge";
import { RequestedByBadge } from "@/components/requested-by-badge";
import { TagBadge, TagDot } from "@/components/tag-badge";
import { Badge } from "@/components/ui/badge";
import { Button, buttonVariants } from "@/components/ui/button";
@@ -28,11 +29,12 @@ import {
type Filters,
matchesFilters,
matchesQuery,
PENDING_APPROVAL,
type SearchableModel,
} from "@/lib/search";
import { FacetFilter } from "./facet-filter";
const OPEN = ["queued", "downloading", "verifying"];
const OPEN = ["pending_approval", "queued", "downloading", "verifying"];
const FACET_LABEL: Record<Facet, string> = {
author: "Author",
@@ -40,9 +42,10 @@ const FACET_LABEL: Record<Facet, string> = {
quant: "Quant",
tag: "Tag",
status: "Status",
requester: "Requested by",
};
const statusLabel = (v: string) => MODEL_STATUS[v as ModelStatus]?.label ?? v;
const statusLabel = (v: string) => (v === PENDING_APPROVAL ? "awaiting approval" : (MODEL_STATUS[v as ModelStatus]?.label ?? v));
function toSearchable(r: LibraryRow): SearchableModel {
return {
@@ -63,6 +66,8 @@ function toSearchable(r: LibraryRow): SearchableModel {
: r.updateAvailable
? "update available"
: null,
requestedBy: r.requestedBy,
pendingApproval: r.pendingApproval,
};
}
@@ -197,6 +202,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{r.repoId}
</Link>
<div className="mt-0.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<RequestedByBadge name={r.requestedBy} className="h-4 text-[10px]" />
{base && base !== r.repoId && <span>base {base}</span>}
{r.architecture && <span>{r.architecture}</span>}
{r.deployments.map((d) => (
@@ -243,7 +249,7 @@ export function LibraryView({ rows }: { rows: LibraryRow[] }) {
{job ? (
<Link href={`/jobs/${job.id}`} className="flex flex-col gap-1">
<JobStateBadge job={job} />
{job.state !== "queued" && <JobProgress job={job} compact />}
{job.state !== "queued" && job.state !== "pending_approval" && <JobProgress job={job} compact />}
</Link>
) : (
<span className="flex flex-wrap gap-1">
@@ -28,7 +28,7 @@ export function ApiKeySettings({ keys }: { keys: ApiKeyRow[] }) {
return (
<Card>
<CardHeader>
<CardTitle>API keys</CardTitle>
<CardTitle>Runtime API keys</CardTitle>
<CardDescription>
Deployments with &ldquo;Require an API key&rdquo; accept any of these keys as <code className="font-mono text-xs">Authorization: Bearer &lt;key&gt;</code>.
Changes apply when a deployment (re)starts.
+1 -1
View File
@@ -3,7 +3,7 @@ import { listApiKeys } from "@/lib/api-keys";
import { ApiKeySettings } from "./api-key-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API keys · Settings" };
export const metadata: Metadata = { title: "Runtime API keys · Settings" };
export default async function ApiKeySettingsPage() {
return <ApiKeySettings keys={await listApiKeys()} />;
@@ -0,0 +1,111 @@
"use client";
import { ShieldCheckIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import { type ApprovalMode, type Guardrails, parseAuthorList } from "@/lib/agent-guardrails";
const GB = 1_000_000_000;
const toGb = (b: number) => String(Math.round((b / GB) * 1000) / 1000);
/** Limits for downloads requested through the API. Saved together with one button. */
export function GuardrailSettings({ initial }: { initial: Guardrails }) {
const router = useRouter();
const [mode, setMode] = useState<ApprovalMode>(initial.approvalMode);
const [maxGb, setMaxGb] = useState(toGb(initial.maxRequestBytes));
const [minFreeGb, setMinFreeGb] = useState(toGb(initial.minFreeBytes));
const [maxJobs, setMaxJobs] = useState(String(initial.maxOpenJobs));
const [authors, setAuthors] = useState(initial.allowedAuthors.join(", "));
const [busy, setBusy] = useState(false);
let authorError: string | null = null;
let authorList: string[] = [];
try {
authorList = parseAuthorList(authors);
} catch (err) {
authorError = err instanceof Error ? err.message : String(err);
}
const num = (s: string) => Number(s.replace(",", "."));
async function save(e: React.FormEvent) {
e.preventDefault();
if (authorError) return;
setBusy(true);
try {
const res = await fetch("/api/settings/agent", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
approvalMode: mode,
maxRequestBytes: Math.round(num(maxGb) * GB),
minFreeBytes: Math.round(num(minFreeGb) * GB),
maxOpenJobs: Math.round(num(maxJobs)),
allowedAuthors: authorList,
}),
});
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not save (${res.status})`);
toast.success("Guardrails saved");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-1.5">
<ShieldCheckIcon className="size-4 text-muted-foreground" />
Guardrails for API downloads
</CardTitle>
<CardDescription>Apply to every download requested with a token, across all tokens. Downloads you start in the UI are not affected.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={save} className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-mode">Approval</Label>
<NativeSelect id="g-mode" value={mode} onChange={(e) => setMode(e.target.value as ApprovalMode)} className="max-w-md">
<option value="approve">Ask me: requests wait as &ldquo;pending approval&rdquo;</option>
<option value="auto">Automatic: downloads start right away</option>
</NativeSelect>
</div>
<div className="grid gap-4 sm:grid-cols-3">
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-max">Max size per request (GB)</Label>
<Input id="g-max" value={maxGb} onChange={(e) => setMaxGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-free">Keep free on the models folder (GB)</Label>
<Input id="g-free" value={minFreeGb} onChange={(e) => setMinFreeGb(e.target.value.replace(/[^\d.,]/g, ""))} inputMode="decimal" />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-jobs">Agent jobs at once</Label>
<Input id="g-jobs" value={maxJobs} onChange={(e) => setMaxJobs(e.target.value.replace(/\D/g, ""))} inputMode="numeric" />
</div>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="g-authors">Allowed authors</Label>
<Input id="g-authors" value={authors} onChange={(e) => setAuthors(e.target.value)} placeholder="Empty: any author. e.g. unsloth, ggml-org, Qwen" aria-invalid={!!authorError} />
<p className="text-xs text-muted-foreground">
{authorError ?? "Hugging Face users or organizations (the part before the slash), comma-separated."}
</p>
</div>
<p className="text-xs text-muted-foreground">
&ldquo;Agent jobs at once&rdquo; counts requests that are pending approval, queued or downloading. The free-space check also subtracts what other open
downloads still need.
</p>
<Button type="submit" className="self-start" disabled={busy || !!authorError}>
Save guardrails
</Button>
</form>
</CardContent>
</Card>
);
}
@@ -0,0 +1,18 @@
import type { Metadata } from "next";
import { listTokens } from "@/lib/api-tokens";
import { getGuardrails } from "@/lib/settings";
import { GuardrailSettings } from "./guardrail-settings";
import { TokenSettings } from "./token-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "API tokens · Settings" };
export default async function ApiTokenSettingsPage() {
const [tokens, guardrails] = await Promise.all([listTokens(), getGuardrails()]);
return (
<div className="flex flex-col gap-4">
<TokenSettings tokens={tokens} />
<GuardrailSettings initial={guardrails} />
</div>
);
}
@@ -0,0 +1,178 @@
"use client";
import { BotIcon, PlusIcon, Trash2Icon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { CopyButton } from "@/components/copy-button";
import { LocalTime } from "@/components/local-time";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { SCOPE_LABEL } from "@/lib/token-scopes";
import type { ApiTokenRow } from "@/lib/api-tokens";
import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
/** Bearer tokens for /api/v1 (e.g. an AI agent). The token is shown once, then only its prefix. */
export function TokenSettings({ tokens }: { tokens: ApiTokenRow[] }) {
const [created, setCreated] = useState<{ name: string; token: string } | null>(null);
return (
<Card>
<CardHeader>
<CardTitle>API tokens</CardTitle>
<CardDescription>
For programs and agents calling Kaname&apos;s API at <code className="font-mono text-xs">/api/v1</code> with{" "}
<code className="font-mono text-xs">Authorization: Bearer &lt;token&gt;</code>. No token can delete models or files, change settings, or manage runtimes and
tokens.
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-3">
<NewTokenForm onCreated={setCreated} />
{created && (
<div className="flex flex-col gap-1.5 rounded-lg border border-primary/40 bg-primary/5 px-4 py-3">
<p className="text-sm font-medium">Token &ldquo;{created.name}&rdquo; created. Copy it now: it is not shown again.</p>
<div className="flex items-center gap-2">
<code className="min-w-0 flex-1 rounded-md bg-muted px-2 py-1 font-mono text-xs break-all">{created.token}</code>
<CopyButton value={created.token} label="Copy token" />
</div>
</div>
)}
{tokens.length === 0 ? (
<p className="text-sm text-muted-foreground">No tokens yet.</p>
) : (
<div className="divide-y rounded-lg ring-1 ring-foreground/10">
{tokens.map((t) => (
<TokenRow key={t.id} token={t} />
))}
</div>
)}
</CardContent>
</Card>
);
}
function NewTokenForm({ onCreated }: { onCreated: (t: { name: string; token: string }) => void }) {
const router = useRouter();
const [name, setName] = useState("");
const [scopes, setScopes] = useState<TokenScope[]>(["models:read"]);
const [busy, setBusy] = useState(false);
async function create(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
try {
const res = await fetch("/api/api-tokens", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name, scopes }) });
const json = await res.json().catch(() => ({}));
if (!res.ok) return toast.error(json.error?.message ?? `Could not create the token (${res.status})`);
onCreated({ name: name.trim().toLowerCase(), token: json.token });
setName("");
router.refresh();
} finally {
setBusy(false);
}
}
return (
<form onSubmit={create} className="flex flex-col gap-3 rounded-lg border border-dashed px-4 py-3">
<div className="flex items-center gap-2">
<Input
value={name}
maxLength={40}
disabled={busy}
onChange={(e) => setName(e.target.value.toLowerCase().replace(/[^a-z0-9._-]/g, ""))}
placeholder="Name, e.g. hermes"
aria-label="Token name"
className="max-w-56"
/>
<Button type="submit" size="sm" disabled={busy || !name || scopes.length === 0}>
<PlusIcon />
Create token
</Button>
</div>
<div className="flex flex-col gap-1.5">
{TOKEN_SCOPES.map((s) => (
<label key={s} className="flex cursor-pointer items-start gap-2 text-sm">
<Checkbox checked={scopes.includes(s)} onCheckedChange={(v) => setScopes((cur) => (v ? [...cur, s] : cur.filter((x) => x !== s)))} className="mt-0.5" />
<span className="flex flex-col">
<code className="font-mono text-xs">{s}</code>
<span className="text-xs text-muted-foreground">{SCOPE_LABEL[s]}</span>
</span>
</label>
))}
</div>
<p className="text-xs text-muted-foreground">The name is shown as &ldquo;requested by&rdquo; on everything the token asks for.</p>
</form>
);
}
function TokenRow({ token }: { token: ApiTokenRow }) {
const router = useRouter();
const revoked = !!token.revokedAt;
async function act(method: "POST" | "DELETE") {
const res = await fetch(`/api/api-tokens/${token.id}`, { method });
const json = await res.json().catch(() => ({}));
if (!res.ok) toast.error(json.error?.message ?? `Failed (${res.status})`);
else toast.success(method === "POST" ? `Token "${token.name}" revoked` : `Token "${token.name}" deleted`);
router.refresh();
}
return (
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2.5">
<BotIcon className="size-4 shrink-0 text-muted-foreground" />
<span className="text-sm font-medium">{token.name}</span>
<code className="font-mono text-xs text-muted-foreground">{token.prefix}…</code>
<span className="flex flex-wrap gap-1">
{token.scopes.map((s) => (
<Badge key={s} variant="outline" className="font-mono text-[10px]">
{s}
</Badge>
))}
</span>
{revoked && <Badge variant="destructive">revoked</Badge>}
<span className="ml-auto text-xs text-muted-foreground">
{token.lastUsedAt ? (
<>
used <LocalTime value={token.lastUsedAt} />
</>
) : (
"never used"
)}
</span>
<AlertDialog>
<AlertDialogTrigger render={<Button variant="ghost" size="sm" />}>{revoked ? <Trash2Icon /> : "Revoke"}</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{revoked ? "Delete" : "Revoke"} token &ldquo;{token.name}&rdquo;?
</AlertDialogTitle>
<AlertDialogDescription>
{revoked
? "The entry goes away and the name can be used again. Models it requested keep their “requested by” label."
: "It stops working immediately. Downloads it already requested are not affected."}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction variant="destructive" onClick={() => act(revoked ? "DELETE" : "POST")}>
{revoked ? "Delete" : "Revoke"}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
@@ -0,0 +1,267 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "sonner";
import { LocalTime } from "@/components/local-time";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { NativeSelect } from "@/components/ui/native-select";
import type { HardwareOverrides, HostHardware } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
import { formatLink, onOff } from "@/lib/hardware";
type GpuForm = { name: string; vramMb: string; linkCurrent: string; linkMax: string; rebar: "" | "on" | "off" };
const toForm = (o: NonNullable<HardwareOverrides["gpus"]>[string] | undefined): GpuForm => ({
name: o?.name ?? "",
vramMb: o?.vramMb != null ? String(o.vramMb) : "",
linkCurrent: o?.linkCurrent ?? "",
linkMax: o?.linkMax ?? "",
rebar: o?.rebar == null ? "" : o.rebar ? "on" : "off",
});
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
/** What Kaname detected on the Docker host, with manual values for what it can't see. */
export function HardwareSettings({
detected,
overrides,
summary,
dockerConnected,
}: {
detected: HostHardware | null;
overrides: HardwareOverrides;
summary: string[];
dockerConnected: boolean;
}) {
const router = useRouter();
const [gpus, setGpus] = useState<Record<string, GpuForm>>(() => Object.fromEntries((detected?.gpus ?? []).map((g) => [g.pciAddress, toForm(overrides.gpus?.[g.pciAddress])])));
const [p2p, setP2p] = useState(overrides.p2p ?? "");
const [storage, setStorage] = useState(overrides.storage ?? "");
const [hypervisor, setHypervisor] = useState(overrides.hypervisor ?? "");
const [passthrough, setPassthrough] = useState(overrides.gpuPassthrough == null ? "" : overrides.gpuPassthrough ? "yes" : "no");
const [gpuDriver, setGpuDriver] = useState(overrides.gpuDriver ?? "");
const [busy, setBusy] = useState(false);
const setGpu = (addr: string, patch: Partial<GpuForm>) => setGpus((g) => ({ ...g, [addr]: { ...g[addr], ...patch } }));
async function save() {
setBusy(true);
try {
const body: HardwareOverrides = {
gpus: Object.fromEntries(
Object.entries(gpus).map(([addr, g]) => [
addr,
{
name: g.name || undefined,
vramMb: g.vramMb ? Number(g.vramMb) : undefined,
linkCurrent: g.linkCurrent || undefined,
linkMax: g.linkMax || undefined,
rebar: g.rebar ? g.rebar === "on" : undefined,
},
]),
),
p2p: (p2p || undefined) as HardwareOverrides["p2p"],
storage: storage || undefined,
hypervisor: hypervisor || undefined,
gpuPassthrough: passthrough ? passthrough === "yes" : undefined,
gpuDriver: gpuDriver || undefined,
};
const res = await fetch("/api/settings/hardware", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
const out = await res.json().catch(() => ({}));
if (!res.ok) return void toast.error(out.error?.message ?? `Could not save (${res.status})`);
toast.success("Saved; new benchmark runs use these values");
router.refresh();
} finally {
setBusy(false);
}
}
if (!detected) {
return (
<Card>
<CardHeader>
<CardTitle>Hardware</CardTitle>
<CardDescription>
{dockerConnected ? "The worker hasn't reported its hardware yet (it checks every few minutes)." : "Hardware is detected by the worker once Docker is connected (Settings → Runtimes)."}
</CardDescription>
</CardHeader>
</Card>
);
}
const v = detected.virtualization;
return (
<form
className="flex flex-col gap-4"
onSubmit={(e) => {
e.preventDefault();
void save();
}}
>
<Card>
<CardHeader>
<CardTitle>GPUs</CardTitle>
<CardDescription>
Recorded with every benchmark run. Detected from sysfs as the worker sees it; in a VM the PCIe link is the one the VM sees, which may not be the physical
slot. Fill in a field to replace the detected value (empty = detected).
</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
{detected.gpus.length === 0 && <p className="text-sm text-muted-foreground">No NVIDIA, Intel or AMD GPU found.</p>}
{detected.gpus.map((g) => {
const f = gpus[g.pciAddress];
return (
<div key={g.pciAddress} className="flex flex-col gap-3 rounded-lg border p-3">
<div className="text-sm">
<span className="font-medium">{g.name ?? "Unknown GPU"}</span>
<span className="text-muted-foreground">
{" "}
· {g.pciAddress} · {g.driver ?? "no driver"}
{g.driverVersion ? ` ${g.driverVersion}` : ""}
</span>
</div>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
<Field id={`n-${g.pciAddress}`} label="Name" detected={g.name} value={f.name} onChange={(x) => setGpu(g.pciAddress, { name: x })} />
<Field
id={`v-${g.pciAddress}`}
label="VRAM (MiB)"
detected={g.vramMb != null ? String(g.vramMb) : null}
value={f.vramMb}
onChange={(x) => setGpu(g.pciAddress, { vramMb: x.replace(/\D/g, "") })}
/>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`r-${g.pciAddress}`}>ReBAR</Label>
<NativeSelect id={`r-${g.pciAddress}`} value={f.rebar} onChange={(e) => setGpu(g.pciAddress, { rebar: e.target.value as GpuForm["rebar"] })}>
<option value="">Detected: {onOff(g.rebar)}</option>
<option value="on">on</option>
<option value="off">off</option>
</NativeSelect>
<p className="text-xs text-muted-foreground">Largest BAR {g.barMb != null ? formatBytes(g.barMb * 2 ** 20) : "unknown"}</p>
</div>
<Field
id={`lc-${g.pciAddress}`}
label="PCIe link (current)"
detected={formatLink(g.linkCurrent)}
value={f.linkCurrent}
placeholderHint="e.g. Gen4 x8"
onChange={(x) => setGpu(g.pciAddress, { linkCurrent: x })}
/>
<Field
id={`lm-${g.pciAddress}`}
label="PCIe link (maximum)"
detected={formatLink(g.linkMax)}
value={f.linkMax}
placeholderHint="e.g. Gen5 x16"
onChange={(x) => setGpu(g.pciAddress, { linkMax: x })}
/>
</div>
</div>
);
})}
{detected.gpus.length > 1 && (
<div className="flex max-w-xs flex-col gap-1.5">
<Label htmlFor="hw-p2p">Peer-to-peer between GPUs</Label>
<NativeSelect id="hw-p2p" value={p2p} onChange={(e) => setP2p(e.target.value as typeof p2p)}>
<option value="">Detected: {detected.p2p ?? "unknown"}</option>
<option value="on">on</option>
<option value="partial">partial</option>
<option value="off">off</option>
</NativeSelect>
</div>
)}
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>System</CardTitle>
<CardDescription>Part of the system summary recorded with each run, passed to BetterBench and shown in the launch80 preview.</CardDescription>
</CardHeader>
<CardContent className="flex flex-col gap-4">
<div className="grid gap-3 sm:grid-cols-2">
<Field
id="hw-storage"
label="Models disk"
detected={detected.storage ? [detected.storage.model, detected.storage.kind && STORAGE_KIND[detected.storage.kind]].filter(Boolean).join(", ") : null}
value={storage}
onChange={setStorage}
/>
<Field
id="hw-virt"
label="Virtualization"
detected={v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}` : "bare metal"}
value={hypervisor}
placeholderHint="e.g. Proxmox VE 9 (KVM)"
onChange={setHypervisor}
/>
<div className="flex flex-col gap-1.5">
<Label htmlFor="hw-pt">GPU passthrough</Label>
<NativeSelect id="hw-pt" value={passthrough} onChange={(e) => setPassthrough(e.target.value)}>
<option value="">Detected: {v.vm ? (detected.gpus.length ? "yes" : "no") : v.vm === false ? "no (bare metal)" : "unknown"}</option>
<option value="yes">yes</option>
<option value="no">no</option>
</NativeSelect>
</div>
<Field
id="hw-driver"
label="GPU driver"
detected={[...new Set(detected.gpus.map((g) => [g.driver, g.driverVersion].filter(Boolean).join(" ")))].join(", ") || null}
value={gpuDriver}
placeholderHint="e.g. xe, compute runtime 25.35"
onChange={setGpuDriver}
/>
</div>
<div>
<Button type="submit" disabled={busy}>
Save
</Button>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>System summary</CardTitle>
<CardDescription>
Exactly what runs record and publish (after saving). Never the hostname, IP addresses, users or paths. Checked <LocalTime value={detected.checkedAt} />.
</CardDescription>
</CardHeader>
<CardContent>
<ul className="flex flex-col gap-1 text-sm">
{summary.map((l) => (
<li key={l}>{l}</li>
))}
</ul>
</CardContent>
</Card>
</form>
);
}
function Field({
id,
label,
detected,
value,
onChange,
placeholderHint,
}: {
id: string;
label: string;
detected: string | null;
value: string;
onChange: (v: string) => void;
placeholderHint?: string;
}) {
return (
<div className="flex flex-col gap-1.5">
<Label htmlFor={id}>{label}</Label>
<Input id={id} value={value} onChange={(e) => onChange(e.target.value)} placeholder={detected ?? placeholderHint ?? "unknown"} maxLength={120} />
<p className="text-xs text-muted-foreground">Detected: {detected ?? "unknown"}</p>
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { Metadata } from "next";
import { kanameVersion } from "@/lib/benchmark-snapshot";
import { applyOverrides, systemSummary, systemSummaryLines } from "@/lib/hardware";
import { getDockerInfo } from "@/lib/runtimes";
import { getHardwareOverrides } from "@/lib/settings";
import { HardwareSettings } from "./hardware-settings";
export const dynamic = "force-dynamic";
export const metadata: Metadata = { title: "Hardware · Settings" };
export default async function HardwareSettingsPage() {
const [docker, overrides] = await Promise.all([getDockerInfo(), getHardwareOverrides()]);
const hardware = docker?.hardware ?? null;
const effective = applyOverrides(hardware, overrides);
return (
<HardwareSettings
detected={hardware}
overrides={overrides}
summary={systemSummaryLines(systemSummary(effective, docker?.os ?? null, kanameVersion()))}
dockerConnected={!!docker?.connected}
/>
);
}
+4 -2
View File
@@ -1,4 +1,4 @@
import { BoxesIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { BotIcon, BoxesIcon, CpuIcon, DownloadIcon, KeyRoundIcon, TagIcon, TagsIcon } from "lucide-react";
import { SettingsNav } from "./settings-nav";
const SECTIONS = [
@@ -6,7 +6,9 @@ const SECTIONS = [
{ href: "/settings/tags", label: "Tags", icon: <TagsIcon className="size-4" /> },
{ href: "/settings/downloads", label: "Downloads", icon: <DownloadIcon className="size-4" /> },
{ href: "/settings/runtimes", label: "Runtimes", icon: <BoxesIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "API keys", icon: <KeyRoundIcon className="size-4" /> },
{ href: "/settings/hardware", label: "Hardware", icon: <CpuIcon className="size-4" /> },
{ href: "/settings/api-keys", label: "Runtime API keys", icon: <KeyRoundIcon className="size-4" /> },
{ href: "/settings/api-tokens", label: "API tokens", icon: <BotIcon className="size-4" /> },
];
export default function SettingsLayout({ children }: LayoutProps<"/settings">) {
@@ -37,6 +37,7 @@ export function RuntimeForm({
const [accelerator, setAccelerator] = useState<RuntimeAccelerator>(initial.accelerator ?? "cpu");
const [image, setImage] = useState(initial.image);
const [description, setDescription] = useState(initial.description ?? "");
const [engineName, setEngineName] = useState(initial.engineName ?? "");
const [envText, setEnvText] = useState(formatEnvLines(initial.env ?? {}));
const [argRows, setArgRows] = useState(() => argsToRows(initial.extraArgs ?? []));
const [devicesText, setDevicesText] = useState((initial.devices ?? []).join(", "));
@@ -55,6 +56,7 @@ export function RuntimeForm({
accelerator,
image,
description,
engineName,
env: parseEnvLines(envText),
extraArgs: rowsToArgs(argRows),
devices: devicesText.split(/[,\s]+/),
@@ -151,6 +153,12 @@ export function RuntimeForm({
<Input id="rt-desc" value={description} onChange={(e) => setDescription(e.target.value)} maxLength={2000} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-engine-name">Engine name</Label>
<Input id="rt-engine-name" value={engineName} onChange={(e) => setEngineName(e.target.value)} maxLength={60} placeholder={engine} spellCheck={false} />
<p className="text-xs text-muted-foreground">For forks: recorded with every benchmark next to the version the server reports, e.g. vllm-radiance.</p>
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor="rt-env">Environment</Label>
<textarea
@@ -66,6 +66,7 @@ const toInput = (r: Runtime): RuntimeInput => ({
accelerator: r.accelerator,
image: r.image,
description: r.description,
engineName: r.engineName,
env: r.env,
extraArgs: r.extraArgs,
devices: r.devices,
@@ -279,6 +280,12 @@ function ImageState({ r }: { r: Runtime }) {
· built <LocalTime value={r.imageCreated} />
</span>
)}
{r.imageDigest && (
<span className="font-mono text-muted-foreground" title={r.imageDigest}>
{" "}
· {r.imageDigest.slice(0, 19)}…
</span>
)}
</span>
);
}
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { deleteToken, revokeToken, TokenError } from "@/lib/api-tokens";
/** Revoke a token: it stops working immediately. */
export const POST = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
try {
await revokeToken((await params).id);
return NextResponse.json({ ok: true });
} catch (err) {
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
throw err;
}
});
/** Delete a revoked token (frees its name). */
export const DELETE = withAuth<RouteContext<"/api/api-tokens/[id]">>(async (_req, { params }) => {
try {
await deleteToken((await params).id);
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+23
View File
@@ -0,0 +1,23 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { createToken, listTokens, TokenError } from "@/lib/api-tokens";
export const dynamic = "force-dynamic";
/** API tokens for machine clients (Settings → API tokens). Never includes the tokens themselves. */
export const GET = withAuth(async () => NextResponse.json(await listTokens()));
const Body = z.object({ name: z.string().max(40), scopes: z.array(z.string()).min(1).max(10) });
/** Create a token. The response is the only time the token is shown. */
export const POST = withAuth(async (req) => {
try {
const body = Body.parse(await req.json());
return NextResponse.json(await createToken(body.name, body.scopes), { status: 201, headers: { "Cache-Control": "no-store" } });
} catch (err) {
if (err instanceof TokenError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+4 -4
View File
@@ -2,7 +2,7 @@ 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";
import { BenchmarkError, DESCRIPTION_MAX, deleteBenchmark, getBenchmark, updateBenchmark } from "@/lib/benchmarks";
export const dynamic = "force-dynamic";
@@ -11,12 +11,12 @@ export const GET = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (_req, {
return run ? NextResponse.json(run) : apiError(404, "not_found", "Benchmark not found.");
});
const Patch = z.object({ label: z.string().max(120).nullable() });
const Patch = z.object({ label: z.string().max(120).nullable().optional(), description: z.string().max(DESCRIPTION_MAX).nullable().optional() });
/** Rename (label) a run. */
/** Rename (label) a run or change its description. */
export const PATCH = withAuth<RouteContext<"/api/benchmarks/[id]">>(async (req, { params }) => {
try {
await updateBenchmarkLabel((await params).id, Patch.parse(await req.json()).label);
await updateBenchmark((await params).id, Patch.parse(await req.json()));
return new NextResponse(null, { status: 204 });
} catch (err) {
if (err instanceof BenchmarkError) return apiError(err.status, err.code, err.message);
+17
View File
@@ -0,0 +1,17 @@
import { NextResponse } from "next/server";
import { approveJob } from "@/lib/agent-downloads";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError } from "@/lib/jobs";
/** Let a download requested through the API start. */
export const POST = withAuth<RouteContext<"/api/jobs/[id]/approve">>(async (_req, { params }) => {
const { id } = await params;
try {
await approveJob(id);
return NextResponse.json({ ok: true });
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+16
View File
@@ -0,0 +1,16 @@
import { NextResponse } from "next/server";
import { rejectJob } from "@/lib/agent-downloads";
import { withAuth } from "@/lib/api-auth";
import { apiError } from "@/lib/api-errors";
import { JobError } from "@/lib/jobs";
/** Turn down a download requested through the API (a model only it added leaves the library). */
export const POST = withAuth<RouteContext<"/api/jobs/[id]/reject">>(async (_req, { params }) => {
const { id } = await params;
try {
return NextResponse.json(await rejectJob(id));
} catch (err) {
if (err instanceof JobError) return apiError(err.status, err.code, err.message);
throw err;
}
});
+30
View File
@@ -0,0 +1,30 @@
import { NextResponse } from "next/server";
import { z } from "zod";
import { APPROVAL_MODES } from "@/lib/agent-guardrails";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getGuardrails, saveGuardrails, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Guardrails for downloads requested through the API. */
export const GET = withAuth(async () => NextResponse.json(await getGuardrails()));
const Body = z
.object({
approvalMode: z.enum(APPROVAL_MODES),
maxRequestBytes: z.number(),
minFreeBytes: z.number(),
maxOpenJobs: z.number().int(),
allowedAuthors: z.array(z.string()).max(100),
})
.partial();
export const PUT = withAuth(async (req) => {
try {
return NextResponse.json(await saveGuardrails(Body.parse(await req.json())));
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+18
View File
@@ -0,0 +1,18 @@
import { NextResponse } from "next/server";
import { withAuth } from "@/lib/api-auth";
import { apiError, handleApiError } from "@/lib/api-errors";
import { getHardwareOverrides, saveHardwareOverrides, SettingsError } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Manual hardware values for benchmark records (Settings → Hardware). */
export const GET = withAuth(async () => NextResponse.json(await getHardwareOverrides()));
export const PUT = withAuth(async (req) => {
try {
return NextResponse.json(await saveHardwareOverrides(await req.json()));
} catch (err) {
if (err instanceof SettingsError) return apiError(err.status, err.code, err.message);
return handleApiError(err);
}
});
+34
View File
@@ -0,0 +1,34 @@
import { reservedBytes } from "@/lib/agent-downloads";
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Json } from "@/lib/api-v1";
import { getGuardrails } from "@/lib/settings";
import { getWorkerStatus } from "@/lib/worker-status";
export const dynamic = "force-dynamic";
/**
* Space on the models folder (reported by the worker every few seconds), what open downloads
* still need, and how much an agent request may use before hitting the minimum-free guardrail.
*/
export const GET = withToken("models:read", async () => {
try {
const [w, reserved, g] = await Promise.all([getWorkerStatus(), reservedBytes(), getGuardrails()]);
const free = w.online ? w.modelsDirFreeBytes : null;
const total = w.online ? w.modelsDirTotalBytes : null;
const available = free == null ? null : Math.max(0, free - reserved - g.minFreeBytes);
return v1Json({
workerOnline: w.online,
freeBytes: free,
totalBytes: total,
usedBytes: free != null && total != null ? total - free : null,
reservedBytes: reserved,
minFreeBytes: g.minFreeBytes,
availableForRequestsBytes: available,
free: size(free),
total: size(total),
availableForRequests: size(available),
});
} catch (err) {
return v1Catch(err);
}
});
+45
View File
@@ -0,0 +1,45 @@
import { z } from "zod";
import { requestDownload } from "@/lib/agent-downloads";
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Json } from "@/lib/api-v1";
import { REPO_ID_RE, SHA_RE } from "@/lib/hub/client";
export const dynamic = "force-dynamic";
const Body = z
.object({
repoId: z.string().trim().regex(REPO_ID_RE, 'must be "org/name"'),
sha: z.string().trim().regex(SHA_RE, "must be the full 40-character commit SHA from GET /api/v1/hub/lookup"),
revision: z.string().trim().min(1).max(255).optional(),
quant: z.string().trim().min(1).max(64).optional(),
include: z.array(z.string().trim().min(1).max(1024)).min(1).max(100).optional(),
tags: z.array(z.string()).max(20).optional(),
})
.strict()
.refine((b) => !!b.quant !== !!b.include, { message: 'pass exactly one of "quant" (e.g. "Q4_K_M") or "include" (globs)' });
/**
* Request a download, within the guardrails. 201: queued or waiting for approval; 200: the same
* repo + commit + files was requested before, nothing new was queued.
*/
export const POST = withToken("downloads:create", async (req, { token }) => {
try {
const body = Body.parse(await req.json());
const r = await requestDownload(token, body);
return v1Json(
{
created: r.created,
modelId: r.modelId,
jobId: r.jobId,
state: r.state,
requestedBytes: r.requestedBytes,
requestedSize: size(r.requestedBytes),
files: r.files,
message: r.message.replace("{jobId}", r.jobId ?? "{jobId}"),
},
r.created ? 201 : 200,
);
} catch (err) {
return v1Catch(err);
}
});
+47
View File
@@ -0,0 +1,47 @@
import { eq } from "drizzle-orm";
import { quantSummary } from "@/lib/agent-selection";
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
import { db } from "@/lib/db/client";
import { models } from "@/lib/db/schema";
import { lookupRepo, normalizeRepoInput } from "@/lib/hub/lookup";
export const dynamic = "force-dynamic";
/** Files listed inline up to this count; more with ?files=all. */
const FILE_LIMIT = 200;
/**
* Resolve a Hub repo (+ revision, default main) to its commit SHA, with the quants and files and
* their sizes: what a download request needs. The same lookup the Add model dialog uses.
*/
export const GET = withToken("models:read", async (req) => {
try {
const url = new URL(req.url);
const repo = url.searchParams.get("repo")?.trim();
if (!repo) return v1Error(400, "invalid_request", 'Pass the repo as ?repo=org/name, e.g. ?repo=unsloth/Qwen3-8B-GGUF.');
const { repoId, revision: urlRevision } = normalizeRepoInput(repo);
const revision = url.searchParams.get("revision")?.trim() || urlRevision || "main";
const r = await lookupRepo(repoId, revision);
const all = url.searchParams.get("files") === "all";
const model = r.existingModelId
? await db().query.models.findFirst({ columns: { id: true, pinnedSha: true, status: true }, where: eq(models.id, r.existingModelId) })
: null;
return v1Json({
repoId: r.repoId,
revision: r.revision,
sha: r.sha,
gated: r.gated,
lastModified: r.lastModified,
inLibrary: model ? { modelId: model.id, pinnedSha: model.pinnedSha, status: model.status } : null,
quants: quantSummary(r.files).map((q) => ({ ...q, size: size(q.bytes) })),
fileCount: r.files.length,
totalBytes: r.files.reduce((s, f) => s + f.size, 0),
files: (all ? r.files : r.files.slice(0, FILE_LIMIT)).map((f) => ({ path: f.path, bytes: f.size })),
filesTruncated: !all && r.files.length > FILE_LIMIT,
next: 'POST /api/v1/downloads with {"repoId", "sha", "quant"} (or "include": [globs]).',
});
} catch (err) {
return v1Catch(err);
}
});
+58
View File
@@ -0,0 +1,58 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
import { getJob, listJobFiles, listJobLogs } from "@/lib/jobs";
export const dynamic = "force-dynamic";
const MAX_LOG = 200;
const NEXT: Record<string, string> = {
pending_approval: "Waiting for the user to approve it. Don't retry; check again in a few minutes.",
queued: "Waiting for a free download slot.",
downloading: "Downloading; check again in a minute.",
verifying: "Checking the downloaded files.",
completed: "Done.",
failed: "Failed; see error. Tell the user; retrying the same request returns this job.",
cancelled: "Cancelled or rejected by the user. Don't request it again unless the user asks.",
interrupted: "Interrupted by a Kaname restart; the user can resume it.",
};
/** Job state with per-file progress. The hf log only with ?log=N (last N lines, max 200). */
export const GET = withToken<RouteContext<"/api/v1/jobs/[id]">>("models:read", async (req, { params }) => {
try {
const id = (await params).id;
const job = await getJob(id);
if (!job) return v1Error(404, "not_found", "No job with this id.");
const n = Math.min(MAX_LOG, Math.max(0, Number(new URL(req.url).searchParams.get("log")) || 0));
const files = await listJobFiles(id);
const log = n > 0 ? (await listJobLogs(id, 0, n)).map((l) => `${new Date(l.ts).toISOString()} [${l.stream}] ${l.line}`) : undefined;
return v1Json({
id: job.id,
modelId: job.modelId,
repoId: job.repoId,
kind: job.kind,
purpose: job.purpose,
state: job.state,
cancelRequested: job.cancelRequested,
requestedBy: job.requestedBy,
progress: {
doneBytes: job.doneBytes,
totalBytes: job.totalBytes,
percent: job.totalBytes > 0 ? Math.round((job.doneBytes / job.totalBytes) * 1000) / 10 : 0,
done: size(job.doneBytes),
total: size(job.totalBytes),
speedBytesPerSecond: job.speedBps,
etaSeconds: job.etaSeconds,
},
error: job.errorCode || job.errorMessage ? { code: job.errorCode, message: job.errorMessage } : null,
files: files.map((f) => ({ path: f.path, state: f.state, doneBytes: f.doneBytes, totalBytes: f.expectedBytes })),
createdAt: new Date(job.createdAt).toISOString(),
startedAt: job.startedAt ? new Date(job.startedAt).toISOString() : null,
finishedAt: job.finishedAt ? new Date(job.finishedAt).toISOString() : null,
next: NEXT[job.state] ?? null,
...(log ? { log } : {}),
});
} catch (err) {
return v1Catch(err);
}
});
+34
View File
@@ -0,0 +1,34 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Catch, v1Error, v1Json } from "@/lib/api-v1";
import { listModelJobs } from "@/lib/jobs";
import { getModel } from "@/lib/library";
export const dynamic = "force-dynamic";
/** One model: status, pinned commit, selected files and its latest job. */
export const GET = withToken<RouteContext<"/api/v1/models/[id]">>("models:read", async (_req, { params }) => {
try {
const data = await getModel((await params).id);
if (!data) return v1Error(404, "not_found", "No model with this id. List models with GET /api/v1/models.");
const { model, files } = data;
const selected = files.filter((f) => f.selected);
const onDisk = selected.filter((f) => f.state === "present" || f.state === "verified").reduce((s, f) => s + f.size, 0);
const [job] = await listModelJobs(model.id, 1);
return v1Json({
id: model.id,
repoId: model.repoId,
status: model.status,
trackedRevision: model.trackedRevision,
pinnedSha: model.pinnedSha,
requestedBy: model.requestedBy,
onDiskBytes: onDisk,
onDisk: size(onDisk),
files: selected.map((f) => ({ path: f.path, bytes: f.size, state: f.state })),
latestJob: job ? { id: job.id, kind: job.kind, state: job.state, requestedBy: job.requestedBy } : null,
createdAt: model.createdAt.toISOString(),
downloadedAt: model.downloadedAt?.toISOString() ?? null,
});
} catch (err) {
return v1Catch(err);
}
});
+61
View File
@@ -0,0 +1,61 @@
import { withToken } from "@/lib/api-tokens";
import { parseModelFilters } from "@/lib/api-v1-filters";
import { size, v1Catch, v1Json } from "@/lib/api-v1";
import { listLibrary } from "@/lib/library";
import { matchesFilters, matchesQuery, type SearchableModel } from "@/lib/search";
export const dynamic = "force-dynamic";
/**
* The local library, filtered like the library page: ?q= (all terms must match) and facets
* author, family, quant, tag, status, requested_by (repeat or comma-separate values).
* Status values: pending, downloading, ready, incomplete, failed, deleting, pending_approval,
* update_available, repo_missing, commit_missing.
*/
export const GET = withToken("models:read", async (req) => {
try {
const { query, filters } = parseModelFilters(new URL(req.url).searchParams);
const rows = await listLibrary();
const out = rows
.filter((r) => {
const m: SearchableModel = {
repoId: r.repoId,
author: r.author,
families: r.families,
baseModels: r.baseModels,
architecture: r.architecture,
quants: r.quants,
tags: r.tags.map((t) => t.name),
hubTags: r.hubTags,
pipelineTag: r.pipelineTag,
license: r.license,
status: r.status,
hubStatus: r.hubState && r.hubState !== "available" ? r.hubState : r.updateAvailable ? "update_available" : null,
requestedBy: r.requestedBy,
pendingApproval: r.pendingApproval,
};
return matchesQuery(m, query) && matchesFilters(m, filters);
})
.map((r) => ({
id: r.id,
repoId: r.repoId,
status: r.status,
pendingApproval: r.pendingApproval,
pinnedSha: r.pinnedSha,
quants: r.quants,
tags: r.tags.map((t) => t.name),
selectedFiles: r.fileCount,
selectedBytes: r.totalBytes,
onDiskBytes: r.presentBytes,
onDisk: size(r.presentBytes),
updateAvailable: r.updateAvailable,
hubState: r.hubState,
requestedBy: r.requestedBy,
createdAt: r.createdAt.toISOString(),
downloadedAt: r.downloadedAt?.toISOString() ?? null,
}));
return v1Json({ count: out.length, models: out });
} catch (err) {
return v1Catch(err);
}
});
+30
View File
@@ -0,0 +1,30 @@
import { withToken } from "@/lib/api-tokens";
import { size, v1Json } from "@/lib/api-v1";
import { getGuardrails } from "@/lib/settings";
export const dynamic = "force-dynamic";
/** Who am I, what may I do, and within which limits. Any valid token. */
export const GET = withToken(null, async (_req, { token }) => {
const g = await getGuardrails();
return v1Json({
token: { name: token.name, scopes: token.scopes },
guardrails: {
approvalMode: g.approvalMode,
maxRequestBytes: g.maxRequestBytes,
maxRequestSize: size(g.maxRequestBytes),
minFreeBytes: g.minFreeBytes,
minFreeSize: size(g.minFreeBytes),
maxOpenAgentJobs: g.maxOpenJobs,
allowedAuthors: g.allowedAuthors,
},
endpoints: [
"GET /api/v1/hub/lookup?repo=org/name[&revision=main][&files=all]",
"GET /api/v1/models[?q=&author=&family=&quant=&tag=&status=&requested_by=]",
"GET /api/v1/models/{id}",
"POST /api/v1/downloads {repoId, sha, quant | include[], tags?, revision?}",
"GET /api/v1/jobs/{id}[?log=50]",
"GET /api/v1/disk",
],
});
});
+56
View File
@@ -0,0 +1,56 @@
"use client";
import { BotIcon, CheckIcon, XIcon } from "lucide-react";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { approveJob, rejectJob } from "@/components/job-actions";
import { Button } from "@/components/ui/button";
import { formatBytes } from "@/lib/format";
/** A download requested through the API that waits for approval: who asked, how much, approve/reject. */
export function ApprovalBar({ job, onRemoved }: { job: { id: string; requestedBy: string | null; totalBytes: number; purpose: string | null }; onRemoved?: () => void }) {
const router = useRouter();
const [busy, setBusy] = useState(false);
async function run(fn: () => Promise<unknown>) {
setBusy(true);
try {
await fn();
router.refresh();
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-col gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2.5 text-sm">
<p className="flex items-center gap-1.5">
<BotIcon className="size-4 shrink-0 text-amber-700 dark:text-amber-300" />
<span>
<strong>{job.requestedBy ?? "An API token"}</strong> asks to download {formatBytes(job.totalBytes)}
{job.purpose === "add" ? " of additional files" : ""}. It starts once you approve it.
</span>
</p>
<div className="flex gap-2">
<Button size="sm" disabled={busy} onClick={() => run(() => approveJob(job.id))}>
<CheckIcon />
Approve
</Button>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() =>
run(async () => {
const r = await rejectJob(job.id);
if (r?.removedModel) onRemoved?.();
})
}
>
<XIcon />
Reject
</Button>
</div>
</div>
);
}
+7 -4
View File
@@ -2,6 +2,8 @@ import type { ResourceStats } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
const cores = (v: number | null) => (v == null ? "—" : v.toFixed(v >= 10 ? 0 : 1));
const mib = (v: number | null | undefined) => (v == null ? "—" : formatBytes(v * 2 ** 20));
const round = (v: number | null | undefined, unit: string) => (v == null ? "—" : `${Math.round(v)}${unit}`);
function Cell({ label, value, note }: { label: string; value: string; note?: string }) {
return (
@@ -42,10 +44,11 @@ export function BenchmarkResources({ stats, names }: { stats: ResourceStats; nam
<span className="text-xs font-medium">
GPU {g.index} · {g.name}
</span>
<div className="grid gap-2 sm:grid-cols-3">
<Cell label="VRAM, peak" value={formatBytes(g.vramPeakMb * 2 ** 20)} note={`of ${formatBytes(g.vramTotalMb * 2 ** 20)} · average ${formatBytes(g.vramAvgMb * 2 ** 20)}`} />
<Cell label="Utilization" value={`${Math.round(g.utilAvg)}%`} note={`average · peak ${Math.round(g.utilPeak)}%`} />
<Cell label="Power" value={g.powerAvgW != null ? `${Math.round(g.powerAvgW)} W` : "—"} note={g.powerPeakW != null ? `average · peak ${Math.round(g.powerPeakW)} W` : undefined} />
<div className="grid gap-2 sm:grid-cols-2 lg:grid-cols-4">
<Cell label="VRAM, peak" value={mib(g.vramPeakMb)} note={`of ${mib(g.vramTotalMb)} · average ${mib(g.vramAvgMb)}`} />
<Cell label="Utilization" value={round(g.utilAvg, "%")} note={g.utilPeak != null ? `average · peak ${round(g.utilPeak, "%")}` : "not reported"} />
<Cell label="Power" value={round(g.powerAvgW, " W")} note={g.powerPeakW != null ? `average · peak ${round(g.powerPeakW, " W")}` : "not reported"} />
<Cell label="Temperature" value={round(g.tempAvgC, " °C")} note={g.tempPeakC != null ? `average · peak ${round(g.tempPeakC, " °C")}` : "not reported"} />
</div>
</div>
))}
+18
View File
@@ -31,3 +31,21 @@ export async function startUpdate(modelId: string): Promise<boolean> {
if (ok) toast.success("Update queued");
return ok;
}
export async function approveJob(jobId: string): Promise<boolean> {
const ok = await post(`/api/jobs/${jobId}/approve`);
if (ok) toast.success("Approved; the download is queued");
return ok;
}
/** Returns whether the model left the library (it was only added by this request), or null on error. */
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean } | null> {
const res = await fetch(`/api/jobs/${jobId}/reject`, { method: "POST" });
const body = await res.json().catch(() => ({}));
if (!res.ok) {
toast.error(body.error?.message ?? `Request failed (${res.status})`);
return null;
}
toast.info(body.removedModel ? "Rejected; the model was removed from the library" : "Rejected");
return body;
}
+7 -1
View File
@@ -4,6 +4,7 @@ import { formatBytes, formatDuration, formatSpeed, percent } from "@/lib/format"
import type { JobSnapshot } from "@/lib/jobs";
const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "outline"> = {
pending_approval: "outline",
queued: "outline",
downloading: "secondary",
verifying: "secondary",
@@ -14,7 +15,12 @@ const STATE_VARIANT: Record<string, "default" | "secondary" | "destructive" | "o
};
export function JobStateBadge({ job }: { job: Pick<JobSnapshot, "state" | "cancelRequested"> }) {
const label = job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state) ? "cancelling" : job.state;
const label =
job.cancelRequested && !["cancelled", "completed", "failed"].includes(job.state)
? "cancelling"
: job.state === "pending_approval"
? "awaiting approval"
: job.state;
return <Badge variant={STATE_VARIANT[job.state] ?? "outline"}>{label}</Badge>;
}
+14
View File
@@ -0,0 +1,14 @@
import { BotIcon } from "lucide-react";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
/** "requested by hermes": added or downloaded through the API with that token. */
export function RequestedByBadge({ name, className }: { name: string | null | undefined; className?: string }) {
if (!name) return null;
return (
<Badge variant="outline" className={cn("gap-1 font-normal", className)} title={`Requested through the API with the token "${name}"`}>
<BotIcon className="size-3" />
{name}
</Badge>
);
}
+52
View File
@@ -0,0 +1,52 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { metaRows } from "@/lib/benchmark-meta";
import type { RunMeta, SystemSummary } from "@/lib/db/schema";
import { systemSummaryLines } from "@/lib/hardware";
/** Hardware, runtime and model a run measured (A and B side by side for an A/B), plus the system summary. */
export function RunMetaCard({ meta, metaB, system }: { meta: RunMeta | null; metaB?: RunMeta | null; system: SystemSummary | null }) {
if (!meta && !system) return null;
const a = meta ? metaRows(meta) : [];
const b = metaB ? metaRows(metaB) : null;
const keys = [...new Set([...a, ...(b ?? [])].map((r) => r.key))];
const label = (k: string) => (a.find((r) => r.key === k) ?? b?.find((r) => r.key === k))!.label;
const value = (rows: typeof a | null, k: string) => rows?.find((r) => r.key === k)?.value ?? "–";
return (
<Card size="sm">
<CardHeader>
<CardTitle>Hardware &amp; runtime</CardTitle>
</CardHeader>
<CardContent className="flex flex-col gap-3">
{meta && (
<dl className={`grid gap-x-4 gap-y-1 text-xs ${b ? "grid-cols-[max-content_1fr_1fr]" : "grid-cols-[max-content_1fr]"}`}>
{b && (
<>
<span />
<span className="font-medium">A</span>
<span className="font-medium">B</span>
</>
)}
{keys.map((k) => (
<div key={k} className="contents">
<dt className="text-muted-foreground">{label(k)}</dt>
<dd className="min-w-0 font-mono break-all">{value(a, k)}</dd>
{b && <dd className="min-w-0 font-mono break-all">{value(b, k)}</dd>}
</div>
))}
</dl>
)}
{meta && meta.overridden.length > 0 && <p className="text-[11px] text-muted-foreground">From Settings → Hardware: {meta.overridden.join(", ")}.</p>}
{system && (
<div className="flex flex-col gap-1">
<span className="text-xs text-muted-foreground">System</span>
<ul className="flex flex-col gap-0.5 text-xs">
{systemSummaryLines(system).map((l) => (
<li key={l}>{l}</li>
))}
</ul>
</div>
)}
</CardContent>
</Card>
);
}
+10 -2
View File
@@ -1,6 +1,6 @@
"use client";
import { BoxesIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import { BotIcon, BoxesIcon, CpuIcon, KeyRoundIcon, LogOutIcon, MonitorIcon, MoonIcon, SunIcon, TagIcon, TagsIcon } from "lucide-react";
import Link from "next/link";
import { useTheme } from "next-themes";
import { useTransition } from "react";
@@ -71,9 +71,17 @@ export function UserMenu({ user, signOutAction }: { user: MenuUser; signOutActio
<BoxesIcon />
Runtimes
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/hardware" />}>
<CpuIcon />
Hardware
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-keys" />}>
<KeyRoundIcon />
API keys
Runtime API keys
</DropdownMenuItem>
<DropdownMenuItem render={<Link href="/settings/api-tokens" />}>
<BotIcon />
API tokens
</DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
+180
View File
@@ -0,0 +1,180 @@
import "server-only";
import { and, eq, inArray, isNotNull, ne, sql } from "drizzle-orm";
import { checkAuthor, checkGuardrails, type Guardrails } from "@/lib/agent-guardrails";
import { newPaths, resolveRequestPaths } from "@/lib/agent-selection";
import type { TokenIdentity } from "@/lib/api-tokens";
import { db } from "@/lib/db/client";
import { jobs, modelFiles, models } from "@/lib/db/schema";
import { lookupRepo } from "@/lib/hub/lookup";
import { JobError, OPEN_STATES, queueDownload } from "@/lib/jobs";
import { purgeModelRows } from "@/lib/model-purge";
import { addFilesToModel, addModel, ModelError, restoreSelection } from "@/lib/models";
import { escapeGlob } from "@/lib/selection";
import { getGuardrails, getRecommendedRoles } from "@/lib/settings";
import { addTag, normalizeTagName } from "@/lib/tags";
import { getWorkerStatus } from "@/lib/worker-status";
export type DownloadRequest = {
repoId: string;
sha: string;
/** Branch to track for update checks (default "main"). */
revision?: string;
quant?: string;
include?: string[];
tags?: string[];
};
export type DownloadOutcome = {
/** false: the same repo + commit + files was requested before; nothing new was queued. */
created: boolean;
modelId: string;
jobId: string | null;
state: string;
requestedBytes: number;
files: string[];
message: string;
};
/** Bytes that open download jobs still have to fetch (pending approval included). */
export async function reservedBytes(): Promise<number> {
const [r] = await db()
.select({ n: sql<number>`coalesce(sum(${jobs.totalBytes} - ${jobs.doneBytes}), 0)` })
.from(jobs)
.where(and(eq(jobs.kind, "download"), inArray(jobs.state, [...OPEN_STATES])));
return Number(r.n);
}
/** API-requested jobs that are pending approval, queued or running (all tokens). */
export async function openAgentJobs(): Promise<number> {
const [r] = await db()
.select({ n: sql<number>`count(*)` })
.from(jobs)
.where(and(isNotNull(jobs.requestedByTokenId), inArray(jobs.state, [...OPEN_STATES])));
return Number(r.n);
}
function stateMessage(state: string, created: boolean): string {
if (state === "pending_approval") {
return `${created ? "Requested" : "Already requested"}; waiting for the user to approve it in Kaname. Do not retry: check GET /api/v1/jobs/{jobId} every few minutes.`;
}
if (state === "queued" || state === "downloading" || state === "verifying") return `${created ? "Queued" : "Already queued"}; poll GET /api/v1/jobs/{jobId} for progress.`;
if (state === "completed") return "Already downloaded.";
return `The last download ended as "${state}"; ask the user to retry it in Kaname.`;
}
/** Latest job of a model, for answers to repeated requests. */
async function latestJob(modelId: string) {
return db().query.jobs.findFirst({ columns: { id: true, state: true }, where: eq(jobs.modelId, modelId), orderBy: (j, { desc }) => desc(j.createdAt) });
}
/**
* A download requested through the API. Checks the author allowlist, resolves the files at the
* pinned commit, applies the guardrails, then uses the same addModel / addFilesToModel / queue path
* as the UI. Repeating a request returns what exists instead of queueing a duplicate.
*/
export async function requestDownload(token: TokenIdentity, req: DownloadRequest, guardrails?: Guardrails): Promise<DownloadOutcome> {
const g = guardrails ?? (await getGuardrails());
// The allowlist first, before anything goes to the Hub.
checkAuthor(g, req.repoId);
(req.tags ?? []).forEach(normalizeTagName); // validate before anything is written
const hub = await lookupRepo(req.repoId, req.sha);
const paths = resolveRequestPaths(hub.files, req, await getRecommendedRoles());
const size = new Map(hub.files.map((f) => [f.path, f.size]));
const requestedBy = { tokenId: token.id, name: token.name };
const pendingApproval = g.approvalMode === "approve";
const existing = await db().query.models.findFirst({ where: sql`lower(${models.repoId}) = lower(${hub.repoId})` });
if (existing && existing.pinnedSha !== hub.sha) {
throw new ModelError(
"already_exists",
`${existing.repoId} is already in the library, pinned to commit ${existing.pinnedSha}; you asked for ${hub.sha}. Updating a model is done by the user in Kaname, not through the API.`,
409,
);
}
let add = paths;
if (existing) {
const selected = await db().select({ path: modelFiles.path }).from(modelFiles).where(and(eq(modelFiles.modelId, existing.id), eq(modelFiles.selected, true)));
add = newPaths(paths, selected.map((f) => f.path));
if (add.length === 0) {
const job = await latestJob(existing.id);
const state = job?.state ?? existing.status;
return { created: false, modelId: existing.id, jobId: job?.id ?? null, state, requestedBytes: 0, files: paths, message: stateMessage(state, false) };
}
const open = await db().query.jobs.findFirst({ columns: { id: true, state: true }, where: and(eq(jobs.modelId, existing.id), inArray(jobs.state, [...OPEN_STATES])) });
if (open) {
throw new JobError("busy", `${existing.repoId} has a download that is still ${open.state.replace("_", " ")} (job ${open.id}). Request the other files once it has finished.`, 409);
}
}
const requestBytes = add.reduce((s, p) => s + (size.get(p) ?? 0), 0);
const worker = await getWorkerStatus();
checkGuardrails(g, {
repoId: hub.repoId,
requestBytes,
freeBytes: worker.online ? worker.modelsDirFreeBytes : null,
reservedBytes: await reservedBytes(),
openAgentJobs: await openAgentJobs(),
});
let modelId: string;
let jobId: string;
if (existing) {
modelId = existing.id;
({ jobId } = await addFilesToModel(existing.id, add, { pendingApproval, requestedBy }));
} else {
({ id: modelId } = await addModel({
repoId: hub.repoId,
revision: req.revision?.trim() || "main",
sha: hub.sha,
rule: { include: paths.map(escapeGlob), exclude: [] },
requestedBy,
}));
({ jobId } = await queueDownload(modelId, "initial", { pendingApproval, requestedBy }));
}
for (const tag of req.tags ?? []) await addTag(modelId, tag);
const state = pendingApproval ? "pending_approval" : "queued";
return { created: true, modelId, jobId, state, requestedBytes: requestBytes, files: paths, message: stateMessage(state, true) };
}
async function pendingJob(jobId: string) {
const job = await db().query.jobs.findFirst({ where: eq(jobs.id, jobId) });
if (!job) throw new JobError("not_found", "Job not found.", 404);
if (job.state !== "pending_approval") throw new JobError("not_cancellable", `This job doesn't wait for approval (it is ${job.state}).`, 409);
return job;
}
/** Let an API-requested download start. */
export async function approveJob(jobId: string): Promise<void> {
const job = await pendingJob(jobId);
const d = db();
await d.batch([
d.update(jobs).set({ state: "queued" }).where(and(eq(jobs.id, job.id), eq(jobs.state, "pending_approval"))),
d.update(models).set({ status: "downloading" }).where(eq(models.id, job.modelId)),
]);
}
/**
* Turn an API-requested download down. A new model that was only added by this request leaves the
* library again; for added files, the model's previous selection is restored.
*/
export async function rejectJob(jobId: string): Promise<{ removedModel: boolean }> {
const job = await pendingJob(jobId);
await db()
.update(jobs)
.set({ state: "cancelled", finishedAt: new Date(), errorMessage: "Rejected by the user." })
.where(eq(jobs.id, job.id));
if (job.purpose === "initial") {
// Only this request ever touched the model: nothing on disk, so it leaves the library again.
const [{ n }] = await db().select({ n: sql<number>`count(*)` }).from(jobs).where(and(eq(jobs.modelId, job.modelId), ne(jobs.id, job.id)));
if (Number(n) === 0) {
await purgeModelRows(job.modelId);
return { removedModel: true };
}
}
// A pending job never changed the model's status, so only the selection needs restoring.
if (job.result?.previousRule) await restoreSelection(job.modelId, job.result.previousRule);
return { removedModel: false };
}
+133
View File
@@ -0,0 +1,133 @@
// Guardrails for downloads requested through the API (an autonomous agent, not a person in the
// UI). Pure: settings parsing and the checks themselves; the request flow is in agent-downloads.ts.
export const APPROVAL_MODES = ["approve", "auto"] as const;
export type ApprovalMode = (typeof APPROVAL_MODES)[number];
export type Guardrails = {
/** approve: requests wait as "pending approval" until someone confirms them in the UI. */
approvalMode: ApprovalMode;
/** Largest download one request may add. */
maxRequestBytes: number;
/** Free space that must remain on the models folder after the download. */
minFreeBytes: number;
/** API-requested jobs that may be pending approval, queued or running at once (all tokens). */
maxOpenJobs: number;
/** Hub authors (orgs/users) the API may download from; empty = any. Case-insensitive. */
allowedAuthors: string[];
};
const GB = 1_000_000_000;
export const DEFAULT_GUARDRAILS: Guardrails = {
approvalMode: "approve",
maxRequestBytes: 60 * GB,
minFreeBytes: 100 * GB,
maxOpenJobs: 2,
allowedAuthors: [],
};
export class GuardrailError extends Error {
constructor(
public code: "too_large" | "disk_space" | "disk_unknown" | "too_many_jobs" | "author_not_allowed",
message: string,
public status = 422,
) {
super(message);
}
}
const AUTHOR_RE = /^[A-Za-z0-9][\w.-]{0,95}$/;
/** Stored value merged over the defaults; anything invalid falls back to the default. */
export function parseGuardrails(v: unknown): Guardrails {
const o = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
const num = (x: unknown, min: number, def: number) => (typeof x === "number" && Number.isFinite(x) && x >= min ? Math.round(x) : def);
return {
approvalMode: APPROVAL_MODES.includes(o.approvalMode as ApprovalMode) ? (o.approvalMode as ApprovalMode) : DEFAULT_GUARDRAILS.approvalMode,
maxRequestBytes: num(o.maxRequestBytes, 1, DEFAULT_GUARDRAILS.maxRequestBytes),
minFreeBytes: num(o.minFreeBytes, 0, DEFAULT_GUARDRAILS.minFreeBytes),
maxOpenJobs: num(o.maxOpenJobs, 1, DEFAULT_GUARDRAILS.maxOpenJobs),
allowedAuthors: Array.isArray(o.allowedAuthors) ? o.allowedAuthors.filter((a): a is string => typeof a === "string" && AUTHOR_RE.test(a)) : [],
};
}
/** "unsloth, ggml-org Qwen" → ["unsloth", "ggml-org", "Qwen"]; throws on an invalid name. */
export function parseAuthorList(text: string): string[] {
const out: string[] = [];
for (const a of text.split(/[\s,]+/).filter(Boolean)) {
if (!AUTHOR_RE.test(a)) throw new Error(`"${a}" is not a valid Hugging Face user or organization name.`);
if (!out.some((x) => x.toLowerCase() === a.toLowerCase())) out.push(a);
}
return out;
}
/** Plain GB (10^9), as the Hub and the settings use: "74.2 GB". */
export function gb(bytes: number): string {
return `${(bytes / GB).toFixed(1)} GB`;
}
export type GuardrailInput = {
repoId: string;
/** Bytes this request would download. */
requestBytes: number;
/** Free bytes on the models folder (worker heartbeat), or null if unknown. */
freeBytes: number | null;
/** Bytes other open jobs still have to download. */
reservedBytes: number;
/** API-requested jobs that are pending approval, queued or running right now. */
openAgentJobs: number;
};
/** The author allowlist alone (checked before anything goes to the Hub). */
export function checkAuthor(g: Guardrails, repoId: string): void {
const author = repoId.split("/")[0];
if (g.allowedAuthors.length > 0 && !g.allowedAuthors.some((a) => a.toLowerCase() === author.toLowerCase())) {
throw new GuardrailError(
"author_not_allowed",
`author "${author}" is not on the allowlist (${g.allowedAuthors.join(", ")}). Pick a repo from one of these authors, or ask the user to extend the allowlist.`,
403,
);
}
}
/** Throws a GuardrailError with a message an agent can act on; returns normally if allowed. */
export function checkGuardrails(g: Guardrails, x: GuardrailInput): void {
checkAuthor(g, x.repoId);
if (x.requestBytes > g.maxRequestBytes) {
throw new GuardrailError(
"too_large",
`exceeds max size per request ${gb(g.maxRequestBytes)}: requested ${gb(x.requestBytes)}. Pick a smaller quant or fewer files.`,
);
}
if (x.openAgentJobs >= g.maxOpenJobs) {
throw new GuardrailError(
"too_many_jobs",
`too many agent downloads at once: ${x.openAgentJobs} pending or running, the limit is ${g.maxOpenJobs}. Wait until one has finished (or been approved and finished) before requesting another.`,
429,
);
}
if (x.freeBytes == null) {
throw new GuardrailError("disk_unknown", "free disk space is unknown (the Kaname worker is offline). Try again later.", 503);
}
const after = x.freeBytes - x.reservedBytes - x.requestBytes;
if (after < g.minFreeBytes) {
throw new GuardrailError(
"disk_space",
`not enough disk space: ${gb(x.requestBytes)} requested, ${gb(x.freeBytes)} free` +
(x.reservedBytes > 0 ? ` (${gb(x.reservedBytes)} of it reserved by other downloads)` : "") +
`, and at least ${gb(g.minFreeBytes)} must stay free (${gb(Math.max(0, after))} would be left). Pick a smaller quant or ask the user to free space.`,
507,
);
}
}
export function describeGuardrails(g: Guardrails): string {
return [
g.approvalMode === "approve" ? "requests wait for approval" : "downloads start immediately",
`max ${gb(g.maxRequestBytes)} per request`,
`${gb(g.minFreeBytes)} must stay free`,
`max ${g.maxOpenJobs} agent jobs at once`,
g.allowedAuthors.length ? `authors: ${g.allowedAuthors.join(", ")}` : "any author",
].join(" · ");
}
+62
View File
@@ -0,0 +1,62 @@
// Which files an API download request means, from a quant name or include globs, the same way the
// Add model dialog picks them. Pure.
import { fileRole, type FileRole } from "@/lib/file-roles";
import { recommendFiles } from "@/lib/recommend";
import { matchesAny, quantGroup } from "@/lib/selection";
type File = { path: string; size: number };
export class SelectionError extends Error {
code = "empty_selection";
status = 400;
}
/** Quant group of a model-weight file (not mmproj/MTP/imatrix), e.g. "Q4_K_M", "UD-Q4_K_XL". */
function weightQuant(path: string): string | null {
return fileRole(path) === "model" ? quantGroup(path) : null;
}
/** Quants in a repo (model weights only) with file count and total size, in file order. */
export function quantSummary(files: File[]): { quant: string; files: number; bytes: number }[] {
const out = new Map<string, { quant: string; files: number; bytes: number }>();
for (const f of files) {
const q = weightQuant(f.path);
if (!q) continue;
const e = out.get(q) ?? { quant: q, files: 0, bytes: 0 };
e.files++;
e.bytes += f.size;
out.set(q, e);
}
return [...out.values()];
}
/**
* Paths for a request: the weight files of `quant` (all split parts) plus the companion files of the
* recommended kinds (Settings → Downloads), or every file matching one of the `include` globs.
*/
export function resolveRequestPaths(files: File[], req: { quant?: string; include?: string[] }, recommendedRoles: FileRole[]): string[] {
if (req.quant) {
const want = req.quant.trim().toLowerCase();
const weights = files.filter((f) => weightQuant(f.path)?.toLowerCase() === want).map((f) => f.path);
if (weights.length === 0) {
const available = quantSummary(files).map((q) => q.quant);
throw new SelectionError(
available.length
? `quant "${req.quant}" not found in this repo. Available: ${available.join(", ")}.`
: `quant "${req.quant}" not found: this repo has no GGUF quants. Use "include" globs instead (e.g. ["*.safetensors", "*.json"]).`,
);
}
return [...new Set([...weights, ...recommendFiles(files, weights, recommendedRoles)])].sort();
}
const globs = req.include ?? [];
const paths = files.filter((f) => matchesAny(f.path, globs)).map((f) => f.path);
if (paths.length === 0) throw new SelectionError(`no file in this repo matches ${JSON.stringify(globs)}. Look up the repo to see its files.`);
return paths.sort();
}
/** Files a request adds to what's already selected, for size checks and idempotency. */
export function newPaths(requested: string[], selected: Iterable<string>): string[] {
const have = new Set(selected);
return requested.filter((p) => !have.has(p));
}
+192
View File
@@ -0,0 +1,192 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, it } from "node:test";
import { checkAuthor, checkGuardrails, DEFAULT_GUARDRAILS, type GuardrailError, type GuardrailInput, parseAuthorList, parseGuardrails } from "./agent-guardrails";
import { newPaths, quantSummary, resolveRequestPaths } from "./agent-selection";
import { bearerToken, generateToken, hashToken, isScope } from "./api-token-core";
import { parseModelFilters } from "./api-v1-filters";
import { EMPTY_FILTERS, facetValues, matchesFilters, type SearchableModel } from "./search";
const GB = 1e9;
describe("API tokens", () => {
it("generates kn_ tokens whose hash and prefix match", () => {
const t = generateToken();
assert.match(t.token, /^kn_[A-Za-z0-9_-]{43}$/);
assert.equal(t.hash, hashToken(t.token));
assert.ok(t.token.startsWith(t.prefix));
assert.notEqual(generateToken().token, t.token);
});
it("reads only well-formed bearer headers", () => {
const { token } = generateToken();
assert.equal(bearerToken(`Bearer ${token}`), token);
assert.equal(bearerToken(`bearer ${token} `), token);
assert.equal(bearerToken(token), null);
assert.equal(bearerToken("Bearer kn_short"), null);
assert.equal(bearerToken("Basic abc"), null);
assert.equal(bearerToken(null), null);
});
it("knows the scopes", () => {
assert.ok(isScope("models:read"));
assert.ok(isScope("downloads:create"));
assert.ok(!isScope("models:delete"));
assert.ok(!isScope("settings:write"));
});
});
describe("guardrails", () => {
const ok: GuardrailInput = { repoId: "unsloth/Qwen3-8B-GGUF", requestBytes: 5 * GB, freeBytes: 500 * GB, reservedBytes: 0, openAgentJobs: 0 };
const rejects = (g: Partial<typeof DEFAULT_GUARDRAILS>, x: Partial<GuardrailInput>, code: GuardrailError["code"], message: RegExp) =>
assert.throws(
() => checkGuardrails({ ...DEFAULT_GUARDRAILS, ...g }, { ...ok, ...x }),
(err: GuardrailError) => err.code === code && message.test(err.message),
);
it("defaults: approve, 60 GB, 100 GB free, 2 jobs, any author", () => {
assert.deepEqual(parseGuardrails(null), DEFAULT_GUARDRAILS);
assert.equal(DEFAULT_GUARDRAILS.approvalMode, "approve");
assert.equal(DEFAULT_GUARDRAILS.maxRequestBytes, 60 * GB);
assert.equal(DEFAULT_GUARDRAILS.minFreeBytes, 100 * GB);
assert.equal(DEFAULT_GUARDRAILS.maxOpenJobs, 2);
assert.deepEqual(DEFAULT_GUARDRAILS.allowedAuthors, []);
});
it("falls back to defaults for invalid stored values", () => {
const g = parseGuardrails({ approvalMode: "yolo", maxRequestBytes: -1, minFreeBytes: "x", maxOpenJobs: 0, allowedAuthors: ["ok", "../bad"] });
assert.equal(g.approvalMode, "approve");
assert.equal(g.maxRequestBytes, DEFAULT_GUARDRAILS.maxRequestBytes);
assert.equal(g.minFreeBytes, DEFAULT_GUARDRAILS.minFreeBytes);
assert.equal(g.maxOpenJobs, DEFAULT_GUARDRAILS.maxOpenJobs);
assert.deepEqual(g.allowedAuthors, ["ok"]);
});
it("passes a request within all limits", () => {
checkGuardrails(DEFAULT_GUARDRAILS, ok);
});
it("rejects requests over the max size, with both sizes in the message", () => {
rejects({}, { requestBytes: 74.2 * GB }, "too_large", /exceeds max size per request 60\.0 GB: requested 74\.2 GB/);
});
it("rejects when the minimum free space would not remain", () => {
rejects({}, { requestBytes: 20 * GB, freeBytes: 110 * GB }, "disk_space", /at least 100\.0 GB must stay free/);
});
it("counts space reserved by other open downloads", () => {
checkGuardrails(DEFAULT_GUARDRAILS, { ...ok, requestBytes: 20 * GB, freeBytes: 130 * GB });
rejects({}, { requestBytes: 20 * GB, freeBytes: 130 * GB, reservedBytes: 20 * GB }, "disk_space", /20\.0 GB of it reserved/);
});
it("rejects when free space is unknown (worker offline)", () => {
rejects({}, { freeBytes: null }, "disk_unknown", /worker is offline/);
});
it("rejects when too many agent jobs are open", () => {
rejects({}, { openAgentJobs: 2 }, "too_many_jobs", /2 pending or running, the limit is 2/);
checkGuardrails({ ...DEFAULT_GUARDRAILS, maxOpenJobs: 3 }, { ...ok, openAgentJobs: 2 });
});
it("enforces the author allowlist case-insensitively", () => {
const g = { allowedAuthors: ["unsloth", "ggml-org"] };
checkAuthor({ ...DEFAULT_GUARDRAILS, ...g }, "Unsloth/x");
rejects(g, { repoId: "TheBloke/x-GGUF" }, "author_not_allowed", /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
});
it("parses the allowlist text", () => {
assert.deepEqual(parseAuthorList("unsloth, ggml-org Qwen,unsloth"), ["unsloth", "ggml-org", "Qwen"]);
assert.deepEqual(parseAuthorList(" "), []);
assert.throws(() => parseAuthorList("ok, ../x"), /not a valid/);
});
});
describe("request file selection", () => {
const files = [
{ path: "Qwen3-8B-Q4_K_M.gguf", size: 5 * GB },
{ path: "Qwen3-8B-Q8_0.gguf", size: 8.7 * GB },
{ path: "mmproj-F16.gguf", size: 0.6 * GB },
{ path: "BF16/Qwen3-8B-BF16-00001-of-00002.gguf", size: 8 * GB },
{ path: "BF16/Qwen3-8B-BF16-00002-of-00002.gguf", size: 8 * GB },
{ path: "README.md", size: 1000 },
];
it("summarizes quants (weights only, split parts together)", () => {
assert.deepEqual(
quantSummary(files).map((q) => [q.quant, q.files]),
[
["Q4_K_M", 1],
["Q8_0", 1],
["BF16", 2],
],
);
});
it("resolves a quant to its weights plus recommended companions", () => {
assert.deepEqual(resolveRequestPaths(files, { quant: "q4_k_m" }, ["vision"]), ["Qwen3-8B-Q4_K_M.gguf", "mmproj-F16.gguf"]);
assert.deepEqual(resolveRequestPaths(files, { quant: "Q4_K_M" }, []), ["Qwen3-8B-Q4_K_M.gguf"]);
assert.deepEqual(resolveRequestPaths(files, { quant: "BF16" }, []), ["BF16/Qwen3-8B-BF16-00001-of-00002.gguf", "BF16/Qwen3-8B-BF16-00002-of-00002.gguf"]);
});
it("explains a missing quant with the available ones", () => {
assert.throws(() => resolveRequestPaths(files, { quant: "Q2_K" }, []), /quant "Q2_K" not found in this repo\. Available: .*Q4_K_M/);
assert.throws(() => resolveRequestPaths([{ path: "model.safetensors", size: 1 }], { quant: "Q4_K_M" }, []), /no GGUF quants\. Use "include"/);
});
it("resolves include globs and rejects ones that match nothing", () => {
assert.deepEqual(resolveRequestPaths(files, { include: ["*Q8_0*", "README.md"] }, []), ["Qwen3-8B-Q8_0.gguf", "README.md"]);
assert.throws(() => resolveRequestPaths(files, { include: ["*.safetensors"] }, []), /no file in this repo matches/);
});
it("finds what a request adds to the selection", () => {
assert.deepEqual(newPaths(["a", "b", "c"], ["b"]), ["a", "c"]);
assert.deepEqual(newPaths(["a"], ["a", "b"]), []);
});
});
describe("GET /api/v1/models filters", () => {
it("reads repeated and comma-separated values, requested_by → requester", () => {
const { query, filters } = parseModelFilters(new URLSearchParams("q=qwen 8b&author=unsloth,bartowski&quant=Q4_K_M&quant=Q8_0&requested_by=hermes&status=pending_approval"));
assert.equal(query, "qwen 8b");
assert.deepEqual(filters, { ...EMPTY_FILTERS, author: ["unsloth", "bartowski"], quant: ["Q4_K_M", "Q8_0"], requester: ["hermes"], status: ["pending_approval"] });
});
it("filters by requester and pending approval like the library", () => {
const m: SearchableModel = {
repoId: "unsloth/Qwen3-8B-GGUF",
author: "unsloth",
families: ["Qwen"],
baseModels: [],
architecture: null,
quants: ["Q4_K_M"],
tags: [],
hubTags: [],
pipelineTag: null,
license: null,
status: "pending",
hubStatus: null,
requestedBy: "hermes",
pendingApproval: true,
};
assert.deepEqual(facetValues(m, "status"), ["pending", "pending_approval"]);
assert.ok(matchesFilters(m, { ...EMPTY_FILTERS, requester: ["Hermes"] }));
assert.ok(!matchesFilters({ ...m, requestedBy: null }, { ...EMPTY_FILTERS, requester: ["hermes"] }));
});
});
describe("proxy", () => {
// The OIDC gate must skip exactly /api/v1 (bearer tokens), nothing that merely starts like it.
const src = readFileSync(new URL("../proxy.ts", import.meta.url), "utf8");
const matcher = JSON.parse(`"${src.match(/matcher: \["([^"]+)"\]/)![1]}"`) as string;
const gated = (path: string) => new RegExp(`^${matcher}$`).test(path);
it("leaves /api/v1 to token auth and gates everything else", () => {
assert.ok(!gated("/api/v1"));
assert.ok(!gated("/api/v1/models"));
assert.ok(!gated("/api/v1/jobs/01ABC"));
assert.ok(gated("/api/v1x"));
assert.ok(gated("/api/models"));
assert.ok(gated("/api/api-tokens"));
assert.ok(gated("/settings/api-tokens"));
});
});
+32
View File
@@ -0,0 +1,32 @@
// API token format, hashing and scope checks. Pure (no DB), shared by the server code and tests.
import { createHash, randomBytes } from "node:crypto";
import { TOKEN_SCOPES, type TokenScope } from "@/lib/db/schema";
/** "kn_" + 32 random bytes as base64url (43 chars). */
export const TOKEN_PREFIX = "kn_";
const TOKEN_RE = /^kn_[A-Za-z0-9_-]{43}$/;
/** Characters of the token kept for display ("kn_AbCd…"). */
const DISPLAY_CHARS = 7;
export const TOKEN_NAME_RE = /^[a-z0-9][a-z0-9._-]{0,39}$/;
export function generateToken(): { token: string; prefix: string; hash: string } {
const token = TOKEN_PREFIX + randomBytes(32).toString("base64url");
return { token, prefix: token.slice(0, DISPLAY_CHARS), hash: hashToken(token) };
}
/** SHA-256 is enough: the tokens are 256 random bits, not passwords that need a slow hash. */
export function hashToken(token: string): string {
return createHash("sha256").update(token).digest("hex");
}
/** The token from an `Authorization: Bearer …` header, or null if it's missing or malformed. */
export function bearerToken(header: string | null): string | null {
const m = header?.match(/^Bearer\s+(\S+)\s*$/i);
return m && TOKEN_RE.test(m[1]) ? m[1] : null;
}
export function isScope(v: unknown): v is TokenScope {
return typeof v === "string" && (TOKEN_SCOPES as readonly string[]).includes(v);
}
+98
View File
@@ -0,0 +1,98 @@
import "server-only";
import { and, desc, eq, isNotNull, isNull } from "drizzle-orm";
import { NextResponse } from "next/server";
import { bearerToken, generateToken, hashToken, isScope, TOKEN_NAME_RE } from "@/lib/api-token-core";
import { db } from "@/lib/db/client";
import { apiTokens, type TokenScope } from "@/lib/db/schema";
export class TokenError extends Error {
constructor(
public code: "invalid" | "exists" | "not_found",
message: string,
public status = 400,
) {
super(message);
}
}
export type ApiTokenRow = Omit<typeof apiTokens.$inferSelect, "hash">;
/** lastUsedAt is written at most this often per token, not on every request. */
const TOUCH_MS = 60_000;
export async function listTokens(): Promise<ApiTokenRow[]> {
return db()
.select({
id: apiTokens.id,
name: apiTokens.name,
prefix: apiTokens.prefix,
scopes: apiTokens.scopes,
lastUsedAt: apiTokens.lastUsedAt,
revokedAt: apiTokens.revokedAt,
createdAt: apiTokens.createdAt,
})
.from(apiTokens)
.orderBy(desc(apiTokens.createdAt));
}
/** Create a token; the plain token is returned only here and never stored. */
export async function createToken(name: string, scopes: string[]): Promise<{ id: string; token: string }> {
const n = name.trim().toLowerCase();
if (!TOKEN_NAME_RE.test(n)) throw new TokenError("invalid", "Name: 1–40 characters, lowercase letters, digits, . _ - (e.g. hermes).");
const s = [...new Set(scopes)];
if (s.length === 0 || !s.every(isScope)) throw new TokenError("invalid", "Pick at least one valid scope.");
if (await db().query.apiTokens.findFirst({ columns: { id: true }, where: eq(apiTokens.name, n) })) {
throw new TokenError("exists", `A token named "${n}" already exists. Delete it first or pick another name.`, 409);
}
const t = generateToken();
const [row] = await db().insert(apiTokens).values({ name: n, prefix: t.prefix, hash: t.hash, scopes: s as TokenScope[] }).returning({ id: apiTokens.id });
return { id: row.id, token: t.token };
}
export async function revokeToken(id: string): Promise<void> {
const res = await db().update(apiTokens).set({ revokedAt: new Date() }).where(and(eq(apiTokens.id, id), isNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
if (res.length === 0) throw new TokenError("not_found", "Token not found or already revoked.", 404);
}
/** Only revoked tokens can be deleted (frees the name; "requested by" labels keep it). */
export async function deleteToken(id: string): Promise<void> {
const res = await db().delete(apiTokens).where(and(eq(apiTokens.id, id), isNotNull(apiTokens.revokedAt))).returning({ id: apiTokens.id });
if (res.length === 0) throw new TokenError("not_found", "Revoke the token before deleting it.", 409);
}
export type TokenIdentity = { id: string; name: string; scopes: TokenScope[] };
/** The active token behind a request's bearer header, or null. */
export async function tokenFromRequest(req: Request): Promise<TokenIdentity | null> {
const token = bearerToken(req.headers.get("authorization"));
if (!token) return null;
const row = await db().query.apiTokens.findFirst({ where: and(eq(apiTokens.hash, hashToken(token)), isNull(apiTokens.revokedAt)) });
if (!row) return null;
if (!row.lastUsedAt || Date.now() - row.lastUsedAt.getTime() > TOUCH_MS) {
await db().update(apiTokens).set({ lastUsedAt: new Date() }).where(eq(apiTokens.id, row.id));
}
return { id: row.id, name: row.name, scopes: row.scopes };
}
function v1Error(status: number, code: string, message: string) {
return NextResponse.json({ error: { code, message } }, { status, headers: status === 401 ? { "WWW-Authenticate": 'Bearer realm="kaname"' } : undefined });
}
type Handler<Ctx> = (req: Request, ctx: Ctx & { token: TokenIdentity }) => Promise<Response> | Response;
/**
* Wraps a /api/v1 route: requires `Authorization: Bearer <token>` with `scope` (null: any valid
* token). Login sessions don't count here; the rest of the app is OIDC-only.
*/
export function withToken<Ctx = unknown>(scope: TokenScope | null, handler: Handler<Ctx>) {
return async (req: Request, ctx: Ctx) => {
const token = await tokenFromRequest(req);
if (!token) {
return v1Error(401, "unauthorized", "Missing or invalid API token. Send it as \"Authorization: Bearer kn_…\"; tokens are created in Kaname under Settings → API tokens.");
}
if (scope && !token.scopes.includes(scope)) {
return v1Error(403, "forbidden", `This token lacks the scope "${scope}" (it has: ${token.scopes.join(", ")}). Ask the user to grant it in Settings → API tokens.`);
}
return handler(req, { ...ctx, token });
};
}
+26
View File
@@ -0,0 +1,26 @@
// Query-string filters for GET /api/v1/models, with the library's search semantics
// (terms AND-ed in `q`; OR within a facet, AND across facets). Pure.
import { EMPTY_FILTERS, type Facet, type Filters } from "@/lib/search";
/** Query parameter per facet; each may repeat or hold a comma-separated list. */
const PARAM: Record<Facet, string> = {
author: "author",
family: "family",
quant: "quant",
tag: "tag",
status: "status",
requester: "requested_by",
};
export function parseModelFilters(params: URLSearchParams): { query: string; filters: Filters } {
const filters = { ...EMPTY_FILTERS };
for (const facet of Object.keys(PARAM) as Facet[]) {
filters[facet] = params
.getAll(PARAM[facet])
.flatMap((v) => v.split(","))
.map((v) => v.trim())
.filter(Boolean);
}
return { query: params.get("q")?.trim() ?? "", filters };
}
+306
View File
@@ -0,0 +1,306 @@
// /api/v1 end to end against a temporary SQLite database and a stubbed Hugging Face API:
// token auth, scopes, every guardrail rejection, idempotency, approve/reject.
// Runs with `--conditions=react-server` (see package.json) so "server-only" modules load.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
const dir = mkdtempSync(join(tmpdir(), "kaname-api-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.MODELS_DIR = join(dir, "models");
delete process.env.HF_TOKEN;
const GB = 1e9;
const SHA = { a: "a".repeat(40), b: "b".repeat(40), c: "c".repeat(40), d: "d".repeat(40) };
/** Fake Hub: repo → commit + files. */
const REPOS: Record<string, { sha: string; files: [string, number][] }> = {
"unsloth/Test-GGUF": {
sha: SHA.a,
files: [
["Test-Q4_K_M.gguf", 5 * GB],
["Test-Q8_0.gguf", 9 * GB],
["Test-F16.gguf", 70 * GB],
["README.md", 1000],
],
},
"unsloth/Other-GGUF": { sha: SHA.b, files: [["Other-Q4_K_M.gguf", 2 * GB]] },
"ggml-org/Third-GGUF": { sha: SHA.c, files: [["Third-Q4_K_M.gguf", 3 * GB]] },
"TheBloke/Old-GGUF": { sha: SHA.d, files: [["Old-Q4_K_M.gguf", 1 * GB]] },
};
const realFetch = globalThis.fetch;
globalThis.fetch = (async (input: string | URL | Request) => {
const url = new URL(typeof input === "string" ? input : input instanceof URL ? input.href : input.url);
const m = url.pathname.match(/^\/api\/models\/([^/]+\/[^/]+)\/(revision|tree)\/([^/]+)/);
// Like the Hub: repo ids are case-insensitive, the response has the canonical one.
const id = m && Object.keys(REPOS).find((k) => k.toLowerCase() === decodeURIComponent(m[1]).toLowerCase());
const repo = id && REPOS[id];
if (!m || !id || !repo) return new Response("not found", { status: 404 });
const rev = decodeURIComponent(m[3]);
if (rev !== "main" && rev !== repo.sha) return new Response("", { status: 404, headers: { "x-error-code": "RevisionNotFound" } });
if (m[2] === "revision") return Response.json({ id, sha: repo.sha, gated: false, private: false, tags: [] });
return Response.json(repo.files.map(([path, size]) => ({ type: "file", path, size, oid: "0".repeat(40), lfs: { oid: "e".repeat(64), size } })));
}) as typeof fetch;
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
tokens: typeof import("./api-tokens");
settings: typeof import("./settings");
agent: typeof import("./agent-downloads");
v1: typeof import("../app/api/v1/route");
downloads: typeof import("../app/api/v1/downloads/route");
job: typeof import("../app/api/v1/jobs/[id]/route");
models: typeof import("../app/api/v1/models/route");
disk: typeof import("../app/api/v1/disk/route");
};
let M: Mods;
let full: string; // models:read + downloads:create
let readOnly: string;
const call = async (handler: (req: Request, ctx: never) => Promise<Response>, path: string, opts: { token?: string; body?: unknown; params?: Record<string, string> } = {}) => {
const req = new Request(`http://kaname.test${path}`, {
method: opts.body ? "POST" : "GET",
headers: { ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}), "Content-Type": "application/json" },
body: opts.body ? JSON.stringify(opts.body) : undefined,
});
const res = await handler(req, { params: Promise.resolve(opts.params ?? {}) } as never);
return { status: res.status, body: (await res.json()) as Record<string, any> }; // eslint-disable-line @typescript-eslint/no-explicit-any
};
const request = (body: unknown, token = full) => call(M.downloads.POST, "/api/v1/downloads", { token, body });
async function setFree(bytes: number) {
const { db } = M.db;
const now = new Date();
await db()
.insert(M.schema.workerState)
.values({ id: "worker", startedAt: now, heartbeatAt: now, modelsDirFreeBytes: bytes, modelsDirTotalBytes: 2000 * GB })
.onConflictDoUpdate({ target: M.schema.workerState.id, set: { heartbeatAt: now, modelsDirFreeBytes: bytes } });
}
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
tokens: await import("./api-tokens"),
settings: await import("./settings"),
agent: await import("./agent-downloads"),
v1: await import("../app/api/v1/route"),
downloads: await import("../app/api/v1/downloads/route"),
job: await import("../app/api/v1/jobs/[id]/route"),
models: await import("../app/api/v1/models/route"),
disk: await import("../app/api/v1/disk/route"),
};
full = (await M.tokens.createToken("hermes", ["models:read", "downloads:create"])).token;
readOnly = (await M.tokens.createToken("reader", ["models:read"])).token;
await setFree(500 * GB);
});
after(() => {
globalThis.fetch = realFetch;
// Close the database first; Windows can't delete an open file.
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment; a leftover temp dir is harmless.
}
});
describe("token auth", () => {
it("rejects missing, malformed and unknown tokens with 401", async () => {
assert.equal((await call(M.v1.GET, "/api/v1")).status, 401);
assert.equal((await call(M.v1.GET, "/api/v1", { token: "kn_nope" })).status, 401);
const unknown = (await import("./api-token-core")).generateToken().token;
const r = await call(M.v1.GET, "/api/v1", { token: unknown });
assert.equal(r.status, 401);
assert.match(r.body.error.message, /Settings → API tokens/);
});
it("answers with the token's name, scopes and the guardrails", async () => {
const r = await call(M.v1.GET, "/api/v1", { token: readOnly });
assert.equal(r.status, 200);
assert.deepEqual(r.body.token, { name: "reader", scopes: ["models:read"] });
assert.equal(r.body.guardrails.approvalMode, "approve");
assert.equal(r.body.guardrails.maxRequestSize, "60.0 GB");
});
it("enforces scopes with 403", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M" }, readOnly);
assert.equal(r.status, 403);
assert.match(r.body.error.message, /lacks the scope "downloads:create"/);
assert.equal((await call(M.disk.GET, "/api/v1/disk", { token: readOnly })).status, 200);
});
it("records last use and stops accepting a revoked token", async () => {
const t = await M.tokens.createToken("temp", ["models:read"]);
assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 200);
const row = (await M.tokens.listTokens()).find((x) => x.name === "temp")!;
assert.ok(row.lastUsedAt);
await M.tokens.revokeToken(t.id);
assert.equal((await call(M.v1.GET, "/api/v1", { token: t.token })).status, 401);
await M.tokens.deleteToken(t.id);
});
it("never stores the token itself", async () => {
const rows = await M.db.db().select().from(M.schema.apiTokens);
assert.ok(rows.every((r) => r.hash !== full && r.hash.length === 64 && !r.hash.startsWith("kn_")));
});
});
describe("download requests", () => {
let first: { modelId: string; jobId: string };
it("validates the body", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: "main", quant: "Q4_K_M" });
assert.equal(r.status, 400);
assert.match(r.body.error.message, /40-character commit SHA/);
assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a })).status, 400);
assert.equal((await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q2_K" })).status, 400);
});
it("creates a model and a job that waits for approval, marked with the token name", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q4_K_M", tags: ["agent"] });
assert.equal(r.status, 201);
assert.equal(r.body.state, "pending_approval");
assert.equal(r.body.requestedSize, "5.0 GB");
assert.deepEqual(r.body.files, ["Test-Q4_K_M.gguf"]);
assert.match(r.body.message, /Do not retry/);
first = { modelId: r.body.modelId, jobId: r.body.jobId };
const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}`, { token: readOnly, params: { id: first.jobId } });
assert.equal(job.body.state, "pending_approval");
assert.equal(job.body.requestedBy, "hermes");
assert.equal(job.body.log, undefined);
assert.deepEqual(job.body.files.map((f: { path: string }) => f.path), ["Test-Q4_K_M.gguf"]);
const model = await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, first.modelId) });
assert.equal(model?.requestedBy, "hermes");
assert.equal(model?.status, "pending"); // not "downloading" until approved
});
it("is idempotent: the same repo + commit + files returns the existing job", async () => {
const r = await request({ repoId: "unsloth/test-gguf", sha: SHA.a, quant: "q4_k_m" });
assert.equal(r.status, 200);
assert.equal(r.body.created, false);
assert.equal(r.body.jobId, first.jobId);
const n = await M.db.db().select().from(M.schema.jobs);
assert.equal(n.length, 1);
});
it("refuses other files while the model has an open job", async () => {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
assert.equal(r.status, 409);
assert.match(r.body.error.message, /still pending approval/);
});
it("refuses a different commit of a model in the library", async () => {
REPOS["unsloth/Test-GGUF"].sha = SHA.d;
try {
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.d, quant: "Q4_K_M" });
assert.equal(r.status, 409);
assert.match(r.body.error.message, /pinned to commit a{40}.*Updating a model is done by the user/);
} finally {
REPOS["unsloth/Test-GGUF"].sha = SHA.a;
}
});
it("rejects over the max agent jobs at once", async () => {
const second = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, quant: "Q4_K_M" });
assert.equal(second.status, 201);
const third = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(third.status, 429);
assert.equal(third.body.error.code, "too_many_jobs");
assert.match(third.body.error.message, /2 pending or running, the limit is 2/);
// Reject the second request again; the model it added leaves the library.
assert.deepEqual(await M.agent.rejectJob(second.body.jobId), { removedModel: true });
assert.equal(await M.db.db().query.models.findFirst({ where: (m, { eq }) => eq(m.id, second.body.modelId) }), undefined);
});
it("rejects requests over the max size", async () => {
await M.settings.saveGuardrails({ maxOpenJobs: 10 });
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(r.status, 201);
await M.agent.rejectJob(r.body.jobId);
await M.settings.saveGuardrails({ maxRequestBytes: 2.5 * GB });
const big = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(big.status, 422);
assert.equal(big.body.error.message, "exceeds max size per request 2.5 GB: requested 3.0 GB. Pick a smaller quant or fewer files.");
await M.settings.saveGuardrails({ maxRequestBytes: 60 * GB });
});
it("rejects when the minimum free space would not remain (counting reserved bytes)", async () => {
await setFree(107 * GB); // 5 GB reserved by the pending first request
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(r.status, 507);
assert.equal(r.body.error.code, "disk_space");
assert.match(r.body.error.message, /107\.0 GB free \(5\.0 GB of it reserved by other downloads\), and at least 100\.0 GB must stay free/);
const disk = await call(M.disk.GET, "/api/v1/disk", { token: readOnly });
assert.equal(disk.body.reservedBytes, 5 * GB);
assert.equal(disk.body.availableForRequestsBytes, 2 * GB);
await setFree(500 * GB);
});
it("rejects when the worker is offline (free space unknown)", async () => {
const { db } = M.db;
await db().update(M.schema.workerState).set({ heartbeatAt: new Date(0) });
const r = await request({ repoId: "ggml-org/Third-GGUF", sha: SHA.c, quant: "Q4_K_M" });
assert.equal(r.status, 503);
assert.equal(r.body.error.code, "disk_unknown");
await setFree(500 * GB);
});
it("rejects authors outside the allowlist before asking the Hub", async () => {
await M.settings.saveGuardrails({ allowedAuthors: ["unsloth", "ggml-org"] });
const r = await request({ repoId: "TheBloke/Old-GGUF", sha: SHA.d, quant: "Q4_K_M" });
assert.equal(r.status, 403);
assert.equal(r.body.error.code, "author_not_allowed");
assert.match(r.body.error.message, /author "TheBloke" is not on the allowlist \(unsloth, ggml-org\)/);
await M.settings.saveGuardrails({ allowedAuthors: [] });
});
it("approve queues the job; the model then shows as downloading", async () => {
await M.agent.approveJob(first.jobId);
const job = await call(M.job.GET, `/api/v1/jobs/${first.jobId}?log=5`, { token: readOnly, params: { id: first.jobId } });
assert.equal(job.body.state, "queued");
assert.ok(Array.isArray(job.body.log));
await assert.rejects(M.agent.approveJob(first.jobId), /doesn't wait for approval/);
});
it("extra files of a finished model are added; rejecting restores the selection", async () => {
const { db } = M.db;
await db().update(M.schema.jobs).set({ state: "completed", finishedAt: new Date() }).where((await import("drizzle-orm")).eq(M.schema.jobs.id, first.jobId));
const r = await request({ repoId: "unsloth/Test-GGUF", sha: SHA.a, quant: "Q8_0" });
assert.equal(r.status, 201);
assert.equal(r.body.requestedSize, "9.0 GB");
const selected = async () =>
(await db().query.modelFiles.findMany({ where: (f, { and, eq }) => and(eq(f.modelId, first.modelId), eq(f.selected, true)) })).map((f) => f.path).sort();
assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf", "Test-Q8_0.gguf"]);
assert.deepEqual(await M.agent.rejectJob(r.body.jobId), { removedModel: false });
assert.deepEqual(await selected(), ["Test-Q4_K_M.gguf"]);
});
it("auto approval queues right away", async () => {
await M.settings.saveGuardrails({ approvalMode: "auto" });
const r = await request({ repoId: "unsloth/Other-GGUF", sha: SHA.b, include: ["*.gguf"] });
assert.equal(r.status, 201);
assert.equal(r.body.state, "queued");
await M.settings.saveGuardrails({ approvalMode: "approve" });
});
it("lists models with the library filters, including requested_by", async () => {
const all = await call(M.models.GET, "/api/v1/models", { token: readOnly });
assert.equal(all.body.count, 2);
const mine = await call(M.models.GET, "/api/v1/models?requested_by=hermes&quant=Q4_K_M&author=unsloth", { token: readOnly });
assert.deepEqual(mine.body.models.map((m: { repoId: string }) => m.repoId).sort(), ["unsloth/Other-GGUF", "unsloth/Test-GGUF"]);
assert.equal(mine.body.models[0].requestedBy, "hermes");
const none = await call(M.models.GET, "/api/v1/models?requested_by=someone-else", { token: readOnly });
assert.equal(none.body.count, 0);
});
});
+49
View File
@@ -0,0 +1,49 @@
import "server-only";
import { NextResponse } from "next/server";
import { z } from "zod";
import { GuardrailError } from "@/lib/agent-guardrails";
import { SelectionError } from "@/lib/agent-selection";
import { HubError } from "@/lib/hub/client";
import { JobError } from "@/lib/jobs";
import { ModelError } from "@/lib/models";
import { TagError } from "@/lib/tags";
// Shared by the /api/v1 routes: compact JSON for an agent to read, errors as
// { error: { code, message } } with a message that says what to do next.
export function v1Json(data: unknown, status = 200) {
return NextResponse.json(data, { status, headers: { "Cache-Control": "no-store" } });
}
export function v1Error(status: number, code: string, message: string) {
return v1Json({ error: { code, message } }, status);
}
const HUB_STATUS: Partial<Record<HubError["code"], number>> = {
invalid_repo_id: 400,
repo_not_found: 404,
revision_not_found: 404,
gated_no_token: 403,
gated_no_access: 403,
rate_limited: 429,
network: 502,
};
/** Known errors → JSON; anything else is logged and becomes a generic 500 (no stack traces). */
export function v1Catch(err: unknown) {
if (err instanceof GuardrailError) return v1Error(err.status, err.code, err.message);
if (err instanceof SelectionError) return v1Error(err.status, err.code, err.message);
if (err instanceof ModelError || err instanceof JobError || err instanceof TagError) return v1Error(err.status, err.code, err.message);
if (err instanceof HubError) return v1Error(HUB_STATUS[err.code] ?? 502, err.code, err.message);
if (err instanceof z.ZodError) {
return v1Error(400, "invalid_request", err.issues.map((i) => `${i.path.join(".") || "body"}: ${i.message}`).join("; "));
}
if (err instanceof SyntaxError) return v1Error(400, "invalid_json", "The request body is not valid JSON.");
console.error("[api/v1]", err);
return v1Error(500, "internal", "Internal error in Kaname. Tell the user; retrying won't help.");
}
/** "74.2 GB" next to byte counts, so a reader doesn't have to convert. */
export function size(bytes: number | null | undefined): string | null {
return bytes == null ? null : `${(bytes / 1e9).toFixed(1)} GB`;
}
+217
View File
@@ -0,0 +1,217 @@
import assert from "node:assert/strict";
import { hostname, userInfo } from "node:os";
import { describe, it } from "node:test";
import { argValue, buildRunMeta, gpuLabel, gpusUsed, imageTag, kvCacheOf, metaNotes, metaRows, modelLabel, quantOf, withLoadLinks } from "./benchmark-meta";
import type { DeploymentOptions, HardwareGpu, HostHardware } from "./db/schema";
import { applyOverrides, formatLinkPair, linkGen, parseLinkText, rebarFrom, systemSummary, systemSummaryText, validateOverrides } from "./hardware";
const intel: HardwareGpu = {
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1",
linkCurrent: { gen: 4, width: 8 },
linkMax: { gen: 5, width: 16 },
barMb: 32768,
rebar: true,
};
const nvidia: HardwareGpu = { ...intel, vendor: "nvidia", pciAddress: "0000:05:00.0", name: "NVIDIA RTX 4090", vramMb: 24564, driver: "nvidia", driverVersion: "580.82.07", barMb: 256, rebar: false };
const hw: HostHardware = {
gpus: [intel, nvidia],
p2p: null,
cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
memoryBytes: 128e9,
kernel: "6.17.1-pve",
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 2e12 },
checkedAt: "2026-10-20T00:00:00.000Z",
};
const opts: DeploymentOptions = { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 8192, extraArgs: [], cacheTypeK: "q8_0", cacheTypeV: "q8_0", parallel: 2 };
describe("PCIe links and ReBAR", () => {
it("maps link speeds to generations and formats current vs maximum", () => {
assert.equal(linkGen("16.0 GT/s PCIe"), 4);
assert.equal(linkGen("2.5 GT/s"), 1);
assert.equal(linkGen("Unknown"), null);
assert.equal(formatLinkPair({ gen: 4, width: 8 }, { gen: 5, width: 16 }), "Gen4 x8 of Gen5 x16");
assert.equal(formatLinkPair({ gen: 5, width: 16 }, { gen: 5, width: 16 }), "Gen5 x16");
assert.equal(formatLinkPair(null, null), null);
});
it("parses typed links", () => {
assert.deepEqual(parseLinkText("Gen4 x8"), { gen: 4, width: 8 });
assert.deepEqual(parseLinkText("gen 5"), { gen: 5, width: null });
assert.deepEqual(parseLinkText("x16"), { gen: null, width: 16 });
assert.equal(parseLinkText("fast"), null);
assert.equal(parseLinkText(""), null);
});
it("calls ReBAR on when a BAR covers the VRAM", () => {
assert.equal(rebarFrom(32768, 32768), true);
assert.equal(rebarFrom(256, 24564), false);
assert.equal(rebarFrom(8192, null), true);
assert.equal(rebarFrom(256, null), null);
assert.equal(rebarFrom(null, 1024), null);
});
});
describe("hardware overrides", () => {
it("replace detected values and are listed", () => {
const e = applyOverrides(hw, { gpus: { "0000:05:00.0": { linkCurrent: "Gen3 x16", rebar: true } }, storage: "Proxmox ZFS mirror", gpuPassthrough: true })!;
assert.deepEqual(e.gpus[1].linkCurrent, { gen: 3, width: 16 });
assert.equal(e.gpus[1].rebar, true);
assert.deepEqual(e.gpus[0], intel);
assert.equal(e.storage?.model, "Proxmox ZFS mirror");
assert.equal(e.gpuPassthrough, true);
assert.deepEqual(e.overridden, ["pcie link", "rebar", "storage", "gpu passthrough"]);
});
it("derive passthrough from a VM with GPUs", () => {
assert.equal(applyOverrides(hw)!.gpuPassthrough, true);
assert.equal(applyOverrides({ ...hw, virtualization: { vm: false, hypervisor: null } })!.gpuPassthrough, false);
});
it("are validated, empty fields dropped", () => {
assert.deepEqual(validateOverrides({ gpus: { "0000:03:00.0": { name: "", linkMax: "Gen5 x16" } }, p2p: "", storage: " " }), { gpus: { "0000:03:00.0": { linkMax: "Gen5 x16" } } });
assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { linkCurrent: "fast" } } }), /isn't a PCIe link/);
assert.throws(() => validateOverrides({ gpus: { "../etc": {} } }), /isn't a PCI address/);
assert.throws(() => validateOverrides({ p2p: "maybe" }), /P2P/);
assert.throws(() => validateOverrides({ gpus: { "0000:03:00.0": { vramMb: 1.5 } } }), /VRAM/);
assert.throws(() => validateOverrides({ storage: "a\nb" }), /one line/);
});
});
describe("system summary", () => {
it("lists the whitelisted facts", () => {
const text = systemSummaryText(systemSummary(applyOverrides(hw), "Debian GNU/Linux 13 (trixie)", "0.11.0"));
assert.match(text, /CPU: AMD EPYC 9124 16-Core Processor \(16 cores, 32 threads\)/);
assert.match(text, /Models disk: Samsung SSD 990 PRO 2TB, NVMe/);
assert.match(text, /OS: Debian GNU\/Linux 13 \(trixie\), kernel 6\.17\.1-pve/);
assert.match(text, /GPU driver: xe kernel 6\.17\.1, nvidia 580\.82\.07/);
assert.match(text, /Virtualization: VM \(KVM\/QEMU\) with GPU passthrough/);
assert.match(text, /Kaname 0\.11\.0/);
});
it("never contains the hostname, user, addresses or paths", () => {
const s = systemSummary(applyOverrides(hw), "Debian GNU/Linux 13", "0.11.0");
const meta = buildRunMeta({
hardware: applyOverrides(hw),
gpus: [intel],
runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: null, extraArgs: [] },
repoId: "unsloth/Qwen3-8B-GGUF",
options: opts,
engineInfo: null,
});
const published = JSON.stringify([s, metaNotes(meta, s, "testing q8 KV")]);
for (const secret of [hostname(), userInfo().username].filter((x) => x.length > 2)) assert.ok(!published.includes(secret), `contains ${secret}`);
assert.doesNotMatch(published, /\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/);
assert.doesNotMatch(published, /\/(models|data|home|srv|mnt|var)\//);
assert.doesNotMatch(published, /0000:0[35]:00\.0/);
// Only these keys exist; a new field must be added here on purpose.
assert.deepEqual(Object.keys(s).sort(), ["cpu", "gpuDrivers", "kaname", "kernel", "memoryBytes", "os", "storage", "virtualization"]);
});
});
describe("run metadata", () => {
it("reads image tags and flags", () => {
assert.equal(imageTag("ghcr.io/ggml-org/llama.cpp:server-b11429"), "server-b11429");
assert.equal(imageTag("registry:5000/vllm/vllm-openai@sha256:abc"), null);
assert.equal(imageTag("vllm/vllm-openai:v0.31.0@sha256:abc"), "v0.31.0");
assert.equal(argValue(["--kv-cache-dtype", "fp8", "--x"], "--kv-cache-dtype"), "fp8");
assert.equal(argValue(["--quantization=awq"], "--quantization", "-q"), "awq");
});
it("finds quant and KV cache type per engine", () => {
assert.equal(quantOf("llama.cpp", "Qwen3-8B-Q4_K_M.gguf", "unsloth/Qwen3-8B-GGUF", []), "Q4_K_M");
assert.equal(quantOf("vllm", null, "Qwen/Qwen3.8-27B-FP8", []), "FP8");
assert.equal(quantOf("vllm", null, "org/model", ["--quantization", "awq"]), "awq");
assert.equal(quantOf("vllm", null, "Qwen/Qwen3-8B", []), null);
assert.equal(kvCacheOf("llama.cpp", {}, []), "f16");
assert.equal(kvCacheOf("llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q4_0" }, []), "K q8_0 / V q4_0");
assert.equal(kvCacheOf("vllm", {}, ["--kv-cache-dtype=fp8"]), "fp8");
assert.equal(kvCacheOf("vllm", {}, []), "auto");
});
it("knows which GPUs a deployment gets", () => {
const e = applyOverrides(hw);
const nv = [{ vendor: "nvidia" as const, index: 0, uuid: "GPU-1", name: "x", memoryMb: 1, driver: "d", pciAddress: "0000:05:00.0" }];
assert.deepEqual(gpusUsed(e, "dri", {}, nv).map((g) => g.pciAddress), ["0000:03:00.0"]);
assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-1"] }, nv).map((g) => g.pciAddress), ["0000:05:00.0"]);
assert.deepEqual(gpusUsed(e, "nvidia", { gpus: ["GPU-other"] }, nv), []);
assert.deepEqual(gpusUsed(e, "cpu", {}, nv), []);
});
it("records what the server reported over the launch options", () => {
const m = buildRunMeta({
hardware: applyOverrides(hw),
gpus: [intel],
runtime: { image: "ghcr.io/ggml-org/llama.cpp:server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "", extraArgs: [] },
repoId: "unsloth/Qwen3-8B-GGUF",
options: opts,
engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 8192, at: "" },
});
assert.equal(m.p2p, "n/a");
assert.equal(m.rebar, true);
assert.equal(m.concurrency, 4);
assert.deepEqual(m.runtime, { image: "ghcr.io/ggml-org/llama.cpp:server-intel", tag: "server-intel", digest: "sha256:abc", engine: "llama.cpp", engineName: "llama.cpp", engineVersion: "b11429-d81235049" });
assert.equal(modelLabel(m), "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache");
assert.equal(gpuLabel(m), "1× Intel Arc Pro B65 (32 GiB)");
const rows = Object.fromEntries(metaRows(m).map((r) => [r.key, r.value]));
assert.equal(rows.pcie, "Gen4 x8 of Gen5 x16 (at idle)");
assert.equal(rows.engine, "llama.cpp b11429-d81235049");
});
it("falls back to the options, and to unknown, when the server didn't say", () => {
const m = buildRunMeta({
hardware: null,
gpus: [nvidia, nvidia],
runtime: { image: "vllm/vllm-openai:v0.31.0", digest: null, engine: "vllm", engineName: "vllm-radiance", extraArgs: ["--kv-cache-dtype", "fp8"] },
repoId: "Qwen/Qwen3.8-27B-FP8",
options: { modelFile: "", contextSize: 32768, extraArgs: [], maxNumSeqs: 8 },
engineInfo: null,
});
assert.equal(m.p2p, null);
assert.equal(m.rebar, false);
assert.equal(m.concurrency, 8);
assert.equal(m.runtime.engineName, "vllm-radiance");
assert.equal(modelLabel(m), "Qwen3.8-27B-FP8 FP8 with fp8 KV cache");
assert.equal(gpuLabel(m), "2× NVIDIA RTX 4090 (24 GiB)");
const notes = metaNotes(m, null, " two\n lines ");
assert.equal(notes.engine, "vllm-radiance");
assert.equal(notes.p2p, "unknown");
assert.equal(notes.description, "two lines");
assert.equal(notes.gpus, "2× NVIDIA RTX 4090 (24 GiB)");
});
});
describe("links under load", () => {
const base = () =>
buildRunMeta({
hardware: applyOverrides(hw),
gpus: [{ ...intel, linkCurrent: { gen: 1, width: 8 } }],
runtime: { image: "x:y", digest: null, engine: "llama.cpp", engineName: null, extraArgs: [] },
repoId: "a/b",
options: opts,
engineInfo: null,
});
it("marks an idle link and uses the fastest one seen under load", () => {
const m = base();
assert.equal(Object.fromEntries(metaRows(m).map((r) => [r.key, r.value])).pcie, "Gen1 x8 of Gen5 x16 (at idle)");
const loaded = withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, false)!;
assert.equal(loaded.linkUnderLoad, true);
assert.equal(Object.fromEntries(metaRows(loaded).map((r) => [r.key, r.value])).pcie, "Gen4 x8 of Gen5 x16");
assert.equal(withLoadLinks(m, { "0000:03:00.0": { gen: 4, width: 8 } }, true), m);
assert.equal(withLoadLinks(m, {}, false), m);
});
it("puts only the maximum link in the notes (known before the run)", () => {
const n = metaNotes(base(), null, null);
assert.equal(n.pcie_max, "Gen5 x16");
assert.equal(n.pcie, undefined);
});
});
+181
View File
@@ -0,0 +1,181 @@
// What a benchmark run records about its setup (RunMeta) and the BetterBench notes made from it.
// Pure; shared by the worker, the web app and tests.
import type { DeploymentOptions, EngineInfo, HardwareGpu, HostGpu, PcieLink, RunMeta, RuntimeAccelerator, RuntimeEngine, SystemSummary } from "@/lib/db/schema";
import { type EffectiveHardware, formatLink, formatLinkPair, onOff, systemSummaryText } from "@/lib/hardware";
import { quantGroup } from "@/lib/selection";
/** "ghcr.io/org/img:tag@sha256:…" → "tag" (null: no tag, i.e. "latest" or digest only). */
export function imageTag(ref: string): string | null {
const noDigest = ref.split("@")[0];
const last = noDigest.slice(noDigest.lastIndexOf("/") + 1);
const i = last.indexOf(":");
return i >= 0 ? last.slice(i + 1) : null;
}
/** Value of `--flag v` or `--flag=v` in an argument list (last one wins). */
export function argValue(args: string[], ...flags: string[]): string | null {
let v: string | null = null;
for (let i = 0; i < args.length; i++) {
for (const f of flags) {
if (args[i] === f && i + 1 < args.length) v = args[i + 1];
else if (args[i].startsWith(`${f}=`)) v = args[i].slice(f.length + 1);
}
}
return v;
}
const REPO_QUANT = /(?:^|[-_.])(nvfp4|mxfp4|fp8(?:[-_]dynamic)?|int8|int4|w8a8|w4a16|awq|gptq|bnb[-_]?4bit|bf16|fp16)(?=$|[-_.])/i;
/** Quant: the GGUF's quant tag, vLLM's --quantization, or one named in the repo (FP8, AWQ, …). */
export function quantOf(engine: RuntimeEngine, file: string | null, repoId: string, args: string[]): string | null {
if (engine === "llama.cpp" && file) return quantGroup(file);
const q = argValue(args, "--quantization", "-q");
if (q) return q;
const m = repoId.split("/").pop()?.match(REPO_QUANT);
return m ? m[1].toUpperCase().replace("_", "-") : null;
}
/** KV cache type: llama.cpp -ctk/-ctv (f16 default), vLLM --kv-cache-dtype ("auto": the model's dtype). */
export function kvCacheOf(engine: RuntimeEngine, o: Pick<DeploymentOptions, "cacheTypeK" | "cacheTypeV">, args: string[]): string {
if (engine === "vllm") return argValue(args, "--kv-cache-dtype") ?? "auto";
const k = argValue(args, "-ctk", "--cache-type-k") ?? o.cacheTypeK ?? "f16";
const v = argValue(args, "-ctv", "--cache-type-v") ?? o.cacheTypeV ?? "f16";
return k === v ? k : `K ${k} / V ${v}`;
}
/** The GPUs a deployment gets: NVIDIA by UUID (all when none picked), /dev/dri ones by vendor. */
export function gpusUsed(hw: EffectiveHardware | null, accelerator: RuntimeAccelerator | undefined, options: Pick<DeploymentOptions, "gpus">, nvidia: HostGpu[]): HardwareGpu[] {
const all = hw?.gpus ?? [];
if (accelerator === "nvidia") {
const picked = options.gpus?.length ? nvidia.filter((g) => options.gpus!.includes(g.uuid)).map((g) => g.pciAddress) : null;
return all.filter((g) => g.vendor === "nvidia" && (!picked || picked.includes(g.pciAddress)));
}
if (accelerator === "dri") return all.filter((g) => g.vendor === "intel" || g.vendor === "amd");
if (accelerator === "rocm") return all.filter((g) => g.vendor === "amd");
return [];
}
export function buildRunMeta(x: {
hardware: EffectiveHardware | null;
gpus: HardwareGpu[];
runtime: { image: string; digest: string | null; engine: RuntimeEngine; engineName: string | null; extraArgs: string[] };
repoId: string;
options: DeploymentOptions;
engineInfo: EngineInfo | null;
}): RunMeta {
const args = [...x.runtime.extraArgs, ...x.options.extraArgs];
const llama = x.runtime.engine === "llama.cpp";
return {
v: 1,
gpus: x.gpus.map((g) => ({ pciAddress: g.pciAddress, name: g.name, vramMb: g.vramMb, linkCurrent: g.linkCurrent, linkMax: g.linkMax, rebar: g.rebar })),
linkUnderLoad: false,
p2p: x.gpus.length < 2 ? "n/a" : (x.hardware?.p2p ?? null),
rebar: x.gpus.length === 0 ? null : x.gpus.every((g) => g.rebar === true) ? true : x.gpus.some((g) => g.rebar === false) ? false : null,
runtime: {
image: x.runtime.image,
tag: imageTag(x.runtime.image),
digest: x.runtime.digest,
engine: x.runtime.engine,
engineName: x.runtime.engineName?.trim() || x.runtime.engine,
engineVersion: x.engineInfo?.version ?? null,
},
model: {
repoId: x.repoId,
file: x.options.modelFile || null,
quant: quantOf(x.runtime.engine, x.options.modelFile || null, x.repoId, args),
kvCache: kvCacheOf(x.runtime.engine, x.options, args),
},
contextSize: x.engineInfo?.contextSize ?? x.options.contextSize ?? null,
concurrency: x.engineInfo?.slots ?? (llama ? x.options.parallel : x.options.maxNumSeqs) ?? null,
overridden: x.hardware?.overridden ?? [],
};
}
/** "2× NVIDIA RTX 4090 (24 GiB)", "1× Intel Arc Pro B65 (32 GiB) + 1× …"; null without GPUs. */
export function gpuLabel(m: RunMeta): string | null {
if (m.gpus.length === 0) return null;
const counts = new Map<string, number>();
for (const g of m.gpus) {
const name = `${g.name ?? "unknown GPU"}${g.vramMb ? ` (${Math.round(g.vramMb / 1024)} GiB)` : ""}`;
counts.set(name, (counts.get(name) ?? 0) + 1);
}
return [...counts].map(([name, n]) => `${n}× ${name}`).join(" + ");
}
/** The PCIe links of the GPUs used, deduplicated; "(idle)" when not measured under load. */
export function pcieLabel(m: RunMeta): string | null {
const links = [...new Set(m.gpus.map((g) => formatLinkPair(g.linkCurrent, g.linkMax) ?? "unknown"))];
if (!links.length) return null;
const idle = !m.linkUnderLoad && m.gpus.some((g) => g.linkCurrent);
return `${links.join(", ")}${idle ? " (at idle)" : ""}`;
}
/** Maximum links only ("Gen5 x16"): known before the run, unlike the link under load. */
export function pcieMaxLabel(m: RunMeta): string | null {
const links = [...new Set(m.gpus.map((g) => formatLink(g.linkMax) ?? "unknown"))];
return links.length ? links.join(", ") : null;
}
/** The run's meta with the fastest links seen during the run as the current links (when sampled). */
export function withLoadLinks(m: RunMeta | null, links: Record<string, PcieLink> | null | undefined, overridden: boolean): RunMeta | null {
if (!m || !links || overridden) return m;
let hit = false;
const gpus = m.gpus.map((g) => {
const l = g.pciAddress ? links[g.pciAddress] : undefined;
if (!l) return g;
hit = true;
return { ...g, linkCurrent: l };
});
return hit ? { ...m, gpus, linkUnderLoad: true } : m;
}
export const engineLabel = (m: RunMeta) => [m.runtime.engineName, m.runtime.engineVersion].filter(Boolean).join(" ");
/** "Qwen3-8B-GGUF Q4_K_M with q8_0 KV cache" */
export function modelLabel(m: RunMeta): string {
const name = m.model.repoId.split("/").pop() ?? m.model.repoId;
return `${name}${m.model.quant ? ` ${m.model.quant}` : ""}${m.model.kvCache ? ` with ${m.model.kvCache} KV cache` : ""}`;
}
/** Rows for the run page, compare views and sweeps (label → value, "unknown" where not known). */
export function metaRows(m: RunMeta): { key: string; label: string; value: string }[] {
return [
{ key: "gpus", label: "GPUs", value: gpuLabel(m) ?? "none (CPU)" },
...(m.gpus.length ? [{ key: "pcie", label: "PCIe", value: pcieLabel(m) ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "p2p", label: "P2P", value: m.p2p ?? "unknown" }] : []),
...(m.gpus.length ? [{ key: "rebar", label: "ReBAR", value: onOff(m.rebar) }] : []),
{ key: "engine", label: "Engine", value: engineLabel(m) || "unknown" },
{ key: "image", label: "Image", value: m.runtime.image },
{ key: "digest", label: "Digest", value: m.runtime.digest ?? "unknown" },
{ key: "model", label: "Model", value: modelLabel(m) },
{ key: "ctx", label: "Context", value: m.contextSize != null ? m.contextSize.toLocaleString("en-US") : "unknown" },
{ key: "concurrency", label: "Concurrency", value: m.concurrency != null ? String(m.concurrency) : "server default" },
];
}
/**
* BetterBench --note values (recorded in results.json, shown in its report and published to
* launch80). `engine` is the key launch80 uses to name the stack.
*/
export function metaNotes(m: RunMeta, system: SystemSummary | null, description: string | null): Record<string, string> {
const notes: Record<string, string> = {
engine: engineLabel(m) || m.runtime.engine,
image: m.runtime.image,
...(m.runtime.digest ? { digest: m.runtime.digest } : {}),
...(m.model.quant ? { quant: m.model.quant } : {}),
...(m.model.kvCache ? { kv_cache: m.model.kvCache } : {}),
...(m.contextSize != null ? { ctx: String(m.contextSize) } : {}),
...(m.concurrency != null ? { concurrency: String(m.concurrency) } : {}),
gpus: gpuLabel(m) ?? "none",
};
if (m.gpus.length) {
// The link under load is only known after the run (idle GPUs drop to a slower link).
notes.pcie_max = pcieMaxLabel(m) ?? "unknown";
notes.p2p = m.p2p ?? "unknown";
notes.rebar = onOff(m.rebar);
}
if (system) notes.system = systemSummaryText(system);
if (description?.trim()) notes.description = description.trim().replace(/\s+/g, " ").slice(0, 2000);
return notes;
}
+167
View File
@@ -0,0 +1,167 @@
// What a run records about its setup, against a temporary database: detected hardware from the
// worker, Settings → Hardware overrides, the runtime's digest and the server's reported version.
import assert from "node:assert/strict";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { after, before, describe, it } from "node:test";
import type { HostHardware } from "./db/schema";
const dir = mkdtempSync(join(tmpdir(), "kaname-setup-"));
process.env.DATABASE_URL = `file:${join(dir, "test.db").replace(/\\/g, "/")}`;
process.env.APP_VERSION = "0.11.0-test";
type Mods = {
db: typeof import("./db/client");
schema: typeof import("./db/schema");
snapshot: typeof import("./benchmark-snapshot");
settings: typeof import("./settings");
benchmarks: typeof import("./benchmarks");
};
let M: Mods;
let deploymentId: string;
const hardware: HostHardware = {
gpus: [
{
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1",
linkCurrent: { gen: 1, width: 1 },
linkMax: { gen: 5, width: 16 },
barMb: 256,
rebar: false,
},
],
p2p: null,
cpu: { model: "AMD EPYC 9124 16-Core Processor", cores: 16, threads: 32 },
memoryBytes: 128e9,
kernel: "6.17.1",
virtualization: { vm: true, hypervisor: "KVM/QEMU" },
storage: { model: "QEMU HARDDISK", kind: "virtual", sizeBytes: 2e12 },
checkedAt: new Date().toISOString(),
};
before(async () => {
const { runMigrations } = await import("./db/migrate");
await runMigrations();
M = {
db: await import("./db/client"),
schema: await import("./db/schema"),
snapshot: await import("./benchmark-snapshot"),
settings: await import("./settings"),
benchmarks: await import("./benchmarks"),
};
const d = M.db.db();
const s = M.schema;
const now = new Date();
await d.insert(s.workerState).values({
id: "worker",
startedAt: now,
heartbeatAt: now,
docker: {
connected: true,
error: null,
serverVersion: "29.0",
os: "Debian GNU/Linux 13 (trixie)",
architecture: "x86_64",
cpus: 32,
memoryBytes: 128e9,
cpuModel: null,
cpuFeatures: [],
network: "kaname_default",
modelsSource: { type: "bind", source: "/srv/models" },
hardware,
checkedAt: now.toISOString(),
},
});
const [model] = await d.insert(s.models).values({ repoId: "unsloth/Qwen3-8B-GGUF", pinnedSha: "a".repeat(40), localPath: "unsloth/Qwen3-8B-GGUF" }).returning();
const [rt] = await d
.insert(s.runtimes)
.values({ name: "llama.cpp (Intel SYCL)", engine: "llama.cpp", accelerator: "dri", image: "ghcr.io/ggml-org/llama.cpp:server-intel", imageDigest: "sha256:feed" })
.returning();
const [dep] = await d
.insert(s.deployments)
.values({
name: "qwen3 b65",
runtimeId: rt.id,
modelId: model.id,
options: { modelFile: "Qwen3-8B-Q4_K_M.gguf", contextSize: 16384, cacheTypeK: "q8_0", cacheTypeV: "q8_0", extraArgs: [] },
state: "running",
engineInfo: { version: "b11429-d81235049", slots: 4, contextSize: 16384, at: now.toISOString() },
})
.returning();
deploymentId = dep.id;
});
after(() => {
(globalThis as { __kanameDb?: { client?: { close(): void } } }).__kanameDb?.client?.close();
try {
rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
} catch {
// Windows may still hold the WAL file for a moment.
}
});
describe("run setup", () => {
it("records GPU, link, ReBAR, engine version, quant, KV cache, context and slots", async () => {
const { metas, system } = await M.snapshot.runSetup([deploymentId, null]);
const m = metas[0]!;
assert.equal(metas[1], null);
assert.equal(m.gpus.length, 1);
assert.equal(m.gpus[0].name, "Intel Arc Pro B65");
assert.deepEqual(m.gpus[0].linkCurrent, { gen: 1, width: 1 });
assert.equal(m.rebar, false);
assert.equal(m.p2p, "n/a");
assert.deepEqual(m.runtime, {
image: "ghcr.io/ggml-org/llama.cpp:server-intel",
tag: "server-intel",
digest: "sha256:feed",
engine: "llama.cpp",
engineName: "llama.cpp",
engineVersion: "b11429-d81235049",
});
assert.deepEqual(m.model, { repoId: "unsloth/Qwen3-8B-GGUF", file: "Qwen3-8B-Q4_K_M.gguf", quant: "Q4_K_M", kvCache: "q8_0" });
assert.equal(m.contextSize, 16384);
assert.equal(m.concurrency, 4);
assert.deepEqual(m.overridden, []);
assert.equal(system.kaname, "0.11.0-test");
assert.equal(system.os, "Debian GNU/Linux 13 (trixie)");
assert.equal(system.virtualization.gpuPassthrough, true);
});
it("applies Settings → Hardware to new runs", async () => {
await M.settings.saveHardwareOverrides({
gpus: { "0000:03:00.0": { linkCurrent: "Gen5 x8", rebar: true } },
storage: "Samsung 990 PRO 2TB (passed through as a virtual disk)",
hypervisor: "Proxmox VE 9 (KVM)",
});
const { metas, system } = await M.snapshot.runSetup([deploymentId]);
assert.deepEqual(metas[0]!.gpus[0].linkCurrent, { gen: 5, width: 8 });
assert.equal(metas[0]!.rebar, true);
assert.deepEqual(metas[0]!.overridden, ["pcie link", "rebar", "storage", "virtualization"]);
assert.equal(system.storage?.model, "Samsung 990 PRO 2TB (passed through as a virtual disk)");
assert.equal(system.virtualization.hypervisor, "Proxmox VE 9 (KVM)");
});
it("rejects invalid overrides and clears them when empty", async () => {
await assert.rejects(M.settings.saveHardwareOverrides({ gpus: { "0000:03:00.0": { linkMax: "Gen9" } } }), (e: Error) => e instanceof M.settings.SettingsError && /PCIe link/.test(e.message));
assert.deepEqual(await M.settings.saveHardwareOverrides({}), {});
assert.deepEqual(await M.settings.getHardwareOverrides(), {});
});
it("keeps a description with the run, editable later", async () => {
const run = await M.benchmarks.createBenchmark(M.benchmarks.BenchmarkBody.parse({ deploymentId, description: " q8_0 KV to fit 16k " }));
assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
await M.benchmarks.updateBenchmark(run.id, { label: "q8 KV" });
assert.equal((await M.benchmarks.getBenchmark(run.id))?.description, "q8_0 KV to fit 16k");
await M.benchmarks.updateBenchmark(run.id, { description: "" });
const row = await M.benchmarks.getBenchmark(run.id);
assert.equal(row?.description, null);
assert.equal(row?.label, "q8 KV");
});
});
+42 -1
View File
@@ -3,7 +3,9 @@
import { and, eq, isNull } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { type BenchmarkSnapshot, deployments, models, runtimes, workerState } from "@/lib/db/schema";
import { buildRunMeta, gpusUsed } from "@/lib/benchmark-meta";
import { type BenchmarkSnapshot, deployments, models, type RunMeta, runtimes, settings, type SystemSummary, workerState } from "@/lib/db/schema";
import { applyOverrides, HARDWARE_OVERRIDES_KEY, parseOverrides, systemSummary } from "@/lib/hardware";
/** Host CPU/RAM and the names of the GPUs a deployment uses (all detected ones when none are picked). */
async function hostFacts(uuids: string[] | null, nvidia: boolean) {
@@ -60,3 +62,42 @@ export async function deploymentSnapshot(deploymentId: string): Promise<{ id: st
},
};
}
/** Kaname's version (the image sets APP_VERSION). */
export const kanameVersion = () => process.env.APP_VERSION ?? "dev";
/** The detected hardware with Settings → Hardware applied, and the host's OS. */
export async function effectiveHardware() {
const [ws, ov] = await Promise.all([
db().query.workerState.findFirst({ columns: { docker: true }, where: eq(workerState.id, "worker") }),
db().query.settings.findFirst({ where: eq(settings.key, HARDWARE_OVERRIDES_KEY) }),
]);
const docker = ws?.docker ?? null;
return { hardware: applyOverrides(docker?.hardware, parseOverrides(ov?.value)), nvidia: docker?.gpus ?? [], os: docker?.os ?? null };
}
/** Hardware, runtime and model facts of a deployment as it runs now, plus the system summary. */
export async function runSetup(deploymentIds: (string | null)[]): Promise<{ metas: (RunMeta | null)[]; system: SystemSummary }> {
const { hardware, nvidia, os } = await effectiveHardware();
const metas = await Promise.all(
deploymentIds.map(async (id) => {
if (!id) return null;
const [d] = await db()
.select({ options: deployments.options, engineInfo: deployments.engineInfo, repoId: models.repoId, runtime: runtimes })
.from(deployments)
.innerJoin(runtimes, eq(runtimes.id, deployments.runtimeId))
.innerJoin(models, eq(models.id, deployments.modelId))
.where(eq(deployments.id, id));
if (!d) return null;
return buildRunMeta({
hardware,
gpus: gpusUsed(hardware, d.runtime.accelerator, d.options, nvidia),
runtime: { image: d.runtime.image, digest: d.runtime.imageDigest, engine: d.runtime.engine, engineName: d.runtime.engineName, extraArgs: d.runtime.extraArgs },
repoId: d.repoId,
options: d.options,
engineInfo: d.engineInfo,
});
}),
);
return { metas, system: systemSummary(hardware, os, kanameVersion()) };
}
+16 -2
View File
@@ -17,9 +17,13 @@ export class BenchmarkError extends Error {
}
}
export const DESCRIPTION_MAX = 4000;
export const BenchmarkBody = z.object({
deploymentId: z.string().min(1),
label: z.string().trim().max(120).nullable().optional(),
/** Free text: what this run tries out. Passed to BetterBench and launch80 with the system summary. */
description: z.string().trim().max(DESCRIPTION_MAX).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(),
@@ -64,6 +68,7 @@ export async function createBenchmark(input: BenchmarkInput) {
deploymentBId: b?.id ?? null,
modelId: a.modelId,
label: input.label || null,
description: input.description || null,
settings: {
quick: input.quick,
passes: input.passes ?? null,
@@ -101,6 +106,10 @@ const listColumns = {
ab: benchmarkRuns.ab,
resources: benchmarkRuns.resources,
sweepId: benchmarkRuns.sweepId,
meta: benchmarkRuns.meta,
metaB: benchmarkRuns.metaB,
system: benchmarkRuns.system,
description: benchmarkRuns.description,
createdAt: benchmarkRuns.createdAt,
};
@@ -141,8 +150,13 @@ export async function cancelBenchmark(id: string) {
}
}
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 });
/** Rename a run (label) and/or change its description; fields left out stay as they are. */
export async function updateBenchmark(id: string, patch: { label?: string | null; description?: string | null }) {
const set: Partial<typeof benchmarkRuns.$inferInsert> = {};
if (patch.label !== undefined) set.label = patch.label?.trim() || null;
if (patch.description !== undefined) set.description = patch.description?.trim() || null;
if (Object.keys(set).length === 0) return;
const res = await db().update(benchmarkRuns).set(set).where(eq(benchmarkRuns.id, id)).returning({ id: benchmarkRuns.id });
if (res.length === 0) throw new BenchmarkError("not_found", "Benchmark not found.", 404);
}
+163 -3
View File
@@ -73,6 +73,8 @@ export type JobResult = {
removePaths?: string[];
/** Delete jobs: files that were kept because they don't belong to the repo. */
kept?: string[];
/** API "add files" requests: the selection rule before, restored if the request is rejected. */
previousRule?: { include: string[]; exclude: string[] };
};
export const models = sqliteTable(
@@ -124,6 +126,9 @@ export const models = sqliteTable(
/** Hub tags, minus noise like arxiv:/region:/deploy:. */
hubTags: text("hub_tags", { mode: "json" }).$type<string[]>(),
metadataFetchedAt: ts("metadata_fetched_at"),
/** Added through the API: the token that asked for it, and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
createdAt: createdAt(),
updatedAt: updatedAt(),
},
@@ -224,6 +229,7 @@ export const JOB_PURPOSES = ["initial", "add", "import", "repair", "update"] as
export type JobPurpose = (typeof JOB_PURPOSES)[number];
export const JOB_STATES = [
"pending_approval", // requested through the API, waits for a human to approve it
"queued",
"downloading",
"verifying",
@@ -269,6 +275,9 @@ export const jobs = sqliteTable(
result: text("result", { mode: "json" }).$type<JobResult>(),
/** Set by the web app; the worker picks it up and stops the job. */
cancelRequestedAt: ts("cancel_requested_at"),
/** Requested through the API: the token, and its name at the time. */
requestedByTokenId: text("requested_by_token_id"),
requestedBy: text("requested_by"),
startedAt: ts("started_at"),
finishedAt: ts("finished_at"),
createdAt: createdAt(),
@@ -368,10 +377,69 @@ export type DockerHostInfo = {
gpus?: HostGpu[];
gpuError?: string | null;
gpuCheckedAt?: string | null;
/** Group IDs owning /dev/dri on the host (render, video); given to Intel/AMD runtime containers. */
driGroups?: number[];
/** PCIe, ReBAR, system facts from sysfs/procfs (what the worker's container sees of the host). */
hardware?: HostHardware | null;
checkedAt: string;
};
export type HostGpu = { vendor: "nvidia"; index: number; uuid: string; name: string; memoryMb: number; driver: string };
export type HostGpu = {
vendor: "nvidia";
index: number;
uuid: string;
name: string;
memoryMb: number;
driver: string;
pciAddress?: string | null;
/** PCIe link as nvidia-smi reports it (also where sysfs isn't visible, e.g. WSL2). */
linkCurrent?: PcieLink | null;
linkMax?: PcieLink | null;
};
/** A PCIe link: generation (1 = 2.5 GT/s … 6 = 64 GT/s) and lanes. */
export type PcieLink = { gen: number | null; width: number | null };
export type GpuVendor = "nvidia" | "intel" | "amd";
/** A GPU as found on the PCI bus. The link is the card's upstream link (behind on-card switches). */
export type HardwareGpu = {
vendor: GpuVendor;
pciAddress: string;
name: string | null;
vramMb: number | null;
/** Kernel driver (nvidia, xe, i915, amdgpu) and its version (the kernel's for in-tree drivers). */
driver: string | null;
driverVersion: string | null;
linkCurrent: PcieLink | null;
linkMax: PcieLink | null;
/** Largest memory BAR in MiB; Resizable BAR is on when it covers the VRAM. */
barMb: number | null;
rebar: boolean | null;
};
export type HostHardware = {
gpus: HardwareGpu[];
/** Peer-to-peer between GPUs (NVIDIA: nvidia-smi topo); null = unknown or a single GPU. */
p2p: "on" | "off" | "partial" | null;
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
kernel: string | null;
virtualization: { vm: boolean | null; hypervisor: string | null };
/** The disk holding the models folder. */
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
checkedAt: string;
};
/** Settings → Hardware: manual values where detection can't see the truth (VMs, new GPUs). */
export type HardwareOverrides = {
gpus?: Record<string, { name?: string; vramMb?: number; linkCurrent?: string; linkMax?: string; rebar?: boolean }>;
p2p?: "on" | "off" | "partial";
storage?: string;
hypervisor?: string;
gpuPassthrough?: boolean;
gpuDriver?: string;
};
// ---------------------------------------------------------------------------
// Runtimes: container images that serve models (llama.cpp, vLLM, forks, …)
@@ -420,6 +488,10 @@ export const runtimes = sqliteTable("runtimes", {
pullProgress: text("pull_progress", { mode: "json" }).$type<{ doneBytes: number; totalBytes: number; status: string }>(),
pullError: text("pull_error"),
imageCheckedAt: ts("image_checked_at"),
/** Registry digest of the pulled image (sha256:…), from its RepoDigests. */
imageDigest: text("image_digest"),
/** Shown instead of the engine type for forks, e.g. "vllm-radiance". */
engineName: text("engine_name"),
createdAt: createdAt(),
updatedAt: updatedAt(),
});
@@ -525,6 +597,8 @@ export const deployments = sqliteTable("deployments", {
exitCode: integer("exit_code"),
error: text("error"),
stats: text("stats", { mode: "json" }).$type<DeploymentStats>(),
/** Version, slots and context the server reported once ready. */
engineInfo: text("engine_info", { mode: "json" }).$type<EngineInfo>(),
/** Temporary deployment created by a benchmark sweep (removed when its variant is done). */
sweepId: text("sweep_id"),
createdAt: createdAt(),
@@ -558,6 +632,31 @@ export const apiKeys = sqliteTable("api_keys", {
createdAt: createdAt(),
});
// ---------------------------------------------------------------------------
// API tokens: machine clients (e.g. an AI agent) calling /api/v1 with a bearer token
// ---------------------------------------------------------------------------
/** What a token may do. Nothing can delete, change settings or manage runtimes/tokens. */
export const TOKEN_SCOPES = ["models:read", "downloads:create"] as const;
export type TokenScope = (typeof TOKEN_SCOPES)[number];
export const apiTokens = sqliteTable(
"api_tokens",
{
id: id(),
name: text("name").notNull(),
/** First characters of the token, shown in the UI to tell tokens apart. */
prefix: text("prefix").notNull(),
/** SHA-256 of the token (hex); the token itself is never stored. */
hash: text("hash").notNull().unique(),
scopes: text("scopes", { mode: "json" }).$type<TokenScope[]>().notNull(),
lastUsedAt: ts("last_used_at"),
revokedAt: ts("revoked_at"),
createdAt: createdAt(),
},
(t) => [uniqueIndex("api_tokens_name_uq").on(t.name)],
);
// ---------------------------------------------------------------------------
// Benchmarks (BetterBench runs against a running deployment)
// ---------------------------------------------------------------------------
@@ -627,8 +726,26 @@ export type ResourceStats = {
memPeakBytes: number | null;
memLimitBytes: number | null;
}[];
/** Whole-GPU figures (nvidia-smi), not per process. */
gpus: { index: number; name: string; vramTotalMb: number; vramPeakMb: number; vramAvgMb: number; utilAvg: number; utilPeak: number; powerAvgW: number | null; powerPeakW: number | null }[];
/** Fastest PCIe link seen per GPU (PCI address) during the run. */
links?: Record<string, PcieLink>;
/**
* Whole-GPU figures, not per process: nvidia-smi; hwmon/sysfs for AMD; hwmon plus the DRM fdinfo
* of all processes for Intel. null where a source doesn't report it.
*/
gpus: {
index: number;
name: string;
pciAddress?: string;
vramTotalMb: number | null;
vramPeakMb: number | null;
vramAvgMb: number | null;
utilAvg: number | null;
utilPeak: number | null;
powerAvgW: number | null;
powerPeakW: number | null;
tempAvgC?: number | null;
tempPeakC?: number | null;
}[];
};
/** The deployment as it was when the run started, so results stay comparable after edits. */
@@ -651,6 +768,43 @@ export type BenchmarkSnapshot = {
command: string;
};
/** What was measured on what, recorded when a run starts (Settings → Hardware overrides applied). */
export type RunMeta = {
v: 1;
gpus: { pciAddress?: string; name: string | null; vramMb: number | null; linkCurrent: PcieLink | null; linkMax: PcieLink | null; rebar: boolean | null }[];
/**
* GPUs lower their link speed when idle: true once linkCurrent is the fastest link seen while the run
* was under load (otherwise it is what detection saw, possibly idle).
*/
linkUnderLoad?: boolean;
/** "n/a" with fewer than two GPUs; null = unknown. */
p2p: "on" | "off" | "partial" | "n/a" | null;
/** On for every GPU used; null = unknown. */
rebar: boolean | null;
runtime: { image: string; tag: string | null; digest: string | null; engine: RuntimeEngine; engineName: string; engineVersion: string | null };
model: { repoId: string; file: string | null; quant: string | null; kvCache: string | null };
contextSize: number | null;
/** Parallel slots (llama.cpp) or max sequences (vLLM); reported by the server where it can. */
concurrency: number | null;
/** Fields taken from Settings → Hardware instead of detection. */
overridden: string[];
};
/** The host, as published: nothing that identifies it (no hostname, IP, user or path). */
export type SystemSummary = {
cpu: { model: string | null; cores: number | null; threads: number | null };
memoryBytes: number | null;
storage: { model: string | null; kind: "nvme" | "ssd" | "hdd" | "virtual" | null; sizeBytes: number | null } | null;
os: string | null;
kernel: string | null;
gpuDrivers: string[];
virtualization: { vm: boolean | null; hypervisor: string | null; gpuPassthrough: boolean | null };
kaname: string;
};
/** What the server reported about itself once ready (llama.cpp /props, vLLM /version and /v1/models). */
export type EngineInfo = { version: string | null; slots: number | null; contextSize: number | null; at: string };
/**
* BetterBench's own report rows for a run (betterbench.report: single_rows, prefill_rows,
* concurrency_rows, combined_score, sample_gate, …), copied as computed. Nothing in Kaname derives
@@ -766,6 +920,12 @@ export const benchmarkRuns = sqliteTable(
resources: text("resources", { mode: "json" }).$type<ResourceStats>(),
/** Run of a sweep variant. */
sweepId: text("sweep_id"),
/** Hardware, runtime and model facts (A, and B of an A/B), recorded at the start. */
meta: text("meta", { mode: "json" }).$type<RunMeta>(),
metaB: text("meta_b", { mode: "json" }).$type<RunMeta>(),
system: text("system", { mode: "json" }).$type<SystemSummary>(),
/** Free text by the user; passed to BetterBench and launch80 with the system summary. */
description: text("description"),
createdAt: createdAt(),
},
(t) => [index("benchmark_runs_created_idx").on(t.createdAt)],
+32 -3
View File
@@ -128,6 +128,37 @@ export const LLAMA_DEFAULT_CACHE_RAM_MB = 8192;
const KV_TYPE_FACTOR: Record<string, number> = { 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 };
/** llama.cpp KV cache in MiB for a model of `modelMb`: the per-token heuristic below, scaled by the cache type. */
function kvCacheMb(modelMb: number, contextSize: number, o: Pick<DeploymentOptions, "cacheTypeK" | "cacheTypeV">): number {
const perTokenKiB = 96 + 24 * Math.sqrt(modelMb / 1024);
const kvFactor = ((KV_TYPE_FACTOR[o.cacheTypeK ?? "f16"] ?? 1) + (KV_TYPE_FACTOR[o.cacheTypeV ?? "f16"] ?? 1)) / 2;
return (contextSize * perTokenKiB * kvFactor) / 1024;
}
/** llama.cpp compute buffers and runtime state on the GPU (measured order of magnitude, not exact). */
const GPU_OVERHEAD_MB = 1024;
/**
* Rough VRAM need of a GPU deployment in MiB, for NVIDIA and Intel/AMD (/dev/dri) alike; null when it
* can't be told without reading the model (only some layers or the MoE experts offloaded).
* - vLLM reserves --gpu-memory-utilization (default 0.9) of each GPU's VRAM up front.
* - llama.cpp with all layers on the GPU ("auto" fits as many as there is room for): weights + KV
* cache + compute buffers.
*/
export function estimateVramMb(
fileBytes: number,
contextSize: number,
engine: RuntimeEngine,
o: Pick<DeploymentOptions, "gpuLayers" | "cacheTypeK" | "cacheTypeV" | "cpuMoe" | "nCpuMoe" | "gpuMemoryUtilization">,
vramTotalMb: number | null,
): number | null {
if (engine === "vllm") return vramTotalMb ? Math.ceil(vramTotalMb * (o.gpuMemoryUtilization ?? 0.9)) : null;
const layers = o.gpuLayers ?? "auto";
if ((layers !== "auto" && layers !== "all") || o.cpuMoe || (o.nCpuMoe ?? 0) > 0) return null;
const model = fileBytes / 2 ** 20;
return Math.ceil(model + kvCacheMb(model, contextSize, o) + GPU_OVERHEAD_MB);
}
/**
* 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.
@@ -144,9 +175,7 @@ export function estimateMemoryMb(
// vLLM CPU: API server, engine core and worker each load torch (~3 GiB measured with v0.31.0).
// 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 kv = kvCacheMb(model, contextSize, o);
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);
+210
View File
@@ -0,0 +1,210 @@
// Host hardware as Kaname reports it: PCIe links, ReBAR, the system summary, and the manual
// overrides from Settings → Hardware. Pure; shared by the web app, the worker and tests.
import type { HardwareGpu, HardwareOverrides, HostHardware, PcieLink, SystemSummary } from "@/lib/db/schema";
import { formatBytes } from "@/lib/format";
const GT_PER_GEN: [number, number][] = [
[2.5, 1],
[5, 2],
[8, 3],
[16, 4],
[32, 5],
[64, 6],
];
/** sysfs "16.0 GT/s PCIe" → 4; unknown speeds → null. */
export function linkGen(speed: string | null | undefined): number | null {
const gt = Number(speed?.match(/([\d.]+)\s*GT\/s/)?.[1]);
return GT_PER_GEN.find(([s]) => Math.abs(s - gt) < 0.01)?.[1] ?? null;
}
export function formatLink(l: PcieLink | null | undefined): string | null {
if (!l || (l.gen == null && l.width == null)) return null;
return [l.gen != null ? `Gen${l.gen}` : null, l.width != null ? `x${l.width}` : null].filter(Boolean).join(" ");
}
/** "Gen4 x8 of Gen5 x16", or just "Gen5 x16" when the link runs at its maximum. */
export function formatLinkPair(current: PcieLink | null | undefined, max: PcieLink | null | undefined): string | null {
const c = formatLink(current);
const m = formatLink(max);
if (!c) return m ? `? of ${m}` : null;
return !m || c === m ? c : `${c} of ${m}`;
}
/** "Gen4 x8", "gen 4 x8", "x16" → a link; null when it isn't one. */
export function parseLinkText(text: string): PcieLink | null {
const t = text.trim();
const m = t.match(/^(?:gen\s*([1-6]))?\s*(?:x\s*(\d{1,2}))?$/i);
if (!t || !m || (!m[1] && !m[2])) return null;
return { gen: m[1] ? Number(m[1]) : null, width: m[2] ? Number(m[2]) : null };
}
/** ReBAR is on when the largest BAR maps (nearly) all of the VRAM; without it BARs are 256 MiB. */
export function rebarFrom(barMb: number | null, vramMb: number | null): boolean | null {
if (barMb == null) return null;
if (vramMb) return barMb >= vramMb * 0.9;
return barMb >= 2048 ? true : null;
}
export const onOff = (v: boolean | null | undefined) => (v == null ? "unknown" : v ? "on" : "off");
export type EffectiveHardware = HostHardware & {
gpuPassthrough: boolean | null;
gpuDriver: string | null;
/** Which values came from Settings → Hardware (e.g. "gpu 0000:03:00.0 link", "storage"). */
overridden: string[];
};
/** Detected hardware with the overrides applied. */
export function applyOverrides(hw: HostHardware | null | undefined, o: HardwareOverrides = {}): EffectiveHardware | null {
if (!hw) return null;
const overridden: string[] = [];
const gpus: HardwareGpu[] = hw.gpus.map((g) => {
const x = o.gpus?.[g.pciAddress];
if (!x) return g;
const cur = x.linkCurrent ? parseLinkText(x.linkCurrent) : null;
const max = x.linkMax ? parseLinkText(x.linkMax) : null;
const set = <K extends keyof HardwareGpu>(key: K, v: HardwareGpu[K] | null | undefined, label: string) => {
if (v == null || v === "") return;
out[key] = v;
overridden.push(label);
};
const out = { ...g };
set("name", x.name, "gpu name");
set("vramMb", x.vramMb, "vram");
set("linkCurrent", cur, "pcie link");
set("linkMax", max, "pcie max link");
set("rebar", x.rebar, "rebar");
if (x.rebar == null && x.vramMb) out.rebar = rebarFrom(g.barMb, x.vramMb);
return out;
});
const passthroughDetected = hw.virtualization.vm ? hw.gpus.length > 0 : hw.virtualization.vm === false ? false : null;
if (o.p2p) overridden.push("p2p");
if (o.storage) overridden.push("storage");
if (o.hypervisor) overridden.push("virtualization");
if (o.gpuPassthrough != null) overridden.push("gpu passthrough");
if (o.gpuDriver) overridden.push("gpu driver");
return {
...hw,
gpus,
p2p: o.p2p ?? hw.p2p,
storage: o.storage ? { model: o.storage, kind: hw.storage?.kind ?? null, sizeBytes: hw.storage?.sizeBytes ?? null } : hw.storage,
virtualization: o.hypervisor ? { vm: true, hypervisor: o.hypervisor } : hw.virtualization,
gpuPassthrough: o.gpuPassthrough ?? passthroughDetected,
gpuDriver: o.gpuDriver ?? null,
overridden: [...new Set(overridden)],
};
}
/** Driver labels, e.g. "nvidia 580.82.07", "xe (kernel 6.17.1)". */
export function driverLabels(gpus: HardwareGpu[]): string[] {
return [...new Set(gpus.filter((g) => g.driver).map((g) => (g.driverVersion ? `${g.driver} ${g.driverVersion}` : g.driver!)))];
}
/**
* The publishable system summary. Only whitelisted facts: CPU, RAM, disk model, OS, kernel, drivers,
* virtualization, Kaname version. Never the hostname, addresses, users or paths.
*/
export function systemSummary(hw: EffectiveHardware | null, os: string | null, kaname: string): SystemSummary {
return {
cpu: hw?.cpu ?? { model: null, cores: null, threads: null },
memoryBytes: hw?.memoryBytes ?? null,
storage: hw?.storage ?? null,
os,
kernel: hw?.kernel ?? null,
gpuDrivers: hw?.gpuDriver ? [hw.gpuDriver] : driverLabels(hw?.gpus ?? []),
virtualization: { vm: hw?.virtualization.vm ?? null, hypervisor: hw?.virtualization.hypervisor ?? null, gpuPassthrough: hw?.gpuPassthrough ?? null },
kaname,
};
}
const STORAGE_KIND: Record<string, string> = { nvme: "NVMe", ssd: "SSD", hdd: "HDD", virtual: "virtual disk" };
/** One line per fact, for notes, the run page and launch80. */
export function systemSummaryLines(s: SystemSummary): string[] {
const cpu = s.cpu.model
? `${s.cpu.model}${s.cpu.cores || s.cpu.threads ? ` (${[s.cpu.cores && `${s.cpu.cores} cores`, s.cpu.threads && `${s.cpu.threads} threads`].filter(Boolean).join(", ")})` : ""}`
: null;
const disk = s.storage ? [s.storage.model, s.storage.kind && STORAGE_KIND[s.storage.kind], s.storage.sizeBytes && formatBytes(s.storage.sizeBytes)].filter(Boolean).join(", ") : null;
const v = s.virtualization;
const virt = v.vm == null ? null : v.vm ? `VM${v.hypervisor ? ` (${v.hypervisor})` : ""}${v.gpuPassthrough ? " with GPU passthrough" : ""}` : "bare metal";
return [
cpu && `CPU: ${cpu}`,
s.memoryBytes && `RAM: ${formatBytes(s.memoryBytes)}`,
disk && `Models disk: ${disk}`,
(s.os || s.kernel) && `OS: ${[s.os, s.kernel && `kernel ${s.kernel}`].filter(Boolean).join(", ")}`,
s.gpuDrivers.length > 0 && `GPU driver: ${s.gpuDrivers.join(", ")}`,
virt && `Virtualization: ${virt}`,
`Kaname ${s.kaname}`,
].filter((x): x is string => !!x);
}
export const systemSummaryText = (s: SystemSummary) => systemSummaryLines(s).join(" · ");
export const HARDWARE_OVERRIDES_KEY = "hardware.overrides";
const TEXT_MAX = 120;
export class HardwareOverrideError extends Error {}
const text = (v: unknown, what: string): string | undefined => {
if (v == null || v === "") return undefined;
if (typeof v !== "string" || v.trim().length > TEXT_MAX || /[\r\n\0]/.test(v)) throw new HardwareOverrideError(`${what}: at most ${TEXT_MAX} characters on one line.`);
return v.trim() || undefined;
};
const bool = (v: unknown, what: string): boolean | undefined => {
if (v == null || v === "") return undefined;
if (typeof v !== "boolean") throw new HardwareOverrideError(`${what} must be on or off.`);
return v;
};
const linkText = (v: unknown, what: string): string | undefined => {
const t = text(v, what);
if (t && !parseLinkText(t)) throw new HardwareOverrideError(`${what}: "${t}" isn't a PCIe link (e.g. "Gen4 x8").`);
return t;
};
/** Validate overrides from the settings form; throws HardwareOverrideError. Empty fields are dropped. */
export function validateOverrides(input: unknown): HardwareOverrides {
const o = (input ?? {}) as Record<string, unknown>;
const out: HardwareOverrides = {};
const gpus: NonNullable<HardwareOverrides["gpus"]> = {};
for (const [addr, raw] of Object.entries((o.gpus ?? {}) as Record<string, Record<string, unknown>>)) {
if (!/^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i.test(addr)) throw new HardwareOverrideError(`"${addr}" isn't a PCI address.`);
const vram = raw?.vramMb;
if (vram != null && vram !== "" && (typeof vram !== "number" || !Number.isInteger(vram) || vram < 256 || vram > 4_194_304)) {
throw new HardwareOverrideError("VRAM must be a whole number of MiB (256 – 4194304).");
}
const g = {
name: text(raw?.name, "GPU name"),
vramMb: typeof vram === "number" ? vram : undefined,
linkCurrent: linkText(raw?.linkCurrent, "Current link"),
linkMax: linkText(raw?.linkMax, "Maximum link"),
rebar: bool(raw?.rebar, "ReBAR"),
};
const set = Object.fromEntries(Object.entries(g).filter(([, v]) => v !== undefined));
if (Object.keys(set).length) gpus[addr.toLowerCase()] = set;
}
if (Object.keys(gpus).length) out.gpus = gpus;
if (o.p2p != null && o.p2p !== "") {
if (o.p2p !== "on" && o.p2p !== "off" && o.p2p !== "partial") throw new HardwareOverrideError("P2P must be on, off or partial.");
out.p2p = o.p2p;
}
const storage = text(o.storage, "Models disk");
const hypervisor = text(o.hypervisor, "Virtualization");
const gpuDriver = text(o.gpuDriver, "GPU driver");
const passthrough = bool(o.gpuPassthrough, "GPU passthrough");
if (storage) out.storage = storage;
if (hypervisor) out.hypervisor = hypervisor;
if (gpuDriver) out.gpuDriver = gpuDriver;
if (passthrough != null) out.gpuPassthrough = passthrough;
return out;
}
/** Stored overrides; anything invalid is ignored rather than breaking a run. */
export function parseOverrides(stored: unknown): HardwareOverrides {
try {
return validateOverrides(stored);
} catch {
return {};
}
}
+24 -7
View File
@@ -24,7 +24,8 @@ export class JobError extends Error {
}
}
const OPEN_STATES = ["queued", ...ACTIVE_JOB_STATES] as const;
/** Jobs that block another job for the same model; pending approval counts (it will run). */
export const OPEN_STATES = ["pending_approval", "queued", ...ACTIVE_JOB_STATES] as const;
const INSERT_CHUNK = 500;
/** True if the model has a queued or running job (only one job per model at a time). */
@@ -36,15 +37,19 @@ export async function hasOpenJob(modelId: string): Promise<boolean> {
return !!open;
}
/** Who asked for a job through the API (token id + its name at the time). */
export type RequestedBy = { tokenId: string; name: string };
/**
* Queue a download of all selected files of a model at its pinned SHA. hf skips files that are
* already complete, so this also serves as resume and repair. `removePaths`: files of an older
* revision to delete once the download succeeded (updates).
* revision to delete once the download succeeded (updates). `pendingApproval`: the job waits in
* "pending_approval" (the worker only picks up "queued") until someone approves it.
*/
export async function queueDownload(
modelId: string,
purpose: JobPurpose = "initial",
options: { removePaths?: string[] } = {},
options: { removePaths?: string[]; pendingApproval?: boolean; requestedBy?: RequestedBy; previousRule?: JobResult["previousRule"] } = {},
): Promise<{ jobId: string }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
@@ -62,18 +67,25 @@ export async function queueDownload(
const jobId = ulid();
const rows = files.map((f) => ({ jobId, modelFileId: f.id, path: f.path, expectedBytes: f.size }));
const result: JobResult = {};
if (options.removePaths?.length) result.removePaths = options.removePaths;
if (options.previousRule) result.previousRule = options.previousRule;
await d.batch([
d.insert(jobs).values({
id: jobId,
modelId,
kind: "download",
purpose,
state: options.pendingApproval ? "pending_approval" : "queued",
targetSha: model.pinnedSha,
totalBytes: files.reduce((s, f) => s + f.size, 0),
result: options.removePaths?.length ? { removePaths: options.removePaths } : null,
result: Object.keys(result).length ? result : null,
requestedByTokenId: options.requestedBy?.tokenId ?? null,
requestedBy: options.requestedBy?.name ?? null,
}),
...chunk(rows, INSERT_CHUNK).map((c) => d.insert(jobFiles).values(c)),
d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId)),
// A job waiting for approval doesn't download yet; the model keeps its status.
...(options.pendingApproval ? [] : [d.update(models).set({ status: "downloading" }).where(eq(models.id, modelId))]),
]);
return { jobId };
}
@@ -110,10 +122,12 @@ export async function queueVerify(modelId: string, deep: boolean): Promise<{ job
/** Ask the worker to stop a job. Queued jobs are cancelled by the worker on its next tick. */
export async function requestCancel(jobId: string): Promise<void> {
const pending = await db().query.jobs.findFirst({ columns: { id: true }, where: and(eq(jobs.id, jobId), eq(jobs.state, "pending_approval")) });
if (pending) throw new JobError("not_cancellable", "This download waits for approval. Approve or reject it instead.", 409);
const res = await db()
.update(jobs)
.set({ cancelRequestedAt: new Date() })
.where(and(eq(jobs.id, jobId), inArray(jobs.state, [...OPEN_STATES]), isNull(jobs.cancelRequestedAt)))
.where(and(eq(jobs.id, jobId), inArray(jobs.state, ["queued", ...ACTIVE_JOB_STATES]), isNull(jobs.cancelRequestedAt)))
.returning({ id: jobs.id });
if (res.length === 0) {
const job = await db().query.jobs.findFirst({ columns: { id: true }, where: eq(jobs.id, jobId) });
@@ -143,6 +157,8 @@ export type JobSnapshot = {
errorMessage: string | null;
result: JobResult | null;
cancelRequested: boolean;
/** Token name if the job was requested through the API. */
requestedBy: string | null;
createdAt: number;
startedAt: number | null;
finishedAt: number | null;
@@ -175,12 +191,13 @@ const jobColumns = {
errorMessage: jobs.errorMessage,
result: jobs.result,
cancelRequestedAt: jobs.cancelRequestedAt,
requestedBy: jobs.requestedBy,
createdAt: jobs.createdAt,
startedAt: jobs.startedAt,
finishedAt: jobs.finishedAt,
};
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt"> & { repoId: string };
type JobRow = Omit<typeof jobs.$inferSelect, "targetSha" | "updatedAt" | "requestedByTokenId"> & { repoId: string };
function toSnapshot(r: JobRow): JobSnapshot {
const { cancelRequestedAt, createdAt, startedAt, finishedAt, ...rest } = r;
+9 -1
View File
@@ -2,7 +2,7 @@ import "server-only";
import { and, asc, desc, eq, sql } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { deploymentsByModel, listDeployableModels } from "@/lib/deployments";
import { modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { jobs, modelFiles, models, modelTags, tags } from "@/lib/db/schema";
import { modelFamilies } from "@/lib/hub/metadata";
import { fileRole } from "@/lib/file-roles";
import { quantGroup } from "@/lib/selection";
@@ -30,8 +30,11 @@ export async function listLibrary() {
pipelineTag: models.pipelineTag,
license: models.license,
hubTags: models.hubTags,
requestedBy: models.requestedBy,
fileCount: sql<number>`count(${modelFiles.id})`,
totalBytes: sql<number>`coalesce(sum(${modelFiles.size}), 0)`,
/** Selected files that are on disk (present or verified). */
presentBytes: sql<number>`coalesce(sum(case when ${modelFiles.state} in ('present', 'verified') then ${modelFiles.size} else 0 end), 0)`,
})
.from(models)
.leftJoin(modelFiles, and(eq(modelFiles.modelId, models.id), eq(modelFiles.selected, true)))
@@ -53,6 +56,10 @@ export async function listLibrary() {
const tagsByModel = new Map<string, Tag[]>();
for (const t of tagRows) tagsByModel.set(t.modelId, [...(tagsByModel.get(t.modelId) ?? []), { id: t.id, name: t.name, color: t.color }]);
const pending = new Set(
(await d.select({ modelId: jobs.modelId }).from(jobs).where(eq(jobs.state, "pending_approval"))).map((j) => j.modelId),
);
const [byModel, deployable] = await Promise.all([deploymentsByModel(), listDeployableModels()]);
const deployableIds = new Set(deployable.map((m) => m.id));
@@ -66,6 +73,7 @@ export async function listLibrary() {
quants: [...(quants.get(r.id) ?? [])].sort(),
tags: tagsByModel.get(r.id) ?? [],
deployable: deployableIds.has(r.id),
pendingApproval: pending.has(r.id),
deployments: byModel.get(r.id) ?? [],
}));
}
+31 -5
View File
@@ -7,7 +7,7 @@ import { hubMissingMessage } from "@/lib/hub/availability";
import { checkFileAccess, getAuthorAvatar, getRepoInfo, listFiles } from "@/lib/hub/client";
import { metadataColumns } from "@/lib/hub/refresh";
import { deploymentsUsing } from "@/lib/deployments";
import { hasOpenJob, queueDownload } from "@/lib/jobs";
import { hasOpenJob, queueDownload, type RequestedBy } from "@/lib/jobs";
import { getLocalFolder, requestFolderScan } from "@/lib/local-folders";
import { purgeModelRows } from "@/lib/model-purge";
import { contentId } from "@/lib/update-diff";
@@ -36,6 +36,8 @@ export async function addModel(input: {
rule: SelectionRule;
/** Import: use this existing folder in MODELS_DIR (must be one the worker's scan found). */
localPath?: string;
/** Added through the API by this token. */
requestedBy?: RequestedBy;
}): Promise<{ id: string }> {
const info = await getRepoInfo(input.repoId, input.sha);
const repoId = info.repoId;
@@ -82,6 +84,8 @@ export async function addModel(input: {
localPath,
includePatterns: input.rule.include,
excludePatterns: input.rule.exclude,
requestedByTokenId: input.requestedBy?.tokenId ?? null,
requestedBy: input.requestedBy?.name ?? null,
...metadataColumns(info.metadata, await getAuthorAvatar(repoId.split("/")[0])),
}),
d.insert(modelRevisions).values({ modelId, sha: info.sha }),
@@ -202,7 +206,11 @@ function chunk<T>(items: T[], size: number): T[][] {
* rule as exact includes; exclude patterns that would block one of them are dropped, then the
* rule is re-applied to the whole file list so `selected` always matches the stored rule.
*/
export async function addFilesToModel(modelId: string, paths: string[]): Promise<{ jobId: string; added: number }> {
export async function addFilesToModel(
modelId: string,
paths: string[],
options: { pendingApproval?: boolean; requestedBy?: RequestedBy } = {},
): Promise<{ jobId: string; added: number }> {
const d = db();
const model = await d.query.models.findFirst({ where: eq(models.id, modelId) });
if (!model) throw new ModelError("not_found", "Model not found.", 404);
@@ -211,9 +219,9 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
const open = await d.query.jobs.findFirst({
columns: { id: true },
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["queued", "downloading", "verifying"])),
where: and(eq(jobs.modelId, modelId), inArray(jobs.state, ["pending_approval", "queued", "downloading", "verifying"])),
});
if (open) throw new ModelError("busy", "A download for this model is still queued or running. Add files when it has finished.", 409);
if (open) throw new ModelError("busy", "A download for this model is still pending, queued or running. Add files when it has finished.", 409);
const files = await d.select().from(modelFiles).where(eq(modelFiles.modelId, modelId));
const known = new Map(files.map((f) => [f.path, f]));
@@ -233,6 +241,24 @@ export async function addFilesToModel(modelId: string, paths: string[]): Promise
d.update(modelFiles).set({ selected: !f.selected, state: "pending" }).where(eq(modelFiles.id, f.id)),
),
]);
const { jobId } = await queueDownload(modelId, "add");
const { jobId } = await queueDownload(modelId, "add", {
...options,
// API requests can be rejected; the rule before goes with the job so it can be restored.
previousRule: options.requestedBy ? { include: model.includePatterns, exclude: model.excludePatterns } : undefined,
});
return { jobId, added: changed.filter((f) => !f.selected).length };
}
/** Put a model's selection rule back (a rejected API "add files" request) and re-apply it. */
export async function restoreSelection(modelId: string, rule: SelectionRule): Promise<void> {
const d = db();
const files = await d
.select({ id: modelFiles.id, path: modelFiles.path, selected: modelFiles.selected })
.from(modelFiles)
.where(eq(modelFiles.modelId, modelId));
const changed = files.filter((f) => f.selected !== isSelected(f.path, rule));
await d.batch([
d.update(models).set({ includePatterns: rule.include, excludePatterns: rule.exclude, updateDiff: null }).where(eq(models.id, modelId)),
...changed.map((f) => d.update(modelFiles).set({ selected: !f.selected }).where(eq(modelFiles.id, f.id))),
]);
}
+4 -1
View File
@@ -89,6 +89,8 @@ export type PayloadPreview = {
summary: string | null;
model: string | null;
notes: Record<string, string>;
/** Page sections: the run's description, hardware/runtime facts and system summary. */
sections: { heading: string; body: string }[];
/** Top-level keys that will be sent, and env keys (endpoint/host must be absent). */
keys: string[];
envKeys: string[];
@@ -105,7 +107,7 @@ export async function readPayloadPreview(runId: string, pubId: string): Promise<
const data = JSON.parse(raw) as Record<string, unknown> & {
$template?: string;
env?: Record<string, unknown>;
l80?: { title?: string; summary?: string };
l80?: { title?: string; summary?: string; sections?: { heading?: string; body?: string }[] };
single_stream?: Record<string, unknown>;
prefill?: unknown[];
concurrency?: unknown[];
@@ -118,6 +120,7 @@ export async function readPayloadPreview(runId: string, pubId: string): Promise<
summary: data.l80?.summary ?? null,
model: typeof env.model === "string" ? env.model : null,
notes: (env.notes as Record<string, string>) ?? {},
sections: (data.l80?.sections ?? []).map((s) => ({ heading: String(s.heading ?? ""), body: String(s.body ?? "") })),
keys: Object.keys(data),
envKeys: Object.keys(env),
hostRemoved: !("endpoint" in env) && !("host" in env),
+12 -6
View File
@@ -18,6 +18,8 @@ export type RuntimeInput = {
accelerator?: RuntimeAccelerator;
image: string;
description?: string | null;
/** Shown instead of the engine type in benchmarks, for forks (e.g. "vllm-radiance"). */
engineName?: string | null;
env?: Record<string, string>;
extraArgs?: string[];
devices?: string[];
@@ -73,8 +75,8 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
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.",
summary: "llama-server over Vulkan: Intel Arc (incl. B-series) and AMD GPUs via /dev/dri.",
description: "Official llama.cpp server, Vulkan build. Works with Intel and AMD GPUs passed through as /dev/dri; compare it with the SYCL build on Intel.",
devices: ["/dev/dri"],
},
{
@@ -83,8 +85,9 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
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).",
summary: "llama-server with Intel oneAPI/SYCL, for Intel Arc GPUs (A- and B-series, Arc Pro).",
description: "Official llama.cpp server, SYCL build for Intel GPUs (/dev/dri). ZES_ENABLE_SYSMAN=1 lets it see free VRAM, which -ngl auto needs.",
env: { ZES_ENABLE_SYSMAN: "1" },
devices: ["/dev/dri"],
},
{
@@ -103,8 +106,8 @@ export const RUNTIME_PRESETS: RuntimePreset[] = [
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.",
summary: "Official vLLM image for Intel GPUs (Arc incl. B-series, Data Center GPU Max) via /dev/dri.",
description: "Official vLLM, XPU build for Intel GPUs. vLLM reserves --gpu-memory-utilization (default 0.9) of the VRAM up front.",
devices: ["/dev/dri"],
shmSizeMb: 8192,
},
@@ -147,6 +150,8 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
if (/[\r\n\0]/.test(v)) throw new RuntimeValidationError(`Value of ${k} must be a single line.`);
env[k] = v;
}
const engineName = input.engineName?.trim() || null;
if (engineName && !/^[\w][\w.+-]{0,59}$/.test(engineName)) throw new RuntimeValidationError("Engine name: letters, digits and . _ + - (up to 60), e.g. vllm-radiance.");
const extraArgs = (input.extraArgs ?? []).map((a) => a.trim()).filter(Boolean);
for (const a of extraArgs) if (/[\r\n\0]/.test(a)) throw new RuntimeValidationError("Arguments must be single lines.");
const devices = (input.devices ?? []).map((d) => d.trim()).filter(Boolean);
@@ -163,6 +168,7 @@ export function validateRuntime(input: RuntimeInput): Required<RuntimeInput> {
accelerator,
image,
description: input.description?.trim() || null,
engineName,
env,
extraArgs,
devices,
+2 -1
View File
@@ -15,6 +15,7 @@ export const RuntimeBody = z.object({
accelerator: z.enum(RUNTIME_ACCELERATORS).optional(),
image: z.string().max(512),
description: z.string().max(2000).nullable().optional(),
engineName: z.string().max(60).nullable().optional(),
env: z.record(z.string(), z.string().max(4000)).optional(),
extraArgs: z.array(z.string().max(4000)).max(200).optional(),
devices: z.array(z.string().max(200)).max(20).optional(),
@@ -70,7 +71,7 @@ export async function updateRuntime(id: string, input: RuntimeInput): Promise<Ru
.set({
...v,
// A different image has to be looked up (and maybe pulled) again.
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, pullError: null } : {}),
...(imageChanged ? { imageState: "unknown", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, pullError: null } : {}),
})
.where(eq(runtimes.id, id))
.returning();
+2
View File
@@ -56,6 +56,8 @@ const model = (over: Partial<SearchableModel>): SearchableModel => ({
license: "apache-2.0",
status: "ready",
hubStatus: null,
requestedBy: null,
pendingApproval: false,
...over,
});
+13 -3
View File
@@ -14,13 +14,20 @@ export type SearchableModel = {
status: string;
/** Extra status value when the repo or commit is gone from the Hub, e.g. "deleted on Hub". */
hubStatus: string | null;
/** API token name if the model was requested through the API. */
requestedBy: string | null;
/** A download of it waits for approval. */
pendingApproval: boolean;
};
export const FACETS = ["author", "family", "quant", "tag", "status"] as const;
/** Status facet value for models with a download waiting for approval. */
export const PENDING_APPROVAL = "pending_approval";
export const FACETS = ["author", "family", "quant", "tag", "status", "requester"] as const;
export type Facet = (typeof FACETS)[number];
export type Filters = Record<Facet, string[]>;
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [] };
export const EMPTY_FILTERS: Filters = { author: [], family: [], quant: [], tag: [], status: [], requester: [] };
export function facetValues(m: SearchableModel, facet: Facet): string[] {
switch (facet) {
@@ -33,7 +40,9 @@ export function facetValues(m: SearchableModel, facet: Facet): string[] {
case "tag":
return m.tags;
case "status":
return m.hubStatus ? [m.status, m.hubStatus] : [m.status];
return [m.status, m.hubStatus, m.pendingApproval ? PENDING_APPROVAL : null].filter((v): v is string => !!v);
case "requester":
return m.requestedBy ? [m.requestedBy] : [];
}
}
@@ -51,6 +60,7 @@ function haystack(m: SearchableModel): string {
m.license,
m.status,
m.hubStatus,
m.requestedBy,
]
.filter(Boolean)
.join(" ")
+40 -1
View File
@@ -1,8 +1,10 @@
import "server-only";
import { eq } from "drizzle-orm";
import { db } from "@/lib/db/client";
import { settings } from "@/lib/db/schema";
import { type HardwareOverrides, settings } from "@/lib/db/schema";
import { APPROVAL_MODES, type Guardrails, parseGuardrails } from "@/lib/agent-guardrails";
import { isLabelColor } from "@/lib/colors";
import { HARDWARE_OVERRIDES_KEY, HardwareOverrideError, parseOverrides, validateOverrides } from "@/lib/hardware";
import { FILE_ROLE_ORDER, FILE_ROLES, type FileRole, type FileRoleStyles } from "@/lib/file-roles";
import { MIN_SPEED_LIMIT, parseSpeedLimit, SPEED_LIMIT_KEY } from "@/lib/download-limit";
import { DEFAULT_RECOMMENDED_ROLES, RECOMMENDABLE_ROLES } from "@/lib/recommend";
@@ -99,3 +101,40 @@ export async function saveDownloadSpeedLimit(bytesPerSecond: number | null): Pro
else await write(SPEED_LIMIT_KEY, Math.round(bytesPerSecond));
return getDownloadSpeedLimit();
}
const GUARDRAILS_KEY = "agent.guardrails";
/** Limits for downloads requested through the API (Settings → API tokens). */
export async function getGuardrails(): Promise<Guardrails> {
return parseGuardrails(await read<unknown>(GUARDRAILS_KEY));
}
export async function saveGuardrails(input: Partial<Guardrails>): Promise<Guardrails> {
const next = { ...(await getGuardrails()), ...input };
if (!APPROVAL_MODES.includes(next.approvalMode)) throw new SettingsError(`Approval mode must be one of: ${APPROVAL_MODES.join(", ")}.`);
if (!(next.maxRequestBytes >= 1_000_000)) throw new SettingsError("Max size per request must be at least 0.001 GB.");
if (!(next.minFreeBytes >= 0)) throw new SettingsError("Minimum free space can't be negative.");
if (!Number.isInteger(next.maxOpenJobs) || next.maxOpenJobs < 1 || next.maxOpenJobs > 50) throw new SettingsError("Max agent jobs at once must be 1–50.");
const parsed = parseGuardrails(next);
if (parsed.allowedAuthors.length !== next.allowedAuthors.length) throw new SettingsError("The author allowlist contains an invalid name.");
await write(GUARDRAILS_KEY, parsed);
return parsed;
}
/** Manual hardware values (Settings → Hardware) that replace what detection reports. */
export async function getHardwareOverrides(): Promise<HardwareOverrides> {
return parseOverrides(await read<unknown>(HARDWARE_OVERRIDES_KEY));
}
export async function saveHardwareOverrides(input: unknown): Promise<HardwareOverrides> {
let next: HardwareOverrides;
try {
next = validateOverrides(input);
} catch (err) {
if (err instanceof HardwareOverrideError) throw new SettingsError(err.message);
throw err;
}
if (Object.keys(next).length === 0) await db().delete(settings).where(eq(settings.key, HARDWARE_OVERRIDES_KEY));
else await write(HARDWARE_OVERRIDES_KEY, next);
return next;
}
+1 -1
View File
@@ -89,7 +89,7 @@ export async function getSweep(id: string) {
const runIds = sweep.variants.map((v) => v.runId).filter((x): x is string => !!x);
const runs = runIds.length
? await db()
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error })
.select({ id: benchmarkRuns.id, state: benchmarkRuns.state, summary: benchmarkRuns.summary, resources: benchmarkRuns.resources, phase: benchmarkRuns.phase, error: benchmarkRuns.error, meta: benchmarkRuns.meta })
.from(benchmarkRuns)
.where(inArray(benchmarkRuns.id, runIds))
: [];
+8
View File
@@ -0,0 +1,8 @@
// What each API token scope allows, for the settings UI. Pure, safe for the browser.
import type { TokenScope } from "@/lib/db/schema";
export const SCOPE_LABEL: Record<TokenScope, string> = {
"models:read": "Look up Hub repos, list models, read jobs and disk space",
"downloads:create": "Request downloads (within the guardrails)",
};
+4 -3
View File
@@ -26,7 +26,8 @@ export async function proxy(req: NextRequest, event: NextFetchEvent) {
}
export const config = {
// Everything except the Auth.js endpoints, the login page and static assets.
// Exact exclusions only: an org like "loginx" must still go through the gate.
matcher: ["/((?!api/auth/|login$|_next/static/|_next/image/|favicon\\.ico$|icon\\.svg$).*)"],
// Everything except the Auth.js endpoints, the token-authenticated API (/api/v1, checked by
// withToken in each route), the login page and static assets.
// Exact exclusions only: an org like "loginx" or a path like "/api/v1x" must still go through the gate.
matcher: ["/((?!api/auth/|api/v1/|api/v1$|login$|_next/static/|_next/image/|favicon\\.ico$|icon\\.svg$).*)"],
};
+72 -7
View File
@@ -6,17 +6,20 @@ import { access, mkdir, readFile } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
import { asc, eq } from "drizzle-orm";
import { engineLabel, metaNotes, modelLabel, withLoadLinks } from "@/lib/benchmark-meta";
import { REPORT_FILE, RESULTS_FILE, runDir } from "@/lib/benchmark-paths";
import { effectiveHardware, runSetup } from "@/lib/benchmark-snapshot";
import { db } from "@/lib/db/client";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, runtimes } from "@/lib/db/schema";
import { apiKeys, benchmarkLogs, benchmarkRuns, type BenchmarkSummary, deployments, type LogStream, type RunMeta, runtimes } from "@/lib/db/schema";
import { ENGINE_PORT } from "@/lib/deploy-command";
import { coreEnv } from "@/lib/env";
import { abSummary } from "./ab-summary";
import { AB_DEFAULT_MAX_PAIRS, AB_DEFAULT_MDE_PCT, AB_FILE, abArgs, betterbenchBin, betterbenchPython, runArgs, SUMMARY_SCRIPT, SUMMARY_VERSION } from "./betterbench";
import { sanitizeLine } from "./job-log";
import { log } from "./log";
import { normalizePciAddress } from "./hardware";
import { errorCauses } from "./log-causes";
import { ResourceSampler } from "./resources";
import { type GpuTargets, ResourceSampler } from "./resources";
import { docker, workerImage } from "./runtimes";
type Current = {
@@ -25,6 +28,9 @@ type Current = {
deploymentIds: string[];
child: ChildProcess;
sampler: ResourceSampler | null;
/** Recorded at the start; the PCIe links are replaced by the ones seen under load at the end. */
meta: RunMeta | null;
metaB: RunMeta | null;
maxPairs: number | null;
cancelled: boolean;
lost: string | null;
@@ -140,6 +146,43 @@ async function target(deploymentId: string | null): Promise<Target | null> {
return { id: deploymentId, containerId: d.containerId, containerName: d.containerName, engine: d.engine, accelerator: d.accelerator };
}
/**
* What the sampler watches for the GPUs a run uses: NVIDIA via nvidia-smi, Intel/AMD via sysfs (and
* the fdinfo probe for Intel), and every GPU's link where sysfs shows it. Probes run from our own image.
*/
async function gpuTargets(metas: (RunMeta | null)[]): Promise<GpuTargets> {
const addrs = [...new Set(metas.flatMap((m) => m?.gpus.map((g) => g.pciAddress) ?? []).filter((a): a is string => !!a))];
const { hardware, nvidia } = await effectiveHardware();
const image = workerImage();
const used = (hardware?.gpus ?? []).filter((g) => addrs.includes(g.pciAddress));
const pciByIndex: Record<number, string> = {};
for (const g of nvidia) {
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
if (addrs.includes(addr)) pciByIndex[g.index] = addr;
}
const others = used.filter((g) => g.vendor !== "nvidia");
return {
nvidia: image && Object.keys(pciByIndex).length ? { image, pciByIndex } : null,
sysfs: others.map((g, i) => ({ index: i, pciAddress: g.pciAddress, name: g.name ?? `${g.vendor} GPU`, vendor: g.vendor, vramTotalMb: g.vramMb })),
intelProbeImage: image,
linkAddresses: addrs.filter((a) => !a.startsWith("nvidia-")),
};
}
/** A/B notes: the shared host facts once, the engine and model per side. */
function abNotes(a: RunMeta | null, b: RunMeta | null, shared: Record<string, string>): Record<string, string> {
const pick = ["gpus", "pcie_max", "p2p", "rebar", "system", "description"];
const out: Record<string, string> = Object.fromEntries(Object.entries(shared).filter(([k]) => pick.includes(k)));
for (const [side, m] of [["a", a], ["b", b]] as const) {
if (!m) continue;
out[`${side}_engine`] = engineLabel(m) || m.runtime.engine;
out[`${side}_model`] = modelLabel(m);
if (m.contextSize != null) out[`${side}_ctx`] = String(m.contextSize);
if (m.concurrency != null) out[`${side}_concurrency`] = String(m.concurrency);
}
return out;
}
const endpoint = (t: Target) => `http://${t.containerName}:${ENGINE_PORT[t.engine]}/v1`;
async function start(run: typeof benchmarkRuns.$inferSelect) {
@@ -156,6 +199,10 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
const keys = needsKey ? (await db().select({ key: apiKeys.key }).from(apiKeys).orderBy(asc(apiKeys.createdAt)).limit(1)).map((k) => k.key) : [];
const s = run.snapshot;
const maxPairs = run.settings.maxPairs ?? AB_DEFAULT_MAX_PAIRS;
// What runs on what, recorded now (the deployments are up, so the server's version is known).
const setup = await runSetup([a.id, b?.id ?? null]);
const [meta, metaB] = setup.metas;
const metaNotesA = meta ? metaNotes(meta, setup.system, run.description) : {};
const args =
run.kind === "ab" && b
? abArgs({
@@ -165,7 +212,12 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
out: join(dir, AB_FILE),
mdePct: run.settings.mdePct ?? AB_DEFAULT_MDE_PCT,
maxPairs,
notes: { a: s.deploymentName, b: run.snapshotB?.deploymentName ?? "B", ...(run.label ? { label: run.label } : {}) },
notes: {
a: s.deploymentName,
b: run.snapshotB?.deploymentName ?? "B",
...(run.label ? { label: run.label } : {}),
...abNotes(meta, metaB, metaNotesA),
},
})
: runArgs({
endpoint: endpoint(a),
@@ -179,6 +231,7 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
image: s.image,
...(s.options.modelFile ? { file: s.options.modelFile } : {}),
ctx: String(s.options.contextSize),
...metaNotesA,
...(run.label ? { label: run.label } : {}),
},
});
@@ -202,16 +255,18 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
: `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));
await db()
.update(benchmarkRuns)
.set({ state: "running", startedAt: new Date(), error: null, phase: null, meta, metaB, system: setup.system })
.where(eq(benchmarkRuns.id, run.id));
// Resource use of the server(s) under test; GPUs when any side runs on NVIDIA.
// Resource use of the server(s) under test, and of the GPUs they use.
const c = docker();
const nvidia = a.accelerator === "nvidia" || b?.accelerator === "nvidia";
const sampler = c
? new ResourceSampler(
c,
[{ side: "a" as const, containerId: a.containerId }, ...(b ? [{ side: "b" as const, containerId: b.containerId }] : [])],
nvidia ? workerImage() : null,
await gpuTargets([meta, metaB]),
)
: null;
await sampler?.start().catch((err) => log.warn(`resource sampling failed: ${message(err)}`));
@@ -223,6 +278,8 @@ async function start(run: typeof benchmarkRuns.$inferSelect) {
deploymentIds: [a.id, ...(b ? [b.id] : [])],
child,
sampler,
meta,
metaB,
maxPairs: run.kind === "ab" ? maxPairs : null,
cancelled: false,
lost: null,
@@ -247,6 +304,14 @@ async function done(cur: Current, code: number | null, signal: NodeJS.Signals |
}
const resources = (await cur.sampler?.stop().catch(() => null)) ?? null;
if (current === cur) current = null;
if (resources?.links) {
const loaded = (m: RunMeta | null) => withLoadLinks(m, resources.links, !!m?.overridden.includes("pcie link"));
await db()
.update(benchmarkRuns)
.set({ meta: loaded(cur.meta), metaB: loaded(cur.metaB) })
.where(eq(benchmarkRuns.id, id))
.catch((err) => log.warn(`benchmark ${id}: link update failed: ${message(err)}`));
}
const dir = runDir(id);
const results = join(dir, cur.kind === "ab" ? AB_FILE : RESULTS_FILE);
const hasReport = cur.kind === "run" && (await exists(join(dir, REPORT_FILE)));
+18 -2
View File
@@ -29,6 +29,12 @@ describe("betterbench runArgs", () => {
]);
});
it("drops --quick when passes are given (BetterBench refuses both)", () => {
const args = runArgs({ ...base, settings: { quick: true, passes: 2, warmup: null, phases: [] }, notes: {} });
assert.ok(!args.includes("--quick"));
assert.deepEqual(args.slice(args.indexOf("--passes"), args.indexOf("--passes") + 2), ["--passes", "2"]);
});
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");
@@ -46,8 +52,18 @@ describe("betterbench runArgs", () => {
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("0, GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84, NVIDIA GeForce RTX 3080, 10240, 617.14, 00000000:2B:00.0, 1, 4, 16, 16\n"), [
{
vendor: "nvidia",
index: 0,
uuid: "GPU-02d5eae7-e371-6b8f-adaf-2b18648bdb84",
name: "NVIDIA GeForce RTX 3080",
memoryMb: 10240,
driver: "617.14",
pciAddress: "0000:2b:00.0",
linkCurrent: { gen: 1, width: 16 },
linkMax: { gen: 4, width: 16 },
},
]);
assert.deepEqual(parseNvidiaSmi("NVIDIA-SMI has failed"), []);
});
+2 -1
View File
@@ -34,7 +34,8 @@ export function runArgs(o: {
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"] : []),
// BetterBench refuses --quick together with --passes; explicit passes win.
...(s.quick && s.passes == null ? ["--quick"] : []),
...(s.passes != null ? ["--passes", String(s.passes)] : []),
...(s.warmup != null ? ["--warmup", String(s.warmup)] : []),
...s.phases.map((p) => `--${p}`),
+19 -2
View File
@@ -6,13 +6,14 @@ import { stat } from "node:fs/promises";
import { join } from "node:path";
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 { apiKeys, deploymentLogs, deployments, type EngineInfo, type LogStream, models, type RuntimeEngine, 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";
import { log } from "./log";
import { fetchEngineInfo, versionFromLog } from "./engine-info";
import { errorCauses } from "./log-causes";
import { docker } from "./runtimes";
import type { DockerClient } from "./docker/client";
@@ -168,6 +169,8 @@ async function start(c: DockerClient, d: Deployment) {
ShmSize: runtime.shmSizeMb ? runtime.shmSizeMb * 2 ** 20 : undefined,
Devices: devices.map((p) => ({ PathOnHost: p, PathInContainer: p, CgroupPermissions: "rwm" })),
DeviceRequests: deviceRequests,
// Images that don't run as root need the render/video group to open /dev/dri.
GroupAdd: devices.some((p) => p.startsWith("/dev/dri")) ? (host.driGroups ?? []).map(String) : [],
CapAdd: runtime.numaTuning ? ["SYS_NICE"] : [],
SecurityOpt: runtime.numaTuning ? ["seccomp=unconfined"] : [],
PortBindings: d.hostPort ? { [portKey]: [{ HostPort: String(d.hostPort) }] } : {},
@@ -196,6 +199,7 @@ async function start(c: DockerClient, d: Deployment) {
error: null,
exitCode: null,
stats: null,
engineInfo: null,
});
await c.startContainer(created.Id);
// A fresh container: everything it printed belongs to this run. (Following before the start
@@ -241,6 +245,19 @@ async function healthy(name: string, port: number): Promise<boolean> {
}
}
/** Version, slots and context from the server; the version from its startup log if it doesn't say. */
async function engineInfo(d: Deployment, engine: RuntimeEngine, base: string): Promise<EngineInfo> {
const key = d.options.requireApiKey ? ((await loadApiKeys())[0] ?? null) : null;
const info = await fetchEngineInfo(engine, base, key);
if (!info.version) {
await flushDeploymentLogs();
const lines = await db().select({ line: deploymentLogs.line }).from(deploymentLogs).where(eq(deploymentLogs.deploymentId, d.id)).orderBy(asc(deploymentLogs.id)).limit(500);
info.version = versionFromLog(engine, lines.map((l) => l.line));
}
if (info.version) addLog(d.id, "system", `Engine: ${engine} ${info.version}${info.slots ? `, ${info.slots} slots` : ""}${info.contextSize ? `, context ${info.contextSize}` : ""}`);
return { ...info, at: new Date().toISOString() };
}
// --- reconcile -----------------------------------------------------------------------------------
const lastStats = new Map<string, number>();
@@ -284,7 +301,7 @@ async function reconcileOne(c: DockerClient, d: Deployment) {
const now = new Date();
const secs = d.startedAt ? ((now.getTime() - d.startedAt.getTime()) / 1000).toFixed(1) : "?";
addLog(d.id, "system", `Ready after ${secs} s.`);
await update(d.id, { state: "running", readyAt: now });
await update(d.id, { state: "running", readyAt: now, engineInfo: await engineInfo(d, runtime?.engine ?? "llama.cpp", `http://${d.containerName}:${port}`) });
} else if (d.startedAt && Date.now() - d.startedAt.getTime() > START_TIMEOUT_MS) {
await c.stopContainer(d.containerId).catch(() => {});
await c.removeContainer(d.containerId).catch(() => {});
+45
View File
@@ -0,0 +1,45 @@
// What a ready inference server says about itself: version, slots and context. llama.cpp: GET /props
// (build_info "b11429-d81235049", total_slots, default_generation_settings.n_ctx; checked with build
// 11429). vLLM: GET /version and GET /v1/models (max_model_len). Startup log lines as a fallback.
import type { EngineInfo, RuntimeEngine } from "@/lib/db/schema";
type Json = Record<string, unknown>;
const int = (v: unknown) => (typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null);
const str = (v: unknown) => (typeof v === "string" && v.trim() ? v.trim().slice(0, 100) : null);
export function parseLlamaProps(props: Json | null): Omit<EngineInfo, "at"> {
const gen = (props?.default_generation_settings ?? {}) as Json;
return { version: str(props?.build_info), slots: int(props?.total_slots), contextSize: int(gen.n_ctx) };
}
export function parseVllm(version: Json | null, models: Json | null): Omit<EngineInfo, "at"> {
const data = Array.isArray(models?.data) ? (models.data as Json[]) : [];
return { version: str(version?.version), slots: null, contextSize: int(data[0]?.max_model_len) };
}
/** "build: 11429 (d8123504)" (llama.cpp), "vLLM API server version 0.31.0" (vLLM and most forks). */
export function versionFromLog(engine: RuntimeEngine, lines: string[]): string | null {
const re = engine === "llama.cpp" ? /\bbuild[:=]\s*(\d+)\s*\(([0-9a-f]+)\)/ : /\bversion\s+v?(\d+\.\d+[\w.+-]*)/i;
for (const l of lines) {
const m = l.match(re);
if (m) return engine === "llama.cpp" ? `b${m[1]}-${m[2]}` : m[1];
}
return null;
}
async function getJson(url: string, key: string | null): Promise<Json | null> {
try {
const res = await fetch(url, { headers: key ? { Authorization: `Bearer ${key}` } : {}, signal: AbortSignal.timeout(3_000) });
return res.ok ? ((await res.json()) as Json) : null;
} catch {
return null;
}
}
/** Ask the server at http://name:port; `key` when the deployment requires an API key. */
export async function fetchEngineInfo(engine: RuntimeEngine, base: string, key: string | null): Promise<Omit<EngineInfo, "at">> {
if (engine === "llama.cpp") return parseLlamaProps(await getJson(`${base}/props`, key));
const [version, models] = await Promise.all([getJson(`${base}/version`, key), getJson(`${base}/v1/models`, key)]);
return parseVllm(version, models);
}
+169
View File
@@ -0,0 +1,169 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { estimateVramMb } from "@/lib/deploy-command";
import { aggregateFdinfo, drmUtilization, parseFdinfo, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs";
import type { SysFs } from "./hardware";
import { parseGpuLine, summarizeSamples } from "./resources";
import { parseDriGroups } from "./runtimes";
/** An in-memory sysfs: files plus directory links. */
function memFs(files: Record<string, string>, links: Record<string, string> = {}): SysFs {
const resolve = (p: string) => {
const hit = Object.keys(links).find((l) => p === l || p.startsWith(`${l}/`));
return hit ? links[hit] + p.slice(hit.length) : p;
};
return {
read: async (p) => files[resolve(p)]?.trim() ?? null,
resolve: async (p) => resolve(p),
list: async (d) => {
const dir = `${resolve(d)}/`;
return [...new Set(Object.keys(files).filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]))];
},
};
}
const xe = (client: number, vramKiB: number, rcs: number, ccs: number, total: number) => `pos:\t0
flags:\t02100002
drm-driver:\txe
drm-client-id:\t${client}
drm-pdev:\t0000:03:00.0
drm-total-system:\t0
drm-resident-system:\t0
drm-total-gtt:\t12 KiB
drm-total-vram0:\t${vramKiB + 1024} KiB
drm-resident-vram0:\t${vramKiB} KiB
drm-cycles-rcs:\t${rcs}
drm-total-cycles-rcs:\t${total}
drm-cycles-ccs:\t${ccs}
drm-total-cycles-ccs:\t${total}
`;
describe("DRM fdinfo", () => {
it("parses xe: resident VRAM, cycles per engine class", () => {
const c = parseFdinfo(xe(42, 9_437_184, 1000, 30_000, 50_000))!;
assert.equal(c.pdev, "0000:03:00.0");
assert.equal(c.clientId, "42");
assert.equal(c.vramBytes, 9_437_184 * 1024);
assert.deepEqual(c.cycles, { rcs: 1000, ccs: 30_000 });
assert.deepEqual(c.totalCycles, { rcs: 50_000, ccs: 50_000 });
});
it("parses i915 (local memory, nanoseconds) and amdgpu's legacy keys", () => {
const i915 = parseFdinfo("drm-driver: i915\ndrm-pdev: 0000:00:02.0\ndrm-client-id: 7\ndrm-engine-render: 1000000 ns\ndrm-engine-capacity-video: 2\ndrm-total-local0: 1024 KiB\ndrm-resident-local0: 512 KiB\n")!;
assert.equal(i915.vramBytes, 512 * 1024);
assert.deepEqual(i915.ns, { render: 1_000_000 });
const amd = parseFdinfo("drm-driver:\tamdgpu\ndrm-pdev:\t0000:0a:00.0\ndrm-client-id:\t3\ndrm-memory-vram:\t2048 KiB\ndrm-memory-gtt:\t16 KiB\ndrm-engine-gfx:\t5000 ns\n")!;
assert.equal(amd.vramBytes, 2048 * 1024);
assert.deepEqual(amd.ns, { gfx: 5000 });
assert.equal(parseFdinfo("pos: 0\nflags: 02\n"), null);
});
it("counts each client once and takes the GPU clock as is", () => {
const s = aggregateFdinfo(1000, [xe(1, 1024, 10, 20, 100), xe(1, 1024, 10, 20, 100), xe(2, 2048, 5, 0, 110), "pos: 0\n"]);
const g = s.gpus["0000:03:00.0"];
assert.equal(g.vramBytes, 3072 * 1024);
assert.deepEqual(g.cycles, { rcs: 15, ccs: 20 });
assert.deepEqual(g.totalCycles, { rcs: 110, ccs: 110 });
});
it("reports the busiest engine class between two snapshots", () => {
const a = aggregateFdinfo(0, [xe(1, 1024, 0, 0, 1000)]).gpus["0000:03:00.0"];
const b = aggregateFdinfo(2000, [xe(1, 1024, 100, 800, 2000)]).gpus["0000:03:00.0"];
assert.equal(drmUtilization(a, b, 2), 80);
assert.equal(drmUtilization(undefined, b, 2), null);
// A client that exited makes the sum drop: idle, not negative.
const c = aggregateFdinfo(4000, [xe(2, 0, 0, 0, 3000)]).gpus["0000:03:00.0"];
assert.equal(drmUtilization(b, c, 2), 0);
// Nanosecond engines: busy time over wall time.
assert.equal(drmUtilization({ vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 0 } }, { vramBytes: 0, cycles: {}, totalCycles: {}, ns: { gfx: 1e9 } }, 2), 50);
});
});
describe("hwmon and amdgpu sysfs", () => {
const dev = "/sys/devices/pci0000:00/0000:00:01.0/0000:03:00.0";
const fs = memFs(
{
[`${dev}/hwmon/hwmon3/name`]: "xe",
[`${dev}/hwmon/hwmon3/energy1_input`]: "5000000",
[`${dev}/hwmon/hwmon3/power1_max`]: "200000000",
[`${dev}/hwmon/hwmon3/temp2_input`]: "61000",
[`${dev}/hwmon/hwmon3/temp2_label`]: "pkg",
[`${dev}/hwmon/hwmon3/temp3_input`]: "70000",
[`${dev}/hwmon/hwmon3/temp3_label`]: "vram",
"/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/power1_average": "150000000",
"/sys/devices/pci0000:00/0000:0a:00.0/hwmon/hwmon1/temp1_input": "55000",
"/sys/devices/pci0000:00/0000:0a:00.0/mem_info_vram_used": String(4 * 2 ** 30),
"/sys/devices/pci0000:00/0000:0a:00.0/gpu_busy_percent": "87",
},
{ "/sys/bus/pci/devices/0000:03:00.0": dev, "/sys/bus/pci/devices/0000:0a:00.0": "/sys/devices/pci0000:00/0000:0a:00.0" },
);
it("reads xe's energy counter and package temperature", async () => {
assert.deepEqual(await readHwmon(fs, "0000:03:00.0"), { energyUj: 5_000_000, powerW: null, tempC: 61 });
});
it("reads amdgpu's power, temperature, VRAM in use and busy percent", async () => {
assert.deepEqual(await readHwmon(fs, "0000:0a:00.0"), { energyUj: null, powerW: 150, tempC: 55 });
assert.deepEqual(await readAmdUsage(fs, "0000:0a:00.0"), { vramUsedMb: 4096, util: 87 });
});
it("turns energy into power between readings", () => {
assert.equal(powerBetween({ energyUj: 1_000_000, powerW: null, tempC: null }, { energyUj: 401_000_000, powerW: null, tempC: null }, 2), 200);
assert.equal(powerBetween(null, { energyUj: 5, powerW: null, tempC: null }, 0), null);
assert.equal(powerBetween(null, { energyUj: null, powerW: 150, tempC: null }, 0), 150);
});
});
describe("GPU summaries", () => {
it("keeps unknown figures unknown and adds temperature", () => {
const s = summarizeSamples(
[],
[
{ index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 120, tempC: 60 },
{ index: 0, name: "Intel Arc Pro B65", pciAddress: "0000:03:00.0", vramTotalMb: 32768, vramUsedMb: null, util: null, powerW: 180, tempC: 70 },
],
4,
);
assert.deepEqual(s.gpus[0], {
index: 0,
name: "Intel Arc Pro B65",
pciAddress: "0000:03:00.0",
vramTotalMb: 32768,
vramPeakMb: null,
vramAvgMb: null,
utilAvg: null,
utilPeak: null,
powerAvgW: 150,
powerPeakW: 180,
tempAvgC: 65,
tempPeakC: 70,
});
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16, 47")?.tempC, 47);
});
it("reads /dev/dri group IDs", () => {
assert.deepEqual(parseDriGroups(["/dev/dri/card0 44", "/dev/dri/renderD128 993", "/dev/dri/renderD129 993", "/dev/dri/by-path 0", "stat: error"]), [44, 993]);
});
});
describe("VRAM estimate", () => {
const GiB = 2 ** 30;
it("adds weights, KV cache and buffers for llama.cpp with all layers on the GPU", () => {
const f16 = estimateVramMb(5 * GiB, 32768, "llama.cpp", {}, 32768)!;
const q8 = estimateVramMb(5 * GiB, 32768, "llama.cpp", { cacheTypeK: "q8_0", cacheTypeV: "q8_0" }, 32768)!;
assert.ok(f16 > 5120 + 1024 && f16 < 5120 + 1024 + 8192, String(f16));
assert.ok(q8 < f16);
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "all" }, null), estimateVramMb(5 * GiB, 4096, "llama.cpp", {}, null));
});
it("can't tell partial offload", () => {
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { gpuLayers: "20" }, 32768), null);
assert.equal(estimateVramMb(5 * GiB, 4096, "llama.cpp", { cpuMoe: true }, 32768), null);
});
it("uses vLLM's memory share of the VRAM", () => {
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, 32768), Math.ceil(32768 * 0.9));
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", { gpuMemoryUtilization: 0.5 }, 32768), 16384);
assert.equal(estimateVramMb(5 * GiB, 4096, "vllm", {}, null), null);
});
});
+175
View File
@@ -0,0 +1,175 @@
// GPU telemetry without nvidia-smi, for Intel and AMD GPUs.
// - hwmon (sysfs, readable unprivileged): power (energy counter or power reading) and temperature.
// - AMD (amdgpu): VRAM in use and busy percent are plain sysfs files.
// - Intel (xe, i915): the driver has no whole-GPU VRAM/utilization file; both are only reported per
// process in DRM fdinfo (/proc/<pid>/fdinfo, kernel "drm-usage-stats"). A probe container in the
// host's PID namespace dumps those (INTEL_PROBE_SCRIPT); parsing and aggregation happen here.
// Pure parsers for tests; the readers take a SysFs.
import { posix } from "node:path";
import type { SysFs } from "./hardware";
const { join } = posix;
export type HwmonReading = { energyUj: number | null; powerW: number | null; tempC: number | null };
const num = (s: string | null) => (s != null && /^-?\d+$/.test(s.trim()) ? Number(s.trim()) : null);
/**
* Power and temperature from the device's hwmon: an energy counter (µJ, xe: energy1_input) when there
* is one, else a power reading (µW, amdgpu: power1_average); the "pkg"/"edge" temperature, else the
* highest one.
*/
export async function readHwmon(fs: SysFs, pciAddress: string): Promise<HwmonReading> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const dirs = (await fs.list(join(dev, "hwmon"))).filter((d) => d.startsWith("hwmon"));
const out: HwmonReading = { energyUj: null, powerW: null, tempC: null };
for (const d of dirs) {
const h = join(dev, "hwmon", d);
const files = await fs.list(h);
const energy = files.filter((f) => /^energy\d+_input$/.test(f)).sort()[0];
if (energy && out.energyUj == null) out.energyUj = num(await fs.read(join(h, energy)));
for (const f of ["power1_average", "power1_input"]) {
if (out.powerW != null || !files.includes(f)) continue;
const uw = num(await fs.read(join(h, f)));
if (uw != null) out.powerW = uw / 1e6;
}
const temps: { label: string; c: number }[] = [];
for (const f of files.filter((x) => /^temp\d+_input$/.test(x))) {
const v = num(await fs.read(join(h, f)));
if (v == null || v <= 0) continue;
const label = (await fs.read(join(h, f.replace("_input", "_label")))) ?? "";
temps.push({ label: label.toLowerCase(), c: v / 1000 });
}
const main = temps.find((t) => t.label === "pkg" || t.label === "edge") ?? temps.sort((a, b) => b.c - a.c)[0];
if (main && out.tempC == null) out.tempC = main.c;
}
return out;
}
/** amdgpu's own whole-GPU figures. */
export async function readAmdUsage(fs: SysFs, pciAddress: string): Promise<{ vramUsedMb: number | null; util: number | null }> {
const dev = await fs.resolve(join("/sys/bus/pci/devices", pciAddress));
const used = num(await fs.read(join(dev, "mem_info_vram_used")));
const busy = num(await fs.read(join(dev, "gpu_busy_percent")));
return { vramUsedMb: used != null ? Math.round(used / 2 ** 20) : null, util: busy };
}
/** Power between two readings: from the energy counter if both have one, else the instant reading. */
export function powerBetween(prev: HwmonReading | null, cur: HwmonReading, seconds: number): number | null {
if (prev?.energyUj != null && cur.energyUj != null && cur.energyUj >= prev.energyUj && seconds > 0) return (cur.energyUj - prev.energyUj) / 1e6 / seconds;
return cur.powerW;
}
// --- DRM fdinfo ---------------------------------------------------------------------------------
export type DrmClient = {
pdev: string;
clientId: string;
/** Bytes resident in device memory (regions named vram* / local*). */
vramBytes: number;
/** Per engine class: busy cycles and the GPU's total cycles (xe), or busy nanoseconds (i915, amdgpu). */
cycles: Record<string, number>;
totalCycles: Record<string, number>;
ns: Record<string, number>;
};
const UNIT: Record<string, number> = { "": 1, KiB: 1024, MiB: 2 ** 20, GiB: 2 ** 30 };
/** One /proc/<pid>/fdinfo/<fd> of a DRM client; null for other files. */
export function parseFdinfo(text: string): DrmClient | null {
const kv = new Map<string, string>();
for (const line of text.split("\n")) {
const i = line.indexOf(":");
if (i > 0) kv.set(line.slice(0, i).trim(), line.slice(i + 1).trim());
}
const pdev = kv.get("drm-pdev");
const clientId = kv.get("drm-client-id");
if (!pdev || !clientId) return null;
const c: DrmClient = { pdev: pdev.toLowerCase(), clientId, vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} };
// Resident is what occupies VRAM now; older drivers only report total or the legacy drm-memory-*.
const mem: Record<"resident" | "total" | "memory", number> = { resident: 0, total: 0, memory: 0 };
const seen = { resident: false, total: false, memory: false };
for (const [k, v] of kv) {
let m = k.match(/^drm-(resident|total|memory)-(.+)$/);
if (m && /vram|local/i.test(m[2])) {
const [, n, unit = ""] = v.match(/^(\d+)\s*(KiB|MiB|GiB)?$/) ?? [];
if (n == null) continue;
const kind = m[1] as keyof typeof mem;
mem[kind] += Number(n) * (UNIT[unit] ?? 1);
seen[kind] = true;
continue;
}
if ((m = k.match(/^drm-total-cycles-(.+)$/))) c.totalCycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-cycles-(.+)$/))) c.cycles[m[1]] = Number(v) || 0;
else if ((m = k.match(/^drm-engine-(.+)$/)) && !k.startsWith("drm-engine-capacity-")) c.ns[m[1]] = Number(v.replace(/\s*ns$/, "")) || 0;
}
c.vramBytes = seen.resident ? mem.resident : seen.total ? mem.total : mem.memory;
return c;
}
export type DrmSnapshot = { t: number; gpus: Record<string, { vramBytes: number; cycles: Record<string, number>; totalCycles: Record<string, number>; ns: Record<string, number> }> };
/**
* Sum the clients per GPU. One client shows up once per open file descriptor (and process), so
* duplicates by client id are counted once. The GPU's total cycles are a clock, not a sum: max.
*/
export function aggregateFdinfo(t: number, texts: string[]): DrmSnapshot {
const seen = new Set<string>();
const gpus: DrmSnapshot["gpus"] = {};
for (const text of texts) {
const c = parseFdinfo(text);
if (!c || seen.has(`${c.pdev}#${c.clientId}`)) continue;
seen.add(`${c.pdev}#${c.clientId}`);
const g = (gpus[c.pdev] ??= { vramBytes: 0, cycles: {}, totalCycles: {}, ns: {} });
g.vramBytes += c.vramBytes;
for (const [k, v] of Object.entries(c.cycles)) g.cycles[k] = (g.cycles[k] ?? 0) + v;
for (const [k, v] of Object.entries(c.totalCycles)) g.totalCycles[k] = Math.max(g.totalCycles[k] ?? 0, v);
for (const [k, v] of Object.entries(c.ns)) g.ns[k] = (g.ns[k] ?? 0) + v;
}
return { t, gpus };
}
/**
* Busy percent of the busiest engine class between two snapshots (like intel_gpu_top's headline).
* Clients that exit in between make a sum drop; those classes count as idle rather than negative.
*/
export function drmUtilization(prev: DrmSnapshot["gpus"][string] | undefined, cur: DrmSnapshot["gpus"][string], seconds: number): number | null {
if (!prev || seconds <= 0) return null;
const busy: number[] = [];
for (const cls of Object.keys(cur.cycles)) {
const dc = cur.cycles[cls] - (prev.cycles[cls] ?? 0);
const dt = (cur.totalCycles[cls] ?? 0) - (prev.totalCycles[cls] ?? 0);
if (dt > 0) busy.push(Math.max(0, dc) / dt);
}
for (const cls of Object.keys(cur.ns)) busy.push(Math.max(0, cur.ns[cls] - (prev.ns[cls] ?? 0)) / (seconds * 1e9));
if (busy.length === 0) return null;
return Math.min(100, Math.max(...busy) * 100);
}
/**
* Runs inside the probe container (Node from Kaname's own image): every interval, the fdinfo of every
* open DRM file on the host, one JSON line. Reads only; prints nothing else.
*/
export const INTEL_PROBE_SCRIPT = `
const fs = require("fs");
const every = Number(process.argv[1]) || 2000;
function tick() {
const f = [];
let pids = [];
try { pids = fs.readdirSync("/proc").filter((p) => /^\\d+$/.test(p)); } catch {}
for (const p of pids) {
let fds = [];
try { fds = fs.readdirSync("/proc/" + p + "/fdinfo"); } catch { continue; }
for (const d of fds) {
try {
const t = fs.readFileSync("/proc/" + p + "/fdinfo/" + d, "utf8");
if (t.includes("drm-client-id:")) f.push(t);
} catch {}
}
}
process.stdout.write(JSON.stringify({ t: Date.now(), f }) + "\\n");
}
tick();
setInterval(tick, every);
`;
+284
View File
@@ -0,0 +1,284 @@
import assert from "node:assert/strict";
import { before, describe, it } from "node:test";
import { fetchEngineInfo, parseLlamaProps, parseVllm, versionFromLog } from "./engine-info";
import { currentLinks, detectHardware, gpuDisplayName, type SysFs, largestBarMb, mountDevice, normalizePciAddress, parseCpu, parseP2p, pciName } from "./hardware";
import { fastestLinks, parseGpuLine, summarizeSamples } from "./resources";
import { parseNvidiaSmi, repoDigest } from "./runtimes";
const GiB = 2 ** 30;
const hex = (n: number) => `0x${n.toString(16).padStart(16, "0")}`;
/** A `resource` line: start, end, flags (0x0014220c = 64-bit prefetchable memory). */
const bar = (start: number, size: number) => `${hex(start)} ${hex(start + size - 1)} 0x000000000014220c`;
const EMPTY = `${hex(0)} ${hex(0)} 0x0000000000000000`;
const PCI_IDS = `# test pci.ids
10de NVIDIA Corporation
\t2684 AD102 [GeForce RTX 4090]
8086 Intel Corporation
\te211 Battlemage G31 [Arc Pro B65]
\t\t8086 1234 Arc Pro B65 32GB
\te20b Battlemage G21 [Arc B580]
1af4 Red Hat, Inc.
`;
const CPUINFO = [0, 1, 2, 3]
.map((p) => `processor\t: ${p}\nmodel name\t: AMD EPYC 9124 16-Core Processor\nphysical id\t: 0\ncore id\t\t: ${p % 2}\nflags\t\t: fpu avx2 hypervisor\n`)
.join("\n");
const files = new Map<string, string>();
const links = new Map<string, string>();
/** An in-memory sysfs: files plus directory symlinks (sysfs names contain ":", which Windows can't store). */
function memFs(): SysFs {
const resolve = (p: string): string => {
for (let i = 0; i < 10; i++) {
const hit = [...links.keys()].find((l) => p === l || p.startsWith(`${l}/`));
if (!hit) return p;
p = links.get(hit)! + p.slice(hit.length);
}
return p;
};
return {
read: async (p) => files.get(resolve(p))?.trim() ?? null,
resolve: async (p) => resolve(p),
list: async (d) => {
const dir = `${resolve(d)}/`;
const names = [...files.keys(), ...links.keys()].filter((k) => k.startsWith(dir)).map((k) => k.slice(dir.length).split("/")[0]);
return [...new Set(names)];
},
};
}
const file = (path: string, content: string) => files.set(`/${path}`, content);
const link = (path: string, target: string) => links.set(`/${path}`, `/${target}`);
before(() => {
// Intel Arc Pro B65: root port 00:01.0 → on-card switch (01:00.0 up, 02:01.0 down) → GPU 03:00.0.
const rp = "sys/devices/pci0000:00/0000:00:01.0";
const up = `${rp}/0000:01:00.0`;
const down = `${up}/0000:02:01.0`;
const gpu = `${down}/0000:03:00.0`;
file(`${rp}/vendor`, "0x1022");
file(`${up}/vendor`, "0x8086");
file(`${up}/current_link_speed`, "16.0 GT/s PCIe");
file(`${up}/current_link_width`, "8");
file(`${up}/max_link_speed`, "32.0 GT/s PCIe");
file(`${up}/max_link_width`, "16");
file(`${down}/vendor`, "0x8086");
file(`${gpu}/vendor`, "0x8086");
file(`${gpu}/device`, "0xe211");
file(`${gpu}/subsystem_vendor`, "0x8086");
file(`${gpu}/subsystem_device`, "0x1234");
file(`${gpu}/class`, "0x030000");
file(`${gpu}/uevent`, "DRIVER=xe\nPCI_CLASS=30000\nPCI_SLOT_NAME=0000:03:00.0");
// What the GPU function itself reports: the switch-internal link.
file(`${gpu}/current_link_speed`, "2.5 GT/s PCIe");
file(`${gpu}/current_link_width`, "1");
file(`${gpu}/resource`, [bar(0xa0000000, 16 * 2 ** 20), EMPTY, bar(0x4000000000, 32 * GiB)].join("\n"));
file(`${gpu}/tile0/physical_vram_size_bytes`, String(32 * GiB));
link("sys/bus/pci/devices/0000:03:00.0", gpu);
// NVIDIA card directly on a root port, 256 MiB BAR (no ReBAR).
const nv = "sys/devices/pci0000:00/0000:00:03.0/0000:05:00.0";
file("sys/devices/pci0000:00/0000:00:03.0/vendor", "0x1022");
file(`${nv}/vendor`, "0x10de");
file(`${nv}/device`, "0x2684");
file(`${nv}/class`, "0x030000");
file(`${nv}/uevent`, "DRIVER=nvidia");
file(`${nv}/current_link_speed`, "16.0 GT/s PCIe");
file(`${nv}/current_link_width`, "16");
file(`${nv}/max_link_speed`, "16.0 GT/s PCIe");
file(`${nv}/max_link_width`, "16");
file(`${nv}/resource`, [bar(0xb0000000, 16 * 2 ** 20), bar(0x6000000000, 256 * 2 ** 20)].join("\n"));
link("sys/bus/pci/devices/0000:05:00.0", nv);
file("sys/module/nvidia/version", "580.82.07");
// A virtio NIC: not a GPU.
file("sys/devices/pci0000:00/0000:00:12.0/vendor", "0x1af4");
file("sys/devices/pci0000:00/0000:00:12.0/class", "0x020000");
link("sys/bus/pci/devices/0000:00:12.0", "sys/devices/pci0000:00/0000:00:12.0");
file("usr/share/misc/pci.ids", PCI_IDS);
file("proc/cpuinfo", CPUINFO);
file("proc/meminfo", "MemTotal: 65536000 kB\nMemFree: 1 kB\n");
file("sys/class/dmi/id/sys_vendor", "QEMU");
file("sys/class/dmi/id/product_name", "Standard PC (Q35 + ICH9, 2009)");
// Models on /dev/nvme0n1p2 (259:2).
file("proc/self/mountinfo", ["22 1 259:1 / / rw - ext4 /dev/nvme0n1p1 rw", "1521 1471 259:2 /srv/models /models rw,relatime - ext4 /dev/nvme0n1p2 rw"].join("\n"));
const disk = "sys/devices/pci0000:00/0000:00:06.0/nvme/nvme0/nvme0n1";
file(`${disk}/device/model`, "Samsung SSD 990 PRO 2TB ");
file(`${disk}/queue/rotational`, "0");
file(`${disk}/size`, String(3_907_029_168));
file(`${disk}/nvme0n1p2/partition`, "2");
link("sys/dev/block/259:2", `${disk}/nvme0n1p2`);
});
describe("hardware detection (sysfs fixture)", () => {
it("finds GPUs, the card's upstream link behind an on-card switch, ReBAR and names", async () => {
const hw = await detectHardware({
fs: memFs(),
modelsDir: "/models",
kernel: "6.17.1-pve",
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 4090", memoryMb: 24564, driver: "580.82.07", pciAddress: "00000000:05:00.0" }],
});
assert.equal(hw.gpus.length, 2);
const [intel, nv] = hw.gpus;
assert.deepEqual(
{ ...intel },
{
vendor: "intel",
pciAddress: "0000:03:00.0",
name: "Intel Arc Pro B65 32GB",
vramMb: 32768,
driver: "xe",
driverVersion: "kernel 6.17.1-pve",
linkCurrent: { gen: 4, width: 8 },
linkMax: { gen: 5, width: 16 },
barMb: 32768,
rebar: true,
},
);
assert.equal(nv.name, "NVIDIA GeForce RTX 4090");
assert.equal(nv.vramMb, 24564);
assert.equal(nv.driverVersion, "580.82.07");
assert.deepEqual(nv.linkCurrent, { gen: 4, width: 16 });
assert.equal(nv.barMb, 256);
assert.equal(nv.rebar, false);
assert.equal(hw.p2p, null);
});
it("reads CPU, RAM, VM and the models disk", async () => {
const hw = await detectHardware({ fs: memFs(), modelsDir: "/models/", kernel: "6.17.1-pve" });
assert.deepEqual(hw.cpu, { model: "AMD EPYC 9124 16-Core Processor", cores: 2, threads: 4 });
assert.equal(hw.memoryBytes, 65536000 * 1024);
assert.deepEqual(hw.virtualization, { vm: true, hypervisor: "KVM/QEMU" });
assert.deepEqual(hw.storage, { model: "Samsung SSD 990 PRO 2TB", kind: "nvme", sizeBytes: 3_907_029_168 * 512 });
});
it("doesn't fail on a host without any of it", async () => {
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
const hw = await detectHardware({ fs: empty, modelsDir: "/models", kernel: null });
assert.deepEqual(hw.gpus, []);
assert.equal(hw.storage, null);
assert.deepEqual(hw.cpu, { model: null, cores: null, threads: null });
assert.deepEqual(hw.virtualization, { vm: null, hypervisor: null });
});
});
describe("hardware parsers", () => {
it("normalizes nvidia-smi bus IDs and reads them from the probe CSV", () => {
assert.equal(normalizePciAddress("00000000:0A:00.0"), "0000:0a:00.0");
assert.deepEqual(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07, 00000000:01:00.0")[0].pciAddress, "0000:01:00.0");
assert.equal(parseNvidiaSmi("0, GPU-abc, NVIDIA RTX A6000, 49140, 580.82.07")[0].pciAddress, null);
});
it("takes the largest memory BAR", () => {
assert.equal(largestBarMb([bar(0x1000, 2 ** 20), bar(0x100000000, 8 * GiB), "0x0000000000001000 0x000000000000107f 0x0000000000040101"].join("\n")), 8192);
assert.equal(largestBarMb(EMPTY), null);
assert.equal(largestBarMb(null), null);
});
it("names GPUs from pci.ids, board name first", () => {
assert.equal(pciName(PCI_IDS, "0x8086", "0xe20b"), "Battlemage G21 [Arc B580]");
assert.equal(pciName(PCI_IDS, "0x8086", "0xe211", "0x8086", "0x1234"), "Arc Pro B65 32GB");
assert.equal(pciName(PCI_IDS, "0x8086", "0xffff"), null);
assert.equal(gpuDisplayName("intel", "Battlemage G21 [Arc B580]"), "Intel Arc B580");
assert.equal(gpuDisplayName("nvidia", "AD102 [GeForce RTX 4090]"), "NVIDIA GeForce RTX 4090");
});
it("reads nvidia-smi's P2P matrix", () => {
const m = (cells: string) => `\tGPU0\tGPU1\n GPU0\tX\t${cells}\n GPU1\t${cells}\tX\n\nLegend:\n X = Self\n OK = Status Ok`;
assert.equal(parseP2p(m("OK")), "on");
assert.equal(parseP2p(m("CNS")), "off");
assert.equal(parseP2p("\tGPU0\tGPU1\tGPU2\n GPU0\tX\tOK\tNS\n GPU1\tOK\tX\tNS\n GPU2\tNS\tNS\tX"), "partial");
assert.equal(parseP2p("garbage"), null);
});
it("counts cores per socket and sees the hypervisor flag", () => {
const c = parseCpu(CPUINFO);
assert.equal(c.cores, 2);
assert.equal(c.threads, 4);
assert.ok(c.hypervisor);
assert.equal(parseCpu(null).model, null);
});
it("finds the mount holding a folder", () => {
const mi = "1 0 8:1 / / rw - ext4 /dev/sda1 rw\n2 1 8:16 / /models rw - ext4 /dev/sdb rw\n3 1 8:32 / /models-old rw - ext4 /dev/sdc rw";
assert.equal(mountDevice(mi, "/models"), "8:16");
assert.equal(mountDevice(mi, "/models/unsloth"), "8:16");
assert.equal(mountDevice(mi, "/models-old"), "8:32");
assert.equal(mountDevice(mi, "/data"), "8:1");
});
it("picks the digest of the image's own repository", () => {
assert.equal(repoDigest("ghcr.io/ggml-org/llama.cpp:server", ["ghcr.io/ggml-org/llama.cpp@sha256:aaa", "mirror.local/llama.cpp@sha256:bbb"]), "sha256:aaa");
assert.equal(repoDigest("vllm/vllm-openai:v0.31.0", ["vllm/vllm-openai@sha256:ccc"]), "sha256:ccc");
assert.equal(repoDigest("local:dev", []), null);
});
});
describe("engine info", () => {
it("reads llama-server /props (build 11429)", () => {
assert.deepEqual(parseLlamaProps({ build_info: "b11429-d81235049", total_slots: 4, default_generation_settings: { n_ctx: 4096 } }), {
version: "b11429-d81235049",
slots: 4,
contextSize: 4096,
});
assert.deepEqual(parseLlamaProps(null), { version: null, slots: null, contextSize: null });
});
it("reads vLLM /version and /v1/models", () => {
assert.deepEqual(parseVllm({ version: "0.5.7" }, { data: [{ id: "x", max_model_len: 32768 }] }), { version: "0.5.7", slots: null, contextSize: 32768 });
});
it("falls back to startup log lines", () => {
assert.equal(versionFromLog("llama.cpp", ["main: build: 11429 (d8123504) with gcc"]), "b11429-d8123504");
assert.equal(versionFromLog("vllm", ["INFO 10-20 api_server.py:1 vLLM API server version 0.31.0"]), "0.31.0");
assert.equal(versionFromLog("vllm", ["nothing here"]), null);
});
it("returns nulls when the server can't be reached", async () => {
const info = await fetchEngineInfo("llama.cpp", "http://127.0.0.1:9", null);
assert.deepEqual(info, { version: null, slots: null, contextSize: null });
});
});
describe("PCIe link under load", () => {
it("reads each card's current link from sysfs", async () => {
assert.deepEqual(await currentLinks(memFs(), ["0000:03:00.0", "0000:05:00.0", "0000:09:00.0"]), {
"0000:03:00.0": { gen: 4, width: 8 },
"0000:05:00.0": { gen: 4, width: 16 },
});
});
it("keeps the fastest link seen and reads nvidia-smi's link columns", () => {
const l = (gen: number, width: number) => ({ gen, width });
assert.deepEqual(
fastestLinks([
{ pciAddress: "a", link: l(1, 16) },
{ pciAddress: "a", link: l(4, 16) },
{ pciAddress: "a", link: l(4, 8) },
{ pciAddress: "b", link: l(3, 4) },
]),
{ a: l(4, 16), b: l(3, 4) },
);
assert.deepEqual(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5, 4, 16")?.link, l(4, 16));
assert.equal(parseGpuLine("0, NVIDIA GeForce RTX 3080, 10240, 812, 3, 21.5")?.link, null);
const stats = summarizeSamples([], [], 10, [{ pciAddress: "a", link: l(1, 16) }, { pciAddress: "a", link: l(4, 16) }]);
assert.deepEqual(stats.links, { a: l(4, 16) });
});
it("lists NVIDIA GPUs that aren't on the visible PCI bus (WSL2), with nvidia-smi's link", async () => {
const empty: SysFs = { read: async () => null, list: async () => [], resolve: async (p) => p };
const hw = await detectHardware({
fs: empty,
modelsDir: "/models",
kernel: null,
nvidia: [{ vendor: "nvidia", index: 0, uuid: "GPU-x", name: "NVIDIA GeForce RTX 3080", memoryMb: 10240, driver: "617.14", pciAddress: "00000000:01:00.0", linkMax: { gen: 4, width: 16 } }],
});
assert.equal(hw.gpus.length, 1);
assert.equal(hw.gpus[0].pciAddress, "0000:01:00.0");
assert.deepEqual(hw.gpus[0].linkMax, { gen: 4, width: 16 });
assert.equal(hw.gpus[0].rebar, null);
});
});
+316
View File
@@ -0,0 +1,316 @@
// Host hardware from sysfs and procfs, which a container sees unprivileged: GPUs on the PCI bus with
// their PCIe link and BAR size (for Resizable BAR), CPU, RAM, kernel, virtualization and the disk
// holding the models folder. Root-only sources (lspci's extended capabilities, DMI serials) and host
// tools (systemd-detect-virt) aren't available in the worker, so this reads the same facts from files.
// Everything reads through a SysFs, so tests run against an in-memory tree.
import { readdir, readFile, realpath } from "node:fs/promises";
import { release } from "node:os";
import { posix } from "node:path";
import type { GpuVendor, HardwareGpu, HostGpu, HostHardware, PcieLink } from "@/lib/db/schema";
import { linkGen, rebarFrom } from "@/lib/hardware";
const VENDORS: Record<string, GpuVendor> = { "0x10de": "nvidia", "0x8086": "intel", "0x1002": "amd" };
const VENDOR_LABEL: Record<GpuVendor, string> = { nvidia: "NVIDIA", intel: "Intel", amd: "AMD" };
const PCI_ADDR = /^[0-9a-f]{4,}:[0-9a-f]{2}:[0-9a-f]{2}\.[0-7]$/i;
const PCI_IDS = ["/usr/share/misc/pci.ids", "/usr/share/hwdata/pci.ids"];
/** Where drivers report total VRAM, if they do (amdgpu; xe/i915 vary by kernel). */
const VRAM_FILES = ["mem_info_vram_total", "tile0/physical_vram_size_bytes", "lmem_total_bytes"];
const IORESOURCE_MEM = BigInt(0x200);
const ZERO = BigInt(0);
const MIB = BigInt(2 ** 20);
const { basename, dirname, join } = posix;
/** The few file operations detection needs (absolute POSIX paths). */
export type SysFs = {
/** Trimmed file content, or null when it can't be read. */
read(path: string): Promise<string | null>;
list(dir: string): Promise<string[]>;
/** Symlinks resolved (sysfs device links); the path itself when it isn't one. */
resolve(path: string): Promise<string>;
};
export const nodeFs: SysFs = {
read: (p) => readFile(p, "utf8").then((t) => t.trim(), () => null),
list: (d) => readdir(d).catch(() => []),
resolve: (p) => realpath(p).catch(() => p),
};
const num = (s: string | null) => (s != null && /^\d+$/.test(s) ? Number(s) : null);
/** nvidia-smi's "00000000:01:00.0" → sysfs "0000:01:00.0". */
export function normalizePciAddress(id: string): string {
const [domain, ...rest] = id.trim().toLowerCase().split(":");
return [domain.slice(-4).padStart(4, "0"), ...rest].join(":");
}
/** Largest memory BAR in MiB, from a device's `resource` file ("start end flags" per line). */
export function largestBarMb(resource: string | null): number | null {
if (!resource) return null;
let max = ZERO;
for (const line of resource.split("\n")) {
const [start, end, flags] = line.trim().split(/\s+/).map((x) => {
try {
return BigInt(x);
} catch {
return ZERO;
}
});
if (!end || !(flags & IORESOURCE_MEM)) continue;
const size = end - start + BigInt(1);
if (size > max) max = size;
}
return max > ZERO ? Number(max / MIB) : null;
}
/**
* The card's own upstream link: cards like Intel's Arc B-series sit behind an on-card PCIe switch,
* whose internal link is what the GPU function reports. Walk up while the parent belongs to the same
* vendor and isn't the root port.
*/
async function cardUpstream(fs: SysFs, dev: string, vendor: string): Promise<string> {
let cur = dev;
for (;;) {
const parent = dirname(cur);
if (!PCI_ADDR.test(basename(parent)) || !PCI_ADDR.test(basename(dirname(parent)))) return cur;
if ((await fs.read(join(parent, "vendor"))) !== vendor) return cur;
cur = parent;
}
}
async function link(fs: SysFs, dir: string, kind: "current" | "max") {
const gen = linkGen(await fs.read(join(dir, `${kind}_link_speed`)));
const width = num(await fs.read(join(dir, `${kind}_link_width`)));
return gen == null && width == null ? null : { gen, width };
}
const pciIds = new WeakMap<SysFs, Promise<string | null>>();
async function pciIdsText(fs: SysFs): Promise<string | null> {
if (!pciIds.has(fs)) {
pciIds.set(
fs,
(async () => {
for (const p of PCI_IDS) {
const text = await fs.read(p);
if (text) return text;
}
return null;
})(),
);
}
return pciIds.get(fs)!;
}
/** Name from pci.ids: the subsystem's (board) name if listed, else the chip's; "[Arc B580]" preferred. */
export function pciName(ids: string, vendor: string, device: string, subVendor?: string | null, subDevice?: string | null): string | null {
const v = vendor.replace(/^0x/, "").toLowerCase();
const d = device.replace(/^0x/, "").toLowerCase();
const sub = subVendor && subDevice ? `${subVendor.replace(/^0x/, "")} ${subDevice.replace(/^0x/, "")}`.toLowerCase() : null;
const lines = ids.split("\n");
let i = lines.findIndex((l) => l.startsWith(`${v} `));
if (i < 0) return null;
let chip: string | null = null;
for (i++; i < lines.length && (lines[i].startsWith("\t") || lines[i].startsWith("#") || !lines[i].trim()); i++) {
const l = lines[i];
if (!l.startsWith("\t\t") && l.startsWith("\t")) {
if (chip) break;
if (l.slice(1, 5).toLowerCase() === d) chip = l.slice(7).trim();
} else if (chip && sub && l.startsWith("\t\t") && l.slice(2, 11).toLowerCase() === sub) {
return l.slice(13).trim();
}
}
return chip;
}
/** "AD102 [GeForce RTX 4090]" → "NVIDIA GeForce RTX 4090". */
export function gpuDisplayName(vendor: GpuVendor, pciIdsName: string | null): string | null {
if (!pciIdsName) return null;
const bracket = pciIdsName.match(/\[([^\]]+)\]/)?.[1];
const name = bracket ?? pciIdsName;
const label = VENDOR_LABEL[vendor];
return name.toLowerCase().startsWith(label.toLowerCase()) ? name : `${label} ${name}`;
}
function uevent(text: string | null): Record<string, string> {
return Object.fromEntries((text ?? "").split("\n").map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]));
}
/** Display controllers (class 0x03…) from NVIDIA, Intel and AMD. NVIDIA names/VRAM come from nvidia-smi. */
export async function detectGpus(fs: SysFs, nvidia: HostGpu[], kernel: string | null): Promise<HardwareGpu[]> {
const base = "/sys/bus/pci/devices";
const addrs = (await fs.list(base)).filter((a) => PCI_ADDR.test(a)).sort();
const out: HardwareGpu[] = [];
for (const addr of addrs) {
const dev = await fs.resolve(join(base, addr));
const [cls, vendorId] = await Promise.all([fs.read(join(dev, "class")), fs.read(join(dev, "vendor"))]);
const vendor = vendorId ? VENDORS[vendorId.toLowerCase()] : undefined;
if (!cls?.startsWith("0x03") || !vendor) continue;
const ev = uevent(await fs.read(join(dev, "uevent")));
const driver = ev.DRIVER || null;
const up = await cardUpstream(fs, dev, vendorId!.toLowerCase());
const nv = nvidia.find((g) => g.pciAddress && normalizePciAddress(g.pciAddress) === addr.toLowerCase());
let vramMb: number | null = nv?.memoryMb ?? null;
for (const f of VRAM_FILES) {
if (vramMb) break;
const bytes = num(await fs.read(join(dev, f)));
if (bytes) vramMb = Math.round(bytes / 2 ** 20);
}
const ids = await pciIdsText(fs);
const [device, subVendor, subDevice] = await Promise.all(["device", "subsystem_vendor", "subsystem_device"].map((f) => fs.read(join(dev, f))));
const barMb = largestBarMb(await fs.read(join(dev, "resource")));
const moduleVersion = driver ? await fs.read(join("/sys/module", driver, "version")) : null;
out.push({
vendor,
pciAddress: addr.toLowerCase(),
name: nv?.name ?? (ids && device ? gpuDisplayName(vendor, pciName(ids, vendorId!, device, subVendor, subDevice)) : null),
vramMb,
driver,
driverVersion: nv?.driver ?? moduleVersion ?? (driver && kernel ? `kernel ${kernel}` : null),
linkCurrent: (await link(fs, up, "current")) ?? nv?.linkCurrent ?? null,
linkMax: (await link(fs, up, "max")) ?? nv?.linkMax ?? null,
barMb,
rebar: rebarFrom(barMb, vramMb),
});
}
// NVIDIA GPUs that aren't on the visible PCI bus (WSL2 passes them through its own driver).
for (const g of nvidia) {
const addr = g.pciAddress ? normalizePciAddress(g.pciAddress) : `nvidia-${g.index}`;
if (out.some((o) => o.pciAddress === addr)) continue;
out.push({
vendor: "nvidia",
pciAddress: addr,
name: g.name,
vramMb: g.memoryMb || null,
driver: "nvidia",
driverVersion: g.driver || null,
linkCurrent: g.linkCurrent ?? null,
linkMax: g.linkMax ?? null,
barMb: null,
rebar: null,
});
}
return out;
}
/** The current link of each GPU's card (upstream port), for sampling during a run; skips unknown ones. */
export async function currentLinks(fs: SysFs, pciAddresses: string[]): Promise<Record<string, PcieLink>> {
const out: Record<string, PcieLink> = {};
for (const addr of pciAddresses) {
const dev = await fs.resolve(join("/sys/bus/pci/devices", addr));
const vendor = await fs.read(join(dev, "vendor"));
if (!vendor) continue;
const l = await link(fs, await cardUpstream(fs, dev, vendor.toLowerCase()), "current");
if (l) out[addr] = l;
}
return out;
}
/** `nvidia-smi topo -p2p r`: "OK" between every pair → on, none → off. */
export function parseP2p(text: string): "on" | "off" | "partial" | null {
const cells = text
.split("\n")
.filter((l) => /^\s*GPU\d+\s/.test(l))
.flatMap((l) => l.trim().split(/\s+/).slice(1))
.filter((c) => c !== "X" && !/^GPU\d+$/.test(c));
if (cells.length === 0) return null;
const ok = cells.filter((c) => c === "OK").length;
return ok === cells.length ? "on" : ok === 0 ? "off" : "partial";
}
export function parseCpu(cpuinfo: string | null): HostHardware["cpu"] & { hypervisor: boolean } {
if (!cpuinfo) return { model: null, cores: null, threads: null, hypervisor: false };
const blocks = cpuinfo.split(/\n\s*\n/).filter((b) => /^processor\s*:/m.test(b));
const field = (b: string, k: string) => b.match(new RegExp(`^${k}\\s*:\\s*(.*)$`, "m"))?.[1]?.trim() ?? null;
const cores = new Set(blocks.map((b) => `${field(b, "physical id") ?? 0}:${field(b, "core id") ?? field(b, "processor")}`));
return {
model: blocks[0] ? field(blocks[0], "model name") : null,
cores: blocks.length ? cores.size : null,
threads: blocks.length || null,
hypervisor: blocks[0] ? /\bhypervisor\b/.test(field(blocks[0], "flags") ?? "") : false,
};
}
const HYPERVISORS: [RegExp, string][] = [
[/^QEMU|KVM/i, "KVM/QEMU"],
[/Microsoft/i, "Hyper-V"],
[/VMware/i, "VMware"],
[/Xen/i, "Xen"],
[/innotek|VirtualBox/i, "VirtualBox"],
[/Amazon/i, "AWS"],
[/Google/i, "Google Cloud"],
];
/** VM or bare metal, from the CPU's hypervisor flag and the DMI vendor (both readable unprivileged). */
export async function detectVirtualization(fs: SysFs, hypervisorFlag: boolean, kernel: string | null): Promise<HostHardware["virtualization"]> {
const dmi = [await fs.read("/sys/class/dmi/id/sys_vendor"), await fs.read("/sys/class/dmi/id/product_name")].filter(Boolean).join(" ");
if (kernel && /microsoft.*wsl/i.test(kernel)) return { vm: true, hypervisor: "WSL2 (Hyper-V)" };
const known = HYPERVISORS.find(([re]) => re.test(dmi))?.[1] ?? null;
if (hypervisorFlag || known) return { vm: true, hypervisor: known };
return { vm: dmi ? false : null, hypervisor: null };
}
/** The mount holding `dir` (longest mount point that is a prefix), as "major:minor". */
export function mountDevice(mountinfo: string, dir: string): string | null {
const target = posix.normalize(dir.replace(/\\/g, "/")).replace(/(.)\/$/, "$1");
let best: { point: string; dev: string } | null = null;
for (const line of mountinfo.split("\n")) {
const f = line.split(" ");
if (f.length < 5) continue;
const point = f[4].replace(/\\040/g, " ");
const inside = target === point || target.startsWith(point.endsWith("/") ? point : `${point}/`);
if (inside && (!best || point.length > best.point.length)) best = { point, dev: f[2] };
}
return best?.dev ?? null;
}
/** The disk behind a block device: partitions → their disk, device-mapper (LVM, LUKS) → first slave. */
async function diskOf(fs: SysFs, devDir: string, depth = 0): Promise<string | null> {
if (depth > 4) return null;
if (await fs.read(join(devDir, "partition"))) return dirname(devDir);
if (basename(devDir).startsWith("dm-") || basename(devDir).startsWith("md")) {
const slaves = await fs.list(join(devDir, "slaves"));
if (!slaves[0]) return devDir;
return diskOf(fs, await fs.resolve(join("/sys/class/block", slaves[0])), depth + 1);
}
return devDir;
}
export async function detectStorage(fs: SysFs, modelsDir: string): Promise<HostHardware["storage"]> {
const mountinfo = await fs.read("/proc/self/mountinfo");
const dev = mountinfo ? mountDevice(mountinfo, modelsDir) : null;
if (!dev || dev.startsWith("0:")) return null; // ZFS, overlay, network filesystems: no block device
const blockDir = join("/sys/dev/block", dev);
if ((await fs.list(blockDir)).length === 0) return null;
const disk = await diskOf(fs, await fs.resolve(blockDir));
if (!disk) return null;
const name = basename(disk);
const model = (await fs.read(join(disk, "device/model")))?.replace(/\s+/g, " ") || null;
const vendor = (await fs.read(join(disk, "device/vendor")))?.trim() ?? "";
const rotational = await fs.read(join(disk, "queue/rotational"));
const sectors = num(await fs.read(join(disk, "size")));
const virtual = /^vd|^xvd/.test(name) || vendor === "0x1af4" || /QEMU|Virtual Disk|VBOX|VMware/i.test(`${vendor} ${model ?? ""}`);
return {
model: model ?? (virtual ? "virtio disk" : null),
kind: virtual ? "virtual" : name.startsWith("nvme") ? "nvme" : rotational === "1" ? "hdd" : rotational === "0" ? "ssd" : null,
sizeBytes: sectors != null ? sectors * 512 : null,
};
}
export async function detectHardware(o: { fs?: SysFs; modelsDir: string; nvidia?: HostGpu[]; p2p?: HostHardware["p2p"]; kernel?: string | null }): Promise<HostHardware> {
const fs = o.fs ?? nodeFs;
const kernel = o.kernel !== undefined ? o.kernel : release();
const cpu = parseCpu(await fs.read("/proc/cpuinfo"));
const memKb = Number((await fs.read("/proc/meminfo"))?.match(/^MemTotal:\s+(\d+)\s*kB/m)?.[1]);
const gpus = await detectGpus(fs, o.nvidia ?? [], kernel);
return {
gpus,
p2p: gpus.length >= 2 ? (o.p2p ?? null) : null,
cpu: { model: cpu.model, cores: cpu.cores, threads: cpu.threads },
memoryBytes: Number.isFinite(memKb) && memKb > 0 ? memKb * 1024 : null,
kernel,
virtualization: await detectVirtualization(fs, cpu.hypervisor, kernel),
storage: await detectStorage(fs, o.modelsDir).catch(() => null),
checkedAt: new Date().toISOString(),
};
}
+14 -1
View File
@@ -10,7 +10,9 @@ 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 { benchmarkPublications, benchmarkRuns, settings } from "@/lib/db/schema";
import { metaRows } from "@/lib/benchmark-meta";
import { systemSummaryLines } from "@/lib/hardware";
import { coreEnv } from "@/lib/env";
import { log } from "./log";
@@ -60,6 +62,16 @@ export async function reportL80Status(): Promise<void> {
log.info(version ? `L80 CLI ${version}, publish token ${value.tokenSet ? "set" : "not set"}` : "L80 CLI not found; publishing to launch80 is unavailable");
}
/** The run's description, hardware/runtime facts and system summary, as page sections (only whitelisted host facts). */
export async function runSections(runId: string): Promise<[string, string][]> {
const run = await db().query.benchmarkRuns.findFirst({ columns: { description: true, system: true, meta: true }, where: eq(benchmarkRuns.id, runId) });
const out: [string, string][] = [];
if (run?.description?.trim()) out.push(["Description", run.description.trim()]);
if (run?.meta) out.push(["Hardware and runtime", metaRows(run.meta).map((r) => `${r.label}: ${r.value}`).join("\n")]);
if (run?.system) out.push(["System", systemSummaryLines(run.system).join("\n")]);
return out;
}
async function exists(p: string) {
return access(p).then(
() => true,
@@ -88,6 +100,7 @@ export async function tickPublications(): Promise<void> {
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);
for (const [heading, body] of await runSections(p.runId)) args.push("--section", `${heading}=${body}`);
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 };
+201 -50
View File
@@ -1,32 +1,77 @@
// Samples resource use while a benchmark runs: CPU and memory of the deployment containers (Docker
// stats, every ~2 s) and, on NVIDIA hosts, whole-GPU VRAM/utilization/power from one long-lived
// `nvidia-smi -lms` probe container. Aggregation is pure (summarizeSamples) for tests.
// Samples resource use while a benchmark runs (every ~2 s):
// - CPU and memory of the deployment containers (Docker stats);
// - NVIDIA GPUs: whole-GPU VRAM/utilization/power/temperature from one long-lived `nvidia-smi -lms`
// probe container;
// - Intel and AMD GPUs: power and temperature from hwmon, AMD VRAM/busy from sysfs, Intel VRAM and
// utilization from DRM fdinfo via a probe container in the host's PID namespace (gpu-sysfs.ts);
// - the GPUs' PCIe link (it drops to a slower speed when idle, so the fastest one seen under load is
// the one worth recording).
// Aggregation is pure (summarizeSamples) for tests.
import type { ResourceStats } from "@/lib/db/schema";
import type { GpuVendor, PcieLink, ResourceStats } from "@/lib/db/schema";
import type { DockerClient } from "./docker/client";
import { aggregateFdinfo, type DrmSnapshot, drmUtilization, type HwmonReading, INTEL_PROBE_SCRIPT, powerBetween, readAmdUsage, readHwmon } from "./gpu-sysfs";
import { currentLinks, nodeFs } from "./hardware";
import { log } from "./log";
const INTERVAL_MS = 2_000;
export type ContainerSample = { side: "a" | "b"; cpuPercent: number; memoryBytes: number; memoryLimitBytes: number };
export type GpuSample = { index: number; name: string; vramTotalMb: number; vramUsedMb: number; util: number; powerW: number | null };
export type GpuSample = {
index: number;
name: string;
pciAddress?: string;
vramTotalMb: number | null;
vramUsedMb: number | null;
util: number | null;
powerW: number | null;
tempC?: number | null;
link?: PcieLink | null;
};
export type LinkSample = { pciAddress: string; link: PcieLink };
const avg = (xs: number[]) => (xs.length ? xs.reduce((s, x) => s + x, 0) / xs.length : null);
const peak = (xs: number[]) => (xs.length ? Math.max(...xs) : null);
const known = (xs: (number | null | undefined)[]) => xs.filter((x): x is number => x != null);
/** One CSV line of `nvidia-smi --query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw`. */
const GPU_QUERY = "index,name,memory.total,memory.used,utilization.gpu,power.draw,pcie.link.gen.current,pcie.link.width.current,temperature.gpu";
/** One CSV line of `nvidia-smi --query-gpu=${GPU_QUERY}` (columns after power are optional). */
export function parseGpuLine(line: string): GpuSample | null {
const p = line.split(",").map((x) => x.trim());
if (p.length < 6 || !/^\d+$/.test(p[0])) return null;
const n = (s: string) => (Number.isFinite(Number(s)) ? Number(s) : null);
return { index: Number(p[0]), name: p[1], vramTotalMb: n(p[2]) ?? 0, vramUsedMb: n(p[3]) ?? 0, util: n(p[4]) ?? 0, powerW: n(p[5]) };
const n = (s: string | undefined) => (s != null && s !== "" && Number.isFinite(Number(s)) ? Number(s) : null);
const gen = n(p[6]);
const width = n(p[7]);
return {
index: Number(p[0]),
name: p[1],
vramTotalMb: n(p[2]),
vramUsedMb: n(p[3]),
util: n(p[4]),
powerW: n(p[5]),
tempC: n(p[8]),
link: gen != null || width != null ? { gen, width } : null,
};
}
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number): ResourceStats {
/** Faster link: higher generation first, then more lanes. */
const faster = (a: PcieLink | undefined, b: PcieLink) => !a || (b.gen ?? 0) > (a.gen ?? 0) || ((b.gen ?? 0) === (a.gen ?? 0) && (b.width ?? 0) > (a.width ?? 0));
/** Fastest link per GPU over the run. */
export function fastestLinks(samples: LinkSample[]): Record<string, PcieLink> {
const out: Record<string, PcieLink> = {};
for (const s of samples) if (faster(out[s.pciAddress], s.link)) out[s.pciAddress] = s.link;
return out;
}
export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[], seconds: number, links: LinkSample[] = []): ResourceStats {
const sides = [...new Set(containers.map((c) => c.side))].sort();
const fastest = fastestLinks(links);
return {
samples: containers.length,
seconds: Math.round(seconds),
...(Object.keys(fastest).length ? { links: fastest } : {}),
containers: sides.map((side) => {
const xs = containers.filter((c) => c.side === side);
// Docker reports CPU in percent of one core; keep cores.
@@ -43,44 +88,73 @@ export function summarizeSamples(containers: ContainerSample[], gpus: GpuSample[
memLimitBytes: limit,
};
}),
gpus: [...new Set(gpus.map((g) => g.index))].sort((a, b) => a - b).map((index) => {
const xs = gpus.filter((g) => g.index === index);
const power = xs.map((x) => x.powerW).filter((x): x is number => x != null);
return {
index,
name: xs[0].name,
vramTotalMb: xs[0].vramTotalMb,
vramPeakMb: peak(xs.map((x) => x.vramUsedMb)) ?? 0,
vramAvgMb: avg(xs.map((x) => x.vramUsedMb)) ?? 0,
utilAvg: avg(xs.map((x) => x.util)) ?? 0,
utilPeak: peak(xs.map((x) => x.util)) ?? 0,
powerAvgW: avg(power),
powerPeakW: peak(power),
};
}),
gpus: [...new Set(gpus.map((g) => g.index))]
.sort((a, b) => a - b)
.map((index) => {
const xs = gpus.filter((g) => g.index === index);
const vram = known(xs.map((x) => x.vramUsedMb));
const util = known(xs.map((x) => x.util));
const power = known(xs.map((x) => x.powerW));
const temp = known(xs.map((x) => x.tempC));
return {
index,
name: xs[0].name,
...(xs[0].pciAddress ? { pciAddress: xs[0].pciAddress } : {}),
vramTotalMb: xs.find((x) => x.vramTotalMb != null)?.vramTotalMb ?? null,
vramPeakMb: peak(vram),
vramAvgMb: avg(vram),
utilAvg: avg(util),
utilPeak: peak(util),
powerAvgW: avg(power),
powerPeakW: peak(power),
tempAvgC: avg(temp),
tempPeakC: peak(temp),
};
}),
};
}
/** A GPU sampled from sysfs (Intel, AMD); `index` is its position among the GPUs of the run. */
export type SysfsGpu = { index: number; pciAddress: string; name: string; vendor: GpuVendor; vramTotalMb: number | null };
export type GpuTargets = {
/** NVIDIA GPUs via nvidia-smi (our own image as the probe); index → PCI address for the link. */
nvidia: { image: string; pciByIndex: Record<number, string> } | null;
sysfs: SysfsGpu[];
/** Image for the Intel fdinfo probe; null: Intel VRAM/utilization aren't sampled. */
intelProbeImage: string | null;
/** PCI addresses whose link is read from sysfs. */
linkAddresses: string[];
};
export const NO_GPUS: GpuTargets = { nvidia: null, sysfs: [], intelProbeImage: null, linkAddresses: [] };
export class ResourceSampler {
private containerSamples: ContainerSample[] = [];
private gpuSamples: GpuSample[] = [];
private linkSamples: LinkSample[] = [];
private timer?: NodeJS.Timeout;
private busy = false;
private probeId: string | null = null;
private probeIds: string[] = [];
private abort = new AbortController();
private started = Date.now();
private lastHwmon = new Map<string, { at: number; r: HwmonReading }>();
private lastDrm: DrmSnapshot | null = null;
private intelNow = new Map<string, { vramMb: number; util: number | null }>();
constructor(
private c: DockerClient,
private targets: { side: "a" | "b"; containerId: string }[],
private gpuProbeImage: string | null,
private gpus: GpuTargets = NO_GPUS,
) {}
async start(): Promise<void> {
this.started = Date.now();
this.timer = setInterval(() => void this.sample(), INTERVAL_MS);
void this.sample();
if (this.gpuProbeImage) await this.startGpuProbe(this.gpuProbeImage).catch((err) => log.warn(`GPU sampling unavailable: ${err instanceof Error ? err.message : err}`));
const warn = (what: string) => (err: unknown) => log.warn(`${what} sampling unavailable: ${err instanceof Error ? err.message : err}`);
if (this.gpus.nvidia) await this.startNvidiaProbe(this.gpus.nvidia.image).catch(warn("NVIDIA GPU"));
if (this.gpus.intelProbeImage && this.gpus.sysfs.some((g) => g.vendor === "intel")) await this.startIntelProbe(this.gpus.intelProbeImage).catch(warn("Intel GPU"));
}
private async sample() {
@@ -91,42 +165,119 @@ export class ResourceSampler {
const s = await this.c.containerStats(t.containerId).catch(() => null);
if (s) this.containerSamples.push({ side: t.side, ...s });
}
if (this.gpus.linkAddresses.length) {
const links = await currentLinks(nodeFs, this.gpus.linkAddresses).catch(() => ({}));
for (const [pciAddress, link] of Object.entries(links)) this.linkSamples.push({ pciAddress, link });
}
for (const g of this.gpus.sysfs) await this.sampleSysfs(g).catch(() => {});
} finally {
this.busy = false;
}
}
private async startGpuProbe(image: string) {
const created = await this.c.createContainer(`kaname-gpu-sampler-${Date.now().toString(36)}`, {
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: ["--query-gpu=index,name,memory.total,memory.used,utilization.gpu,power.draw", "--format=csv,noheader,nounits", `-lms`, String(INTERVAL_MS)],
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
Labels: { "kaname.managed": "true", "kaname.probe": "gpu-sampler" },
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false, AutoRemove: false },
});
this.probeId = created.Id;
private async sampleSysfs(g: SysfsGpu) {
const now = Date.now();
const r = await readHwmon(nodeFs, g.pciAddress);
const prev = this.lastHwmon.get(g.pciAddress);
this.lastHwmon.set(g.pciAddress, { at: now, r });
const powerW = powerBetween(prev?.r ?? null, r, prev ? (now - prev.at) / 1000 : 0);
let vramUsedMb: number | null = null;
let util: number | null = null;
if (g.vendor === "amd") ({ vramUsedMb, util } = await readAmdUsage(nodeFs, g.pciAddress));
if (g.vendor === "intel") {
const x = this.intelNow.get(g.pciAddress);
vramUsedMb = x?.vramMb ?? null;
util = x?.util ?? null;
}
// The first energy reading has nothing to compare with; skip it rather than record no power.
if (prev || r.energyUj == null) {
this.gpuSamples.push({ index: g.index, name: g.name, pciAddress: g.pciAddress, vramTotalMb: g.vramTotalMb, vramUsedMb, util, powerW, tempC: r.tempC });
}
}
private async startProbe(name: string, spec: Record<string, unknown>, onLine: (line: string) => void) {
const created = await this.c.createContainer(`kaname-${name}-${Date.now().toString(36)}`, spec);
this.probeIds.push(created.Id);
await this.c.startContainer(created.Id);
void this.c
.followLogs(
created.Id,
(_s, line) => {
const g = parseGpuLine(line);
if (g) this.gpuSamples.push(g);
void this.c.followLogs(created.Id, (_s, line) => onLine(line), { tail: "all", signal: this.abort.signal }).catch(() => {});
}
private startNvidiaProbe(image: string) {
return this.startProbe(
"gpu-sampler",
{
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: [`--query-gpu=${GPU_QUERY}`, "--format=csv,noheader,nounits", `-lms`, String(INTERVAL_MS)],
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
Labels: { "kaname.managed": "true", "kaname.probe": "gpu-sampler" },
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false, AutoRemove: false },
},
(line) => {
const g = parseGpuLine(line);
if (!g) return;
const addr = this.gpus.nvidia?.pciByIndex[g.index];
this.gpuSamples.push(addr ? { ...g, pciAddress: addr } : g);
if (addr && g.link) this.linkSamples.push({ pciAddress: addr, link: g.link });
},
);
}
/**
* Intel GPUs report VRAM and engine time only per process (DRM fdinfo). The probe runs Node from
* Kaname's image in the host's PID namespace, reads /proc/<pid>/fdinfo and prints it: no network,
* read-only, all capabilities dropped except reading other processes' fdinfo.
*/
private startIntelProbe(image: string) {
return this.startProbe(
"intel-sampler",
{
Image: image,
User: "0:0",
Entrypoint: ["node", "-e", INTEL_PROBE_SCRIPT],
Cmd: [String(INTERVAL_MS)],
Labels: { "kaname.managed": "true", "kaname.probe": "intel-sampler" },
HostConfig: {
PidMode: "host",
NetworkMode: "none",
ReadonlyRootfs: true,
CapDrop: ["ALL"],
CapAdd: ["SYS_PTRACE", "DAC_READ_SEARCH"],
SecurityOpt: ["no-new-privileges"],
Memory: 256 * 2 ** 20,
PidsLimit: 32,
Privileged: false,
AutoRemove: false,
},
{ tail: "all", signal: this.abort.signal },
)
.catch(() => {});
},
(line) => {
let msg: { t?: number; f?: string[] };
try {
msg = JSON.parse(line);
} catch {
return;
}
if (typeof msg.t !== "number" || !Array.isArray(msg.f)) return;
const snap = aggregateFdinfo(msg.t, msg.f);
const prev = this.lastDrm;
this.lastDrm = snap;
for (const g of this.gpus.sysfs.filter((x) => x.vendor === "intel")) {
const cur = snap.gpus[g.pciAddress];
const util = cur ? drmUtilization(prev?.gpus[g.pciAddress], cur, prev ? (snap.t - prev.t) / 1000 : 0) : prev ? 0 : null;
this.intelNow.set(g.pciAddress, { vramMb: Math.round((cur?.vramBytes ?? 0) / 2 ** 20), util });
}
},
);
}
/** Stop sampling and return the aggregate (never throws). */
async stop(): Promise<ResourceStats> {
clearInterval(this.timer);
this.abort.abort();
if (this.probeId) {
await this.c.stopContainer(this.probeId, 1).catch(() => {});
await this.c.removeContainer(this.probeId).catch(() => {});
for (const id of this.probeIds) {
await this.c.stopContainer(id, 1).catch(() => {});
await this.c.removeContainer(id).catch(() => {});
}
return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000);
return summarizeSamples(this.containerSamples, this.gpuSamples, (Date.now() - this.started) / 1000, this.linkSamples);
}
}
+126 -19
View File
@@ -6,10 +6,11 @@ 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, type HostGpu, runtimes, settings, workerState } from "@/lib/db/schema";
import { type DockerHostInfo, type HostGpu, type HostHardware, type PcieLink, 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";
import { detectHardware, normalizePciAddress, parseP2p } from "./hardware";
import { log } from "./log";
const PROGRESS_MS = 1_000;
@@ -66,7 +67,7 @@ let ownImage: string | null = null;
/** The worker's own image (from the last host check); probe containers run from it. */
export const workerImage = () => ownImage;
let gpuCache: { at: number; gpus: HostGpu[]; error: string | null } | null = null;
let gpuCache: { at: number; gpus: HostGpu[]; p2p: HostHardware["p2p"]; error: string | null } | null = null;
/** nvidia-smi's CSV (index, uuid, name, memory.total MiB, driver) → GPUs. */
export function parseNvidiaSmi(csv: string): HostGpu[] {
@@ -74,29 +75,78 @@ export function parseNvidiaSmi(csv: string): HostGpu[] {
.split(/\r?\n/)
.map((l) => 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 }));
.map(([index, uuid, name, mem, driver, bus, genCur, genMax, widthCur, widthMax]) => ({
vendor: "nvidia" as const,
index: Number(index),
uuid,
name,
memoryMb: Number(mem) || 0,
driver,
pciAddress: bus ? normalizePciAddress(bus) : null,
linkCurrent: nvLink(genCur, widthCur),
linkMax: nvLink(genMax, widthMax),
}));
}
const nvNum = (s: string | undefined) => (s && /^\d+$/.test(s) ? Number(s) : null);
function nvLink(gen: string | undefined, width: string | undefined): PcieLink | null {
const l = { gen: nvNum(gen), width: nvNum(width) };
return l.gen == null && l.width == null ? null : l;
}
/**
* 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.
* Lists the GPUs containers get from Docker (nvidia-smi, which the NVIDIA Container Toolkit injects)
* and, with two or more, whether they can talk peer-to-peer.
*/
async function probeNvidia(c: DockerClient, image: string): Promise<HostGpu[]> {
const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, {
async function probeNvidia(c: DockerClient, image: string): Promise<{ gpus: HostGpu[]; p2p: HostHardware["p2p"] }> {
const gpus = parseNvidiaSmi((await nvidiaSmi(c, image, ["--query-gpu=index,uuid,name,memory.total,driver_version,pci.bus_id,pcie.link.gen.current,pcie.link.gen.max,pcie.link.width.current,pcie.link.width.max", "--format=csv,noheader,nounits"])).join("\n"));
let p2p: HostHardware["p2p"] = null;
if (gpus.length >= 2) p2p = parseP2p((await nvidiaSmi(c, image, ["topo", "-p2p", "r"]).catch(() => [])).join("\n"));
return { gpus, p2p };
}
/** Runs `nvidia-smi <args>` in a short-lived container (our own image) that gets every GPU; its output lines. */
function nvidiaSmi(c: DockerClient, image: string, args: string[]): Promise<string[]> {
return runProbe(c, {
Image: image,
Entrypoint: ["nvidia-smi"],
Cmd: ["--query-gpu=index,uuid,name,memory.total,driver_version", "--format=csv,noheader,nounits"],
Cmd: args,
Env: ["NVIDIA_DRIVER_CAPABILITIES=utility"],
Labels: { "kaname.managed": "true", "kaname.probe": "gpu" },
HostConfig: { DeviceRequests: [{ Driver: "", Count: -1, Capabilities: [["gpu", "utility"]] }], NetworkMode: "none", Privileged: false },
});
}
/**
* Group IDs of the host's /dev/dri nodes (render, video), as a short-lived container with /dev/dri
* sees them (Docker copies the host's owner and mode). Runtime containers get them as extra groups,
* so images that don't run as root can open the GPU.
*/
async function probeDriGroups(c: DockerClient, image: string): Promise<number[]> {
const lines = await runProbe(c, {
Image: image,
Entrypoint: ["sh", "-c", "stat -c '%n %g' /dev/dri/*"],
Cmd: [],
HostConfig: { Devices: [{ PathOnHost: "/dev/dri", PathInContainer: "/dev/dri", CgroupPermissions: "r" }], NetworkMode: "none", Privileged: false, ReadonlyRootfs: true },
});
return parseDriGroups(lines);
}
/** "`/dev/dri/renderD128 993`" lines → the distinct non-root group IDs. */
export function parseDriGroups(lines: string[]): number[] {
const gids = lines.map((l) => l.trim().match(/^\/dev\/dri\/\S+\s+(\d+)$/)?.[1]).filter((g): g is string => !!g).map(Number);
return [...new Set(gids.filter((g) => g > 0))].sort((a, b) => a - b);
}
/** Runs a short-lived probe container from our own image and returns its output lines. */
async function runProbe(c: DockerClient, spec: { Image: string; Entrypoint: string[]; Cmd: string[]; Env?: string[]; HostConfig: Record<string, unknown> }): Promise<string[]> {
const created = await c.createContainer(`kaname-gpu-probe-${Date.now().toString(36)}`, { ...spec, Labels: { "kaname.managed": "true", "kaname.probe": "gpu" } });
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"));
if (st && st.ExitCode !== 0) throw new Error(`${spec.Entrypoint[0]} exited with ${st.ExitCode}: ${lines.slice(-3).join(" ")}`);
return lines;
} finally {
await c.removeContainer(created.Id).catch(() => {});
}
@@ -104,22 +154,22 @@ async function probeNvidia(c: DockerClient, image: string): Promise<HostGpu[]> {
async function gpuFacts(c: DockerClient, info: Awaited<ReturnType<DockerClient["info"]>>, 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 (!nvidia) return { nvidia, gpus: [], p2p: null, 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 };
const { gpus, p2p } = await probeNvidia(c, selfImage);
gpuCache = { at: Date.now(), gpus, p2p, 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) };
gpuCache = { at: Date.now(), gpus: [], p2p: null, error: message(err) };
log.warn(`GPU probe failed: ${message(err)}`);
}
}
return { nvidia, gpus: gpuCache.gpus, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
return { nvidia, gpus: gpuCache.gpus, p2p: gpuCache.p2p, gpuError: gpuCache.error, gpuCheckedAt: new Date(gpuCache.at).toISOString() };
}
const CUDA_SEEDED_KEY = "runtimes.cudaPresetSeeded";
@@ -136,6 +186,45 @@ async function seedGpuPresets() {
await d.insert(settings).values({ key: CUDA_SEEDED_KEY, value: true }).onConflictDoNothing();
}
const INTEL_SEEDED_KEY = "runtimes.intelPresetSeeded";
/** The first time an Intel GPU shows up, add the llama.cpp runtimes for it (SYCL and Vulkan, once). */
async function seedIntelPresets() {
const d = db();
if (await d.query.settings.findFirst({ where: eq(settings.key, INTEL_SEEDED_KEY) })) return;
for (const p of RUNTIME_PRESETS.filter((x) => x.id === "llama.cpp-intel" || x.id === "llama.cpp-vulkan")) {
await d.insert(runtimes).values({
name: p.name,
engine: p.engine,
accelerator: p.accelerator ?? "dri",
image: p.image,
description: p.description ?? null,
env: p.env ?? {},
devices: p.devices ?? [],
preset: p.id,
});
log.info(`Intel GPU found: added the "${p.name}" runtime`);
}
await d.insert(settings).values({ key: INTEL_SEEDED_KEY, value: true }).onConflictDoNothing();
}
let driCache: { at: number; gids: number[] } | null = null;
/** Render/video group IDs of /dev/dri, re-checked hourly while there are Intel or AMD GPUs. */
async function driGroups(c: DockerClient, image: string | null, hardware: HostHardware | null): Promise<number[] | undefined> {
if (!image || !hardware?.gpus.some((g) => g.vendor !== "nvidia")) return undefined;
if (!driCache || Date.now() - driCache.at > GPU_PROBE_MS) {
try {
driCache = { at: Date.now(), gids: await probeDriGroups(c, image) };
log.info(`/dev/dri groups: ${driCache.gids.join(", ") || "none besides root"}`);
} catch (err) {
driCache = { at: Date.now(), gids: [] };
log.warn(`/dev/dri group check failed: ${message(err)}`);
}
}
return driCache.gids;
}
/** Report Docker connectivity and host facts in worker_state (null when DOCKER_HOST isn't set). */
export async function refreshDockerInfo(instanceId: string): Promise<void> {
const c = docker();
@@ -151,6 +240,13 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
const [v, i] = await Promise.all([c.version(), c.info()]);
const self = await selfDetect(c);
ownImage = self.image;
const { p2p, ...gpu } = await gpuFacts(c, i, self.image);
const hardware = await detectHardware({ modelsDir: coreEnv().MODELS_DIR, nvidia: gpu.gpus, p2p }).catch((err) => {
log.warn(`hardware detection failed: ${message(err)}`);
return null;
});
if (hardware?.gpus.some((g) => g.vendor === "intel")) await seedIntelPresets();
const driGids = await driGroups(c, self.image, hardware);
info = {
connected: true,
error: null,
@@ -162,7 +258,9 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
...base,
network: self.network,
modelsSource: self.modelsSource,
...(await gpuFacts(c, i, self.image)),
...gpu,
hardware,
...(driGids ? { driGroups: driGids } : {}),
};
} catch (err) {
info = {
@@ -182,6 +280,14 @@ export async function refreshDockerInfo(instanceId: string): Promise<void> {
await db().update(workerState).set({ docker: info }).where(and(eq(workerState.id, "worker"), eq(workerState.instanceId, instanceId)));
}
/** The registry digest ("sha256:…") of an image reference, from Docker's RepoDigests ("repo@sha256:…"). */
export function repoDigest(ref: string, repoDigests: string[] | null | undefined): string | null {
const repo = ref.split("@")[0].replace(/:[^/:]+$/, "");
const all = repoDigests ?? [];
const hit = all.find((d) => d.split("@")[0] === repo) ?? all[0];
return hit?.split("@")[1] ?? null;
}
const SEEDED_KEY = "runtimes.presetsSeeded";
/** Create the preset runtimes once (deleted presets don't come back). */
@@ -225,8 +331,8 @@ export async function syncImageStates(): Promise<void> {
.update(runtimes)
.set(
img
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageCheckedAt: new Date() }
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageCheckedAt: new Date() },
? { imageState: "present", imageId: img.Id, imageSize: img.Size, imageCreated: img.Created, imageDigest: repoDigest(r.image, img.RepoDigests), imageCheckedAt: new Date() }
: { imageState: r.imageState === "failed" ? "failed" : "missing", imageId: null, imageSize: null, imageCreated: null, imageDigest: null, imageCheckedAt: new Date() },
)
.where(eq(runtimes.id, r.id));
} catch (err) {
@@ -278,6 +384,7 @@ export async function handlePullRequests(): Promise<void> {
imageId: img?.Id ?? null,
imageSize: img?.Size ?? null,
imageCreated: img?.Created ?? null,
imageDigest: img ? repoDigest(next.image, img.RepoDigests) : null,
pullProgress: null,
pullError: img ? null : "Pull finished but the image isn't there.",
imageCheckedAt: new Date(),