v0.2 step 3 — server configuration file (#33)
ServerConfig + ServerConfigLoader (server, defaults, locked, models, limits; every problem reported with its line), GenerationOverrides (locked values imposed, max_tokens/thinking_budget as ceilings), ModelCatalog (declared ids, else any Hugging Face MLX id; cached GGUF-only repositories refused), rzb config validate, rzb serve --config, examples/server.yaml. Tests: Linux 73, Mac 78. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
b48915d parent: efa10e1 modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +13 -7 | @@ -1,18 +1,24 @@ | ||
| 1 | -# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32) | |
| 1 | +# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config file (#33) | |
| 2 | 2 | |
| 3 | 3 | ## State |
| 4 | +Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). | |
| 4 | 5 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 5 | 6 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 6 | 7 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 7 | 8 | closed. Nothing pushed. |
| 8 | 9 | |
| 9 | 10 | ## Next steps |
| 10 | -1. #33 — server configuration file (`--config server.yaml`, reusing `ConfigReader`); its two open | |
| 11 | - questions (accept any HF id as `model`? which defaults a client may not override?) need the user. | |
| 12 | -2. #34 — model lifecycle + `GET /v1/models`; #35 non-streaming chat completions; #36 streaming | |
| 13 | - (use `ServerSentEvents.response`; record model/tokens with `context.usage.record`). | |
| 14 | -3. `rzb serve` runs on the Mac (user's curl on `/v1/models` got the expected OpenAI-style 404, | |
| 15 | - 2026-11-25). Ctrl-C stop checked on Linux only. | |
| 11 | +1. #34 — model lifecycle + `GET /v1/models`: use `ModelCatalog` (from `ServerSettings.config` + | |
| 12 | + `ModelStore`) to resolve names, map `ModelResolutionError` to `OpenAIError.modelNotFound` / a 400 | |
| 13 | + for not-MLX; for undeclared, uncached ids check MLX compliance (config.json + .safetensors on the | |
| 14 | + Hub) before downloading; honour `limits` (max_loaded_models, keep_alive, max_queue) and `preload`. | |
| 15 | + Open point to raise: a network-exposed server accepting any HF id lets clients trigger large | |
| 16 | + downloads — maybe an option later (the user only decided "accept any MLX id"). | |
| 17 | +2. #35 non-streaming chat completions; #36 streaming (`ServerSentEvents.response`; record | |
| 18 | + model/tokens with `context.usage.record`); request sampling fields → `GenerationOverrides` → | |
| 19 | + `ResolvedModel.generation(client:)`. | |
| 20 | +3. `rzb serve` runs on the Mac (user's curl got the expected 404, 2026-11-25). Ctrl-C stop checked | |
| 21 | + on Linux only. | |
| 16 | 22 | |
| 17 | 23 | ## Watch out for |
| 18 | 24 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -1,18 +1,24 @@ | |||
| 1 | -# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32) | 1 | +# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config file (#33) |
| 2 | 2 | ||
| 3 | ## State | 3 | ## State |
| 4 | +Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). | ||
| 4 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP | 5 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 5 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket | 6 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 6 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task | 7 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 7 | closed. Nothing pushed. | 8 | closed. Nothing pushed. |
| 8 | 9 | ||
| 9 | ## Next steps | 10 | ## Next steps |
| 10 | -1. #33 — server configuration file (`--config server.yaml`, reusing `ConfigReader`); its two open | 11 | +1. #34 — model lifecycle + `GET /v1/models`: use `ModelCatalog` (from `ServerSettings.config` + |
| 11 | - questions (accept any HF id as `model`? which defaults a client may not override?) need the user. | 12 | + `ModelStore`) to resolve names, map `ModelResolutionError` to `OpenAIError.modelNotFound` / a 400 |
| 12 | -2. #34 — model lifecycle + `GET /v1/models`; #35 non-streaming chat completions; #36 streaming | 13 | + for not-MLX; for undeclared, uncached ids check MLX compliance (config.json + .safetensors on the |
| 13 | - (use `ServerSentEvents.response`; record model/tokens with `context.usage.record`). | 14 | + Hub) before downloading; honour `limits` (max_loaded_models, keep_alive, max_queue) and `preload`. |
| 14 | -3. `rzb serve` runs on the Mac (user's curl on `/v1/models` got the expected OpenAI-style 404, | 15 | + Open point to raise: a network-exposed server accepting any HF id lets clients trigger large |
| 15 | - 2026-11-25). Ctrl-C stop checked on Linux only. | 16 | + downloads — maybe an option later (the user only decided "accept any MLX id"). |
| 17 | +2. #35 non-streaming chat completions; #36 streaming (`ServerSentEvents.response`; record | ||
| 18 | + model/tokens with `context.usage.record`); request sampling fields → `GenerationOverrides` → | ||
| 19 | + `ResolvedModel.generation(client:)`. | ||
| 20 | +3. `rzb serve` runs on the Mac (user's curl got the expected 404, 2026-11-25). Ctrl-C stop checked | ||
| 21 | + on Linux only. | ||
| 16 | 22 | ||
| 17 | ## Watch out for | 23 | ## Watch out for |
| 18 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns | 24 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
modified
.memory/history.md +7 -0 | @@ -141,3 +141,10 @@ | ||
| 141 | 141 | on Linux (health, 401, 404, logs, SIGINT stop). Quality gate PASS (run #4). Ticket #32 closed. |
| 142 | 142 | - User set the repo's git identity; #32 committed as `9f8dda1`; branch `main` created at that commit |
| 143 | 143 | (there was no `main` before). Not pushed. `rzb serve` confirmed running on the Mac by the user. |
| 144 | +- #33 (user's decisions: any MLX-compliant HF id accepted; locked settings only when listed): | |
| 145 | + `ServerConfig`/`ServerConfigLoader`, `GenerationOverrides` (locked = imposed, or ceiling for | |
| 146 | + max_tokens/thinking_budget), `ModelCatalog` (declared ids, else `org/name[@rev]`, cached GGUF-only | |
| 147 | + refused), `rzb config validate`, `rzb serve --config`, `examples/server.yaml`. Rejected: an | |
| 148 | + `allow_any_model` switch (not asked), `${env.X}` interpolation for the key (`api_key_env` instead). | |
| 149 | + Tests Linux 73, Mac 78; Release build + `rzb config validate examples/server.yaml` on the Mac OK; | |
| 150 | + quality gate PASS (run #5). #33 closed. User asked to stay local (no push). | |
| @@ -141,3 +141,10 @@ | |||
| 141 | on Linux (health, 401, 404, logs, SIGINT stop). Quality gate PASS (run #4). Ticket #32 closed. | 141 | on Linux (health, 401, 404, logs, SIGINT stop). Quality gate PASS (run #4). Ticket #32 closed. |
| 142 | - User set the repo's git identity; #32 committed as `9f8dda1`; branch `main` created at that commit | 142 | - User set the repo's git identity; #32 committed as `9f8dda1`; branch `main` created at that commit |
| 143 | (there was no `main` before). Not pushed. `rzb serve` confirmed running on the Mac by the user. | 143 | (there was no `main` before). Not pushed. `rzb serve` confirmed running on the Mac by the user. |
| 144 | +- #33 (user's decisions: any MLX-compliant HF id accepted; locked settings only when listed): | ||
| 145 | + `ServerConfig`/`ServerConfigLoader`, `GenerationOverrides` (locked = imposed, or ceiling for | ||
| 146 | + max_tokens/thinking_budget), `ModelCatalog` (declared ids, else `org/name[@rev]`, cached GGUF-only | ||
| 147 | + refused), `rzb config validate`, `rzb serve --config`, `examples/server.yaml`. Rejected: an | ||
| 148 | + `allow_any_model` switch (not asked), `${env.X}` interpolation for the key (`api_key_env` instead). | ||
| 149 | + Tests Linux 73, Mac 78; Release build + `rzb config validate examples/server.yaml` on the Mac OK; | ||
| 150 | + quality gate PASS (run #5). #33 closed. User asked to stay local (no push). | ||
modified
.memory/summary.md +19 -5 | @@ -6,7 +6,8 @@ | ||
| 6 | 6 | **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming |
| 7 | 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in |
| 8 | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | -removed (`132c60f`), HTTP server foundation #32 (`rzb serve`, see Architecture). Decided by the user (#31): the | |
| 9 | +removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33 | |
| 10 | +(see Architecture). Decided by the user (#31): the | |
| 10 | 11 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 11 | 12 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 12 | 13 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -34,13 +35,17 @@ User docs: `docs/en`, `docs/fr` (Diátaxis), module diagram `docs/diagrams/packa | ||
| 34 | 35 | ## Architecture (v0.2 branch, as built) |
| 35 | 36 | |
| 36 | 37 | Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `ThinkingSplitter`, |
| 37 | -`ModelStore`, `ConfigReader` kept for #33, `Quantities`, `GenerationSettings`), `RazorbillMLX` | |
| 38 | +`ModelStore`, `ConfigReader`, `Quantities`, `GenerationSettings`; server config: `ServerConfig`, | |
| 39 | +`ServerConfigLoader`, `GenerationOverrides`, `ModelCatalog`), `RazorbillMLX` | |
| 38 | 40 | (unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit |
| 39 | 41 | and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS → |
| 40 | 42 | error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`, |
| 41 | 43 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` |
| 42 | -runner for tests). `rzb serve --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin`; | |
| 43 | -the API key is read only from the environment. No `/v1/*` endpoint exists yet (#33–#35 next). | |
| 44 | +runner for tests; `ServerSettings.config` carries the loaded file to the server). | |
| 45 | +`rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` | |
| 46 | +(options win over the file's `server:` section); `rzb config validate <file>`; example | |
| 47 | +`examples/server.yaml`. The API key is read only from the environment (`server.api_key_env` names | |
| 48 | +the variable). No `/v1/*` endpoint exists yet (#34–#35 next). | |
| 44 | 49 | |
| 45 | 50 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 46 | 51 | |
| @@ -54,6 +59,15 @@ parser commands, `CLIEnvironment` task-local for tests), executable `rzb`. Engin | ||
| 54 | 59 | |
| 55 | 60 | ## Decisions in force |
| 56 | 61 | |
| 62 | +- v0.2 (#33, user 2026-11-25): any Hugging Face id in MLX format is accepted as `model`, declared | |
| 63 | + or not (cached GGUF-only repos refused; uncached ones checked at download, #34). Nothing is locked | |
| 64 | + unless listed in a `locked:` block; temperature/top_p/thinking imposed, max_tokens and | |
| 65 | + thinking_budget are ceilings. Order: built-in → defaults (server, model) → client → locked. | |
| 66 | +- Work stays local: no push to `origin` until the user says so. `main` is fast-forwarded to the | |
| 67 | + feature branch at the end of each step. | |
| 68 | + | |
| 69 | +Decisions below are from v0.1 (agent) unless they concern quality tooling: | |
| 70 | + | |
| 57 | 71 | - One agent per YAML file; lookup `--config`, `./razorbill.yaml`, `~/.config/razorbill/agent.yaml`. |
| 58 | 72 | Prompt variables `{{date}}`, `{{cwd}}`, `{{env.NAME}}`. Unknown keys are errors (with line). |
| 59 | 73 | - TUI on an own ANSI layer (no dependency). Mode chosen by the command, not the YAML. |
| @@ -119,7 +133,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | ||
| 119 | 133 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 120 | 134 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 121 | 135 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 122 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #32): Linux 55, Mac 60. | |
| 136 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #33): Linux 73, Mac 78. | |
| 123 | 137 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 124 | 138 | |
| 125 | 139 | ## mlx-swift-lm API version trap |
| @@ -6,7 +6,8 @@ | |||
| 6 | **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming | 6 | **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming |
| 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in | 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in |
| 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | -removed (`132c60f`), HTTP server foundation #32 (`rzb serve`, see Architecture). Decided by the user (#31): the | 9 | +removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33 |
| 10 | +(see Architecture). Decided by the user (#31): the | ||
| 10 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, | 11 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 11 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` | 12 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| 12 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by | 13 | (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by |
| @@ -34,13 +35,17 @@ User docs: `docs/en`, `docs/fr` (Diátaxis), module diagram `docs/diagrams/packa | |||
| 34 | ## Architecture (v0.2 branch, as built) | 35 | ## Architecture (v0.2 branch, as built) |
| 35 | 36 | ||
| 36 | Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `ThinkingSplitter`, | 37 | Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `ThinkingSplitter`, |
| 37 | -`ModelStore`, `ConfigReader` kept for #33, `Quantities`, `GenerationSettings`), `RazorbillMLX` | 38 | +`ModelStore`, `ConfigReader`, `Quantities`, `GenerationSettings`; server config: `ServerConfig`, |
| 39 | +`ServerConfigLoader`, `GenerationOverrides`, `ModelCatalog`), `RazorbillMLX` | ||
| 38 | (unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit | 40 | (unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit |
| 39 | and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS → | 41 | and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS → |
| 40 | error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`, | 42 | error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`, |
| 41 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` | 43 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` |
| 42 | -runner for tests). `rzb serve --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin`; | 44 | +runner for tests; `ServerSettings.config` carries the loaded file to the server). |
| 43 | -the API key is read only from the environment. No `/v1/*` endpoint exists yet (#33–#35 next). | 45 | +`rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` |
| 46 | +(options win over the file's `server:` section); `rzb config validate <file>`; example | ||
| 47 | +`examples/server.yaml`. The API key is read only from the environment (`server.api_key_env` names | ||
| 48 | +the variable). No `/v1/*` endpoint exists yet (#34–#35 next). | ||
| 44 | 49 | ||
| 45 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 50 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 46 | 51 | ||
| @@ -54,6 +59,15 @@ parser commands, `CLIEnvironment` task-local for tests), executable `rzb`. Engin | |||
| 54 | 59 | ||
| 55 | ## Decisions in force | 60 | ## Decisions in force |
| 56 | 61 | ||
| 62 | +- v0.2 (#33, user 2026-11-25): any Hugging Face id in MLX format is accepted as `model`, declared | ||
| 63 | + or not (cached GGUF-only repos refused; uncached ones checked at download, #34). Nothing is locked | ||
| 64 | + unless listed in a `locked:` block; temperature/top_p/thinking imposed, max_tokens and | ||
| 65 | + thinking_budget are ceilings. Order: built-in → defaults (server, model) → client → locked. | ||
| 66 | +- Work stays local: no push to `origin` until the user says so. `main` is fast-forwarded to the | ||
| 67 | + feature branch at the end of each step. | ||
| 68 | + | ||
| 69 | +Decisions below are from v0.1 (agent) unless they concern quality tooling: | ||
| 70 | + | ||
| 57 | - One agent per YAML file; lookup `--config`, `./razorbill.yaml`, `~/.config/razorbill/agent.yaml`. | 71 | - One agent per YAML file; lookup `--config`, `./razorbill.yaml`, `~/.config/razorbill/agent.yaml`. |
| 58 | Prompt variables `{{date}}`, `{{cwd}}`, `{{env.NAME}}`. Unknown keys are errors (with line). | 72 | Prompt variables `{{date}}`, `{{cwd}}`, `{{env.NAME}}`. Unknown keys are errors (with line). |
| 59 | - TUI on an own ANSI layer (no dependency). Mode chosen by the command, not the YAML. | 73 | - TUI on an own ANSI layer (no dependency). Mode chosen by the command, not the YAML. |
| @@ -119,7 +133,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | |||
| 119 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). | 133 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 120 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped | 134 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 121 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). | 135 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 122 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #32): Linux 55, Mac 60. | 136 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #33): Linux 73, Mac 78. |
| 123 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). | 137 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 124 | 138 | ||
| 125 | ## mlx-swift-lm API version trap | 139 | ## mlx-swift-lm API version trap |
modified
.quality/history.jsonl +1 -0 | @@ -2,3 +2,4 @@ | ||
| 2 | 2 | {"branch": "", "breaches": ["code smells: 14 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 518, "cyclo": 626, "fields": 665, "funcs": 445, "lcom": 80, "lines": 8127, "loc": 6425}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 2, "smells": 14, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:52:09Z"} |
| 3 | 3 | {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 132, "complex": 358, "cyclo": 448, "fields": 657, "funcs": 391, "lcom": 79, "lines": 6531, "loc": 5084}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 3, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:57:47Z"} |
| 4 | 4 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"} |
| 5 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "efa10e1", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 105, "complex": 198, "cyclo": 251, "fields": 436, "funcs": 235, "lcom": 56, "lines": 4348, "loc": 3305}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 5, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T08:05:17Z"} | |
| @@ -2,3 +2,4 @@ | |||
| 2 | {"branch": "", "breaches": ["code smells: 14 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 518, "cyclo": 626, "fields": 665, "funcs": 445, "lcom": 80, "lines": 8127, "loc": 6425}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 2, "smells": 14, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:52:09Z"} | 2 | {"branch": "", "breaches": ["code smells: 14 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 133, "complex": 518, "cyclo": 626, "fields": 665, "funcs": 445, "lcom": 80, "lines": 8127, "loc": 6425}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 2, "smells": 14, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:52:09Z"} |
| 3 | {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 132, "complex": 358, "cyclo": 448, "fields": 657, "funcs": 391, "lcom": 79, "lines": 6531, "loc": 5084}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 3, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:57:47Z"} | 3 | {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 132, "complex": 358, "cyclo": 448, "fields": 657, "funcs": 391, "lcom": 79, "lines": 6531, "loc": 5084}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 3, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-24T05:57:47Z"} |
| 4 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"} | 4 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "132c60f", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 87, "complex": 153, "cyclo": 204, "fields": 340, "funcs": 188, "lcom": 45, "lines": 3437, "loc": 2570}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 4, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T07:51:14Z"} |
| 5 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "efa10e1", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 105, "complex": 198, "cyclo": 251, "fields": 436, "funcs": 235, "lcom": 56, "lines": 4348, "loc": 3305}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 5, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T08:05:17Z"} | ||
added
.quality/report-20261125T080517Z.md +68 -0 | new file mode 100644 | ||
| @@ -0,0 +1,68 @@ | ||
| 1 | +# Quality report — 2026-11-25T08:05:17Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `efa10e1` on `feature/v0.2-openai-server` | |
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | |
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | |
| 7 | +- **Run**: #5 (previous: 2026-11-25T07:51:14Z) | |
| 8 | + | |
| 9 | +## Lint issues (`qlty check`) | |
| 10 | + | |
| 11 | +_none_ | |
| 12 | + | |
| 13 | +### Top rules | |
| 14 | + | |
| 15 | +_none_ | |
| 16 | + | |
| 17 | +### Most affected files | |
| 18 | + | |
| 19 | +_none_ | |
| 20 | + | |
| 21 | +## Code smells (`qlty smells`) | |
| 22 | + | |
| 23 | +Total: **0** (vs previous: ±0) | |
| 24 | + | |
| 25 | +_none_ | |
| 26 | + | |
| 27 | +## Metrics (`qlty metrics`) | |
| 28 | + | |
| 29 | +| metric | total | vs previous | | |
| 30 | +|---|---|---| | |
| 31 | +| funcs | 235 | +47 | | |
| 32 | +| classes | 105 | +18 | | |
| 33 | +| fields | 436 | +96 | | |
| 34 | +| cyclo | 251 | +47 | | |
| 35 | +| complex | 198 | +45 | | |
| 36 | +| lcom | 56 | +11 | | |
| 37 | +| lines | 4348 | +911 | | |
| 38 | +| loc | 3305 | +735 | | |
| 39 | + | |
| 40 | +### Most complex files | |
| 41 | + | |
| 42 | +| file | complex | cyclo | loc | | |
| 43 | +|---|---|---|---| | |
| 44 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 | | |
| 46 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 47 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 48 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 49 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 50 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 51 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 52 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 53 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | | |
| 54 | +| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | | |
| 55 | +| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | | |
| 56 | +| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | | |
| 57 | +| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | | |
| 58 | +| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 | | |
| 59 | + | |
| 60 | +## Trend | |
| 61 | + | |
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 63 | +|---|---|---|---|---|---|---| | |
| 64 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | |
| 65 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | |
| 66 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | |
| 67 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 68 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | +# Quality report — 2026-11-25T08:05:17Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `efa10e1` on `feature/v0.2-openai-server` | ||
| 5 | +- **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | ||
| 6 | +- **swiftlint**: 0.65.1 (run directly, merged into lint issues) | ||
| 7 | +- **Run**: #5 (previous: 2026-11-25T07:51:14Z) | ||
| 8 | + | ||
| 9 | +## Lint issues (`qlty check`) | ||
| 10 | + | ||
| 11 | +_none_ | ||
| 12 | + | ||
| 13 | +### Top rules | ||
| 14 | + | ||
| 15 | +_none_ | ||
| 16 | + | ||
| 17 | +### Most affected files | ||
| 18 | + | ||
| 19 | +_none_ | ||
| 20 | + | ||
| 21 | +## Code smells (`qlty smells`) | ||
| 22 | + | ||
| 23 | +Total: **0** (vs previous: ±0) | ||
| 24 | + | ||
| 25 | +_none_ | ||
| 26 | + | ||
| 27 | +## Metrics (`qlty metrics`) | ||
| 28 | + | ||
| 29 | +| metric | total | vs previous | | ||
| 30 | +|---|---|---| | ||
| 31 | +| funcs | 235 | +47 | | ||
| 32 | +| classes | 105 | +18 | | ||
| 33 | +| fields | 436 | +96 | | ||
| 34 | +| cyclo | 251 | +47 | | ||
| 35 | +| complex | 198 | +45 | | ||
| 36 | +| lcom | 56 | +11 | | ||
| 37 | +| lines | 4348 | +911 | | ||
| 38 | +| loc | 3305 | +735 | | ||
| 39 | + | ||
| 40 | +### Most complex files | ||
| 41 | + | ||
| 42 | +| file | complex | cyclo | loc | | ||
| 43 | +|---|---|---|---| | ||
| 44 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 45 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 | | ||
| 46 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 47 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 48 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 49 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 50 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 51 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 52 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 53 | +| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | | ||
| 54 | +| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | | ||
| 55 | +| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | | ||
| 56 | +| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | | ||
| 57 | +| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | | ||
| 58 | +| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 | | ||
| 59 | + | ||
| 60 | +## Trend | ||
| 61 | + | ||
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 63 | +|---|---|---|---|---|---|---| | ||
| 64 | +| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | ||
| 65 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | ||
| 66 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | ||
| 67 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 68 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
modified
.quality/report-latest.md +16 -15 | @@ -1,10 +1,10 @@ | ||
| 1 | -# Quality report — 2026-11-25T07:51:14Z | |
| 1 | +# Quality report — 2026-11-25T08:05:17Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `132c60f` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `efa10e1` on `feature/v0.2-openai-server` | |
| 5 | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #4 (previous: 2026-11-24T05:57:47Z) | |
| 7 | +- **Run**: #5 (previous: 2026-11-25T07:51:14Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| @@ -28,14 +28,14 @@ _none_ | ||
| 28 | 28 | |
| 29 | 29 | | metric | total | vs previous | |
| 30 | 30 | |---|---|---| |
| 31 | -| funcs | 188 | -203 | | |
| 32 | -| classes | 87 | -45 | | |
| 33 | -| fields | 340 | -317 | | |
| 34 | -| cyclo | 204 | -244 | | |
| 35 | -| complex | 153 | -205 | | |
| 36 | -| lcom | 45 | -34 | | |
| 37 | -| lines | 3437 | -3094 | | |
| 38 | -| loc | 2570 | -2514 | | |
| 31 | +| funcs | 235 | +47 | | |
| 32 | +| classes | 105 | +18 | | |
| 33 | +| fields | 436 | +96 | | |
| 34 | +| cyclo | 251 | +47 | | |
| 35 | +| complex | 198 | +45 | | |
| 36 | +| lcom | 56 | +11 | | |
| 37 | +| lines | 4348 | +911 | | |
| 38 | +| loc | 3305 | +735 | | |
| 39 | 39 | |
| 40 | 40 | ### Most complex files |
| 41 | 41 | |
| @@ -43,19 +43,19 @@ _none_ | ||
| 43 | 43 | |---|---|---|---| |
| 44 | 44 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 45 | 45 | | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 | |
| 46 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 46 | 47 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 48 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 49 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 47 | 50 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 48 | 51 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | |
| 52 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 49 | 53 | | Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | |
| 50 | 54 | | Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | |
| 51 | 55 | | Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | |
| 52 | -| Sources/RazorbillCLI/Commands/ServeCommand.swift | 6 | 4 | 56 | | |
| 53 | 56 | | Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | |
| 54 | 57 | | Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | |
| 55 | 58 | | Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 | |
| 56 | -| Sources/RazorbillCore/Models/ModelStore.swift | 4 | 6 | 101 | | |
| 57 | -| Sources/RazorbillServer/RazorbillServer.swift | 4 | 4 | 50 | | |
| 58 | -| Tests/RazorbillCLITests/Harness.swift | 4 | 4 | 82 | | |
| 59 | 59 | |
| 60 | 60 | ## Trend |
| 61 | 61 | |
| @@ -65,3 +65,4 @@ _none_ | ||
| 65 | 65 | | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | |
| 66 | 66 | | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | |
| 67 | 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | |
| 68 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| @@ -1,10 +1,10 @@ | |||
| 1 | -# Quality report — 2026-11-25T07:51:14Z | 1 | +# Quality report — 2026-11-25T08:05:17Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `132c60f` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `efa10e1` on `feature/v0.2-openai-server` |
| 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #4 (previous: 2026-11-24T05:57:47Z) | 7 | +- **Run**: #5 (previous: 2026-11-25T07:51:14Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| @@ -28,14 +28,14 @@ _none_ | |||
| 28 | 28 | ||
| 29 | | metric | total | vs previous | | 29 | | metric | total | vs previous | |
| 30 | |---|---|---| | 30 | |---|---|---| |
| 31 | -| funcs | 188 | -203 | | 31 | +| funcs | 235 | +47 | |
| 32 | -| classes | 87 | -45 | | 32 | +| classes | 105 | +18 | |
| 33 | -| fields | 340 | -317 | | 33 | +| fields | 436 | +96 | |
| 34 | -| cyclo | 204 | -244 | | 34 | +| cyclo | 251 | +47 | |
| 35 | -| complex | 153 | -205 | | 35 | +| complex | 198 | +45 | |
| 36 | -| lcom | 45 | -34 | | 36 | +| lcom | 56 | +11 | |
| 37 | -| lines | 3437 | -3094 | | 37 | +| lines | 4348 | +911 | |
| 38 | -| loc | 2570 | -2514 | | 38 | +| loc | 3305 | +735 | |
| 39 | 39 | ||
| 40 | ### Most complex files | 40 | ### Most complex files |
| 41 | 41 | ||
| @@ -43,19 +43,19 @@ _none_ | |||
| 43 | |---|---|---|---| | 43 | |---|---|---|---| |
| 44 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 44 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 45 | | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 | | 45 | | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 | |
| 46 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 46 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 47 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 48 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 49 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 47 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | 50 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 48 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | 51 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | |
| 52 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 49 | | Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | | 53 | | Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 | |
| 50 | | Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | | 54 | | Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 | |
| 51 | | Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | | 55 | | Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 | |
| 52 | -| Sources/RazorbillCLI/Commands/ServeCommand.swift | 6 | 4 | 56 | | ||
| 53 | | Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | | 56 | | Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 | |
| 54 | | Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | | 57 | | Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 | |
| 55 | | Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 | | 58 | | Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 | |
| 56 | -| Sources/RazorbillCore/Models/ModelStore.swift | 4 | 6 | 101 | | ||
| 57 | -| Sources/RazorbillServer/RazorbillServer.swift | 4 | 4 | 50 | | ||
| 58 | -| Tests/RazorbillCLITests/Harness.swift | 4 | 4 | 82 | | ||
| 59 | 59 | ||
| 60 | ## Trend | 60 | ## Trend |
| 61 | 61 | ||
| @@ -65,3 +65,4 @@ _none_ | |||
| 65 | | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | 65 | | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | |
| 66 | | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | 66 | | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | |
| 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | |
| 68 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
modified
.tickets/issues/0033-server-configuration-file-models-aliases-default.yaml +27 -7 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 33 |
| 3 | 3 | title: "Server configuration file (models, aliases, defaults, limits)" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T09:10:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::config" |
| @@ -45,34 +45,54 @@ body: | | ||
| 45 | 45 | tasks: |
| 46 | 46 | - id: 1 |
| 47 | 47 | title: "Define the schema and write examples/server.yaml" |
| 48 | - state: open | |
| 48 | + state: closed | |
| 49 | 49 | priority: high |
| 50 | 50 | author: |
| 51 | 51 | name: k33g |
| 52 | 52 | email: ph.charriere@gmail.com |
| 53 | 53 | createdAt: 2026-11-24T21:17:08.000Z |
| 54 | + updatedAt: 2026-11-25T09:10:00.000Z | |
| 55 | + closedAt: 2026-11-25T09:10:00.000Z | |
| 54 | 56 | - id: 2 |
| 55 | 57 | title: "Loader + validation with line-numbered errors, rzb config validate" |
| 56 | - state: open | |
| 58 | + state: closed | |
| 57 | 59 | priority: high |
| 58 | 60 | author: |
| 59 | 61 | name: k33g |
| 60 | 62 | email: ph.charriere@gmail.com |
| 61 | 63 | createdAt: 2026-11-24T21:17:08.000Z |
| 64 | + updatedAt: 2026-11-25T09:10:00.000Z | |
| 65 | + closedAt: 2026-11-25T09:10:00.000Z | |
| 62 | 66 | - id: 3 |
| 63 | 67 | title: "Decide the policy for undeclared model ids" |
| 64 | - state: open | |
| 68 | + state: closed | |
| 65 | 69 | priority: medium |
| 66 | 70 | author: |
| 67 | 71 | name: k33g |
| 68 | 72 | email: ph.charriere@gmail.com |
| 69 | 73 | createdAt: 2026-11-24T21:17:08.000Z |
| 74 | + updatedAt: 2026-11-25T09:10:00.000Z | |
| 75 | + closedAt: 2026-11-25T09:10:00.000Z | |
| 70 | 76 | - id: 4 |
| 71 | 77 | title: "Server-side caps a client cannot exceed" |
| 72 | - state: open | |
| 78 | + state: closed | |
| 73 | 79 | priority: medium |
| 74 | 80 | author: |
| 75 | 81 | name: k33g |
| 76 | 82 | email: ph.charriere@gmail.com |
| 77 | 83 | createdAt: 2026-11-24T21:17:08.000Z |
| 78 | -comments: [] | |
| 84 | + updatedAt: 2026-11-25T09:10:00.000Z | |
| 85 | + closedAt: 2026-11-25T09:10:00.000Z | |
| 86 | +comments: | |
| 87 | + - id: 1 | |
| 88 | + author: | |
| 89 | + name: k33g | |
| 90 | + email: ph.charriere@gmail.com | |
| 91 | + createdAt: 2026-11-25T09:10:00.000Z | |
| 92 | + body: | | |
| 93 | + Decisions (user, 2026-11-25): | |
| 94 | + - **Undeclared model ids**: any Hugging Face id (`org/name`, optional `@revision`) is accepted when it is MLX-compliant. Implemented in `ModelCatalog.resolve`: declared ids first; otherwise the id shape is checked, and a repository already cached with GGUF weights and no `.safetensors` is refused (`notMLX`). A repository not yet downloaded is checked at download time (#34). | |
| 95 | + - **Locked settings**: nothing is locked unless listed in a `locked:` block (server-wide and/or per model). `temperature`, `top_p`, `thinking` are imposed; `max_tokens` and `thinking_budget` are ceilings (a smaller request is kept). Order: built-in → `defaults` (server, then model) → client → `locked` (server, then model). | |
| 96 | + | |
| 97 | + Done: `ServerConfig` / `ServerConfigLoader` (sections `server`, `defaults`, `locked`, `models`, `limits`; unknown keys, types, ranges, duplicate ids, all reported with their line), `GenerationOverrides`, `ModelCatalog`, `rzb config validate <file>`, `rzb serve --config <file>` (command-line options win over the file). The API key stays out of the file: `server.api_key_env` names the variable (replaces the `${env.…}` draft). `examples/server.yaml` is checked by a test. Tests +18 (Linux 73, Mac 78), quality gate PASS. | |
| 98 | + | |
| @@ -1,12 +1,12 @@ | |||
| 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | id: 33 | 2 | id: 33 |
| 3 | title: "Server configuration file (models, aliases, defaults, limits)" | 3 | title: "Server configuration file (models, aliases, defaults, limits)" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T09:10:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::config" | 12 | - "area::config" |
| @@ -45,34 +45,54 @@ body: | | |||
| 45 | tasks: | 45 | tasks: |
| 46 | - id: 1 | 46 | - id: 1 |
| 47 | title: "Define the schema and write examples/server.yaml" | 47 | title: "Define the schema and write examples/server.yaml" |
| 48 | - state: open | 48 | + state: closed |
| 49 | priority: high | 49 | priority: high |
| 50 | author: | 50 | author: |
| 51 | name: k33g | 51 | name: k33g |
| 52 | email: ph.charriere@gmail.com | 52 | email: ph.charriere@gmail.com |
| 53 | createdAt: 2026-11-24T21:17:08.000Z | 53 | createdAt: 2026-11-24T21:17:08.000Z |
| 54 | + updatedAt: 2026-11-25T09:10:00.000Z | ||
| 55 | + closedAt: 2026-11-25T09:10:00.000Z | ||
| 54 | - id: 2 | 56 | - id: 2 |
| 55 | title: "Loader + validation with line-numbered errors, rzb config validate" | 57 | title: "Loader + validation with line-numbered errors, rzb config validate" |
| 56 | - state: open | 58 | + state: closed |
| 57 | priority: high | 59 | priority: high |
| 58 | author: | 60 | author: |
| 59 | name: k33g | 61 | name: k33g |
| 60 | email: ph.charriere@gmail.com | 62 | email: ph.charriere@gmail.com |
| 61 | createdAt: 2026-11-24T21:17:08.000Z | 63 | createdAt: 2026-11-24T21:17:08.000Z |
| 64 | + updatedAt: 2026-11-25T09:10:00.000Z | ||
| 65 | + closedAt: 2026-11-25T09:10:00.000Z | ||
| 62 | - id: 3 | 66 | - id: 3 |
| 63 | title: "Decide the policy for undeclared model ids" | 67 | title: "Decide the policy for undeclared model ids" |
| 64 | - state: open | 68 | + state: closed |
| 65 | priority: medium | 69 | priority: medium |
| 66 | author: | 70 | author: |
| 67 | name: k33g | 71 | name: k33g |
| 68 | email: ph.charriere@gmail.com | 72 | email: ph.charriere@gmail.com |
| 69 | createdAt: 2026-11-24T21:17:08.000Z | 73 | createdAt: 2026-11-24T21:17:08.000Z |
| 74 | + updatedAt: 2026-11-25T09:10:00.000Z | ||
| 75 | + closedAt: 2026-11-25T09:10:00.000Z | ||
| 70 | - id: 4 | 76 | - id: 4 |
| 71 | title: "Server-side caps a client cannot exceed" | 77 | title: "Server-side caps a client cannot exceed" |
| 72 | - state: open | 78 | + state: closed |
| 73 | priority: medium | 79 | priority: medium |
| 74 | author: | 80 | author: |
| 75 | name: k33g | 81 | name: k33g |
| 76 | email: ph.charriere@gmail.com | 82 | email: ph.charriere@gmail.com |
| 77 | createdAt: 2026-11-24T21:17:08.000Z | 83 | createdAt: 2026-11-24T21:17:08.000Z |
| 78 | -comments: [] | 84 | + updatedAt: 2026-11-25T09:10:00.000Z |
| 85 | + closedAt: 2026-11-25T09:10:00.000Z | ||
| 86 | +comments: | ||
| 87 | + - id: 1 | ||
| 88 | + author: | ||
| 89 | + name: k33g | ||
| 90 | + email: ph.charriere@gmail.com | ||
| 91 | + createdAt: 2026-11-25T09:10:00.000Z | ||
| 92 | + body: | | ||
| 93 | + Decisions (user, 2026-11-25): | ||
| 94 | + - **Undeclared model ids**: any Hugging Face id (`org/name`, optional `@revision`) is accepted when it is MLX-compliant. Implemented in `ModelCatalog.resolve`: declared ids first; otherwise the id shape is checked, and a repository already cached with GGUF weights and no `.safetensors` is refused (`notMLX`). A repository not yet downloaded is checked at download time (#34). | ||
| 95 | + - **Locked settings**: nothing is locked unless listed in a `locked:` block (server-wide and/or per model). `temperature`, `top_p`, `thinking` are imposed; `max_tokens` and `thinking_budget` are ceilings (a smaller request is kept). Order: built-in → `defaults` (server, then model) → client → `locked` (server, then model). | ||
| 96 | + | ||
| 97 | + Done: `ServerConfig` / `ServerConfigLoader` (sections `server`, `defaults`, `locked`, `models`, `limits`; unknown keys, types, ranges, duplicate ids, all reported with their line), `GenerationOverrides`, `ModelCatalog`, `rzb config validate <file>`, `rzb serve --config <file>` (command-line options win over the file). The API key stays out of the file: `server.api_key_env` names the variable (replaces the `${env.…}` draft). `examples/server.yaml` is checked by a test. Tests +18 (Linux 73, Mac 78), quality gate PASS. | ||
| 98 | + | ||
added
Sources/RazorbillCLI/Commands/ConfigCommand.swift +37 -0 | new file mode 100644 | ||
| @@ -0,0 +1,37 @@ | ||
| 1 | +import ArgumentParser | |
| 2 | +import RazorbillCore | |
| 3 | + | |
| 4 | +/// `rzb config validate <file>`. | |
| 5 | +struct ConfigCommand: AsyncParsableCommand { | |
| 6 | + static let configuration = CommandConfiguration( | |
| 7 | + commandName: "config", | |
| 8 | + abstract: "Work with server configuration files.", | |
| 9 | + subcommands: [Validate.self] | |
| 10 | + ) | |
| 11 | + | |
| 12 | + struct Validate: AsyncParsableCommand { | |
| 13 | + static let configuration = CommandConfiguration( | |
| 14 | + abstract: | |
| 15 | + "Check a server configuration file: keys, types and values, with line numbers.") | |
| 16 | + | |
| 17 | + @Argument(help: "The file, e.g. server.yaml.") | |
| 18 | + var file: String | |
| 19 | + | |
| 20 | + func run() async throws { | |
| 21 | + let console = CLIEnvironment.current.console | |
| 22 | + try await reportingErrors(console) { | |
| 23 | + let config = try ServerConfigLoader().load(file: file) | |
| 24 | + console.write(Self.summary(file: file, config: config) + "\n") | |
| 25 | + } | |
| 26 | + } | |
| 27 | + | |
| 28 | + /// `server.yaml is valid: 2 models (qwen3, embed), any Hugging Face MLX id accepted` | |
| 29 | + static func summary(file: String, config: ServerConfig) -> String { | |
| 30 | + let names = config.models.map(\.id).joined(separator: ", ") | |
| 31 | + let models = | |
| 32 | + config.models.isEmpty | |
| 33 | + ? "no declared models" : "\(config.models.count) models (\(names))" | |
| 34 | + return "\(file) is valid: \(models), any Hugging Face MLX id accepted" | |
| 35 | + } | |
| 36 | + } | |
| 37 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,37 @@ | |||
| 1 | +import ArgumentParser | ||
| 2 | +import RazorbillCore | ||
| 3 | + | ||
| 4 | +/// `rzb config validate <file>`. | ||
| 5 | +struct ConfigCommand: AsyncParsableCommand { | ||
| 6 | + static let configuration = CommandConfiguration( | ||
| 7 | + commandName: "config", | ||
| 8 | + abstract: "Work with server configuration files.", | ||
| 9 | + subcommands: [Validate.self] | ||
| 10 | + ) | ||
| 11 | + | ||
| 12 | + struct Validate: AsyncParsableCommand { | ||
| 13 | + static let configuration = CommandConfiguration( | ||
| 14 | + abstract: | ||
| 15 | + "Check a server configuration file: keys, types and values, with line numbers.") | ||
| 16 | + | ||
| 17 | + @Argument(help: "The file, e.g. server.yaml.") | ||
| 18 | + var file: String | ||
| 19 | + | ||
| 20 | + func run() async throws { | ||
| 21 | + let console = CLIEnvironment.current.console | ||
| 22 | + try await reportingErrors(console) { | ||
| 23 | + let config = try ServerConfigLoader().load(file: file) | ||
| 24 | + console.write(Self.summary(file: file, config: config) + "\n") | ||
| 25 | + } | ||
| 26 | + } | ||
| 27 | + | ||
| 28 | + /// `server.yaml is valid: 2 models (qwen3, embed), any Hugging Face MLX id accepted` | ||
| 29 | + static func summary(file: String, config: ServerConfig) -> String { | ||
| 30 | + let names = config.models.map(\.id).joined(separator: ", ") | ||
| 31 | + let models = | ||
| 32 | + config.models.isEmpty | ||
| 33 | + ? "no declared models" : "\(config.models.count) models (\(names))" | ||
| 34 | + return "\(file) is valid: \(models), any Hugging Face MLX id accepted" | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | +} | ||
modified
Sources/RazorbillCLI/Commands/Rzb.swift +3 -1 | @@ -11,7 +11,9 @@ public struct Rzb: AsyncParsableCommand { | ||
| 11 | 11 | commandName: "rzb", |
| 12 | 12 | abstract: "razorbill — an MLX model server for Apple Silicon.", |
| 13 | 13 | version: Razorbill.version, |
| 14 | - subcommands: [ServeCommand.self, ModelsCommand.self, VersionCommand.self] | |
| 14 | + subcommands: [ | |
| 15 | + ServeCommand.self, ConfigCommand.self, ModelsCommand.self, VersionCommand.self, | |
| 16 | + ] | |
| 15 | 17 | ) |
| 16 | 18 | |
| 17 | 19 | public init() {} |
| @@ -11,7 +11,9 @@ public struct Rzb: AsyncParsableCommand { | |||
| 11 | commandName: "rzb", | 11 | commandName: "rzb", |
| 12 | abstract: "razorbill — an MLX model server for Apple Silicon.", | 12 | abstract: "razorbill — an MLX model server for Apple Silicon.", |
| 13 | version: Razorbill.version, | 13 | version: Razorbill.version, |
| 14 | - subcommands: [ServeCommand.self, ModelsCommand.self, VersionCommand.self] | 14 | + subcommands: [ |
| 15 | + ServeCommand.self, ConfigCommand.self, ModelsCommand.self, VersionCommand.self, | ||
| 16 | + ] | ||
| 15 | ) | 17 | ) |
| 16 | 18 | ||
| 17 | public init() {} | 19 | public init() {} |
modified
Sources/RazorbillCLI/Commands/ServeCommand.swift +41 -14 | @@ -17,18 +17,25 @@ struct ServeCommand: AsyncParsableCommand { | ||
| 17 | 17 | whole network, and set an API key when you do. Stop with Ctrl-C. |
| 18 | 18 | """) |
| 19 | 19 | |
| 20 | - @Option(help: "Address to listen on (0.0.0.0 for every network interface).") | |
| 21 | - var host = "127.0.0.1" | |
| 20 | + @Option( | |
| 21 | + help: ArgumentHelp( | |
| 22 | + "Server configuration file (models, defaults, locked settings, limits).", | |
| 23 | + valueName: "file")) | |
| 24 | + var config: String? | |
| 22 | 25 | |
| 23 | - @Option(help: "TCP port.") | |
| 24 | - var port = 8080 | |
| 26 | + @Option(help: "Address to listen on, 0.0.0.0 for every network interface. (default: 127.0.0.1)") | |
| 27 | + var host: String? | |
| 28 | + | |
| 29 | + @Option(help: "TCP port. (default: 8080)") | |
| 30 | + var port: Int? | |
| 25 | 31 | |
| 26 | 32 | @Option( |
| 27 | 33 | name: .customLong("api-key-env"), |
| 28 | 34 | help: ArgumentHelp( |
| 29 | - "Environment variable holding the API key clients must send as a Bearer token.", | |
| 35 | + "Environment variable holding the API key clients must send as a Bearer token. " | |
| 36 | + + "(default: RZB_API_KEY)", | |
| 30 | 37 | valueName: "name")) |
| 31 | - var apiKeyVariable = "RZB_API_KEY" | |
| 38 | + var apiKeyVariable: String? | |
| 32 | 39 | |
| 33 | 40 | @Option( |
| 34 | 41 | name: .customLong("cors-origin"), |
| @@ -37,30 +44,50 @@ struct ServeCommand: AsyncParsableCommand { | ||
| 37 | 44 | valueName: "origin")) |
| 38 | 45 | var corsOrigin: String? |
| 39 | 46 | |
| 47 | + static let defaultAPIKeyVariable = "RZB_API_KEY" | |
| 48 | + | |
| 40 | 49 | func validate() throws { |
| 41 | - guard (1 ... 65_535).contains(port) else { | |
| 50 | + if let port, !(1 ... 65_535).contains(port) { | |
| 42 | 51 | throw ValidationError("--port must be between 1 and 65535") |
| 43 | 52 | } |
| 44 | - guard !host.trimmingCharacters(in: .whitespaces).isEmpty else { | |
| 53 | + if let host, host.trimmingCharacters(in: .whitespaces).isEmpty { | |
| 45 | 54 | throw ValidationError("--host must not be empty") |
| 46 | 55 | } |
| 47 | 56 | } |
| 48 | 57 | |
| 49 | - /// The server settings these options and `variables` (the process environment) describe. | |
| 50 | - func settings(variables: [String: String]) -> ServerSettings { | |
| 51 | - let key = variables[apiKeyVariable].flatMap { $0.isEmpty ? nil : $0 } | |
| 52 | - return ServerSettings(host: host, port: port, apiKey: key, corsOrigin: corsOrigin) | |
| 58 | + /// The server settings: these options first, then the file's `server:` section, then the | |
| 59 | + /// defaults. The API key is read from the environment `variables`. | |
| 60 | + func settings(config: ServerConfig, variables: [String: String]) -> ServerSettings { | |
| 61 | + let section = config.server | |
| 62 | + let defaults = ServerSettings() | |
| 63 | + let variable = keyVariable(config) | |
| 64 | + let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 } | |
| 65 | + return ServerSettings( | |
| 66 | + host: host ?? section.host ?? defaults.host, | |
| 67 | + port: port ?? section.port ?? defaults.port, | |
| 68 | + apiKey: key, corsOrigin: corsOrigin ?? section.corsOrigin, config: config) | |
| 69 | + } | |
| 70 | + | |
| 71 | + func keyVariable(_ config: ServerConfig) -> String { | |
| 72 | + apiKeyVariable ?? config.server.apiKeyVariable ?? Self.defaultAPIKeyVariable | |
| 53 | 73 | } |
| 54 | 74 | |
| 55 | 75 | func run() async throws { |
| 56 | 76 | let environment = CLIEnvironment.current |
| 57 | 77 | let console = environment.console |
| 58 | - let settings = settings(variables: environment.variables) | |
| 59 | 78 | try await reportingErrors(console) { |
| 79 | + let serverConfig = | |
| 80 | + try config.map { try ServerConfigLoader().load(file: $0) } ?? ServerConfig() | |
| 81 | + let settings = settings(config: serverConfig, variables: environment.variables) | |
| 82 | + if let config { | |
| 83 | + console.writeErrorLine( | |
| 84 | + "config: \(config) (\(serverConfig.models.count) declared models)") | |
| 85 | + } | |
| 60 | 86 | for warning in settings.warnings { |
| 61 | 87 | console.writeErrorLine("warning: \(warning)") |
| 62 | 88 | } |
| 63 | - let keyNote = settings.apiKey == nil ? "no API key" : "API key from $\(apiKeyVariable)" | |
| 89 | + let keyNote = | |
| 90 | + settings.apiKey == nil ? "no API key" : "API key from $\(keyVariable(serverConfig))" | |
| 64 | 91 | try await environment.serve(settings) { port in |
| 65 | 92 | let url = settings.baseURL(port: port) |
| 66 | 93 | let banner = "\(Razorbill.commandName) \(Razorbill.version) serving \(url)" |
| @@ -17,18 +17,25 @@ struct ServeCommand: AsyncParsableCommand { | |||
| 17 | whole network, and set an API key when you do. Stop with Ctrl-C. | 17 | whole network, and set an API key when you do. Stop with Ctrl-C. |
| 18 | """) | 18 | """) |
| 19 | 19 | ||
| 20 | - @Option(help: "Address to listen on (0.0.0.0 for every network interface).") | 20 | + @Option( |
| 21 | - var host = "127.0.0.1" | 21 | + help: ArgumentHelp( |
| 22 | + "Server configuration file (models, defaults, locked settings, limits).", | ||
| 23 | + valueName: "file")) | ||
| 24 | + var config: String? | ||
| 22 | 25 | ||
| 23 | - @Option(help: "TCP port.") | 26 | + @Option(help: "Address to listen on, 0.0.0.0 for every network interface. (default: 127.0.0.1)") |
| 24 | - var port = 8080 | 27 | + var host: String? |
| 28 | + | ||
| 29 | + @Option(help: "TCP port. (default: 8080)") | ||
| 30 | + var port: Int? | ||
| 25 | 31 | ||
| 26 | @Option( | 32 | @Option( |
| 27 | name: .customLong("api-key-env"), | 33 | name: .customLong("api-key-env"), |
| 28 | help: ArgumentHelp( | 34 | help: ArgumentHelp( |
| 29 | - "Environment variable holding the API key clients must send as a Bearer token.", | 35 | + "Environment variable holding the API key clients must send as a Bearer token. " |
| 36 | + + "(default: RZB_API_KEY)", | ||
| 30 | valueName: "name")) | 37 | valueName: "name")) |
| 31 | - var apiKeyVariable = "RZB_API_KEY" | 38 | + var apiKeyVariable: String? |
| 32 | 39 | ||
| 33 | @Option( | 40 | @Option( |
| 34 | name: .customLong("cors-origin"), | 41 | name: .customLong("cors-origin"), |
| @@ -37,30 +44,50 @@ struct ServeCommand: AsyncParsableCommand { | |||
| 37 | valueName: "origin")) | 44 | valueName: "origin")) |
| 38 | var corsOrigin: String? | 45 | var corsOrigin: String? |
| 39 | 46 | ||
| 47 | + static let defaultAPIKeyVariable = "RZB_API_KEY" | ||
| 48 | + | ||
| 40 | func validate() throws { | 49 | func validate() throws { |
| 41 | - guard (1 ... 65_535).contains(port) else { | 50 | + if let port, !(1 ... 65_535).contains(port) { |
| 42 | throw ValidationError("--port must be between 1 and 65535") | 51 | throw ValidationError("--port must be between 1 and 65535") |
| 43 | } | 52 | } |
| 44 | - guard !host.trimmingCharacters(in: .whitespaces).isEmpty else { | 53 | + if let host, host.trimmingCharacters(in: .whitespaces).isEmpty { |
| 45 | throw ValidationError("--host must not be empty") | 54 | throw ValidationError("--host must not be empty") |
| 46 | } | 55 | } |
| 47 | } | 56 | } |
| 48 | 57 | ||
| 49 | - /// The server settings these options and `variables` (the process environment) describe. | 58 | + /// The server settings: these options first, then the file's `server:` section, then the |
| 50 | - func settings(variables: [String: String]) -> ServerSettings { | 59 | + /// defaults. The API key is read from the environment `variables`. |
| 51 | - let key = variables[apiKeyVariable].flatMap { $0.isEmpty ? nil : $0 } | 60 | + func settings(config: ServerConfig, variables: [String: String]) -> ServerSettings { |
| 52 | - return ServerSettings(host: host, port: port, apiKey: key, corsOrigin: corsOrigin) | 61 | + let section = config.server |
| 62 | + let defaults = ServerSettings() | ||
| 63 | + let variable = keyVariable(config) | ||
| 64 | + let key = variables[variable].flatMap { $0.isEmpty ? nil : $0 } | ||
| 65 | + return ServerSettings( | ||
| 66 | + host: host ?? section.host ?? defaults.host, | ||
| 67 | + port: port ?? section.port ?? defaults.port, | ||
| 68 | + apiKey: key, corsOrigin: corsOrigin ?? section.corsOrigin, config: config) | ||
| 69 | + } | ||
| 70 | + | ||
| 71 | + func keyVariable(_ config: ServerConfig) -> String { | ||
| 72 | + apiKeyVariable ?? config.server.apiKeyVariable ?? Self.defaultAPIKeyVariable | ||
| 53 | } | 73 | } |
| 54 | 74 | ||
| 55 | func run() async throws { | 75 | func run() async throws { |
| 56 | let environment = CLIEnvironment.current | 76 | let environment = CLIEnvironment.current |
| 57 | let console = environment.console | 77 | let console = environment.console |
| 58 | - let settings = settings(variables: environment.variables) | ||
| 59 | try await reportingErrors(console) { | 78 | try await reportingErrors(console) { |
| 79 | + let serverConfig = | ||
| 80 | + try config.map { try ServerConfigLoader().load(file: $0) } ?? ServerConfig() | ||
| 81 | + let settings = settings(config: serverConfig, variables: environment.variables) | ||
| 82 | + if let config { | ||
| 83 | + console.writeErrorLine( | ||
| 84 | + "config: \(config) (\(serverConfig.models.count) declared models)") | ||
| 85 | + } | ||
| 60 | for warning in settings.warnings { | 86 | for warning in settings.warnings { |
| 61 | console.writeErrorLine("warning: \(warning)") | 87 | console.writeErrorLine("warning: \(warning)") |
| 62 | } | 88 | } |
| 63 | - let keyNote = settings.apiKey == nil ? "no API key" : "API key from $\(apiKeyVariable)" | 89 | + let keyNote = |
| 90 | + settings.apiKey == nil ? "no API key" : "API key from $\(keyVariable(serverConfig))" | ||
| 64 | try await environment.serve(settings) { port in | 91 | try await environment.serve(settings) { port in |
| 65 | let url = settings.baseURL(port: port) | 92 | let url = settings.baseURL(port: port) |
| 66 | let banner = "\(Razorbill.commandName) \(Razorbill.version) serving \(url)" | 93 | let banner = "\(Razorbill.commandName) \(Razorbill.version) serving \(url)" |
added
Sources/RazorbillCore/Config/GenerationOverrides.swift +68 -0 | new file mode 100644 | ||
| @@ -0,0 +1,68 @@ | ||
| 1 | +/// Some generation settings, each one optional: a `defaults:` or `locked:` block of the server | |
| 2 | +/// configuration, or the sampling fields a client sent. | |
| 3 | +/// | |
| 4 | +/// ```swift | |
| 5 | +/// let defaults = GenerationOverrides(temperature: 0.2) | |
| 6 | +/// let locked = GenerationOverrides(maxTokens: 512) | |
| 7 | +/// let client = GenerationOverrides(temperature: 0.9, maxTokens: 4096) | |
| 8 | +/// let settings = GenerationOverrides.resolve(defaults: [defaults], client: client, locked: [locked]) | |
| 9 | +/// // temperature 0.9 (the client may change a default), maxTokens 512 (locked: a ceiling) | |
| 10 | +/// ``` | |
| 11 | +public struct GenerationOverrides: Sendable, Equatable { | |
| 12 | + public var temperature: Double? | |
| 13 | + public var topP: Double? | |
| 14 | + public var maxTokens: Int? | |
| 15 | + public var thinking: Bool? | |
| 16 | + public var thinkingBudget: Int? | |
| 17 | + | |
| 18 | + public init( | |
| 19 | + temperature: Double? = nil, topP: Double? = nil, maxTokens: Int? = nil, | |
| 20 | + thinking: Bool? = nil, thinkingBudget: Int? = nil | |
| 21 | + ) { | |
| 22 | + self.temperature = temperature | |
| 23 | + self.topP = topP | |
| 24 | + self.maxTokens = maxTokens | |
| 25 | + self.thinking = thinking | |
| 26 | + self.thinkingBudget = thinkingBudget | |
| 27 | + } | |
| 28 | + | |
| 29 | + /// No setting given. | |
| 30 | + public var isEmpty: Bool { self == GenerationOverrides() } | |
| 31 | + | |
| 32 | + /// `settings` with every value given here replacing its own. | |
| 33 | + public func replacing(in settings: GenerationSettings) -> GenerationSettings { | |
| 34 | + var result = settings | |
| 35 | + if let temperature { result.temperature = temperature } | |
| 36 | + if let topP { result.topP = topP } | |
| 37 | + if let maxTokens { result.maxTokens = maxTokens } | |
| 38 | + if let thinking { result.thinking = thinking } | |
| 39 | + if let thinkingBudget { result.thinkingBudget = thinkingBudget } | |
| 40 | + return result | |
| 41 | + } | |
| 42 | + | |
| 43 | + /// `settings` with this block enforced as locked values: `temperature`, `topP` and `thinking` | |
| 44 | + /// are imposed; `maxTokens` and `thinkingBudget` are ceilings (a smaller request is kept). | |
| 45 | + public func enforcing(on settings: GenerationSettings) -> GenerationSettings { | |
| 46 | + var result = settings | |
| 47 | + if let temperature { result.temperature = temperature } | |
| 48 | + if let topP { result.topP = topP } | |
| 49 | + if let thinking { result.thinking = thinking } | |
| 50 | + if let maxTokens { result.maxTokens = min(result.maxTokens, maxTokens) } | |
| 51 | + if let thinkingBudget { | |
| 52 | + result.thinkingBudget = min(result.thinkingBudget ?? thinkingBudget, thinkingBudget) | |
| 53 | + } | |
| 54 | + return result | |
| 55 | + } | |
| 56 | + | |
| 57 | + /// The settings of one request: built-in defaults, then each `defaults` block in order, then | |
| 58 | + /// the client's values, then each `locked` block in order. | |
| 59 | + public static func resolve( | |
| 60 | + defaults: [GenerationOverrides], client: GenerationOverrides, | |
| 61 | + locked: [GenerationOverrides] | |
| 62 | + ) -> GenerationSettings { | |
| 63 | + let base = (defaults + [client]).reduce(GenerationSettings()) { settings, block in | |
| 64 | + block.replacing(in: settings) | |
| 65 | + } | |
| 66 | + return locked.reduce(base) { settings, block in block.enforcing(on: settings) } | |
| 67 | + } | |
| 68 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,68 @@ | |||
| 1 | +/// Some generation settings, each one optional: a `defaults:` or `locked:` block of the server | ||
| 2 | +/// configuration, or the sampling fields a client sent. | ||
| 3 | +/// | ||
| 4 | +/// ```swift | ||
| 5 | +/// let defaults = GenerationOverrides(temperature: 0.2) | ||
| 6 | +/// let locked = GenerationOverrides(maxTokens: 512) | ||
| 7 | +/// let client = GenerationOverrides(temperature: 0.9, maxTokens: 4096) | ||
| 8 | +/// let settings = GenerationOverrides.resolve(defaults: [defaults], client: client, locked: [locked]) | ||
| 9 | +/// // temperature 0.9 (the client may change a default), maxTokens 512 (locked: a ceiling) | ||
| 10 | +/// ``` | ||
| 11 | +public struct GenerationOverrides: Sendable, Equatable { | ||
| 12 | + public var temperature: Double? | ||
| 13 | + public var topP: Double? | ||
| 14 | + public var maxTokens: Int? | ||
| 15 | + public var thinking: Bool? | ||
| 16 | + public var thinkingBudget: Int? | ||
| 17 | + | ||
| 18 | + public init( | ||
| 19 | + temperature: Double? = nil, topP: Double? = nil, maxTokens: Int? = nil, | ||
| 20 | + thinking: Bool? = nil, thinkingBudget: Int? = nil | ||
| 21 | + ) { | ||
| 22 | + self.temperature = temperature | ||
| 23 | + self.topP = topP | ||
| 24 | + self.maxTokens = maxTokens | ||
| 25 | + self.thinking = thinking | ||
| 26 | + self.thinkingBudget = thinkingBudget | ||
| 27 | + } | ||
| 28 | + | ||
| 29 | + /// No setting given. | ||
| 30 | + public var isEmpty: Bool { self == GenerationOverrides() } | ||
| 31 | + | ||
| 32 | + /// `settings` with every value given here replacing its own. | ||
| 33 | + public func replacing(in settings: GenerationSettings) -> GenerationSettings { | ||
| 34 | + var result = settings | ||
| 35 | + if let temperature { result.temperature = temperature } | ||
| 36 | + if let topP { result.topP = topP } | ||
| 37 | + if let maxTokens { result.maxTokens = maxTokens } | ||
| 38 | + if let thinking { result.thinking = thinking } | ||
| 39 | + if let thinkingBudget { result.thinkingBudget = thinkingBudget } | ||
| 40 | + return result | ||
| 41 | + } | ||
| 42 | + | ||
| 43 | + /// `settings` with this block enforced as locked values: `temperature`, `topP` and `thinking` | ||
| 44 | + /// are imposed; `maxTokens` and `thinkingBudget` are ceilings (a smaller request is kept). | ||
| 45 | + public func enforcing(on settings: GenerationSettings) -> GenerationSettings { | ||
| 46 | + var result = settings | ||
| 47 | + if let temperature { result.temperature = temperature } | ||
| 48 | + if let topP { result.topP = topP } | ||
| 49 | + if let thinking { result.thinking = thinking } | ||
| 50 | + if let maxTokens { result.maxTokens = min(result.maxTokens, maxTokens) } | ||
| 51 | + if let thinkingBudget { | ||
| 52 | + result.thinkingBudget = min(result.thinkingBudget ?? thinkingBudget, thinkingBudget) | ||
| 53 | + } | ||
| 54 | + return result | ||
| 55 | + } | ||
| 56 | + | ||
| 57 | + /// The settings of one request: built-in defaults, then each `defaults` block in order, then | ||
| 58 | + /// the client's values, then each `locked` block in order. | ||
| 59 | + public static func resolve( | ||
| 60 | + defaults: [GenerationOverrides], client: GenerationOverrides, | ||
| 61 | + locked: [GenerationOverrides] | ||
| 62 | + ) -> GenerationSettings { | ||
| 63 | + let base = (defaults + [client]).reduce(GenerationSettings()) { settings, block in | ||
| 64 | + block.replacing(in: settings) | ||
| 65 | + } | ||
| 66 | + return locked.reduce(base) { settings, block in block.enforcing(on: settings) } | ||
| 67 | + } | ||
| 68 | +} | ||
added
Sources/RazorbillCore/Config/ServerConfig.swift +106 -0 | new file mode 100644 | ||
| @@ -0,0 +1,106 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// The server configuration file (`rzb serve --config server.yaml`), loaded by | |
| 4 | +/// ``ServerConfigLoader``. Every section is optional: an empty file is a valid configuration. | |
| 5 | +/// | |
| 6 | +/// ```yaml | |
| 7 | +/// server: | |
| 8 | +/// host: 127.0.0.1 | |
| 9 | +/// port: 8080 | |
| 10 | +/// api_key_env: RZB_API_KEY | |
| 11 | +/// defaults: { temperature: 0.6 } | |
| 12 | +/// locked: { max_tokens: 4096 } | |
| 13 | +/// models: | |
| 14 | +/// - id: qwen3 | |
| 15 | +/// source: mlx-community/Qwen3-4B-4bit | |
| 16 | +/// limits: | |
| 17 | +/// max_loaded_models: 2 | |
| 18 | +/// keep_alive: 10m | |
| 19 | +/// ``` | |
| 20 | +public struct ServerConfig: Sendable, Equatable { | |
| 21 | + public var server: ServerSection | |
| 22 | + /// Settings every model starts from; clients may change them. | |
| 23 | + public var defaults: GenerationOverrides | |
| 24 | + /// Settings clients cannot exceed, for every model. | |
| 25 | + public var locked: GenerationOverrides | |
| 26 | + /// Models declared by name. Undeclared Hugging Face ids are accepted too (see ``ModelCatalog``). | |
| 27 | + public var models: [ModelEntry] | |
| 28 | + public var limits: ServerLimits | |
| 29 | + | |
| 30 | + public init( | |
| 31 | + server: ServerSection = ServerSection(), defaults: GenerationOverrides = .init(), | |
| 32 | + locked: GenerationOverrides = .init(), models: [ModelEntry] = [], | |
| 33 | + limits: ServerLimits = ServerLimits() | |
| 34 | + ) { | |
| 35 | + self.server = server | |
| 36 | + self.defaults = defaults | |
| 37 | + self.locked = locked | |
| 38 | + self.models = models | |
| 39 | + self.limits = limits | |
| 40 | + } | |
| 41 | +} | |
| 42 | + | |
| 43 | +/// The `server:` section. `nil` values leave the `rzb serve` defaults (or options) in place. | |
| 44 | +public struct ServerSection: Sendable, Equatable { | |
| 45 | + public var host: String? | |
| 46 | + public var port: Int? | |
| 47 | + /// Name of the environment variable holding the API key (the key itself never goes in the file). | |
| 48 | + public var apiKeyVariable: String? | |
| 49 | + public var corsOrigin: String? | |
| 50 | + | |
| 51 | + public init( | |
| 52 | + host: String? = nil, port: Int? = nil, apiKeyVariable: String? = nil, | |
| 53 | + corsOrigin: String? = nil | |
| 54 | + ) { | |
| 55 | + self.host = host | |
| 56 | + self.port = port | |
| 57 | + self.apiKeyVariable = apiKeyVariable | |
| 58 | + self.corsOrigin = corsOrigin | |
| 59 | + } | |
| 60 | +} | |
| 61 | + | |
| 62 | +/// What a declared model is for. | |
| 63 | +public enum ModelKind: String, Sendable, Equatable, CaseIterable { | |
| 64 | + case chat | |
| 65 | + case embedding | |
| 66 | +} | |
| 67 | + | |
| 68 | +/// One entry of `models:`. | |
| 69 | +public struct ModelEntry: Sendable, Equatable { | |
| 70 | + /// The name clients put in `"model"`. | |
| 71 | + public var id: String | |
| 72 | + public var source: ModelReference | |
| 73 | + public var kind: ModelKind | |
| 74 | + /// Load at start-up instead of on the first request. | |
| 75 | + public var preload: Bool | |
| 76 | + public var defaults: GenerationOverrides | |
| 77 | + public var locked: GenerationOverrides | |
| 78 | + | |
| 79 | + public init( | |
| 80 | + id: String, source: ModelReference, kind: ModelKind = .chat, preload: Bool = false, | |
| 81 | + defaults: GenerationOverrides = .init(), locked: GenerationOverrides = .init() | |
| 82 | + ) { | |
| 83 | + self.id = id | |
| 84 | + self.source = source | |
| 85 | + self.kind = kind | |
| 86 | + self.preload = preload | |
| 87 | + self.defaults = defaults | |
| 88 | + self.locked = locked | |
| 89 | + } | |
| 90 | +} | |
| 91 | + | |
| 92 | +/// The `limits:` section. | |
| 93 | +public struct ServerLimits: Sendable, Equatable { | |
| 94 | + /// Models kept in memory at once; the least recently used one is unloaded beyond it. | |
| 95 | + public var maxLoadedModels: Int | |
| 96 | + /// An idle model is unloaded after this long. | |
| 97 | + public var keepAlive: Duration | |
| 98 | + /// Requests waiting for one model; more get a 429. | |
| 99 | + public var maxQueue: Int | |
| 100 | + | |
| 101 | + public init(maxLoadedModels: Int = 1, keepAlive: Duration = .seconds(600), maxQueue: Int = 16) { | |
| 102 | + self.maxLoadedModels = maxLoadedModels | |
| 103 | + self.keepAlive = keepAlive | |
| 104 | + self.maxQueue = maxQueue | |
| 105 | + } | |
| 106 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,106 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// The server configuration file (`rzb serve --config server.yaml`), loaded by | ||
| 4 | +/// ``ServerConfigLoader``. Every section is optional: an empty file is a valid configuration. | ||
| 5 | +/// | ||
| 6 | +/// ```yaml | ||
| 7 | +/// server: | ||
| 8 | +/// host: 127.0.0.1 | ||
| 9 | +/// port: 8080 | ||
| 10 | +/// api_key_env: RZB_API_KEY | ||
| 11 | +/// defaults: { temperature: 0.6 } | ||
| 12 | +/// locked: { max_tokens: 4096 } | ||
| 13 | +/// models: | ||
| 14 | +/// - id: qwen3 | ||
| 15 | +/// source: mlx-community/Qwen3-4B-4bit | ||
| 16 | +/// limits: | ||
| 17 | +/// max_loaded_models: 2 | ||
| 18 | +/// keep_alive: 10m | ||
| 19 | +/// ``` | ||
| 20 | +public struct ServerConfig: Sendable, Equatable { | ||
| 21 | + public var server: ServerSection | ||
| 22 | + /// Settings every model starts from; clients may change them. | ||
| 23 | + public var defaults: GenerationOverrides | ||
| 24 | + /// Settings clients cannot exceed, for every model. | ||
| 25 | + public var locked: GenerationOverrides | ||
| 26 | + /// Models declared by name. Undeclared Hugging Face ids are accepted too (see ``ModelCatalog``). | ||
| 27 | + public var models: [ModelEntry] | ||
| 28 | + public var limits: ServerLimits | ||
| 29 | + | ||
| 30 | + public init( | ||
| 31 | + server: ServerSection = ServerSection(), defaults: GenerationOverrides = .init(), | ||
| 32 | + locked: GenerationOverrides = .init(), models: [ModelEntry] = [], | ||
| 33 | + limits: ServerLimits = ServerLimits() | ||
| 34 | + ) { | ||
| 35 | + self.server = server | ||
| 36 | + self.defaults = defaults | ||
| 37 | + self.locked = locked | ||
| 38 | + self.models = models | ||
| 39 | + self.limits = limits | ||
| 40 | + } | ||
| 41 | +} | ||
| 42 | + | ||
| 43 | +/// The `server:` section. `nil` values leave the `rzb serve` defaults (or options) in place. | ||
| 44 | +public struct ServerSection: Sendable, Equatable { | ||
| 45 | + public var host: String? | ||
| 46 | + public var port: Int? | ||
| 47 | + /// Name of the environment variable holding the API key (the key itself never goes in the file). | ||
| 48 | + public var apiKeyVariable: String? | ||
| 49 | + public var corsOrigin: String? | ||
| 50 | + | ||
| 51 | + public init( | ||
| 52 | + host: String? = nil, port: Int? = nil, apiKeyVariable: String? = nil, | ||
| 53 | + corsOrigin: String? = nil | ||
| 54 | + ) { | ||
| 55 | + self.host = host | ||
| 56 | + self.port = port | ||
| 57 | + self.apiKeyVariable = apiKeyVariable | ||
| 58 | + self.corsOrigin = corsOrigin | ||
| 59 | + } | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +/// What a declared model is for. | ||
| 63 | +public enum ModelKind: String, Sendable, Equatable, CaseIterable { | ||
| 64 | + case chat | ||
| 65 | + case embedding | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/// One entry of `models:`. | ||
| 69 | +public struct ModelEntry: Sendable, Equatable { | ||
| 70 | + /// The name clients put in `"model"`. | ||
| 71 | + public var id: String | ||
| 72 | + public var source: ModelReference | ||
| 73 | + public var kind: ModelKind | ||
| 74 | + /// Load at start-up instead of on the first request. | ||
| 75 | + public var preload: Bool | ||
| 76 | + public var defaults: GenerationOverrides | ||
| 77 | + public var locked: GenerationOverrides | ||
| 78 | + | ||
| 79 | + public init( | ||
| 80 | + id: String, source: ModelReference, kind: ModelKind = .chat, preload: Bool = false, | ||
| 81 | + defaults: GenerationOverrides = .init(), locked: GenerationOverrides = .init() | ||
| 82 | + ) { | ||
| 83 | + self.id = id | ||
| 84 | + self.source = source | ||
| 85 | + self.kind = kind | ||
| 86 | + self.preload = preload | ||
| 87 | + self.defaults = defaults | ||
| 88 | + self.locked = locked | ||
| 89 | + } | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +/// The `limits:` section. | ||
| 93 | +public struct ServerLimits: Sendable, Equatable { | ||
| 94 | + /// Models kept in memory at once; the least recently used one is unloaded beyond it. | ||
| 95 | + public var maxLoadedModels: Int | ||
| 96 | + /// An idle model is unloaded after this long. | ||
| 97 | + public var keepAlive: Duration | ||
| 98 | + /// Requests waiting for one model; more get a 429. | ||
| 99 | + public var maxQueue: Int | ||
| 100 | + | ||
| 101 | + public init(maxLoadedModels: Int = 1, keepAlive: Duration = .seconds(600), maxQueue: Int = 16) { | ||
| 102 | + self.maxLoadedModels = maxLoadedModels | ||
| 103 | + self.keepAlive = keepAlive | ||
| 104 | + self.maxQueue = maxQueue | ||
| 105 | + } | ||
| 106 | +} | ||
added
Sources/RazorbillCore/Config/ServerConfigLoader.swift +256 -0 | new file mode 100644 | ||
| @@ -0,0 +1,256 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Yams | |
| 3 | + | |
| 4 | +/// Loads and validates a server configuration file into a ``ServerConfig``. | |
| 5 | +/// | |
| 6 | +/// Every problem is collected and thrown at once as a ``ConfigError``: unknown keys, wrong types, | |
| 7 | +/// missing or out-of-range values, duplicate model ids — each with its line. | |
| 8 | +/// | |
| 9 | +/// ```swift | |
| 10 | +/// let config = try ServerConfigLoader().load(file: "server.yaml") | |
| 11 | +/// let inline = try ServerConfigLoader().parse("server:\n port: 9000\n") | |
| 12 | +/// ``` | |
| 13 | +public struct ServerConfigLoader: Sendable { | |
| 14 | + /// Directory that `~` stands for in local model paths. | |
| 15 | + public var homeDirectory: String | |
| 16 | + | |
| 17 | + public init(homeDirectory: String = NSHomeDirectory()) { | |
| 18 | + self.homeDirectory = homeDirectory | |
| 19 | + } | |
| 20 | + | |
| 21 | + /// Reads and validates the file at `path`. Relative model paths start at the file's folder. | |
| 22 | + public func load(file path: String) throws -> ServerConfig { | |
| 23 | + guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { | |
| 24 | + throw ConfigError( | |
| 25 | + file: path, | |
| 26 | + issues: [ConfigIssue(keyPath: "", line: nil, message: "cannot read the file")]) | |
| 27 | + } | |
| 28 | + let folder = URL(fileURLWithPath: path).deletingLastPathComponent().path | |
| 29 | + return try parse(text, file: path, baseDirectory: folder) | |
| 30 | + } | |
| 31 | + | |
| 32 | + /// Validates YAML `text`. `file` only labels the errors. | |
| 33 | + public func parse( | |
| 34 | + _ text: String, file: String? = nil, | |
| 35 | + baseDirectory: String = FileManager.default.currentDirectoryPath | |
| 36 | + ) throws -> ServerConfig { | |
| 37 | + let root: Node? | |
| 38 | + do { | |
| 39 | + root = try Yams.compose(yaml: text) | |
| 40 | + } catch { | |
| 41 | + let issue = ConfigIssue(keyPath: "", line: nil, message: "not valid YAML: \(error)") | |
| 42 | + throw ConfigError(file: file, issues: [issue]) | |
| 43 | + } | |
| 44 | + // An empty file is the default configuration. | |
| 45 | + guard let root else { return ServerConfig() } | |
| 46 | + let reader = ConfigReader() | |
| 47 | + let context = Context(reader: reader, baseDirectory: baseDirectory, home: homeDirectory) | |
| 48 | + let config = context.document(root) | |
| 49 | + guard reader.issues.isEmpty, let config else { | |
| 50 | + throw ConfigError(file: file, issues: reader.issues) | |
| 51 | + } | |
| 52 | + return config | |
| 53 | + } | |
| 54 | + | |
| 55 | + static let topLevelKeys = ["server", "defaults", "locked", "models", "limits"] | |
| 56 | + static let serverKeys = ["host", "port", "api_key_env", "cors_origin"] | |
| 57 | + static let generationKeys = [ | |
| 58 | + "temperature", "top_p", "max_tokens", "thinking", "thinking_budget", | |
| 59 | + ] | |
| 60 | + static let modelKeys = [ | |
| 61 | + "id", "source", "revision", "path", "kind", "preload", "defaults", "locked", | |
| 62 | + ] | |
| 63 | + static let limitKeys = ["max_loaded_models", "keep_alive", "max_queue"] | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// One loading pass: the reader collecting issues and where relative paths start. | |
| 67 | +private struct Context { | |
| 68 | + let reader: ConfigReader | |
| 69 | + let baseDirectory: String | |
| 70 | + let home: String | |
| 71 | + | |
| 72 | + func document(_ root: Node) -> ServerConfig? { | |
| 73 | + guard let document = reader.mapping(root, path: "") else { return nil } | |
| 74 | + reader.rejectUnknownKeys(document, allowed: ServerConfigLoader.topLevelKeys, path: "") | |
| 75 | + return ServerConfig( | |
| 76 | + server: section(document["server"], path: "server", read: server) ?? ServerSection(), | |
| 77 | + defaults: section(document["defaults"], path: "defaults", read: generation) ?? .init(), | |
| 78 | + locked: section(document["locked"], path: "locked", read: generation) ?? .init(), | |
| 79 | + models: models(document["models"]), | |
| 80 | + limits: section(document["limits"], path: "limits", read: limits) ?? ServerLimits()) | |
| 81 | + } | |
| 82 | + | |
| 83 | + /// Reads an optional mapping section, rejecting keys `read` does not know. | |
| 84 | + func section<T>( | |
| 85 | + _ node: Node?, path: String, read: (Node.Mapping, String) -> T | |
| 86 | + ) -> T? { | |
| 87 | + guard let node, !reader.isNull(node), let mapping = reader.mapping(node, path: path) else { | |
| 88 | + return nil | |
| 89 | + } | |
| 90 | + return read(mapping, path) | |
| 91 | + } | |
| 92 | + | |
| 93 | + func server(_ mapping: Node.Mapping, path: String) -> ServerSection { | |
| 94 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.serverKeys, path: path) | |
| 95 | + let port = reader.int(mapping, "port", path: path) | |
| 96 | + if let port, !(1 ... 65_535).contains(port) { | |
| 97 | + reader.report("\(path).port", mapping["port"], "must be between 1 and 65535") | |
| 98 | + } | |
| 99 | + return ServerSection( | |
| 100 | + host: nonEmpty(mapping, "host", path: path), port: port, | |
| 101 | + apiKeyVariable: nonEmpty(mapping, "api_key_env", path: path), | |
| 102 | + corsOrigin: nonEmpty(mapping, "cors_origin", path: path)) | |
| 103 | + } | |
| 104 | + | |
| 105 | + func generation(_ mapping: Node.Mapping, path: String) -> GenerationOverrides { | |
| 106 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.generationKeys, path: path) | |
| 107 | + let block = GenerationOverrides( | |
| 108 | + temperature: number( | |
| 109 | + mapping, "temperature", path: path, rule: "must be between 0 and 2" | |
| 110 | + ) { (0 ... 2).contains($0) }, | |
| 111 | + topP: number( | |
| 112 | + mapping, "top_p", path: path, rule: "must be above 0 and at most 1" | |
| 113 | + ) { $0 > 0 && $0 <= 1 }, | |
| 114 | + maxTokens: whole(mapping, "max_tokens", path: path, atLeast: 1), | |
| 115 | + thinking: reader.bool(mapping, "thinking", path: path), | |
| 116 | + thinkingBudget: whole(mapping, "thinking_budget", path: path, atLeast: 0)) | |
| 117 | + if let budget = block.thinkingBudget, let maxTokens = block.maxTokens, budget >= maxTokens { | |
| 118 | + reader.report( | |
| 119 | + "\(path).thinking_budget", mapping["thinking_budget"], | |
| 120 | + "must be smaller than max_tokens (\(maxTokens))") | |
| 121 | + } | |
| 122 | + return block | |
| 123 | + } | |
| 124 | + | |
| 125 | + func limits(_ mapping: Node.Mapping, path: String) -> ServerLimits { | |
| 126 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.limitKeys, path: path) | |
| 127 | + var limits = ServerLimits() | |
| 128 | + if let value = whole(mapping, "max_loaded_models", path: path, atLeast: 1) { | |
| 129 | + limits.maxLoadedModels = value | |
| 130 | + } | |
| 131 | + if let value = whole(mapping, "max_queue", path: path, atLeast: 1) { | |
| 132 | + limits.maxQueue = value | |
| 133 | + } | |
| 134 | + if let text = reader.string(mapping, "keep_alive", path: path) { | |
| 135 | + if let duration = Quantities.duration(text) { | |
| 136 | + limits.keepAlive = duration | |
| 137 | + } else { | |
| 138 | + reader.report( | |
| 139 | + "\(path).keep_alive", mapping["keep_alive"], | |
| 140 | + "must be a duration such as 30s, 10m or 1h") | |
| 141 | + } | |
| 142 | + } | |
| 143 | + return limits | |
| 144 | + } | |
| 145 | + | |
| 146 | + // MARK: Models | |
| 147 | + | |
| 148 | + func models(_ node: Node?) -> [ModelEntry] { | |
| 149 | + guard let node, !reader.isNull(node) else { return [] } | |
| 150 | + guard case .sequence(let sequence) = node else { | |
| 151 | + reader.report("models", node, "must be a list (lines starting with -)") | |
| 152 | + return [] | |
| 153 | + } | |
| 154 | + var seen: Set<String> = [] | |
| 155 | + return sequence.enumerated().compactMap { index, item in | |
| 156 | + let path = "models[\(index)]" | |
| 157 | + guard let mapping = reader.mapping(item, path: path), | |
| 158 | + let entry = model(mapping, node: item, path: path) | |
| 159 | + else { return nil } | |
| 160 | + if !seen.insert(entry.id).inserted { | |
| 161 | + reader.report("\(path).id", mapping["id"], "duplicate id \(entry.id)") | |
| 162 | + } | |
| 163 | + return entry | |
| 164 | + } | |
| 165 | + } | |
| 166 | + | |
| 167 | + func model(_ mapping: Node.Mapping, node: Node, path: String) -> ModelEntry? { | |
| 168 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.modelKeys, path: path) | |
| 169 | + let id = nonEmpty(mapping, "id", path: path) | |
| 170 | + if id == nil && mapping["id"] == nil { | |
| 171 | + reader.report("\(path).id", node, "is required (the name clients send as \"model\")") | |
| 172 | + } | |
| 173 | + let source = modelSource(mapping, node: node, path: path) | |
| 174 | + let kind = modelKind(mapping, path: path) | |
| 175 | + let defaults = section(mapping["defaults"], path: "\(path).defaults", read: generation) | |
| 176 | + let locked = section(mapping["locked"], path: "\(path).locked", read: generation) | |
| 177 | + guard let id, let source else { return nil } | |
| 178 | + return ModelEntry( | |
| 179 | + id: id, source: source, kind: kind ?? .chat, | |
| 180 | + preload: reader.bool(mapping, "preload", path: path) ?? false, | |
| 181 | + defaults: defaults ?? .init(), locked: locked ?? .init()) | |
| 182 | + } | |
| 183 | + | |
| 184 | + /// `source: org/name` (+ optional `revision:`), or `path: dir` for a model on disk. | |
| 185 | + func modelSource(_ mapping: Node.Mapping, node: Node, path: String) -> ModelReference? { | |
| 186 | + let source = nonEmpty(mapping, "source", path: path) | |
| 187 | + let revision = nonEmpty(mapping, "revision", path: path) | |
| 188 | + let directory = nonEmpty(mapping, "path", path: path) | |
| 189 | + switch (source, directory) { | |
| 190 | + case (let source?, nil): | |
| 191 | + return .huggingFace(id: source, revision: revision ?? ModelReference.defaultRevision) | |
| 192 | + case (nil, let directory?): | |
| 193 | + if revision != nil { | |
| 194 | + reader.report("\(path).revision", mapping["revision"], "only applies to source") | |
| 195 | + } | |
| 196 | + return .local(path: resolve(directory)) | |
| 197 | + case (.some, .some): | |
| 198 | + reader.report(path, node, "give either source or path, not both") | |
| 199 | + case (nil, nil): | |
| 200 | + reader.report("\(path).source", node, "is required (a Hugging Face id, or path:)") | |
| 201 | + } | |
| 202 | + return nil | |
| 203 | + } | |
| 204 | + | |
| 205 | + func modelKind(_ mapping: Node.Mapping, path: String) -> ModelKind? { | |
| 206 | + guard let text = reader.string(mapping, "kind", path: path) else { return nil } | |
| 207 | + guard let kind = ModelKind(rawValue: text) else { | |
| 208 | + let allowed = ModelKind.allCases.map(\.rawValue).joined(separator: ", ") | |
| 209 | + reader.report("\(path).kind", mapping["kind"], "must be one of: \(allowed)") | |
| 210 | + return nil | |
| 211 | + } | |
| 212 | + return kind | |
| 213 | + } | |
| 214 | + | |
| 215 | + // MARK: Values | |
| 216 | + | |
| 217 | + func nonEmpty(_ mapping: Node.Mapping, _ key: String, path: String) -> String? { | |
| 218 | + guard let text = reader.string(mapping, key, path: path) else { return nil } | |
| 219 | + guard !text.trimmingCharacters(in: .whitespaces).isEmpty else { | |
| 220 | + reader.report("\(path).\(key)", mapping[key], "must not be empty") | |
| 221 | + return nil | |
| 222 | + } | |
| 223 | + return text | |
| 224 | + } | |
| 225 | + | |
| 226 | + /// A number accepted by `isValid`; otherwise an issue saying `rule`. | |
| 227 | + func number( | |
| 228 | + _ mapping: Node.Mapping, _ key: String, path: String, rule: String, | |
| 229 | + _ isValid: (Double) -> Bool | |
| 230 | + ) -> Double? { | |
| 231 | + guard let value = reader.double(mapping, key, path: path) else { return nil } | |
| 232 | + guard isValid(value) else { | |
| 233 | + reader.report("\(path).\(key)", mapping[key], rule) | |
| 234 | + return nil | |
| 235 | + } | |
| 236 | + return value | |
| 237 | + } | |
| 238 | + | |
| 239 | + func whole(_ mapping: Node.Mapping, _ key: String, path: String, atLeast minimum: Int) -> Int? { | |
| 240 | + guard let value = reader.int(mapping, key, path: path) else { return nil } | |
| 241 | + guard value >= minimum else { | |
| 242 | + reader.report("\(path).\(key)", mapping[key], "must be \(minimum) or more") | |
| 243 | + return nil | |
| 244 | + } | |
| 245 | + return value | |
| 246 | + } | |
| 247 | + | |
| 248 | + /// `~/x` → home, relative → from the configuration file's folder. | |
| 249 | + func resolve(_ directory: String) -> URL { | |
| 250 | + if directory == "~" || directory.hasPrefix("~/") { | |
| 251 | + return URL(fileURLWithPath: home + directory.dropFirst()) | |
| 252 | + } | |
| 253 | + if directory.hasPrefix("/") { return URL(fileURLWithPath: directory) } | |
| 254 | + return URL(fileURLWithPath: baseDirectory).appendingPathComponent(directory) | |
| 255 | + } | |
| 256 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,256 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Yams | ||
| 3 | + | ||
| 4 | +/// Loads and validates a server configuration file into a ``ServerConfig``. | ||
| 5 | +/// | ||
| 6 | +/// Every problem is collected and thrown at once as a ``ConfigError``: unknown keys, wrong types, | ||
| 7 | +/// missing or out-of-range values, duplicate model ids — each with its line. | ||
| 8 | +/// | ||
| 9 | +/// ```swift | ||
| 10 | +/// let config = try ServerConfigLoader().load(file: "server.yaml") | ||
| 11 | +/// let inline = try ServerConfigLoader().parse("server:\n port: 9000\n") | ||
| 12 | +/// ``` | ||
| 13 | +public struct ServerConfigLoader: Sendable { | ||
| 14 | + /// Directory that `~` stands for in local model paths. | ||
| 15 | + public var homeDirectory: String | ||
| 16 | + | ||
| 17 | + public init(homeDirectory: String = NSHomeDirectory()) { | ||
| 18 | + self.homeDirectory = homeDirectory | ||
| 19 | + } | ||
| 20 | + | ||
| 21 | + /// Reads and validates the file at `path`. Relative model paths start at the file's folder. | ||
| 22 | + public func load(file path: String) throws -> ServerConfig { | ||
| 23 | + guard let text = try? String(contentsOfFile: path, encoding: .utf8) else { | ||
| 24 | + throw ConfigError( | ||
| 25 | + file: path, | ||
| 26 | + issues: [ConfigIssue(keyPath: "", line: nil, message: "cannot read the file")]) | ||
| 27 | + } | ||
| 28 | + let folder = URL(fileURLWithPath: path).deletingLastPathComponent().path | ||
| 29 | + return try parse(text, file: path, baseDirectory: folder) | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + /// Validates YAML `text`. `file` only labels the errors. | ||
| 33 | + public func parse( | ||
| 34 | + _ text: String, file: String? = nil, | ||
| 35 | + baseDirectory: String = FileManager.default.currentDirectoryPath | ||
| 36 | + ) throws -> ServerConfig { | ||
| 37 | + let root: Node? | ||
| 38 | + do { | ||
| 39 | + root = try Yams.compose(yaml: text) | ||
| 40 | + } catch { | ||
| 41 | + let issue = ConfigIssue(keyPath: "", line: nil, message: "not valid YAML: \(error)") | ||
| 42 | + throw ConfigError(file: file, issues: [issue]) | ||
| 43 | + } | ||
| 44 | + // An empty file is the default configuration. | ||
| 45 | + guard let root else { return ServerConfig() } | ||
| 46 | + let reader = ConfigReader() | ||
| 47 | + let context = Context(reader: reader, baseDirectory: baseDirectory, home: homeDirectory) | ||
| 48 | + let config = context.document(root) | ||
| 49 | + guard reader.issues.isEmpty, let config else { | ||
| 50 | + throw ConfigError(file: file, issues: reader.issues) | ||
| 51 | + } | ||
| 52 | + return config | ||
| 53 | + } | ||
| 54 | + | ||
| 55 | + static let topLevelKeys = ["server", "defaults", "locked", "models", "limits"] | ||
| 56 | + static let serverKeys = ["host", "port", "api_key_env", "cors_origin"] | ||
| 57 | + static let generationKeys = [ | ||
| 58 | + "temperature", "top_p", "max_tokens", "thinking", "thinking_budget", | ||
| 59 | + ] | ||
| 60 | + static let modelKeys = [ | ||
| 61 | + "id", "source", "revision", "path", "kind", "preload", "defaults", "locked", | ||
| 62 | + ] | ||
| 63 | + static let limitKeys = ["max_loaded_models", "keep_alive", "max_queue"] | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// One loading pass: the reader collecting issues and where relative paths start. | ||
| 67 | +private struct Context { | ||
| 68 | + let reader: ConfigReader | ||
| 69 | + let baseDirectory: String | ||
| 70 | + let home: String | ||
| 71 | + | ||
| 72 | + func document(_ root: Node) -> ServerConfig? { | ||
| 73 | + guard let document = reader.mapping(root, path: "") else { return nil } | ||
| 74 | + reader.rejectUnknownKeys(document, allowed: ServerConfigLoader.topLevelKeys, path: "") | ||
| 75 | + return ServerConfig( | ||
| 76 | + server: section(document["server"], path: "server", read: server) ?? ServerSection(), | ||
| 77 | + defaults: section(document["defaults"], path: "defaults", read: generation) ?? .init(), | ||
| 78 | + locked: section(document["locked"], path: "locked", read: generation) ?? .init(), | ||
| 79 | + models: models(document["models"]), | ||
| 80 | + limits: section(document["limits"], path: "limits", read: limits) ?? ServerLimits()) | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + /// Reads an optional mapping section, rejecting keys `read` does not know. | ||
| 84 | + func section<T>( | ||
| 85 | + _ node: Node?, path: String, read: (Node.Mapping, String) -> T | ||
| 86 | + ) -> T? { | ||
| 87 | + guard let node, !reader.isNull(node), let mapping = reader.mapping(node, path: path) else { | ||
| 88 | + return nil | ||
| 89 | + } | ||
| 90 | + return read(mapping, path) | ||
| 91 | + } | ||
| 92 | + | ||
| 93 | + func server(_ mapping: Node.Mapping, path: String) -> ServerSection { | ||
| 94 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.serverKeys, path: path) | ||
| 95 | + let port = reader.int(mapping, "port", path: path) | ||
| 96 | + if let port, !(1 ... 65_535).contains(port) { | ||
| 97 | + reader.report("\(path).port", mapping["port"], "must be between 1 and 65535") | ||
| 98 | + } | ||
| 99 | + return ServerSection( | ||
| 100 | + host: nonEmpty(mapping, "host", path: path), port: port, | ||
| 101 | + apiKeyVariable: nonEmpty(mapping, "api_key_env", path: path), | ||
| 102 | + corsOrigin: nonEmpty(mapping, "cors_origin", path: path)) | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + func generation(_ mapping: Node.Mapping, path: String) -> GenerationOverrides { | ||
| 106 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.generationKeys, path: path) | ||
| 107 | + let block = GenerationOverrides( | ||
| 108 | + temperature: number( | ||
| 109 | + mapping, "temperature", path: path, rule: "must be between 0 and 2" | ||
| 110 | + ) { (0 ... 2).contains($0) }, | ||
| 111 | + topP: number( | ||
| 112 | + mapping, "top_p", path: path, rule: "must be above 0 and at most 1" | ||
| 113 | + ) { $0 > 0 && $0 <= 1 }, | ||
| 114 | + maxTokens: whole(mapping, "max_tokens", path: path, atLeast: 1), | ||
| 115 | + thinking: reader.bool(mapping, "thinking", path: path), | ||
| 116 | + thinkingBudget: whole(mapping, "thinking_budget", path: path, atLeast: 0)) | ||
| 117 | + if let budget = block.thinkingBudget, let maxTokens = block.maxTokens, budget >= maxTokens { | ||
| 118 | + reader.report( | ||
| 119 | + "\(path).thinking_budget", mapping["thinking_budget"], | ||
| 120 | + "must be smaller than max_tokens (\(maxTokens))") | ||
| 121 | + } | ||
| 122 | + return block | ||
| 123 | + } | ||
| 124 | + | ||
| 125 | + func limits(_ mapping: Node.Mapping, path: String) -> ServerLimits { | ||
| 126 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.limitKeys, path: path) | ||
| 127 | + var limits = ServerLimits() | ||
| 128 | + if let value = whole(mapping, "max_loaded_models", path: path, atLeast: 1) { | ||
| 129 | + limits.maxLoadedModels = value | ||
| 130 | + } | ||
| 131 | + if let value = whole(mapping, "max_queue", path: path, atLeast: 1) { | ||
| 132 | + limits.maxQueue = value | ||
| 133 | + } | ||
| 134 | + if let text = reader.string(mapping, "keep_alive", path: path) { | ||
| 135 | + if let duration = Quantities.duration(text) { | ||
| 136 | + limits.keepAlive = duration | ||
| 137 | + } else { | ||
| 138 | + reader.report( | ||
| 139 | + "\(path).keep_alive", mapping["keep_alive"], | ||
| 140 | + "must be a duration such as 30s, 10m or 1h") | ||
| 141 | + } | ||
| 142 | + } | ||
| 143 | + return limits | ||
| 144 | + } | ||
| 145 | + | ||
| 146 | + // MARK: Models | ||
| 147 | + | ||
| 148 | + func models(_ node: Node?) -> [ModelEntry] { | ||
| 149 | + guard let node, !reader.isNull(node) else { return [] } | ||
| 150 | + guard case .sequence(let sequence) = node else { | ||
| 151 | + reader.report("models", node, "must be a list (lines starting with -)") | ||
| 152 | + return [] | ||
| 153 | + } | ||
| 154 | + var seen: Set<String> = [] | ||
| 155 | + return sequence.enumerated().compactMap { index, item in | ||
| 156 | + let path = "models[\(index)]" | ||
| 157 | + guard let mapping = reader.mapping(item, path: path), | ||
| 158 | + let entry = model(mapping, node: item, path: path) | ||
| 159 | + else { return nil } | ||
| 160 | + if !seen.insert(entry.id).inserted { | ||
| 161 | + reader.report("\(path).id", mapping["id"], "duplicate id \(entry.id)") | ||
| 162 | + } | ||
| 163 | + return entry | ||
| 164 | + } | ||
| 165 | + } | ||
| 166 | + | ||
| 167 | + func model(_ mapping: Node.Mapping, node: Node, path: String) -> ModelEntry? { | ||
| 168 | + reader.rejectUnknownKeys(mapping, allowed: ServerConfigLoader.modelKeys, path: path) | ||
| 169 | + let id = nonEmpty(mapping, "id", path: path) | ||
| 170 | + if id == nil && mapping["id"] == nil { | ||
| 171 | + reader.report("\(path).id", node, "is required (the name clients send as \"model\")") | ||
| 172 | + } | ||
| 173 | + let source = modelSource(mapping, node: node, path: path) | ||
| 174 | + let kind = modelKind(mapping, path: path) | ||
| 175 | + let defaults = section(mapping["defaults"], path: "\(path).defaults", read: generation) | ||
| 176 | + let locked = section(mapping["locked"], path: "\(path).locked", read: generation) | ||
| 177 | + guard let id, let source else { return nil } | ||
| 178 | + return ModelEntry( | ||
| 179 | + id: id, source: source, kind: kind ?? .chat, | ||
| 180 | + preload: reader.bool(mapping, "preload", path: path) ?? false, | ||
| 181 | + defaults: defaults ?? .init(), locked: locked ?? .init()) | ||
| 182 | + } | ||
| 183 | + | ||
| 184 | + /// `source: org/name` (+ optional `revision:`), or `path: dir` for a model on disk. | ||
| 185 | + func modelSource(_ mapping: Node.Mapping, node: Node, path: String) -> ModelReference? { | ||
| 186 | + let source = nonEmpty(mapping, "source", path: path) | ||
| 187 | + let revision = nonEmpty(mapping, "revision", path: path) | ||
| 188 | + let directory = nonEmpty(mapping, "path", path: path) | ||
| 189 | + switch (source, directory) { | ||
| 190 | + case (let source?, nil): | ||
| 191 | + return .huggingFace(id: source, revision: revision ?? ModelReference.defaultRevision) | ||
| 192 | + case (nil, let directory?): | ||
| 193 | + if revision != nil { | ||
| 194 | + reader.report("\(path).revision", mapping["revision"], "only applies to source") | ||
| 195 | + } | ||
| 196 | + return .local(path: resolve(directory)) | ||
| 197 | + case (.some, .some): | ||
| 198 | + reader.report(path, node, "give either source or path, not both") | ||
| 199 | + case (nil, nil): | ||
| 200 | + reader.report("\(path).source", node, "is required (a Hugging Face id, or path:)") | ||
| 201 | + } | ||
| 202 | + return nil | ||
| 203 | + } | ||
| 204 | + | ||
| 205 | + func modelKind(_ mapping: Node.Mapping, path: String) -> ModelKind? { | ||
| 206 | + guard let text = reader.string(mapping, "kind", path: path) else { return nil } | ||
| 207 | + guard let kind = ModelKind(rawValue: text) else { | ||
| 208 | + let allowed = ModelKind.allCases.map(\.rawValue).joined(separator: ", ") | ||
| 209 | + reader.report("\(path).kind", mapping["kind"], "must be one of: \(allowed)") | ||
| 210 | + return nil | ||
| 211 | + } | ||
| 212 | + return kind | ||
| 213 | + } | ||
| 214 | + | ||
| 215 | + // MARK: Values | ||
| 216 | + | ||
| 217 | + func nonEmpty(_ mapping: Node.Mapping, _ key: String, path: String) -> String? { | ||
| 218 | + guard let text = reader.string(mapping, key, path: path) else { return nil } | ||
| 219 | + guard !text.trimmingCharacters(in: .whitespaces).isEmpty else { | ||
| 220 | + reader.report("\(path).\(key)", mapping[key], "must not be empty") | ||
| 221 | + return nil | ||
| 222 | + } | ||
| 223 | + return text | ||
| 224 | + } | ||
| 225 | + | ||
| 226 | + /// A number accepted by `isValid`; otherwise an issue saying `rule`. | ||
| 227 | + func number( | ||
| 228 | + _ mapping: Node.Mapping, _ key: String, path: String, rule: String, | ||
| 229 | + _ isValid: (Double) -> Bool | ||
| 230 | + ) -> Double? { | ||
| 231 | + guard let value = reader.double(mapping, key, path: path) else { return nil } | ||
| 232 | + guard isValid(value) else { | ||
| 233 | + reader.report("\(path).\(key)", mapping[key], rule) | ||
| 234 | + return nil | ||
| 235 | + } | ||
| 236 | + return value | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + func whole(_ mapping: Node.Mapping, _ key: String, path: String, atLeast minimum: Int) -> Int? { | ||
| 240 | + guard let value = reader.int(mapping, key, path: path) else { return nil } | ||
| 241 | + guard value >= minimum else { | ||
| 242 | + reader.report("\(path).\(key)", mapping[key], "must be \(minimum) or more") | ||
| 243 | + return nil | ||
| 244 | + } | ||
| 245 | + return value | ||
| 246 | + } | ||
| 247 | + | ||
| 248 | + /// `~/x` → home, relative → from the configuration file's folder. | ||
| 249 | + func resolve(_ directory: String) -> URL { | ||
| 250 | + if directory == "~" || directory.hasPrefix("~/") { | ||
| 251 | + return URL(fileURLWithPath: home + directory.dropFirst()) | ||
| 252 | + } | ||
| 253 | + if directory.hasPrefix("/") { return URL(fileURLWithPath: directory) } | ||
| 254 | + return URL(fileURLWithPath: baseDirectory).appendingPathComponent(directory) | ||
| 255 | + } | ||
| 256 | +} | ||
added
Sources/RazorbillCore/Models/ModelCatalog.swift +111 -0 | new file mode 100644 | ||
| @@ -0,0 +1,111 @@ | ||
| 1 | +import Foundation | |
| 2 | + | |
| 3 | +/// The model a request asked for, with the settings that apply to it. | |
| 4 | +public struct ResolvedModel: Sendable, Equatable { | |
| 5 | + /// The name the client sent. | |
| 6 | + public var name: String | |
| 7 | + public var source: ModelReference | |
| 8 | + public var kind: ModelKind | |
| 9 | + /// Declared in the configuration (`false`: a Hugging Face id accepted as is). | |
| 10 | + public var isDeclared: Bool | |
| 11 | + /// `defaults` blocks, server-wide first, then the model's. | |
| 12 | + public var defaults: [GenerationOverrides] | |
| 13 | + /// `locked` blocks, server-wide first, then the model's. | |
| 14 | + public var locked: [GenerationOverrides] | |
| 15 | + | |
| 16 | + /// The settings of a request that sent `client`. | |
| 17 | + public func generation(client: GenerationOverrides = .init()) -> GenerationSettings { | |
| 18 | + GenerationOverrides.resolve(defaults: defaults, client: client, locked: locked) | |
| 19 | + } | |
| 20 | +} | |
| 21 | + | |
| 22 | +/// Why a `"model"` value cannot be served. | |
| 23 | +public enum ModelResolutionError: Error, Sendable, Equatable, CustomStringConvertible { | |
| 24 | + /// Neither a declared id nor a Hugging Face repository id. | |
| 25 | + case unknown(String) | |
| 26 | + /// The repository is in the cache but not in MLX format (GGUF only, for instance). | |
| 27 | + case notMLX(String) | |
| 28 | + | |
| 29 | + public var description: String { | |
| 30 | + switch self { | |
| 31 | + case .unknown(let name): | |
| 32 | + "the model '\(name)' does not exist (not declared, and not a Hugging Face id org/name)" | |
| 33 | + case .notMLX(let id): | |
| 34 | + "the model '\(id)' is not in MLX format (no .safetensors weights)" | |
| 35 | + } | |
| 36 | + } | |
| 37 | +} | |
| 38 | + | |
| 39 | +/// Turns the `"model"` of a request into a model to load. | |
| 40 | +/// | |
| 41 | +/// Declared ids (`models:` in the configuration) come first. Any other value is accepted when it | |
| 42 | +/// is a Hugging Face repository id, `org/name` or `org/name@revision` (decided in #33), unless the | |
| 43 | +/// cache already shows it is not an MLX model. A repository not yet downloaded is checked when it | |
| 44 | +/// is downloaded. | |
| 45 | +/// | |
| 46 | +/// ```swift | |
| 47 | +/// let catalog = ModelCatalog(config: config, store: ModelStore()) | |
| 48 | +/// let model = try catalog.resolve("mlx-community/Qwen3-0.6B-4bit") | |
| 49 | +/// let settings = model.generation(client: GenerationOverrides(temperature: 0)) | |
| 50 | +/// ``` | |
| 51 | +public struct ModelCatalog: Sendable { | |
| 52 | + public let config: ServerConfig | |
| 53 | + public let store: ModelStore | |
| 54 | + | |
| 55 | + public init(config: ServerConfig, store: ModelStore) { | |
| 56 | + self.config = config | |
| 57 | + self.store = store | |
| 58 | + } | |
| 59 | + | |
| 60 | + public func resolve(_ name: String) throws -> ResolvedModel { | |
| 61 | + if let entry = config.models.first(where: { $0.id == name }) { | |
| 62 | + return ResolvedModel( | |
| 63 | + name: name, source: entry.source, kind: entry.kind, isDeclared: true, | |
| 64 | + defaults: [config.defaults, entry.defaults], locked: [config.locked, entry.locked]) | |
| 65 | + } | |
| 66 | + guard let reference = Self.huggingFaceReference(name) else { | |
| 67 | + throw ModelResolutionError.unknown(name) | |
| 68 | + } | |
| 69 | + if case .huggingFace(let id, _) = reference, isKnownNotMLX(id) { | |
| 70 | + throw ModelResolutionError.notMLX(id) | |
| 71 | + } | |
| 72 | + return ResolvedModel( | |
| 73 | + name: name, source: reference, kind: .chat, isDeclared: false, | |
| 74 | + defaults: [config.defaults], locked: [config.locked]) | |
| 75 | + } | |
| 76 | + | |
| 77 | + /// `org/name` or `org/name@revision`, with Hugging Face's characters (letters, digits, `-`, | |
| 78 | + /// `_`, `.`); `nil` for anything else. | |
| 79 | + static func huggingFaceReference(_ name: String) -> ModelReference? { | |
| 80 | + let parts = name.split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false) | |
| 81 | + let id = String(parts[0]) | |
| 82 | + let revision = parts.count == 2 ? String(parts[1]) : ModelReference.defaultRevision | |
| 83 | + let segments = id.split(separator: "/", omittingEmptySubsequences: false) | |
| 84 | + guard segments.count == 2, segments.allSatisfy(isRepositoryName), !revision.isEmpty else { | |
| 85 | + return nil | |
| 86 | + } | |
| 87 | + return .huggingFace(id: id, revision: revision) | |
| 88 | + } | |
| 89 | + | |
| 90 | + private static func isRepositoryName(_ segment: Substring) -> Bool { | |
| 91 | + guard let first = segment.first, first.isLetter || first.isNumber else { return false } | |
| 92 | + return segment.allSatisfy { character in | |
| 93 | + character.isASCII | |
| 94 | + && (character.isLetter || character.isNumber || "-_.".contains(character)) | |
| 95 | + } | |
| 96 | + } | |
| 97 | + | |
| 98 | + /// The cache holds GGUF weights for `id` and no `.safetensors` at all. | |
| 99 | + private func isKnownNotMLX(_ id: String) -> Bool { | |
| 100 | + let snapshots = store.directory(for: id).appendingPathComponent("snapshots") | |
| 101 | + guard let walker = FileManager.default.enumerator(atPath: snapshots.path) else { | |
| 102 | + return false | |
| 103 | + } | |
| 104 | + var hasGGUF = false | |
| 105 | + while let file = walker.nextObject() as? String { | |
| 106 | + if file.hasSuffix(".safetensors") { return false } | |
| 107 | + if file.hasSuffix(".gguf") { hasGGUF = true } | |
| 108 | + } | |
| 109 | + return hasGGUF | |
| 110 | + } | |
| 111 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,111 @@ | |||
| 1 | +import Foundation | ||
| 2 | + | ||
| 3 | +/// The model a request asked for, with the settings that apply to it. | ||
| 4 | +public struct ResolvedModel: Sendable, Equatable { | ||
| 5 | + /// The name the client sent. | ||
| 6 | + public var name: String | ||
| 7 | + public var source: ModelReference | ||
| 8 | + public var kind: ModelKind | ||
| 9 | + /// Declared in the configuration (`false`: a Hugging Face id accepted as is). | ||
| 10 | + public var isDeclared: Bool | ||
| 11 | + /// `defaults` blocks, server-wide first, then the model's. | ||
| 12 | + public var defaults: [GenerationOverrides] | ||
| 13 | + /// `locked` blocks, server-wide first, then the model's. | ||
| 14 | + public var locked: [GenerationOverrides] | ||
| 15 | + | ||
| 16 | + /// The settings of a request that sent `client`. | ||
| 17 | + public func generation(client: GenerationOverrides = .init()) -> GenerationSettings { | ||
| 18 | + GenerationOverrides.resolve(defaults: defaults, client: client, locked: locked) | ||
| 19 | + } | ||
| 20 | +} | ||
| 21 | + | ||
| 22 | +/// Why a `"model"` value cannot be served. | ||
| 23 | +public enum ModelResolutionError: Error, Sendable, Equatable, CustomStringConvertible { | ||
| 24 | + /// Neither a declared id nor a Hugging Face repository id. | ||
| 25 | + case unknown(String) | ||
| 26 | + /// The repository is in the cache but not in MLX format (GGUF only, for instance). | ||
| 27 | + case notMLX(String) | ||
| 28 | + | ||
| 29 | + public var description: String { | ||
| 30 | + switch self { | ||
| 31 | + case .unknown(let name): | ||
| 32 | + "the model '\(name)' does not exist (not declared, and not a Hugging Face id org/name)" | ||
| 33 | + case .notMLX(let id): | ||
| 34 | + "the model '\(id)' is not in MLX format (no .safetensors weights)" | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// Turns the `"model"` of a request into a model to load. | ||
| 40 | +/// | ||
| 41 | +/// Declared ids (`models:` in the configuration) come first. Any other value is accepted when it | ||
| 42 | +/// is a Hugging Face repository id, `org/name` or `org/name@revision` (decided in #33), unless the | ||
| 43 | +/// cache already shows it is not an MLX model. A repository not yet downloaded is checked when it | ||
| 44 | +/// is downloaded. | ||
| 45 | +/// | ||
| 46 | +/// ```swift | ||
| 47 | +/// let catalog = ModelCatalog(config: config, store: ModelStore()) | ||
| 48 | +/// let model = try catalog.resolve("mlx-community/Qwen3-0.6B-4bit") | ||
| 49 | +/// let settings = model.generation(client: GenerationOverrides(temperature: 0)) | ||
| 50 | +/// ``` | ||
| 51 | +public struct ModelCatalog: Sendable { | ||
| 52 | + public let config: ServerConfig | ||
| 53 | + public let store: ModelStore | ||
| 54 | + | ||
| 55 | + public init(config: ServerConfig, store: ModelStore) { | ||
| 56 | + self.config = config | ||
| 57 | + self.store = store | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + public func resolve(_ name: String) throws -> ResolvedModel { | ||
| 61 | + if let entry = config.models.first(where: { $0.id == name }) { | ||
| 62 | + return ResolvedModel( | ||
| 63 | + name: name, source: entry.source, kind: entry.kind, isDeclared: true, | ||
| 64 | + defaults: [config.defaults, entry.defaults], locked: [config.locked, entry.locked]) | ||
| 65 | + } | ||
| 66 | + guard let reference = Self.huggingFaceReference(name) else { | ||
| 67 | + throw ModelResolutionError.unknown(name) | ||
| 68 | + } | ||
| 69 | + if case .huggingFace(let id, _) = reference, isKnownNotMLX(id) { | ||
| 70 | + throw ModelResolutionError.notMLX(id) | ||
| 71 | + } | ||
| 72 | + return ResolvedModel( | ||
| 73 | + name: name, source: reference, kind: .chat, isDeclared: false, | ||
| 74 | + defaults: [config.defaults], locked: [config.locked]) | ||
| 75 | + } | ||
| 76 | + | ||
| 77 | + /// `org/name` or `org/name@revision`, with Hugging Face's characters (letters, digits, `-`, | ||
| 78 | + /// `_`, `.`); `nil` for anything else. | ||
| 79 | + static func huggingFaceReference(_ name: String) -> ModelReference? { | ||
| 80 | + let parts = name.split(separator: "@", maxSplits: 1, omittingEmptySubsequences: false) | ||
| 81 | + let id = String(parts[0]) | ||
| 82 | + let revision = parts.count == 2 ? String(parts[1]) : ModelReference.defaultRevision | ||
| 83 | + let segments = id.split(separator: "/", omittingEmptySubsequences: false) | ||
| 84 | + guard segments.count == 2, segments.allSatisfy(isRepositoryName), !revision.isEmpty else { | ||
| 85 | + return nil | ||
| 86 | + } | ||
| 87 | + return .huggingFace(id: id, revision: revision) | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + private static func isRepositoryName(_ segment: Substring) -> Bool { | ||
| 91 | + guard let first = segment.first, first.isLetter || first.isNumber else { return false } | ||
| 92 | + return segment.allSatisfy { character in | ||
| 93 | + character.isASCII | ||
| 94 | + && (character.isLetter || character.isNumber || "-_.".contains(character)) | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + /// The cache holds GGUF weights for `id` and no `.safetensors` at all. | ||
| 99 | + private func isKnownNotMLX(_ id: String) -> Bool { | ||
| 100 | + let snapshots = store.directory(for: id).appendingPathComponent("snapshots") | ||
| 101 | + guard let walker = FileManager.default.enumerator(atPath: snapshots.path) else { | ||
| 102 | + return false | ||
| 103 | + } | ||
| 104 | + var hasGGUF = false | ||
| 105 | + while let file = walker.nextObject() as? String { | ||
| 106 | + if file.hasSuffix(".safetensors") { return false } | ||
| 107 | + if file.hasSuffix(".gguf") { hasGGUF = true } | ||
| 108 | + } | ||
| 109 | + return hasGGUF | ||
| 110 | + } | ||
| 111 | +} | ||
modified
Sources/RazorbillServer/ServerSettings.swift +6 -1 | @@ -1,3 +1,5 @@ | ||
| 1 | +import RazorbillCore | |
| 2 | + | |
| 1 | 3 | /// How `rzb serve` listens and who it accepts. |
| 2 | 4 | /// |
| 3 | 5 | /// ```swift |
| @@ -15,15 +17,18 @@ public struct ServerSettings: Sendable, Equatable { | ||
| 15 | 17 | public var apiKey: String? |
| 16 | 18 | /// When set, browsers may call the API from this origin (`*` for any origin). |
| 17 | 19 | public var corsOrigin: String? |
| 20 | + /// The configuration file's content: models, generation defaults and locks, limits. | |
| 21 | + public var config: ServerConfig | |
| 18 | 22 | |
| 19 | 23 | public init( |
| 20 | 24 | host: String = "127.0.0.1", port: Int = 8080, apiKey: String? = nil, |
| 21 | - corsOrigin: String? = nil | |
| 25 | + corsOrigin: String? = nil, config: ServerConfig = ServerConfig() | |
| 22 | 26 | ) { |
| 23 | 27 | self.host = host |
| 24 | 28 | self.port = port |
| 25 | 29 | self.apiKey = apiKey |
| 26 | 30 | self.corsOrigin = corsOrigin |
| 31 | + self.config = config | |
| 27 | 32 | } |
| 28 | 33 | |
| 29 | 34 | /// The address only accepts connections from this machine. |
| @@ -1,3 +1,5 @@ | |||
| 1 | +import RazorbillCore | ||
| 2 | + | ||
| 1 | /// How `rzb serve` listens and who it accepts. | 3 | /// How `rzb serve` listens and who it accepts. |
| 2 | /// | 4 | /// |
| 3 | /// ```swift | 5 | /// ```swift |
| @@ -15,15 +17,18 @@ public struct ServerSettings: Sendable, Equatable { | |||
| 15 | public var apiKey: String? | 17 | public var apiKey: String? |
| 16 | /// When set, browsers may call the API from this origin (`*` for any origin). | 18 | /// When set, browsers may call the API from this origin (`*` for any origin). |
| 17 | public var corsOrigin: String? | 19 | public var corsOrigin: String? |
| 20 | + /// The configuration file's content: models, generation defaults and locks, limits. | ||
| 21 | + public var config: ServerConfig | ||
| 18 | 22 | ||
| 19 | public init( | 23 | public init( |
| 20 | host: String = "127.0.0.1", port: Int = 8080, apiKey: String? = nil, | 24 | host: String = "127.0.0.1", port: Int = 8080, apiKey: String? = nil, |
| 21 | - corsOrigin: String? = nil | 25 | + corsOrigin: String? = nil, config: ServerConfig = ServerConfig() |
| 22 | ) { | 26 | ) { |
| 23 | self.host = host | 27 | self.host = host |
| 24 | self.port = port | 28 | self.port = port |
| 25 | self.apiKey = apiKey | 29 | self.apiKey = apiKey |
| 26 | self.corsOrigin = corsOrigin | 30 | self.corsOrigin = corsOrigin |
| 31 | + self.config = config | ||
| 27 | } | 32 | } |
| 28 | 33 | ||
| 29 | /// The address only accepts connections from this machine. | 34 | /// The address only accepts connections from this machine. |
added
Tests/RazorbillCLITests/ConfigCommandTests.swift +62 -0 | new file mode 100644 | ||
| @@ -0,0 +1,62 @@ | ||
| 1 | +import Foundation | |
| 2 | +import RazorbillCore | |
| 3 | +import RazorbillServer | |
| 4 | +import Testing | |
| 5 | + | |
| 6 | +@testable import RazorbillCLI | |
| 7 | + | |
| 8 | +@Suite struct ConfigCommandTests { | |
| 9 | + func write(_ yaml: String, in world: World) throws -> String { | |
| 10 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("server.yaml").path | |
| 11 | + try yaml.write(toFile: path, atomically: true, encoding: .utf8) | |
| 12 | + return path | |
| 13 | + } | |
| 14 | + | |
| 15 | + @Test func validFileIsSummarised() async throws { | |
| 16 | + let world = try World() | |
| 17 | + let path = try write("models:\n - id: qwen3\n source: org/q\n", in: world) | |
| 18 | + let result = await world.rzb("config", "validate", path) | |
| 19 | + #expect(result.exitCode == 0) | |
| 20 | + #expect( | |
| 21 | + result.stdout | |
| 22 | + == "\(path) is valid: 1 models (qwen3), any Hugging Face MLX id accepted\n") | |
| 23 | + } | |
| 24 | + | |
| 25 | + @Test func invalidFileListsProblemsAndExitsWith2() async throws { | |
| 26 | + let world = try World() | |
| 27 | + let path = try write("server:\n port: 0\n", in: world) | |
| 28 | + let result = await world.rzb("config", "validate", path) | |
| 29 | + #expect(result.exitCode == 2) | |
| 30 | + #expect(result.stderr.contains("line 2: server.port: must be between 1 and 65535")) | |
| 31 | + } | |
| 32 | +} | |
| 33 | + | |
| 34 | +@Suite struct ServeWithConfigTests { | |
| 35 | + @Test func fileSettingsApplyAndOptionsWin() async throws { | |
| 36 | + var world = try World() | |
| 37 | + world.variables = ["TEAM_KEY": "k"] | |
| 38 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | |
| 39 | + try """ | |
| 40 | + server: { host: 0.0.0.0, port: 9000, api_key_env: TEAM_KEY, cors_origin: "http://a" } | |
| 41 | + models: [{ id: q, source: org/q }] | |
| 42 | + """.write(toFile: path, atomically: true, encoding: .utf8) | |
| 43 | + | |
| 44 | + let result = await world.rzb("serve", "--config", path, "--port", "9100") | |
| 45 | + let started = try #require(world.servers.started.first) | |
| 46 | + #expect(started.host == "0.0.0.0" && started.port == 9100) | |
| 47 | + #expect(started.apiKey == "k" && started.corsOrigin == "http://a") | |
| 48 | + #expect(started.config.models.map(\.id) == ["q"]) | |
| 49 | + #expect(result.stderr.contains("config: \(path) (1 declared models)")) | |
| 50 | + #expect(result.stderr.contains("(API key from $TEAM_KEY)")) | |
| 51 | + } | |
| 52 | + | |
| 53 | + @Test func invalidConfigDoesNotStart() async throws { | |
| 54 | + let world = try World() | |
| 55 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | |
| 56 | + try "limits: { keep_alive: never }\n".write(toFile: path, atomically: true, encoding: .utf8) | |
| 57 | + let result = await world.rzb("serve", "--config", path) | |
| 58 | + #expect(result.exitCode == 2) | |
| 59 | + #expect(world.servers.started.isEmpty) | |
| 60 | + #expect(result.stderr.contains("limits.keep_alive")) | |
| 61 | + } | |
| 62 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,62 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import RazorbillCore | ||
| 3 | +import RazorbillServer | ||
| 4 | +import Testing | ||
| 5 | + | ||
| 6 | +@testable import RazorbillCLI | ||
| 7 | + | ||
| 8 | +@Suite struct ConfigCommandTests { | ||
| 9 | + func write(_ yaml: String, in world: World) throws -> String { | ||
| 10 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("server.yaml").path | ||
| 11 | + try yaml.write(toFile: path, atomically: true, encoding: .utf8) | ||
| 12 | + return path | ||
| 13 | + } | ||
| 14 | + | ||
| 15 | + @Test func validFileIsSummarised() async throws { | ||
| 16 | + let world = try World() | ||
| 17 | + let path = try write("models:\n - id: qwen3\n source: org/q\n", in: world) | ||
| 18 | + let result = await world.rzb("config", "validate", path) | ||
| 19 | + #expect(result.exitCode == 0) | ||
| 20 | + #expect( | ||
| 21 | + result.stdout | ||
| 22 | + == "\(path) is valid: 1 models (qwen3), any Hugging Face MLX id accepted\n") | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + @Test func invalidFileListsProblemsAndExitsWith2() async throws { | ||
| 26 | + let world = try World() | ||
| 27 | + let path = try write("server:\n port: 0\n", in: world) | ||
| 28 | + let result = await world.rzb("config", "validate", path) | ||
| 29 | + #expect(result.exitCode == 2) | ||
| 30 | + #expect(result.stderr.contains("line 2: server.port: must be between 1 and 65535")) | ||
| 31 | + } | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +@Suite struct ServeWithConfigTests { | ||
| 35 | + @Test func fileSettingsApplyAndOptionsWin() async throws { | ||
| 36 | + var world = try World() | ||
| 37 | + world.variables = ["TEAM_KEY": "k"] | ||
| 38 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | ||
| 39 | + try """ | ||
| 40 | + server: { host: 0.0.0.0, port: 9000, api_key_env: TEAM_KEY, cors_origin: "http://a" } | ||
| 41 | + models: [{ id: q, source: org/q }] | ||
| 42 | + """.write(toFile: path, atomically: true, encoding: .utf8) | ||
| 43 | + | ||
| 44 | + let result = await world.rzb("serve", "--config", path, "--port", "9100") | ||
| 45 | + let started = try #require(world.servers.started.first) | ||
| 46 | + #expect(started.host == "0.0.0.0" && started.port == 9100) | ||
| 47 | + #expect(started.apiKey == "k" && started.corsOrigin == "http://a") | ||
| 48 | + #expect(started.config.models.map(\.id) == ["q"]) | ||
| 49 | + #expect(result.stderr.contains("config: \(path) (1 declared models)")) | ||
| 50 | + #expect(result.stderr.contains("(API key from $TEAM_KEY)")) | ||
| 51 | + } | ||
| 52 | + | ||
| 53 | + @Test func invalidConfigDoesNotStart() async throws { | ||
| 54 | + let world = try World() | ||
| 55 | + let path = URL(fileURLWithPath: world.directory).appendingPathComponent("s.yaml").path | ||
| 56 | + try "limits: { keep_alive: never }\n".write(toFile: path, atomically: true, encoding: .utf8) | ||
| 57 | + let result = await world.rzb("serve", "--config", path) | ||
| 58 | + #expect(result.exitCode == 2) | ||
| 59 | + #expect(world.servers.started.isEmpty) | ||
| 60 | + #expect(result.stderr.contains("limits.keep_alive")) | ||
| 61 | + } | ||
| 62 | +} | ||
added
Tests/RazorbillCoreTests/ServerConfigLoaderTests.swift +237 -0 | new file mode 100644 | ||
| @@ -0,0 +1,237 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Testing | |
| 3 | + | |
| 4 | +@testable import RazorbillCore | |
| 5 | + | |
| 6 | +@Suite struct ServerConfigLoaderTests { | |
| 7 | + let loader = ServerConfigLoader(homeDirectory: "/home/me") | |
| 8 | + | |
| 9 | + func issues(_ yaml: String) -> [String] { | |
| 10 | + do { | |
| 11 | + _ = try loader.parse(yaml, baseDirectory: "/etc/rzb") | |
| 12 | + return [] | |
| 13 | + } catch let error as ConfigError { | |
| 14 | + return error.issues.map(\.description) | |
| 15 | + } catch { | |
| 16 | + return ["unexpected \(error)"] | |
| 17 | + } | |
| 18 | + } | |
| 19 | + | |
| 20 | + @Test func emptyFileIsTheDefaultConfiguration() throws { | |
| 21 | + #expect(try loader.parse("") == ServerConfig()) | |
| 22 | + #expect(try loader.parse("# only a comment\n") == ServerConfig()) | |
| 23 | + } | |
| 24 | + | |
| 25 | + @Test func readsEverySection() throws { | |
| 26 | + let config = try loader.parse( | |
| 27 | + """ | |
| 28 | + server: { host: 0.0.0.0, port: 9000, api_key_env: MY_KEY, cors_origin: "*" } | |
| 29 | + defaults: { temperature: 0.2, top_p: 0.9, max_tokens: 100, thinking: true, thinking_budget: 10 } | |
| 30 | + locked: { max_tokens: 500 } | |
| 31 | + models: | |
| 32 | + - id: qwen3 | |
| 33 | + source: mlx-community/Qwen3-4B-4bit | |
| 34 | + revision: v1 | |
| 35 | + kind: chat | |
| 36 | + preload: true | |
| 37 | + defaults: { temperature: 0.7 } | |
| 38 | + locked: { thinking: false } | |
| 39 | + - id: embed | |
| 40 | + path: ~/models/embed | |
| 41 | + kind: embedding | |
| 42 | + - id: rel | |
| 43 | + path: models/rel | |
| 44 | + limits: { max_loaded_models: 2, keep_alive: 30s, max_queue: 4 } | |
| 45 | + """, baseDirectory: "/etc/rzb") | |
| 46 | + #expect( | |
| 47 | + config.server | |
| 48 | + == ServerSection( | |
| 49 | + host: "0.0.0.0", port: 9000, apiKeyVariable: "MY_KEY", corsOrigin: "*")) | |
| 50 | + #expect( | |
| 51 | + config.defaults | |
| 52 | + == GenerationOverrides( | |
| 53 | + temperature: 0.2, topP: 0.9, maxTokens: 100, thinking: true, thinkingBudget: 10) | |
| 54 | + ) | |
| 55 | + #expect(config.locked == GenerationOverrides(maxTokens: 500)) | |
| 56 | + #expect( | |
| 57 | + config.models[0] | |
| 58 | + == ModelEntry( | |
| 59 | + id: "qwen3", | |
| 60 | + source: .huggingFace(id: "mlx-community/Qwen3-4B-4bit", revision: "v1"), | |
| 61 | + kind: .chat, preload: true, defaults: GenerationOverrides(temperature: 0.7), | |
| 62 | + locked: GenerationOverrides(thinking: false))) | |
| 63 | + #expect( | |
| 64 | + config.models[1].source == .local(path: URL(fileURLWithPath: "/home/me/models/embed"))) | |
| 65 | + #expect(config.models[1].kind == .embedding) | |
| 66 | + #expect( | |
| 67 | + config.models[2].source == .local(path: URL(fileURLWithPath: "/etc/rzb/models/rel"))) | |
| 68 | + #expect( | |
| 69 | + config.limits == ServerLimits(maxLoadedModels: 2, keepAlive: .seconds(30), maxQueue: 4)) | |
| 70 | + } | |
| 71 | + | |
| 72 | + @Test func everyProblemIsReportedWithItsLine() { | |
| 73 | + let found = issues( | |
| 74 | + """ | |
| 75 | + server: | |
| 76 | + port: 70000 | |
| 77 | + hots: x | |
| 78 | + defaults: | |
| 79 | + temperature: 3 | |
| 80 | + top_p: 0 | |
| 81 | + max_tokens: 10 | |
| 82 | + thinking_budget: 10 | |
| 83 | + models: | |
| 84 | + - source: org/a | |
| 85 | + - id: a | |
| 86 | + source: org/a | |
| 87 | + path: /x | |
| 88 | + - id: b | |
| 89 | + kind: vision | |
| 90 | + - id: c | |
| 91 | + source: org/c | |
| 92 | + - id: c | |
| 93 | + source: org/c | |
| 94 | + limits: | |
| 95 | + keep_alive: soon | |
| 96 | + max_queue: 0 | |
| 97 | + """) | |
| 98 | + #expect( | |
| 99 | + found == [ | |
| 100 | + "line 3: server.hots: unknown key (expected one of: host, port, api_key_env, cors_origin)", | |
| 101 | + "line 2: server.port: must be between 1 and 65535", | |
| 102 | + "line 5: defaults.temperature: must be between 0 and 2", | |
| 103 | + "line 6: defaults.top_p: must be above 0 and at most 1", | |
| 104 | + "line 8: defaults.thinking_budget: must be smaller than max_tokens (10)", | |
| 105 | + "line 10: models[0].id: is required (the name clients send as \"model\")", | |
| 106 | + "line 11: models[1]: give either source or path, not both", | |
| 107 | + "line 14: models[2].source: is required (a Hugging Face id, or path:)", | |
| 108 | + "line 15: models[2].kind: must be one of: chat, embedding", | |
| 109 | + "line 18: models[4].id: duplicate id c", | |
| 110 | + "line 22: limits.max_queue: must be 1 or more", | |
| 111 | + "line 21: limits.keep_alive: must be a duration such as 30s, 10m or 1h", | |
| 112 | + ]) | |
| 113 | + } | |
| 114 | + | |
| 115 | + @Test func wrongShapesAreReported() { | |
| 116 | + #expect( | |
| 117 | + issues("models: qwen3\n") == ["line 1: models: must be a list (lines starting with -)"]) | |
| 118 | + #expect(issues("- a\n") == ["line 1: must be a mapping (key: value lines)"]) | |
| 119 | + #expect(issues("server: [1]\n") == ["line 1: server: must be a mapping (key: value lines)"]) | |
| 120 | + #expect(issues("{ bad\n").first?.hasPrefix("not valid YAML") == true) | |
| 121 | + } | |
| 122 | + | |
| 123 | + @Test func unreadableFileIsAConfigError() { | |
| 124 | + #expect(throws: ConfigError.self) { try loader.load(file: "/nonexistent/server.yaml") } | |
| 125 | + } | |
| 126 | + | |
| 127 | + @Test func theShippedExampleIsValid() throws { | |
| 128 | + let example = URL(fileURLWithPath: #filePath) | |
| 129 | + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() | |
| 130 | + .appendingPathComponent("examples/server.yaml") | |
| 131 | + let config = try loader.load(file: example.path) | |
| 132 | + #expect(config.models.map(\.id) == ["qwen3"]) | |
| 133 | + #expect(config.server.apiKeyVariable == "RZB_API_KEY") | |
| 134 | + } | |
| 135 | +} | |
| 136 | + | |
| 137 | +@Suite struct GenerationOverridesTests { | |
| 138 | + @Test func defaultsThenClientThenLocked() { | |
| 139 | + let settings = GenerationOverrides.resolve( | |
| 140 | + defaults: [ | |
| 141 | + GenerationOverrides(temperature: 0.2, maxTokens: 100), | |
| 142 | + GenerationOverrides(topP: 0.5), | |
| 143 | + ], | |
| 144 | + client: GenerationOverrides(temperature: 0.9, topP: 0.8, maxTokens: 5000), | |
| 145 | + locked: [GenerationOverrides(maxTokens: 1000)]) | |
| 146 | + #expect(settings.temperature == 0.9) // a default the client changed | |
| 147 | + #expect(settings.topP == 0.8) | |
| 148 | + #expect(settings.maxTokens == 1000) // locked: a ceiling | |
| 149 | + } | |
| 150 | + | |
| 151 | + @Test func nothingIsLockedUnlessListed() { | |
| 152 | + let settings = GenerationOverrides.resolve( | |
| 153 | + defaults: [GenerationOverrides(temperature: 0.2)], | |
| 154 | + client: GenerationOverrides(temperature: 1.5, thinking: true), | |
| 155 | + locked: [.init(), .init()]) | |
| 156 | + #expect(settings.temperature == 1.5 && settings.thinking) | |
| 157 | + } | |
| 158 | + | |
| 159 | + @Test func lockedValuesAreImposedAndCeilingsKeepSmallerRequests() { | |
| 160 | + let locked = GenerationOverrides(temperature: 0, thinking: false, thinkingBudget: 64) | |
| 161 | + let small = GenerationOverrides.resolve( | |
| 162 | + defaults: [], | |
| 163 | + client: GenerationOverrides( | |
| 164 | + temperature: 1, maxTokens: 50, thinking: true, thinkingBudget: 10), | |
| 165 | + locked: [locked, GenerationOverrides(maxTokens: 100)]) | |
| 166 | + #expect(small.temperature == 0 && !small.thinking) | |
| 167 | + #expect(small.maxTokens == 50 && small.thinkingBudget == 10) | |
| 168 | + let unlimited = GenerationOverrides.resolve(defaults: [], client: .init(), locked: [locked]) | |
| 169 | + #expect(unlimited.thinkingBudget == 64) | |
| 170 | + } | |
| 171 | + | |
| 172 | + @Test func laterLockedBlocksTightenFurther() { | |
| 173 | + let settings = GenerationOverrides.resolve( | |
| 174 | + defaults: [], client: .init(), | |
| 175 | + locked: [GenerationOverrides(maxTokens: 500), GenerationOverrides(maxTokens: 800)]) | |
| 176 | + #expect(settings.maxTokens == 500) | |
| 177 | + #expect(GenerationOverrides().isEmpty && !GenerationOverrides(topP: 1).isEmpty) | |
| 178 | + } | |
| 179 | +} | |
| 180 | + | |
| 181 | +@Suite struct ModelCatalogTests { | |
| 182 | + static let qwen = ModelEntry( | |
| 183 | + id: "qwen3", source: .huggingFace(id: "org/Qwen3", revision: "main"), | |
| 184 | + defaults: GenerationOverrides(temperature: 0.7), | |
| 185 | + locked: GenerationOverrides(maxTokens: 400)) | |
| 186 | + | |
| 187 | + let config = ServerConfig( | |
| 188 | + defaults: GenerationOverrides(temperature: 0.3), | |
| 189 | + locked: GenerationOverrides(maxTokens: 900), | |
| 190 | + models: [Self.qwen]) | |
| 191 | + | |
| 192 | + func catalog(_ store: ModelStore? = nil) throws -> ModelCatalog { | |
| 193 | + ModelCatalog( | |
| 194 | + config: config, | |
| 195 | + store: try store | |
| 196 | + ?? ModelStore(cacheDirectory: URL(fileURLWithPath: temporaryDirectory()))) | |
| 197 | + } | |
| 198 | + | |
| 199 | + @Test func declaredIdsUseTheirSourceAndSettings() throws { | |
| 200 | + let model = try catalog().resolve("qwen3") | |
| 201 | + #expect(model.isDeclared && model.source == .huggingFace(id: "org/Qwen3", revision: "main")) | |
| 202 | + let settings = model.generation() | |
| 203 | + #expect(settings.temperature == 0.7 && settings.maxTokens == 400) | |
| 204 | + } | |
| 205 | + | |
| 206 | + @Test func anyHuggingFaceIdIsAcceptedWithServerWideSettings() throws { | |
| 207 | + let model = try catalog().resolve("mlx-community/Llama-3.2-1B-Instruct-4bit") | |
| 208 | + #expect(!model.isDeclared && model.kind == .chat) | |
| 209 | + #expect( | |
| 210 | + model.source | |
| 211 | + == .huggingFace(id: "mlx-community/Llama-3.2-1B-Instruct-4bit", revision: "main")) | |
| 212 | + #expect(model.generation(client: GenerationOverrides(maxTokens: 5000)).maxTokens == 900) | |
| 213 | + #expect(model.generation().temperature == 0.3) | |
| 214 | + let pinned = try catalog().resolve("org/m@refs/pr/1") | |
| 215 | + #expect(pinned.source == .huggingFace(id: "org/m", revision: "refs/pr/1")) | |
| 216 | + } | |
| 217 | + | |
| 218 | + @Test func namesThatAreNotIdsAreUnknown() throws { | |
| 219 | + for name in ["gpt-4o", "", "a/b/c", "/abs", "org/", "org/na me", "org/m@", "-org/m"] { | |
| 220 | + #expect(throws: ModelResolutionError.unknown(name)) { try catalog().resolve(name) } | |
| 221 | + } | |
| 222 | + } | |
| 223 | + | |
| 224 | + @Test func cachedGGUFRepositoryIsNotMLX() throws { | |
| 225 | + let store = ModelStore(cacheDirectory: URL(fileURLWithPath: try temporaryDirectory())) | |
| 226 | + let snapshot = store.directory(for: "org/gguf").appendingPathComponent("snapshots/c1") | |
| 227 | + try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true) | |
| 228 | + try Data().write(to: snapshot.appendingPathComponent("model-q4.gguf")) | |
| 229 | + #expect(throws: ModelResolutionError.notMLX("org/gguf")) { | |
| 230 | + try catalog(store).resolve("org/gguf") | |
| 231 | + } | |
| 232 | + try Data().write(to: snapshot.appendingPathComponent("model.safetensors")) | |
| 233 | + #expect( | |
| 234 | + try catalog(store).resolve("org/gguf").source | |
| 235 | + == .huggingFace(id: "org/gguf", revision: "main")) | |
| 236 | + } | |
| 237 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,237 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Testing | ||
| 3 | + | ||
| 4 | +@testable import RazorbillCore | ||
| 5 | + | ||
| 6 | +@Suite struct ServerConfigLoaderTests { | ||
| 7 | + let loader = ServerConfigLoader(homeDirectory: "/home/me") | ||
| 8 | + | ||
| 9 | + func issues(_ yaml: String) -> [String] { | ||
| 10 | + do { | ||
| 11 | + _ = try loader.parse(yaml, baseDirectory: "/etc/rzb") | ||
| 12 | + return [] | ||
| 13 | + } catch let error as ConfigError { | ||
| 14 | + return error.issues.map(\.description) | ||
| 15 | + } catch { | ||
| 16 | + return ["unexpected \(error)"] | ||
| 17 | + } | ||
| 18 | + } | ||
| 19 | + | ||
| 20 | + @Test func emptyFileIsTheDefaultConfiguration() throws { | ||
| 21 | + #expect(try loader.parse("") == ServerConfig()) | ||
| 22 | + #expect(try loader.parse("# only a comment\n") == ServerConfig()) | ||
| 23 | + } | ||
| 24 | + | ||
| 25 | + @Test func readsEverySection() throws { | ||
| 26 | + let config = try loader.parse( | ||
| 27 | + """ | ||
| 28 | + server: { host: 0.0.0.0, port: 9000, api_key_env: MY_KEY, cors_origin: "*" } | ||
| 29 | + defaults: { temperature: 0.2, top_p: 0.9, max_tokens: 100, thinking: true, thinking_budget: 10 } | ||
| 30 | + locked: { max_tokens: 500 } | ||
| 31 | + models: | ||
| 32 | + - id: qwen3 | ||
| 33 | + source: mlx-community/Qwen3-4B-4bit | ||
| 34 | + revision: v1 | ||
| 35 | + kind: chat | ||
| 36 | + preload: true | ||
| 37 | + defaults: { temperature: 0.7 } | ||
| 38 | + locked: { thinking: false } | ||
| 39 | + - id: embed | ||
| 40 | + path: ~/models/embed | ||
| 41 | + kind: embedding | ||
| 42 | + - id: rel | ||
| 43 | + path: models/rel | ||
| 44 | + limits: { max_loaded_models: 2, keep_alive: 30s, max_queue: 4 } | ||
| 45 | + """, baseDirectory: "/etc/rzb") | ||
| 46 | + #expect( | ||
| 47 | + config.server | ||
| 48 | + == ServerSection( | ||
| 49 | + host: "0.0.0.0", port: 9000, apiKeyVariable: "MY_KEY", corsOrigin: "*")) | ||
| 50 | + #expect( | ||
| 51 | + config.defaults | ||
| 52 | + == GenerationOverrides( | ||
| 53 | + temperature: 0.2, topP: 0.9, maxTokens: 100, thinking: true, thinkingBudget: 10) | ||
| 54 | + ) | ||
| 55 | + #expect(config.locked == GenerationOverrides(maxTokens: 500)) | ||
| 56 | + #expect( | ||
| 57 | + config.models[0] | ||
| 58 | + == ModelEntry( | ||
| 59 | + id: "qwen3", | ||
| 60 | + source: .huggingFace(id: "mlx-community/Qwen3-4B-4bit", revision: "v1"), | ||
| 61 | + kind: .chat, preload: true, defaults: GenerationOverrides(temperature: 0.7), | ||
| 62 | + locked: GenerationOverrides(thinking: false))) | ||
| 63 | + #expect( | ||
| 64 | + config.models[1].source == .local(path: URL(fileURLWithPath: "/home/me/models/embed"))) | ||
| 65 | + #expect(config.models[1].kind == .embedding) | ||
| 66 | + #expect( | ||
| 67 | + config.models[2].source == .local(path: URL(fileURLWithPath: "/etc/rzb/models/rel"))) | ||
| 68 | + #expect( | ||
| 69 | + config.limits == ServerLimits(maxLoadedModels: 2, keepAlive: .seconds(30), maxQueue: 4)) | ||
| 70 | + } | ||
| 71 | + | ||
| 72 | + @Test func everyProblemIsReportedWithItsLine() { | ||
| 73 | + let found = issues( | ||
| 74 | + """ | ||
| 75 | + server: | ||
| 76 | + port: 70000 | ||
| 77 | + hots: x | ||
| 78 | + defaults: | ||
| 79 | + temperature: 3 | ||
| 80 | + top_p: 0 | ||
| 81 | + max_tokens: 10 | ||
| 82 | + thinking_budget: 10 | ||
| 83 | + models: | ||
| 84 | + - source: org/a | ||
| 85 | + - id: a | ||
| 86 | + source: org/a | ||
| 87 | + path: /x | ||
| 88 | + - id: b | ||
| 89 | + kind: vision | ||
| 90 | + - id: c | ||
| 91 | + source: org/c | ||
| 92 | + - id: c | ||
| 93 | + source: org/c | ||
| 94 | + limits: | ||
| 95 | + keep_alive: soon | ||
| 96 | + max_queue: 0 | ||
| 97 | + """) | ||
| 98 | + #expect( | ||
| 99 | + found == [ | ||
| 100 | + "line 3: server.hots: unknown key (expected one of: host, port, api_key_env, cors_origin)", | ||
| 101 | + "line 2: server.port: must be between 1 and 65535", | ||
| 102 | + "line 5: defaults.temperature: must be between 0 and 2", | ||
| 103 | + "line 6: defaults.top_p: must be above 0 and at most 1", | ||
| 104 | + "line 8: defaults.thinking_budget: must be smaller than max_tokens (10)", | ||
| 105 | + "line 10: models[0].id: is required (the name clients send as \"model\")", | ||
| 106 | + "line 11: models[1]: give either source or path, not both", | ||
| 107 | + "line 14: models[2].source: is required (a Hugging Face id, or path:)", | ||
| 108 | + "line 15: models[2].kind: must be one of: chat, embedding", | ||
| 109 | + "line 18: models[4].id: duplicate id c", | ||
| 110 | + "line 22: limits.max_queue: must be 1 or more", | ||
| 111 | + "line 21: limits.keep_alive: must be a duration such as 30s, 10m or 1h", | ||
| 112 | + ]) | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + @Test func wrongShapesAreReported() { | ||
| 116 | + #expect( | ||
| 117 | + issues("models: qwen3\n") == ["line 1: models: must be a list (lines starting with -)"]) | ||
| 118 | + #expect(issues("- a\n") == ["line 1: must be a mapping (key: value lines)"]) | ||
| 119 | + #expect(issues("server: [1]\n") == ["line 1: server: must be a mapping (key: value lines)"]) | ||
| 120 | + #expect(issues("{ bad\n").first?.hasPrefix("not valid YAML") == true) | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + @Test func unreadableFileIsAConfigError() { | ||
| 124 | + #expect(throws: ConfigError.self) { try loader.load(file: "/nonexistent/server.yaml") } | ||
| 125 | + } | ||
| 126 | + | ||
| 127 | + @Test func theShippedExampleIsValid() throws { | ||
| 128 | + let example = URL(fileURLWithPath: #filePath) | ||
| 129 | + .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent() | ||
| 130 | + .appendingPathComponent("examples/server.yaml") | ||
| 131 | + let config = try loader.load(file: example.path) | ||
| 132 | + #expect(config.models.map(\.id) == ["qwen3"]) | ||
| 133 | + #expect(config.server.apiKeyVariable == "RZB_API_KEY") | ||
| 134 | + } | ||
| 135 | +} | ||
| 136 | + | ||
| 137 | +@Suite struct GenerationOverridesTests { | ||
| 138 | + @Test func defaultsThenClientThenLocked() { | ||
| 139 | + let settings = GenerationOverrides.resolve( | ||
| 140 | + defaults: [ | ||
| 141 | + GenerationOverrides(temperature: 0.2, maxTokens: 100), | ||
| 142 | + GenerationOverrides(topP: 0.5), | ||
| 143 | + ], | ||
| 144 | + client: GenerationOverrides(temperature: 0.9, topP: 0.8, maxTokens: 5000), | ||
| 145 | + locked: [GenerationOverrides(maxTokens: 1000)]) | ||
| 146 | + #expect(settings.temperature == 0.9) // a default the client changed | ||
| 147 | + #expect(settings.topP == 0.8) | ||
| 148 | + #expect(settings.maxTokens == 1000) // locked: a ceiling | ||
| 149 | + } | ||
| 150 | + | ||
| 151 | + @Test func nothingIsLockedUnlessListed() { | ||
| 152 | + let settings = GenerationOverrides.resolve( | ||
| 153 | + defaults: [GenerationOverrides(temperature: 0.2)], | ||
| 154 | + client: GenerationOverrides(temperature: 1.5, thinking: true), | ||
| 155 | + locked: [.init(), .init()]) | ||
| 156 | + #expect(settings.temperature == 1.5 && settings.thinking) | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + @Test func lockedValuesAreImposedAndCeilingsKeepSmallerRequests() { | ||
| 160 | + let locked = GenerationOverrides(temperature: 0, thinking: false, thinkingBudget: 64) | ||
| 161 | + let small = GenerationOverrides.resolve( | ||
| 162 | + defaults: [], | ||
| 163 | + client: GenerationOverrides( | ||
| 164 | + temperature: 1, maxTokens: 50, thinking: true, thinkingBudget: 10), | ||
| 165 | + locked: [locked, GenerationOverrides(maxTokens: 100)]) | ||
| 166 | + #expect(small.temperature == 0 && !small.thinking) | ||
| 167 | + #expect(small.maxTokens == 50 && small.thinkingBudget == 10) | ||
| 168 | + let unlimited = GenerationOverrides.resolve(defaults: [], client: .init(), locked: [locked]) | ||
| 169 | + #expect(unlimited.thinkingBudget == 64) | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + @Test func laterLockedBlocksTightenFurther() { | ||
| 173 | + let settings = GenerationOverrides.resolve( | ||
| 174 | + defaults: [], client: .init(), | ||
| 175 | + locked: [GenerationOverrides(maxTokens: 500), GenerationOverrides(maxTokens: 800)]) | ||
| 176 | + #expect(settings.maxTokens == 500) | ||
| 177 | + #expect(GenerationOverrides().isEmpty && !GenerationOverrides(topP: 1).isEmpty) | ||
| 178 | + } | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +@Suite struct ModelCatalogTests { | ||
| 182 | + static let qwen = ModelEntry( | ||
| 183 | + id: "qwen3", source: .huggingFace(id: "org/Qwen3", revision: "main"), | ||
| 184 | + defaults: GenerationOverrides(temperature: 0.7), | ||
| 185 | + locked: GenerationOverrides(maxTokens: 400)) | ||
| 186 | + | ||
| 187 | + let config = ServerConfig( | ||
| 188 | + defaults: GenerationOverrides(temperature: 0.3), | ||
| 189 | + locked: GenerationOverrides(maxTokens: 900), | ||
| 190 | + models: [Self.qwen]) | ||
| 191 | + | ||
| 192 | + func catalog(_ store: ModelStore? = nil) throws -> ModelCatalog { | ||
| 193 | + ModelCatalog( | ||
| 194 | + config: config, | ||
| 195 | + store: try store | ||
| 196 | + ?? ModelStore(cacheDirectory: URL(fileURLWithPath: temporaryDirectory()))) | ||
| 197 | + } | ||
| 198 | + | ||
| 199 | + @Test func declaredIdsUseTheirSourceAndSettings() throws { | ||
| 200 | + let model = try catalog().resolve("qwen3") | ||
| 201 | + #expect(model.isDeclared && model.source == .huggingFace(id: "org/Qwen3", revision: "main")) | ||
| 202 | + let settings = model.generation() | ||
| 203 | + #expect(settings.temperature == 0.7 && settings.maxTokens == 400) | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + @Test func anyHuggingFaceIdIsAcceptedWithServerWideSettings() throws { | ||
| 207 | + let model = try catalog().resolve("mlx-community/Llama-3.2-1B-Instruct-4bit") | ||
| 208 | + #expect(!model.isDeclared && model.kind == .chat) | ||
| 209 | + #expect( | ||
| 210 | + model.source | ||
| 211 | + == .huggingFace(id: "mlx-community/Llama-3.2-1B-Instruct-4bit", revision: "main")) | ||
| 212 | + #expect(model.generation(client: GenerationOverrides(maxTokens: 5000)).maxTokens == 900) | ||
| 213 | + #expect(model.generation().temperature == 0.3) | ||
| 214 | + let pinned = try catalog().resolve("org/m@refs/pr/1") | ||
| 215 | + #expect(pinned.source == .huggingFace(id: "org/m", revision: "refs/pr/1")) | ||
| 216 | + } | ||
| 217 | + | ||
| 218 | + @Test func namesThatAreNotIdsAreUnknown() throws { | ||
| 219 | + for name in ["gpt-4o", "", "a/b/c", "/abs", "org/", "org/na me", "org/m@", "-org/m"] { | ||
| 220 | + #expect(throws: ModelResolutionError.unknown(name)) { try catalog().resolve(name) } | ||
| 221 | + } | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + @Test func cachedGGUFRepositoryIsNotMLX() throws { | ||
| 225 | + let store = ModelStore(cacheDirectory: URL(fileURLWithPath: try temporaryDirectory())) | ||
| 226 | + let snapshot = store.directory(for: "org/gguf").appendingPathComponent("snapshots/c1") | ||
| 227 | + try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true) | ||
| 228 | + try Data().write(to: snapshot.appendingPathComponent("model-q4.gguf")) | ||
| 229 | + #expect(throws: ModelResolutionError.notMLX("org/gguf")) { | ||
| 230 | + try catalog(store).resolve("org/gguf") | ||
| 231 | + } | ||
| 232 | + try Data().write(to: snapshot.appendingPathComponent("model.safetensors")) | ||
| 233 | + #expect( | ||
| 234 | + try catalog(store).resolve("org/gguf").source | ||
| 235 | + == .huggingFace(id: "org/gguf", revision: "main")) | ||
| 236 | + } | ||
| 237 | +} | ||
added
examples/server.yaml +36 -0 | new file mode 100644 | ||
| @@ -0,0 +1,36 @@ | ||
| 1 | +# razorbill server configuration — use it with: rzb serve --config examples/server.yaml | |
| 2 | +# Check it with: rzb config validate examples/server.yaml | |
| 3 | +# Every section is optional. Command-line options (--host, --port, …) win over this file. | |
| 4 | + | |
| 5 | +server: | |
| 6 | + host: 127.0.0.1 # 0.0.0.0 serves the whole network: set an API key then | |
| 7 | + port: 8080 | |
| 8 | + api_key_env: RZB_API_KEY # the variable holding the key; the key never goes in this file | |
| 9 | + # cors_origin: "*" # let browser pages call the API | |
| 10 | + | |
| 11 | +# Settings every model starts from. Clients may change them in their requests. | |
| 12 | +defaults: | |
| 13 | + temperature: 0.6 | |
| 14 | + max_tokens: 2048 | |
| 15 | + | |
| 16 | +# Settings clients cannot change. Nothing is locked unless listed here (or under a model). | |
| 17 | +# temperature, top_p and thinking are imposed; max_tokens and thinking_budget are ceilings. | |
| 18 | +locked: | |
| 19 | + max_tokens: 8192 | |
| 20 | + | |
| 21 | +# Models declared by name. Any other Hugging Face id in MLX format (org/name) is accepted too. | |
| 22 | +models: | |
| 23 | + - id: qwen3 # what clients put in "model" | |
| 24 | + source: mlx-community/Qwen3-0.6B-4bit | |
| 25 | + # revision: main | |
| 26 | + kind: chat # chat | embedding | |
| 27 | + preload: false | |
| 28 | + defaults: { thinking: true, thinking_budget: 512 } | |
| 29 | + locked: { max_tokens: 4096 } | |
| 30 | + # - id: local | |
| 31 | + # path: ~/models/my-mlx-model # a model already on disk | |
| 32 | + | |
| 33 | +limits: | |
| 34 | + max_loaded_models: 1 # least recently used model unloaded beyond this | |
| 35 | + keep_alive: 10m # idle model unloaded after this long | |
| 36 | + max_queue: 16 # waiting requests per model; more get a 429 | |
| new file mode 100644 | |||
| @@ -0,0 +1,36 @@ | |||
| 1 | +# razorbill server configuration — use it with: rzb serve --config examples/server.yaml | ||
| 2 | +# Check it with: rzb config validate examples/server.yaml | ||
| 3 | +# Every section is optional. Command-line options (--host, --port, …) win over this file. | ||
| 4 | + | ||
| 5 | +server: | ||
| 6 | + host: 127.0.0.1 # 0.0.0.0 serves the whole network: set an API key then | ||
| 7 | + port: 8080 | ||
| 8 | + api_key_env: RZB_API_KEY # the variable holding the key; the key never goes in this file | ||
| 9 | + # cors_origin: "*" # let browser pages call the API | ||
| 10 | + | ||
| 11 | +# Settings every model starts from. Clients may change them in their requests. | ||
| 12 | +defaults: | ||
| 13 | + temperature: 0.6 | ||
| 14 | + max_tokens: 2048 | ||
| 15 | + | ||
| 16 | +# Settings clients cannot change. Nothing is locked unless listed here (or under a model). | ||
| 17 | +# temperature, top_p and thinking are imposed; max_tokens and thinking_budget are ceilings. | ||
| 18 | +locked: | ||
| 19 | + max_tokens: 8192 | ||
| 20 | + | ||
| 21 | +# Models declared by name. Any other Hugging Face id in MLX format (org/name) is accepted too. | ||
| 22 | +models: | ||
| 23 | + - id: qwen3 # what clients put in "model" | ||
| 24 | + source: mlx-community/Qwen3-0.6B-4bit | ||
| 25 | + # revision: main | ||
| 26 | + kind: chat # chat | embedding | ||
| 27 | + preload: false | ||
| 28 | + defaults: { thinking: true, thinking_budget: 512 } | ||
| 29 | + locked: { max_tokens: 4096 } | ||
| 30 | + # - id: local | ||
| 31 | + # path: ~/models/my-mlx-model # a model already on disk | ||
| 32 | + | ||
| 33 | +limits: | ||
| 34 | + max_loaded_models: 1 # least recently used model unloaded beyond this | ||
| 35 | + keep_alive: 10m # idle model unloaded after this long | ||
| 36 | + max_queue: 16 # waiting requests per model; more get a 429 | ||