bots-garden/razorbillpublic Fork
⑂ 4d3623e
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/razorbill.git
git clone ssh://git@rickub.com/bots-garden/razorbill.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

v0.2 step 4 — model lifecycle and /v1/models (#34)

ModelManager: load on demand (one engine per model, shared between a
declared name and its repository id), per-model turn queue bounded by
max_queue (429), cancellable waiters, LRU eviction of idle models within
max_loaded_models and a memory budget (75 % of RAM), keep_alive unload,
not-MLX detection after a failed load. ModelLifecycleService preloads,
sweeps idle models and unloads everything at shutdown.

GET /v1/models and /v1/models/{id}: declared models, cached MLX models and
loaded ones, OpenAI shape plus loaded and kind.

Tests: Linux 89, Mac 94.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-25T13:13:32+01:00 Browse files
4d3623e parent: b48915d
modified .memory/handoffs/2026-11-25-v0-2-server-foundation.md +15 -12
@@ -1,24 +1,21 @@
1-# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config file (#33)
1+# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config (#33), models (#34)
22
33 ## State
44 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).
5+Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).
56 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
67 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
78 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
89 closed. Nothing pushed.
910
1011 ## Next steps
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.
12+1. #35 — `POST /v1/chat/completions` (non-streaming): `models.acquire(name)` → lease →
13+ `engine.makeSession(SessionSetup(system:…, generation: lease.model.generation(client: …)))`,
14+ release the lease when the answer is complete (for streaming #36: when the stream ends or is
15+ cancelled). Task 7 (moved from #34): cancel generation when the client disconnects.
16+2. User check on the Mac: a config with `preload: true` for an MLX model → `rzb serve --config …`
17+ → `curl /v1/models` should show `"loaded": true` (never run with a real model yet).
18+3. Open point: a network-exposed server accepting any HF id lets clients trigger downloads.
2219
2320 ## Watch out for
2421 - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns
@@ -36,4 +33,10 @@ closed. Nothing pushed.
3633 `git commit` works now.
3734 - `main` was created at `9f8dda1` (fast-forward of `feature/v0.2-openai-server`); keep working on
3835 the feature branch and fast-forward `main` when a step is done. Nothing pushed to `origin`.
36+- `pgrep -f "rzb serve"` matches the Bash tool's own command line: check a server's state by PID
37+ (`$!`, `kill -0`), not by pattern — a false "still running after SIGINT" cost time here.
38+- Swift 6.2 crashed ("failed to produce diagnostic") on an untyped `withCheckedThrowingContinuation`
39+ closure that mutated actor state inline: type the continuation and call an isolated method.
40+- `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by
41+ the requested name.
3942 - Docs/README still describe the agent; rewritten in #45 at the end of v0.2.
@@ -1,24 +1,21 @@
1-# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config file (#33)1+# Handoff — 2026-11-25 — v0.2: agent removed, server foundation (#32), config (#33), models (#34)
2 2
3 ## State3 ## State
4 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).4 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).
5+Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).
5 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP6 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
6 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket7 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
7 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task8 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
8 closed. Nothing pushed.9 closed. Nothing pushed.
9 10
10 ## Next steps11 ## Next steps
11-1. #34 — model lifecycle + `GET /v1/models`: use `ModelCatalog` (from `ServerSettings.config` +12+1. #35 — `POST /v1/chat/completions` (non-streaming): `models.acquire(name)` → lease →
12- `ModelStore`) to resolve names, map `ModelResolutionError` to `OpenAIError.modelNotFound` / a 40013+ `engine.makeSession(SessionSetup(system:…, generation: lease.model.generation(client: …)))`,
13- for not-MLX; for undeclared, uncached ids check MLX compliance (config.json + .safetensors on the14+ release the lease when the answer is complete (for streaming #36: when the stream ends or is
14- Hub) before downloading; honour `limits` (max_loaded_models, keep_alive, max_queue) and `preload`.15+ cancelled). Task 7 (moved from #34): cancel generation when the client disconnects.
15- Open point to raise: a network-exposed server accepting any HF id lets clients trigger large16+2. User check on the Mac: a config with `preload: true` for an MLX model → `rzb serve --config …`
16- downloads — maybe an option later (the user only decided "accept any MLX id").17+ → `curl /v1/models` should show `"loaded": true` (never run with a real model yet).
17-2. #35 non-streaming chat completions; #36 streaming (`ServerSentEvents.response`; record18+3. Open point: a network-exposed server accepting any HF id lets clients trigger downloads.
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.
22 19
23 ## Watch out for20 ## Watch out for
24 - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns21 - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns
@@ -36,4 +33,10 @@ closed. Nothing pushed.
36 `git commit` works now.33 `git commit` works now.
37 - `main` was created at `9f8dda1` (fast-forward of `feature/v0.2-openai-server`); keep working on34 - `main` was created at `9f8dda1` (fast-forward of `feature/v0.2-openai-server`); keep working on
38 the feature branch and fast-forward `main` when a step is done. Nothing pushed to `origin`.35 the feature branch and fast-forward `main` when a step is done. Nothing pushed to `origin`.
36+- `pgrep -f "rzb serve"` matches the Bash tool's own command line: check a server's state by PID
37+ (`$!`, `kill -0`), not by pattern — a false "still running after SIGINT" cost time here.
38+- Swift 6.2 crashed ("failed to produce diagnostic") on an untyped `withCheckedThrowingContinuation`
39+ closure that mutated actor state inline: type the continuation and call an isolated method.
40+- `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by
41+ the requested name.
39 - Docs/README still describe the agent; rewritten in #45 at the end of v0.2.42 - Docs/README still describe the agent; rewritten in #45 at the end of v0.2.
modified .memory/history.md +8 -0
@@ -148,3 +148,11 @@
148148 `allow_any_model` switch (not asked), `${env.X}` interpolation for the key (`api_key_env` instead).
149149 Tests Linux 73, Mac 78; Release build + `rzb config validate examples/server.yaml` on the Mac OK;
150150 quality gate PASS (run #5). #33 closed. User asked to stay local (no push).
151+- #34: `ModelManager` (turn queue per model with max_queue/429 and cancellable waiters, shared load,
152+ LRU eviction of idle models only, memory budget 75 % of RAM from safetensors size, keep_alive
153+ sweep, not-MLX detection after a failed load), `ModelLifecycleService` (preload, sweep, unload at
154+ shutdown), `GET /v1/models` + `/v1/models/{id}`, error mapping (429 queue_full, 503 server_busy /
155+ insufficient_memory, 400 model_not_supported, 500 model_load_failed). Rejected for now: waiting
156+ for a busy model to free a slot (503 instead), batching across requests. A route test caught a
157+ duplicate listing of loaded declared models (fixed). Linux 89, Mac 94, gate PASS (run #6). #34
158+ closed; its "cancel on disconnect" task moved to #35.
@@ -148,3 +148,11 @@
148 `allow_any_model` switch (not asked), `${env.X}` interpolation for the key (`api_key_env` instead).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;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).150 quality gate PASS (run #5). #33 closed. User asked to stay local (no push).
151+- #34: `ModelManager` (turn queue per model with max_queue/429 and cancellable waiters, shared load,
152+ LRU eviction of idle models only, memory budget 75 % of RAM from safetensors size, keep_alive
153+ sweep, not-MLX detection after a failed load), `ModelLifecycleService` (preload, sweep, unload at
154+ shutdown), `GET /v1/models` + `/v1/models/{id}`, error mapping (429 queue_full, 503 server_busy /
155+ insufficient_memory, 400 model_not_supported, 500 model_load_failed). Rejected for now: waiting
156+ for a busy model to free a slot (503 instead), batching across requests. A route test caught a
157+ duplicate listing of loaded declared models (fixed). Linux 89, Mac 94, gate PASS (run #6). #34
158+ closed; its "cancel on disconnect" task moved to #35.
modified .memory/summary.md +12 -5
@@ -6,8 +6,8 @@
66 **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming
77 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in
88 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`), server configuration file #33
10-(see Architecture). Decided by the user (#31): the
9+removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33,
10+model lifecycle + `/v1/models` #34 (see Architecture). Decided by the user (#31): the
1111 agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore,
1212 MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb`
1313 (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by
@@ -39,13 +39,16 @@ Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `Thin
3939 `ServerConfigLoader`, `GenerationOverrides`, `ModelCatalog`), `RazorbillMLX`
4040 (unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit
4141 and a `usage` record for the log, `OpenAIError` envelope, middlewares in order request log → CORS →
42-error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`,
42+error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelManager` actor = load on
43+demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService`
44+for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`), `RazorbillCLI` (`serve`,
4345 `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve`
4446 runner for tests; `ServerSettings.config` carries the loaded file to the server).
4547 `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin`
4648 (options win over the file's `server:` section); `rzb config validate <file>`; example
4749 `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).
50+the variable). One engine instance per loaded model (`InferenceEngine.unload()`); the engine is the
51+registry's default (`mlx` on the Mac, `fake` on Linux). Next: chat completions (#35).
4952
5053 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
5154
@@ -133,7 +136,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
133136 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
134137 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
135138 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).
136-Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #33): Linux 73, Mac 78.
139+Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #34): Linux 89, Mac 94.
137140 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
138141
139142 ## mlx-swift-lm API version trap
@@ -145,6 +148,10 @@ of the resolved version.
145148
146149 ## Not yet established
147150
151+- A real MLX model loaded through the server (`ModelManager` + `MLXEngine`, e.g. with `preload: true`)
152+ on the Mac: not run yet. Whether dropping `MLXEngine`'s container frees GPU memory promptly (no
153+ `MLX.GPU.clearCache` call) is unverified.
154+
148155 - Behaviour of the quality skill on macOS (qlty running swiftlint via its plugin) — untested.
149156 - Whether `~/.qlty` survives sandbox recreation (`sbx env run --force`); `/usr/local/bin/swiftlint`
150157 and `/opt/libxml2-2.14` do not, according to the quality skill (not observed).
@@ -6,8 +6,8 @@
6 **model server dedicated to MLX exposing an OpenAI-compatible API** (chat completions incl. streaming6 **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 in7 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 code8 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`), server configuration file #339+removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33,
10-(see Architecture). Decided by the user (#31): the10+model lifecycle + `/v1/models` #34 (see Architecture). Decided by the user (#31): the
11 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,
12 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`
13 (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by13 (`rzb serve`); Hummingbird 2; OpenAI-compatible API only (no Ollama `/api/*`); binds 127.0.0.1 by
@@ -39,13 +39,16 @@ Modules: `RazorbillCore` (engine protocol, `EngineRegistry`, `FakeEngine`, `Thin
39 `ServerConfigLoader`, `GenerationOverrides`, `ModelCatalog`), `RazorbillMLX`39 `ServerConfigLoader`, `GenerationOverrides`, `ModelCatalog`), `RazorbillMLX`
40 (unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit40 (unchanged), `RazorbillServer` (Hummingbird 2.29, no MLX: `ServerContext` with a 16 MiB body limit
41 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 →
42-error envelope → API key, `GET /health`, `ServerSentEvents` helper), `RazorbillCLI` (`serve`,42+error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelManager` actor = load on
43+demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService`
44+for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`), `RazorbillCLI` (`serve`,
43 `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve`45 `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve`
44 runner for tests; `ServerSettings.config` carries the loaded file to the server).46 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`47 `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>`; example48 (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` names49 `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).50+the variable). One engine instance per loaded model (`InferenceEngine.unload()`); the engine is the
51+registry's default (`mlx` on the Mac, `fake` on Linux). Next: chat completions (#35).
49 52
50 ## Architecture of v0.1 (agent, removed on the v0.2 branch)53 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
51 54
@@ -133,7 +136,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
133 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).136 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
134 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped137 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
135 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).138 signatures as `) throws -> T {` or on one line (the two tools fight over brace placement).
136-Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #33): Linux 73, Mac 78.139+Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #34): Linux 89, Mac 94.
137 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).140 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
138 141
139 ## mlx-swift-lm API version trap142 ## mlx-swift-lm API version trap
@@ -145,6 +148,10 @@ of the resolved version.
145 148
146 ## Not yet established149 ## Not yet established
147 150
151+- A real MLX model loaded through the server (`ModelManager` + `MLXEngine`, e.g. with `preload: true`)
152+ on the Mac: not run yet. Whether dropping `MLXEngine`'s container frees GPU memory promptly (no
153+ `MLX.GPU.clearCache` call) is unverified.
154+
148 - Behaviour of the quality skill on macOS (qlty running swiftlint via its plugin) — untested.155 - Behaviour of the quality skill on macOS (qlty running swiftlint via its plugin) — untested.
149 - Whether `~/.qlty` survives sandbox recreation (`sbx env run --force`); `/usr/local/bin/swiftlint`156 - Whether `~/.qlty` survives sandbox recreation (`sbx env run --force`); `/usr/local/bin/swiftlint`
150 and `/opt/libxml2-2.14` do not, according to the quality skill (not observed).157 and `/opt/libxml2-2.14` do not, according to the quality skill (not observed).
modified .quality/history.jsonl +1 -0
@@ -3,3 +3,4 @@
33 {"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"}
44 {"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"}
55 {"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"}
6+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b48915d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 122, "complex": 228, "cyclo": 296, "fields": 531, "funcs": 290, "lcom": 63, "lines": 5247, "loc": 4035}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 6, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:12:54Z"}
@@ -3,3 +3,4 @@
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"}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"}
6+{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "b48915d", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 122, "complex": 228, "cyclo": 296, "fields": 531, "funcs": 290, "lcom": 63, "lines": 5247, "loc": 4035}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 6, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:12:54Z"}
added .quality/report-20261125T121254Z.md +69 -0
new file mode 100644
@@ -0,0 +1,69 @@
1+# Quality report — 2026-11-25T12:12:54Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `b48915d` 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**: #6 (previous: 2026-11-25T08:05:17Z)
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 | 290 | +55 |
32+| classes | 122 | +17 |
33+| fields | 531 | +95 |
34+| cyclo | 296 | +45 |
35+| complex | 228 | +30 |
36+| lcom | 63 | +7 |
37+| lines | 5247 | +899 |
38+| loc | 4035 | +730 |
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 | 201 |
46+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |
47+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 |
48+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
49+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
50+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
51+| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
52+| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
53+| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 |
54+| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 |
55+| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 |
56+| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
57+| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
58+| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
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 |
69+| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS |
new file mode 100644
@@ -0,0 +1,69 @@
1+# Quality report — 2026-11-25T12:12:54Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `b48915d` 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**: #6 (previous: 2026-11-25T08:05:17Z)
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 | 290 | +55 |
32+| classes | 122 | +17 |
33+| fields | 531 | +95 |
34+| cyclo | 296 | +45 |
35+| complex | 228 | +30 |
36+| lcom | 63 | +7 |
37+| lines | 5247 | +899 |
38+| loc | 4035 | +730 |
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 | 201 |
46+| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |
47+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 |
48+| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
49+| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
50+| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
51+| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
52+| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
53+| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 |
54+| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 63 |
55+| Sources/RazorbillCLI/Console.swift | 7 | 10 | 65 |
56+| Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
57+| Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
58+| Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
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 |
69+| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS |
modified .quality/report-latest.md +14 -13
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-25T08:05:17Z
1+# Quality report — 2026-11-25T12:12:54Z
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `efa10e1` on `feature/v0.2-openai-server`
4+- **Commit**: `b48915d` on `feature/v0.2-openai-server`
55 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
66 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #5 (previous: 2026-11-25T07:51:14Z)
7+- **Run**: #6 (previous: 2026-11-25T08:05:17Z)
88
99 ## Lint issues (`qlty check`)
1010
@@ -28,22 +28,23 @@ _none_
2828
2929 | metric | total | vs previous |
3030 |---|---|---|
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 |
31+| funcs | 290 | +55 |
32+| classes | 122 | +17 |
33+| fields | 531 | +95 |
34+| cyclo | 296 | +45 |
35+| complex | 228 | +30 |
36+| lcom | 63 | +7 |
37+| lines | 5247 | +899 |
38+| loc | 4035 | +730 |
3939
4040 ### Most complex files
4141
4242 | file | complex | cyclo | loc |
4343 |---|---|---|---|
4444 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
45-| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 198 |
45+| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 201 |
4646 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |
47+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 |
4748 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
4849 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
4950 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
@@ -55,7 +56,6 @@ _none_
5556 | Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
5657 | Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
5758 | Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
58-| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 |
5959
6060 ## Trend
6161
@@ -66,3 +66,4 @@ _none_
6666 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
6767 | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
6868 | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |
69+| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS |
@@ -1,10 +1,10 @@
1-# Quality report — 2026-11-25T08:05:17Z1+# Quality report — 2026-11-25T12:12:54Z
2 2
3 - **Gate**: ✅ **PASS**3 - **Gate**: ✅ **PASS**
4-- **Commit**: `efa10e1` on `feature/v0.2-openai-server`4+- **Commit**: `b48915d` 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**: #5 (previous: 2026-11-25T07:51:14Z)7+- **Run**: #6 (previous: 2026-11-25T08:05:17Z)
8 8
9 ## Lint issues (`qlty check`)9 ## Lint issues (`qlty check`)
10 10
@@ -28,22 +28,23 @@ _none_
28 28
29 | metric | total | vs previous |29 | metric | total | vs previous |
30 |---|---|---|30 |---|---|---|
31-| funcs | 235 | +47 |31+| funcs | 290 | +55 |
32-| classes | 105 | +18 |32+| classes | 122 | +17 |
33-| fields | 436 | +96 |33+| fields | 531 | +95 |
34-| cyclo | 251 | +47 |34+| cyclo | 296 | +45 |
35-| complex | 198 | +45 |35+| complex | 228 | +30 |
36-| lcom | 56 | +11 |36+| lcom | 63 | +7 |
37-| lines | 4348 | +911 |37+| lines | 5247 | +899 |
38-| loc | 3305 | +735 |38+| loc | 4035 | +730 |
39 39
40 ### Most complex files40 ### Most complex files
41 41
42 | file | complex | cyclo | loc |42 | file | complex | cyclo | loc |
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 | 201 |
46 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |46 | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 |
47+| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 |
47 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |48 | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 |
48 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |49 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
49 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |50 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
@@ -55,7 +56,6 @@ _none_
55 | Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |56 | Sources/RazorbillCLI/DownloadProgress.swift | 7 | 4 | 32 |
56 | Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |57 | Sources/RazorbillServer/ServerContext.swift | 6 | 4 | 36 |
57 | Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |58 | Sources/RazorbillCore/Config/ConfigValue.swift | 5 | 8 | 37 |
58-| Sources/RazorbillCore/Engine/FakeEngine.swift | 5 | 4 | 59 |
59 59
60 ## Trend60 ## Trend
61 61
@@ -66,3 +66,4 @@ _none_
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 |68 | 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS |
69+| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS |
modified .tickets/issues/0034-model-lifecycle-in-the-server-load-on-demand-kee.yaml +32 -9
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 34
33 title: "Model lifecycle in the server: load on demand, keep-alive, queueing, /v1/models"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z
9+updatedAt: 2026-11-25T12:20:00.000Z
1010 labels:
1111 - "kind::feature"
1212 - "area::models"
@@ -33,50 +33,73 @@ body: |
3333 tasks:
3434 - id: 1
3535 title: "/v1/models and /v1/models/{id}"
36- state: open
36+ state: closed
3737 priority: high
3838 author:
3939 name: k33g
4040 email: ph.charriere@gmail.com
4141 createdAt: 2026-11-24T21:17:08.000Z
42+ updatedAt: 2026-11-25T12:20:00.000Z
43+ closedAt: 2026-11-25T12:20:00.000Z
4244 - id: 2
4345 title: "Loaded-model registry: load on demand, shared in-flight load, preload"
44- state: open
46+ state: closed
4547 priority: high
4648 author:
4749 name: k33g
4850 email: ph.charriere@gmail.com
4951 createdAt: 2026-11-24T21:17:08.000Z
52+ updatedAt: 2026-11-25T12:20:00.000Z
53+ closedAt: 2026-11-25T12:20:00.000Z
5054 - id: 3
5155 title: "keep_alive unload and LRU eviction"
52- state: open
56+ state: closed
5357 priority: medium
5458 author:
5559 name: k33g
5660 email: ph.charriere@gmail.com
5761 createdAt: 2026-11-24T21:17:08.000Z
62+ updatedAt: 2026-11-25T12:20:00.000Z
63+ closedAt: 2026-11-25T12:20:00.000Z
5864 - id: 4
5965 title: "Per-model request queue with max_queue and 429"
60- state: open
66+ state: closed
6167 priority: high
6268 author:
6369 name: k33g
6470 email: ph.charriere@gmail.com
6571 createdAt: 2026-11-24T21:17:08.000Z
72+ updatedAt: 2026-11-25T12:20:00.000Z
73+ closedAt: 2026-11-25T12:20:00.000Z
6674 - id: 5
6775 title: "Cancel generation when the client disconnects"
68- state: open
76+ state: closed
6977 priority: high
7078 author:
7179 name: k33g
7280 email: ph.charriere@gmail.com
7381 createdAt: 2026-11-24T21:17:08.000Z
82+ updatedAt: 2026-11-25T12:20:00.000Z
83+ closedAt: 2026-11-25T12:20:00.000Z
7484 - id: 6
7585 title: "Refuse loads that do not fit in memory"
76- state: open
86+ state: closed
7787 priority: medium
7888 author:
7989 name: k33g
8090 email: ph.charriere@gmail.com
8191 createdAt: 2026-11-24T21:17:08.000Z
82-comments: []
92+ updatedAt: 2026-11-25T12:20:00.000Z
93+ closedAt: 2026-11-25T12:20:00.000Z
94+comments:
95+ - id: 1
96+ author:
97+ name: k33g
98+ email: ph.charriere@gmail.com
99+ createdAt: 2026-11-25T12:20:00.000Z
100+ body: |
101+ Done. `ModelManager` (actor, RazorbillServer): resolves names through `ModelCatalog`, one engine instance per loaded model (`InferenceEngine.unload()` added), keyed by source so a declared name and its repo id share one load. Requests for a model take turns in arrival order (the turn holder loads, so a load in progress is shared); at most `max_queue` wait → 429 `queue_full`; a cancelled waiter leaves the queue. Room is made by unloading the least recently used **idle** model; if every loaded model is busy → 503 `server_busy`. Memory: weights size from the cache (`ModelStore.weightsSize`, symlinks followed) against a budget of 75 % of physical memory → 503 `insufficient_memory`; size of a not-yet-downloaded model is unknown (0) until it is downloaded. A load failure on a repo with config.json but no .safetensors → 400 `model_not_supported`, other failures → 500 `model_load_failed`; the next request retries. `ModelLifecycleService` (swift-service-lifecycle, next to the HTTP server): preload, idle sweep every min(keep_alive/4, 30 s), unload all at shutdown.
102+ `GET /v1/models`: declared models, then every MLX model in the HF cache, then loaded undeclared ones, with extra `loaded` and `kind`; `GET /v1/models/{id}` accepts ids with `/`.
103+ Task 5 (cancel generation on client disconnect) moved to #35: there is no generation yet; cancelling a waiting request already works.
104+ Tests: 13 manager + 3 routes; Linux 89, Mac 94; quality gate PASS. Not checked yet: a real MLX load through the server on the Mac (preload).
105+
@@ -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: 342 id: 34
3 title: "Model lifecycle in the server: load on demand, keep-alive, queueing, /v1/models"3 title: "Model lifecycle in the server: load on demand, keep-alive, queueing, /v1/models"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z9+updatedAt: 2026-11-25T12:20:00.000Z
10 labels:10 labels:
11 - "kind::feature"11 - "kind::feature"
12 - "area::models"12 - "area::models"
@@ -33,50 +33,73 @@ body: |
33 tasks:33 tasks:
34 - id: 134 - id: 1
35 title: "/v1/models and /v1/models/{id}"35 title: "/v1/models and /v1/models/{id}"
36- state: open36+ state: closed
37 priority: high37 priority: high
38 author:38 author:
39 name: k33g39 name: k33g
40 email: ph.charriere@gmail.com40 email: ph.charriere@gmail.com
41 createdAt: 2026-11-24T21:17:08.000Z41 createdAt: 2026-11-24T21:17:08.000Z
42+ updatedAt: 2026-11-25T12:20:00.000Z
43+ closedAt: 2026-11-25T12:20:00.000Z
42 - id: 244 - id: 2
43 title: "Loaded-model registry: load on demand, shared in-flight load, preload"45 title: "Loaded-model registry: load on demand, shared in-flight load, preload"
44- state: open46+ state: closed
45 priority: high47 priority: high
46 author:48 author:
47 name: k33g49 name: k33g
48 email: ph.charriere@gmail.com50 email: ph.charriere@gmail.com
49 createdAt: 2026-11-24T21:17:08.000Z51 createdAt: 2026-11-24T21:17:08.000Z
52+ updatedAt: 2026-11-25T12:20:00.000Z
53+ closedAt: 2026-11-25T12:20:00.000Z
50 - id: 354 - id: 3
51 title: "keep_alive unload and LRU eviction"55 title: "keep_alive unload and LRU eviction"
52- state: open56+ state: closed
53 priority: medium57 priority: medium
54 author:58 author:
55 name: k33g59 name: k33g
56 email: ph.charriere@gmail.com60 email: ph.charriere@gmail.com
57 createdAt: 2026-11-24T21:17:08.000Z61 createdAt: 2026-11-24T21:17:08.000Z
62+ updatedAt: 2026-11-25T12:20:00.000Z
63+ closedAt: 2026-11-25T12:20:00.000Z
58 - id: 464 - id: 4
59 title: "Per-model request queue with max_queue and 429"65 title: "Per-model request queue with max_queue and 429"
60- state: open66+ state: closed
61 priority: high67 priority: high
62 author:68 author:
63 name: k33g69 name: k33g
64 email: ph.charriere@gmail.com70 email: ph.charriere@gmail.com
65 createdAt: 2026-11-24T21:17:08.000Z71 createdAt: 2026-11-24T21:17:08.000Z
72+ updatedAt: 2026-11-25T12:20:00.000Z
73+ closedAt: 2026-11-25T12:20:00.000Z
66 - id: 574 - id: 5
67 title: "Cancel generation when the client disconnects"75 title: "Cancel generation when the client disconnects"
68- state: open76+ state: closed
69 priority: high77 priority: high
70 author:78 author:
71 name: k33g79 name: k33g
72 email: ph.charriere@gmail.com80 email: ph.charriere@gmail.com
73 createdAt: 2026-11-24T21:17:08.000Z81 createdAt: 2026-11-24T21:17:08.000Z
82+ updatedAt: 2026-11-25T12:20:00.000Z
83+ closedAt: 2026-11-25T12:20:00.000Z
74 - id: 684 - id: 6
75 title: "Refuse loads that do not fit in memory"85 title: "Refuse loads that do not fit in memory"
76- state: open86+ state: closed
77 priority: medium87 priority: medium
78 author:88 author:
79 name: k33g89 name: k33g
80 email: ph.charriere@gmail.com90 email: ph.charriere@gmail.com
81 createdAt: 2026-11-24T21:17:08.000Z91 createdAt: 2026-11-24T21:17:08.000Z
82-comments: []92+ updatedAt: 2026-11-25T12:20:00.000Z
93+ closedAt: 2026-11-25T12:20:00.000Z
94+comments:
95+ - id: 1
96+ author:
97+ name: k33g
98+ email: ph.charriere@gmail.com
99+ createdAt: 2026-11-25T12:20:00.000Z
100+ body: |
101+ Done. `ModelManager` (actor, RazorbillServer): resolves names through `ModelCatalog`, one engine instance per loaded model (`InferenceEngine.unload()` added), keyed by source so a declared name and its repo id share one load. Requests for a model take turns in arrival order (the turn holder loads, so a load in progress is shared); at most `max_queue` wait → 429 `queue_full`; a cancelled waiter leaves the queue. Room is made by unloading the least recently used **idle** model; if every loaded model is busy → 503 `server_busy`. Memory: weights size from the cache (`ModelStore.weightsSize`, symlinks followed) against a budget of 75 % of physical memory → 503 `insufficient_memory`; size of a not-yet-downloaded model is unknown (0) until it is downloaded. A load failure on a repo with config.json but no .safetensors → 400 `model_not_supported`, other failures → 500 `model_load_failed`; the next request retries. `ModelLifecycleService` (swift-service-lifecycle, next to the HTTP server): preload, idle sweep every min(keep_alive/4, 30 s), unload all at shutdown.
102+ `GET /v1/models`: declared models, then every MLX model in the HF cache, then loaded undeclared ones, with extra `loaded` and `kind`; `GET /v1/models/{id}` accepts ids with `/`.
103+ Task 5 (cancel generation on client disconnect) moved to #35: there is no generation yet; cancelling a waiting request already works.
104+ Tests: 13 manager + 3 routes; Linux 89, Mac 94; quality gate PASS. Not checked yet: a real MLX load through the server on the Mac (preload).
105+
modified .tickets/issues/0035-chat-completions-post-v1-chat-completions-non-st.yaml +9 -1
@@ -6,7 +6,7 @@ author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z
9+updatedAt: 2026-11-25T12:20:00.000Z
1010 labels:
1111 - "kind::feature"
1212 - "area::server"
@@ -80,4 +80,12 @@ tasks:
8080 name: k33g
8181 email: ph.charriere@gmail.com
8282 createdAt: 2026-11-24T21:17:08.000Z
83+ - id: 7
84+ title: "Cancel generation when the client disconnects (moved from #34)"
85+ state: open
86+ priority: high
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-11-25T12:20:00.000Z
8391 comments: []
@@ -6,7 +6,7 @@ author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z9+updatedAt: 2026-11-25T12:20:00.000Z
10 labels:10 labels:
11 - "kind::feature"11 - "kind::feature"
12 - "area::server"12 - "area::server"
@@ -80,4 +80,12 @@ tasks:
80 name: k33g80 name: k33g
81 email: ph.charriere@gmail.com81 email: ph.charriere@gmail.com
82 createdAt: 2026-11-24T21:17:08.000Z82 createdAt: 2026-11-24T21:17:08.000Z
83+ - id: 7
84+ title: "Cancel generation when the client disconnects (moved from #34)"
85+ state: open
86+ priority: high
87+ author:
88+ name: k33g
89+ email: ph.charriere@gmail.com
90+ createdAt: 2026-11-25T12:20:00.000Z
83 comments: []91 comments: []
modified Package.swift +3 -0
@@ -32,6 +32,8 @@ let package = Package(
3232 .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.28.0"),
3333 // Logging API used by Hummingbird; `rzb serve` writes its request log through it.
3434 .package(url: "https://github.com/apple/swift-log", from: "1.6.0"),
35+ // Runs the model lifecycle (preload, keep_alive, unload at shutdown) next to the server.
36+ .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"),
3537 ],
3638 targets: [
3739 // Engine protocol, model cache, configuration reading, FakeEngine. No MLX.
@@ -57,6 +59,7 @@ let package = Package(
5759 dependencies: [
5860 "RazorbillCore",
5961 .product(name: "Hummingbird", package: "hummingbird"),
62+ .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),
6063 ]
6164 ),
6265 // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.
@@ -32,6 +32,8 @@ let package = Package(
32 .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.28.0"),32 .package(url: "https://github.com/hummingbird-project/hummingbird", from: "2.28.0"),
33 // Logging API used by Hummingbird; `rzb serve` writes its request log through it.33 // Logging API used by Hummingbird; `rzb serve` writes its request log through it.
34 .package(url: "https://github.com/apple/swift-log", from: "1.6.0"),34 .package(url: "https://github.com/apple/swift-log", from: "1.6.0"),
35+ // Runs the model lifecycle (preload, keep_alive, unload at shutdown) next to the server.
36+ .package(url: "https://github.com/swift-server/swift-service-lifecycle", from: "2.6.0"),
35 ],37 ],
36 targets: [38 targets: [
37 // Engine protocol, model cache, configuration reading, FakeEngine. No MLX.39 // Engine protocol, model cache, configuration reading, FakeEngine. No MLX.
@@ -57,6 +59,7 @@ let package = Package(
57 dependencies: [59 dependencies: [
58 "RazorbillCore",60 "RazorbillCore",
59 .product(name: "Hummingbird", package: "hummingbird"),61 .product(name: "Hummingbird", package: "hummingbird"),
62+ .product(name: "ServiceLifecycle", package: "swift-service-lifecycle"),
60 ]63 ]
61 ),64 ),
62 // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.65 // Command-line front-end: `rzb serve`, `rzb models`, `rzb version`.
modified Sources/RazorbillCLI/CLIEnvironment.swift +10 -4
@@ -30,13 +30,17 @@ public struct CLIEnvironment: Sendable {
3030
3131 public init(
3232 engines: EngineRegistry, console: any Console, modelStore: ModelStore,
33- variables: [String: String] = [:], serve: @escaping ServerRunner = Self.runServer
33+ variables: [String: String] = [:], serve: ServerRunner? = nil
3434 ) {
3535 self.engines = engines
3636 self.console = console
3737 self.modelStore = modelStore
3838 self.variables = variables
39- self.serve = serve
39+ self.serve =
40+ serve ?? { settings, onRunning in
41+ try await Self.runServer(
42+ settings, engines: engines, store: modelStore, onRunning: onRunning)
43+ }
4044 }
4145
4246 /// The real terminal, model cache, environment variables and server, with the given engines.
@@ -48,13 +52,15 @@ public struct CLIEnvironment: Sendable {
4852
4953 /// Runs ``RazorbillServer`` with request logs on standard error.
5054 public static func runServer(
51- _ settings: ServerSettings, onRunning: @escaping @Sendable (Int) async -> Void
55+ _ settings: ServerSettings, engines: EngineRegistry, store: ModelStore,
56+ onRunning: @escaping @Sendable (Int) async -> Void
5257 ) async throws {
5358 var logger = Logger(label: Razorbill.commandName) { label in
5459 StreamLogHandler.standardError(label: label)
5560 }
5661 logger.logLevel = .info
57- try await RazorbillServer.run(settings, logger: logger, onRunning: onRunning)
62+ try await RazorbillServer.run(
63+ settings, engines: engines, store: store, logger: logger, onRunning: onRunning)
5864 }
5965
6066 /// The environment the running command uses.
@@ -30,13 +30,17 @@ public struct CLIEnvironment: Sendable {
30 30
31 public init(31 public init(
32 engines: EngineRegistry, console: any Console, modelStore: ModelStore,32 engines: EngineRegistry, console: any Console, modelStore: ModelStore,
33- variables: [String: String] = [:], serve: @escaping ServerRunner = Self.runServer33+ variables: [String: String] = [:], serve: ServerRunner? = nil
34 ) {34 ) {
35 self.engines = engines35 self.engines = engines
36 self.console = console36 self.console = console
37 self.modelStore = modelStore37 self.modelStore = modelStore
38 self.variables = variables38 self.variables = variables
39- self.serve = serve39+ self.serve =
40+ serve ?? { settings, onRunning in
41+ try await Self.runServer(
42+ settings, engines: engines, store: modelStore, onRunning: onRunning)
43+ }
40 }44 }
41 45
42 /// The real terminal, model cache, environment variables and server, with the given engines.46 /// The real terminal, model cache, environment variables and server, with the given engines.
@@ -48,13 +52,15 @@ public struct CLIEnvironment: Sendable {
48 52
49 /// Runs ``RazorbillServer`` with request logs on standard error.53 /// Runs ``RazorbillServer`` with request logs on standard error.
50 public static func runServer(54 public static func runServer(
51- _ settings: ServerSettings, onRunning: @escaping @Sendable (Int) async -> Void55+ _ settings: ServerSettings, engines: EngineRegistry, store: ModelStore,
56+ onRunning: @escaping @Sendable (Int) async -> Void
52 ) async throws {57 ) async throws {
53 var logger = Logger(label: Razorbill.commandName) { label in58 var logger = Logger(label: Razorbill.commandName) { label in
54 StreamLogHandler.standardError(label: label)59 StreamLogHandler.standardError(label: label)
55 }60 }
56 logger.logLevel = .info61 logger.logLevel = .info
57- try await RazorbillServer.run(settings, logger: logger, onRunning: onRunning)62+ try await RazorbillServer.run(
63+ settings, engines: engines, store: store, logger: logger, onRunning: onRunning)
58 }64 }
59 65
60 /// The environment the running command uses.66 /// The environment the running command uses.
modified Sources/RazorbillCore/Engine/FakeEngine.swift +7 -0
@@ -15,6 +15,7 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable {
1515 private var received: [[ChatMessage]] = []
1616 private var setups: [SessionSetup] = []
1717 private var loaded: [ModelReference] = []
18+ private var unloads = 0
1819 /// When set, ``load(_:offline:progress:)`` throws it.
1920 public var loadError: (any Error)?
2021
@@ -28,6 +29,12 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable {
2829 public var sessionSetups: [SessionSetup] { lock.withLock { setups } }
2930 /// The models loaded.
3031 public var loadedModels: [ModelReference] { lock.withLock { loaded } }
32+ /// How many times ``unload()`` was called.
33+ public var unloadCount: Int { lock.withLock { unloads } }
34+
35+ public func unload() async {
36+ lock.withLock { unloads += 1 }
37+ }
3138
3239 public func load(
3340 _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void
@@ -15,6 +15,7 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable {
15 private var received: [[ChatMessage]] = []15 private var received: [[ChatMessage]] = []
16 private var setups: [SessionSetup] = []16 private var setups: [SessionSetup] = []
17 private var loaded: [ModelReference] = []17 private var loaded: [ModelReference] = []
18+ private var unloads = 0
18 /// When set, ``load(_:offline:progress:)`` throws it.19 /// When set, ``load(_:offline:progress:)`` throws it.
19 public var loadError: (any Error)?20 public var loadError: (any Error)?
20 21
@@ -28,6 +29,12 @@ public final class FakeEngine: InferenceEngine, @unchecked Sendable {
28 public var sessionSetups: [SessionSetup] { lock.withLock { setups } }29 public var sessionSetups: [SessionSetup] { lock.withLock { setups } }
29 /// The models loaded.30 /// The models loaded.
30 public var loadedModels: [ModelReference] { lock.withLock { loaded } }31 public var loadedModels: [ModelReference] { lock.withLock { loaded } }
32+ /// How many times ``unload()`` was called.
33+ public var unloadCount: Int { lock.withLock { unloads } }
34+
35+ public func unload() async {
36+ lock.withLock { unloads += 1 }
37+ }
31 38
32 public func load(39 public func load(
33 _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void40 _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void
modified Sources/RazorbillCore/Engine/InferenceEngine.swift +8 -0
@@ -48,6 +48,14 @@ public protocol InferenceEngine: Sendable {
4848
4949 /// Starts a conversation. Requires a loaded model.
5050 func makeSession(_ setup: SessionSetup) async throws -> any EngineSession
51+
52+ /// Frees the loaded model. The server calls it before dropping the engine.
53+ func unload() async
54+}
55+
56+extension InferenceEngine {
57+ /// Engines that hold nothing worth freeing early do nothing.
58+ public func unload() async {}
5159 }
5260
5361 /// One conversation with a loaded model. It keeps the history (and the model's cache), so each
@@ -48,6 +48,14 @@ public protocol InferenceEngine: Sendable {
48 48
49 /// Starts a conversation. Requires a loaded model.49 /// Starts a conversation. Requires a loaded model.
50 func makeSession(_ setup: SessionSetup) async throws -> any EngineSession50 func makeSession(_ setup: SessionSetup) async throws -> any EngineSession
51+
52+ /// Frees the loaded model. The server calls it before dropping the engine.
53+ func unload() async
54+}
55+
56+extension InferenceEngine {
57+ /// Engines that hold nothing worth freeing early do nothing.
58+ public func unload() async {}
51 }59 }
52 60
53 /// One conversation with a loaded model. It keeps the history (and the model's cache), so each61 /// One conversation with a loaded model. It keeps the history (and the model's cache), so each
modified Sources/RazorbillCore/Models/ModelStore.swift +35 -0
@@ -102,6 +102,41 @@ public struct ModelStore: Sendable {
102102 }
103103 }
104104
105+ /// Bytes of `.safetensors` weights of `model` on disk (following the cache's symbolic links),
106+ /// or `nil` when none are there yet. Roughly the memory the model takes once loaded.
107+ public func weightsSize(of model: ModelReference) -> Int64? {
108+ let folder: URL?
109+ switch model {
110+ case .huggingFace(let id, let revision): folder = snapshot(id: id, revision: revision)
111+ case .local(let path): folder = path
112+ }
113+ guard let folder,
114+ let files = try? FileManager.default.contentsOfDirectory(atPath: folder.path)
115+ else { return nil }
116+ let weights = files.filter { $0.hasSuffix(".safetensors") }
117+ guard !weights.isEmpty else { return nil }
118+ return weights.reduce(Int64(0)) { total, file in
119+ let path = folder.appendingPathComponent(file).resolvingSymlinksInPath().path
120+ let size =
121+ (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? NSNumber
122+ return total + (size?.int64Value ?? 0)
123+ }
124+ }
125+
126+ /// The repository has a snapshot with a `config.json` but no `.safetensors` weights: it was
127+ /// downloaded with razorbill's file patterns and is not an MLX model (GGUF, PyTorch .bin…).
128+ public func lacksMLXWeights(id: String) -> Bool {
129+ let snapshots = directory(for: id).appendingPathComponent("snapshots")
130+ let commits = (try? FileManager.default.contentsOfDirectory(atPath: snapshots.path)) ?? []
131+ guard !commits.isEmpty else { return false }
132+ return commits.allSatisfy { commit in
133+ let files =
134+ (try? FileManager.default.contentsOfDirectory(
135+ atPath: snapshots.appendingPathComponent(commit).path)) ?? []
136+ return files.contains("config.json") && !files.contains { $0.hasSuffix(".safetensors") }
137+ }
138+ }
139+
105140 /// Deletes every file of repository `id` from the cache.
106141 public func remove(id: String) throws {
107142 let repository = directory(for: id)
@@ -102,6 +102,41 @@ public struct ModelStore: Sendable {
102 }102 }
103 }103 }
104 104
105+ /// Bytes of `.safetensors` weights of `model` on disk (following the cache's symbolic links),
106+ /// or `nil` when none are there yet. Roughly the memory the model takes once loaded.
107+ public func weightsSize(of model: ModelReference) -> Int64? {
108+ let folder: URL?
109+ switch model {
110+ case .huggingFace(let id, let revision): folder = snapshot(id: id, revision: revision)
111+ case .local(let path): folder = path
112+ }
113+ guard let folder,
114+ let files = try? FileManager.default.contentsOfDirectory(atPath: folder.path)
115+ else { return nil }
116+ let weights = files.filter { $0.hasSuffix(".safetensors") }
117+ guard !weights.isEmpty else { return nil }
118+ return weights.reduce(Int64(0)) { total, file in
119+ let path = folder.appendingPathComponent(file).resolvingSymlinksInPath().path
120+ let size =
121+ (try? FileManager.default.attributesOfItem(atPath: path))?[.size] as? NSNumber
122+ return total + (size?.int64Value ?? 0)
123+ }
124+ }
125+
126+ /// The repository has a snapshot with a `config.json` but no `.safetensors` weights: it was
127+ /// downloaded with razorbill's file patterns and is not an MLX model (GGUF, PyTorch .bin…).
128+ public func lacksMLXWeights(id: String) -> Bool {
129+ let snapshots = directory(for: id).appendingPathComponent("snapshots")
130+ let commits = (try? FileManager.default.contentsOfDirectory(atPath: snapshots.path)) ?? []
131+ guard !commits.isEmpty else { return false }
132+ return commits.allSatisfy { commit in
133+ let files =
134+ (try? FileManager.default.contentsOfDirectory(
135+ atPath: snapshots.appendingPathComponent(commit).path)) ?? []
136+ return files.contains("config.json") && !files.contains { $0.hasSuffix(".safetensors") }
137+ }
138+ }
139+
105 /// Deletes every file of repository `id` from the cache.140 /// Deletes every file of repository `id` from the cache.
106 public func remove(id: String) throws {141 public func remove(id: String) throws {
107 let repository = directory(for: id)142 let repository = directory(for: id)
modified Sources/RazorbillMLX/MLXEngine.swift +5 -0
@@ -56,6 +56,11 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable {
5656 useLatest: true, progressHandler: { progress($0.fractionCompleted) })
5757 }
5858
59+ /// Drops the model; its weights are freed once no session uses them any more.
60+ public func unload() async {
61+ lock.withLock { container = nil }
62+ }
63+
5964 public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession {
6065 guard let container = lock.withLock({ container }) else { throw NotLoaded() }
6166 let parameters = GenerateParameters(
@@ -56,6 +56,11 @@ public final class MLXEngine: InferenceEngine, @unchecked Sendable {
56 useLatest: true, progressHandler: { progress($0.fractionCompleted) })56 useLatest: true, progressHandler: { progress($0.fractionCompleted) })
57 }57 }
58 58
59+ /// Drops the model; its weights are freed once no session uses them any more.
60+ public func unload() async {
61+ lock.withLock { container = nil }
62+ }
63+
59 public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession {64 public func makeSession(_ setup: SessionSetup) async throws -> any EngineSession {
60 guard let container = lock.withLock({ container }) else { throw NotLoaded() }65 guard let container = lock.withLock({ container }) else { throw NotLoaded() }
61 let parameters = GenerateParameters(66 let parameters = GenerateParameters(
added Sources/RazorbillServer/ModelLifecycleService.swift +30 -0
new file mode 100644
@@ -0,0 +1,30 @@
1+import Logging
2+import ServiceLifecycle
3+
4+/// Runs next to the HTTP server: preloads the `preload` models, unloads idle ones every
5+/// little while, and unloads everything when the server shuts down.
6+struct ModelLifecycleService: Service {
7+ let models: ModelManager
8+ /// How often idle models are looked for: a fraction of keep_alive, at most 30 s.
9+ let interval: Duration
10+
11+ init(models: ModelManager) {
12+ self.models = models
13+ interval = min(models.limitsKeepAlive / 4, .seconds(30))
14+ }
15+
16+ func run() async throws {
17+ await models.preload()
18+ await cancelWhenGracefulShutdown {
19+ while !Task.isCancelled {
20+ try? await Task.sleep(for: interval)
21+ await models.unloadIdle()
22+ }
23+ }
24+ await models.unloadAll()
25+ }
26+}
27+
28+extension ModelManager {
29+ nonisolated var limitsKeepAlive: Duration { catalog.config.limits.keepAlive }
30+}
new file mode 100644
@@ -0,0 +1,30 @@
1+import Logging
2+import ServiceLifecycle
3+
4+/// Runs next to the HTTP server: preloads the `preload` models, unloads idle ones every
5+/// little while, and unloads everything when the server shuts down.
6+struct ModelLifecycleService: Service {
7+ let models: ModelManager
8+ /// How often idle models are looked for: a fraction of keep_alive, at most 30 s.
9+ let interval: Duration
10+
11+ init(models: ModelManager) {
12+ self.models = models
13+ interval = min(models.limitsKeepAlive / 4, .seconds(30))
14+ }
15+
16+ func run() async throws {
17+ await models.preload()
18+ await cancelWhenGracefulShutdown {
19+ while !Task.isCancelled {
20+ try? await Task.sleep(for: interval)
21+ await models.unloadIdle()
22+ }
23+ }
24+ await models.unloadAll()
25+ }
26+}
27+
28+extension ModelManager {
29+ nonisolated var limitsKeepAlive: Duration { catalog.config.limits.keepAlive }
30+}
added Sources/RazorbillServer/ModelManager.swift +292 -0
new file mode 100644
@@ -0,0 +1,292 @@
1+import Foundation
2+import Logging
3+import RazorbillCore
4+
5+/// Why a request could not get its model.
6+public enum ModelManagerError: Error, Sendable, Equatable, CustomStringConvertible {
7+ /// `limit` requests are already waiting for this model.
8+ case queueFull(model: String, limit: Int)
9+ /// Every loaded model is busy, so none can be unloaded to make room.
10+ case allModelsBusy(model: String)
11+ /// The model does not fit in the memory razorbill may use, even after unloading idle models.
12+ case insufficientMemory(model: String, needed: Int64, available: Int64)
13+ /// The engine failed to download or load the model.
14+ case loadFailed(model: String, reason: String)
15+
16+ public var description: String {
17+ switch self {
18+ case .queueFull(let model, let limit):
19+ "too many requests waiting for '\(model)' (max_queue: \(limit)); retry later"
20+ case .allModelsBusy(let model):
21+ "cannot load '\(model)': every loaded model is busy (max_loaded_models reached); retry later"
22+ case .insufficientMemory(let model, let needed, let available):
23+ "'\(model)' needs about \(Self.gigabytes(needed)) of memory, "
24+ + "only \(Self.gigabytes(available)) can be freed for it"
25+ case .loadFailed(let model, let reason):
26+ "cannot load '\(model)': \(reason)"
27+ }
28+ }
29+
30+ static func gigabytes(_ bytes: Int64) -> String {
31+ String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
32+ }
33+}
34+
35+/// The right to use one loaded model. Requests for the same model run one at a time: release
36+/// the lease when the answer is complete so the next request can start.
37+public struct ModelLease: Sendable {
38+ public let model: ResolvedModel
39+ public let engine: any InferenceEngine
40+ let key: String
41+ let manager: ModelManager
42+
43+ public func release() async {
44+ await manager.release(key)
45+ }
46+}
47+
48+/// Loads models on demand and keeps the server within its limits (ticket #34).
49+///
50+/// - A model is loaded on its first request (or at start-up with `preload`), once, and shared.
51+/// - Requests for one model are served one at a time, in arrival order; at most
52+/// `limits.maxQueue` wait, the next ones get ``ModelManagerError/queueFull(model:limit:)``.
53+/// - Beyond `limits.maxLoadedModels`, or when memory runs short, the least recently used idle
54+/// model is unloaded first.
55+/// - ``unloadIdle(now:)`` unloads models unused for `limits.keepAlive`.
56+///
57+/// ```swift
58+/// let lease = try await manager.acquire("qwen3")
59+/// defer { Task { await lease.release() } }
60+/// let session = try await lease.engine.makeSession(setup)
61+/// ```
62+public actor ModelManager {
63+ public typealias EngineFactory = @Sendable () throws -> any InferenceEngine
64+
65+ public nonisolated let catalog: ModelCatalog
66+ let limits: ServerLimits
67+ let makeEngine: EngineFactory
68+ let memoryBudget: Int64
69+ let logger: Logger
70+
71+ private var slots: [String: Slot] = [:]
72+
73+ /// A request waiting for its turn.
74+ private typealias Waiter = CheckedContinuation<Void, any Error>
75+
76+ /// One model, loaded or not, with its queue.
77+ private struct Slot {
78+ var model: ResolvedModel
79+ var engine: (any InferenceEngine)?
80+ /// Bytes of weights, when known.
81+ var size: Int64 = 0
82+ /// A request holds the model (loading it or generating).
83+ var busy = false
84+ var waiters: [(id: UUID, continuation: Waiter)] = []
85+ var lastUsed = ContinuousClock.now
86+
87+ var isIdle: Bool { !busy && waiters.isEmpty }
88+ }
89+
90+ /// - Parameter memoryBudget: bytes of model weights razorbill may keep loaded; default 75 %
91+ /// of the physical memory (Apple Silicon shares it between CPU and GPU).
92+ public init(
93+ catalog: ModelCatalog, limits: ServerLimits, memoryBudget: Int64? = nil,
94+ logger: Logger = Logger(label: "rzb"), makeEngine: @escaping EngineFactory
95+ ) {
96+ self.catalog = catalog
97+ self.limits = limits
98+ self.memoryBudget = memoryBudget ?? Int64(ProcessInfo.processInfo.physicalMemory / 4 * 3)
99+ self.logger = logger
100+ self.makeEngine = makeEngine
101+ }
102+
103+ // MARK: Requests
104+
105+ /// Waits for the model's turn, loads it if needed and hands it over. Cancelling the calling
106+ /// task while it waits removes it from the queue.
107+ public func acquire(_ name: String) async throws -> ModelLease {
108+ let model = try catalog.resolve(name)
109+ let key = model.source.description
110+ try await takeTurn(key: key, model: model)
111+ do {
112+ let engine = try await loadedEngine(key: key)
113+ return ModelLease(model: model, engine: engine, key: key, manager: self)
114+ } catch {
115+ release(key)
116+ throw error
117+ }
118+ }
119+
120+ /// Runs `body` with the model, releasing it afterwards.
121+ public func withModel<T: Sendable>(
122+ _ name: String, _ body: @Sendable (ModelLease) async throws -> T
123+ ) async throws -> T {
124+ let lease = try await acquire(name)
125+ do {
126+ let result = try await body(lease)
127+ await lease.release()
128+ return result
129+ } catch {
130+ await lease.release()
131+ throw error
132+ }
133+ }
134+
135+ /// Ends a turn: the next waiting request gets the model, or it becomes idle.
136+ func release(_ key: String) {
137+ guard var slot = slots[key] else { return }
138+ slot.lastUsed = .now
139+ if slot.waiters.isEmpty {
140+ slot.busy = false
141+ slots[key] = slot
142+ } else {
143+ let next = slot.waiters.removeFirst()
144+ slots[key] = slot
145+ next.continuation.resume()
146+ }
147+ }
148+
149+ private func takeTurn(key: String, model: ResolvedModel) async throws {
150+ var slot = slots[key] ?? Slot(model: model)
151+ guard slot.busy else {
152+ slot.busy = true
153+ slots[key] = slot
154+ return
155+ }
156+ guard slot.waiters.count < limits.maxQueue else {
157+ throw ModelManagerError.queueFull(model: model.name, limit: limits.maxQueue)
158+ }
159+ let id = UUID()
160+ try await withTaskCancellationHandler {
161+ try await withCheckedThrowingContinuation { (continuation: Waiter) in
162+ enqueue(key: key, id: id, continuation: continuation)
163+ }
164+ } onCancel: {
165+ Task { await self.cancelWaiter(key: key, id: id) }
166+ }
167+ }
168+
169+ /// Adds a waiter, unless its task was cancelled before it could be queued.
170+ private func enqueue(key: String, id: UUID, continuation: Waiter) {
171+ if Task.isCancelled {
172+ continuation.resume(throwing: CancellationError())
173+ } else {
174+ slots[key]?.waiters.append((id, continuation))
175+ }
176+ }
177+
178+ private func cancelWaiter(key: String, id: UUID) {
179+ guard let index = slots[key]?.waiters.firstIndex(where: { $0.id == id }) else { return }
180+ let waiter = slots[key]?.waiters.remove(at: index)
181+ waiter?.continuation.resume(throwing: CancellationError())
182+ }
183+
184+ // MARK: Loading
185+
186+ /// The slot's engine, loading the model first when needed. Called while holding the turn.
187+ private func loadedEngine(key: String) async throws -> any InferenceEngine {
188+ guard let slot = slots[key] else { throw CancellationError() }
189+ if let engine = slot.engine { return engine }
190+ let model = slot.model
191+ let size = catalog.store.weightsSize(of: model.source) ?? 0
192+ try await makeRoom(for: key, model: model.name, size: size)
193+ let engine: any InferenceEngine
194+ do {
195+ engine = try makeEngine()
196+ let start = ContinuousClock.now
197+ try await engine.load(model.source, offline: false) { _ in }
198+ logger.info("loaded \(model.source) in \(ContinuousClock.now - start)")
199+ } catch {
200+ throw loadError(error, model: model)
201+ }
202+ slots[key]?.engine = engine
203+ // Downloaded just now: its size is known only after the download.
204+ slots[key]?.size = catalog.store.weightsSize(of: model.source) ?? size
205+ return engine
206+ }
207+
208+ /// Unloads least recently used idle models until `key` fits, or fails.
209+ private func makeRoom(for key: String, model: String, size: Int64) async throws {
210+ if size > memoryBudget {
211+ throw ModelManagerError.insufficientMemory(
212+ model: model, needed: size, available: memoryBudget)
213+ }
214+ while true {
215+ let loaded = slots.filter { $0.key != key && $0.value.engine != nil }
216+ let used = loaded.values.reduce(Int64(0)) { $0 + $1.size }
217+ let fits = loaded.count < limits.maxLoadedModels && used + size <= memoryBudget
218+ if fits { return }
219+ let idle = loaded.filter { $0.value.isIdle }
220+ guard let victim = idle.min(by: { $0.value.lastUsed < $1.value.lastUsed })?.key else {
221+ if loaded.count >= limits.maxLoadedModels {
222+ throw ModelManagerError.allModelsBusy(model: model)
223+ }
224+ throw ModelManagerError.insufficientMemory(
225+ model: model, needed: size, available: memoryBudget - used)
226+ }
227+ await unload(victim, reason: "to make room for \(model)")
228+ }
229+ }
230+
231+ private func loadError(_ error: any Error, model: ResolvedModel) -> any Error {
232+ if error is CancellationError { return error }
233+ if case .huggingFace(let id, _) = model.source, catalog.store.lacksMLXWeights(id: id) {
234+ return ModelResolutionError.notMLX(id)
235+ }
236+ return ModelManagerError.loadFailed(model: model.name, reason: "\(error)")
237+ }
238+
239+ private func unload(_ key: String, reason: String) async {
240+ guard let engine = slots[key]?.engine else { return }
241+ slots[key]?.engine = nil
242+ slots[key]?.size = 0
243+ if slots[key]?.isIdle == true {
244+ slots[key] = nil
245+ }
246+ await engine.unload()
247+ logger.info("unloaded \(key) (\(reason))")
248+ }
249+
250+ // MARK: Housekeeping
251+
252+ /// Loads the declared models marked `preload`. Failures are logged, not fatal.
253+ public func preload() async {
254+ for entry in catalog.config.models where entry.preload {
255+ do {
256+ let lease = try await acquire(entry.id)
257+ await lease.release()
258+ } catch {
259+ logger.error("cannot preload \(entry.id): \(error)")
260+ }
261+ }
262+ }
263+
264+ /// Unloads the models idle for at least `limits.keepAlive`.
265+ public func unloadIdle(now: ContinuousClock.Instant = .now) async {
266+ let expired = slots.filter { slot in
267+ slot.value.engine != nil && slot.value.isIdle
268+ && now - slot.value.lastUsed >= limits.keepAlive
269+ }
270+ for key in expired.keys {
271+ await unload(key, reason: "idle for \(limits.keepAlive)")
272+ }
273+ }
274+
275+ /// Unloads everything (server shutdown).
276+ public func unloadAll() async {
277+ for key in slots.keys where slots[key]?.engine != nil {
278+ await unload(key, reason: "shutdown")
279+ }
280+ }
281+
282+ /// Requests waiting for `name` (tests and diagnostics).
283+ func queueLength(_ name: String) throws -> Int {
284+ let key = try catalog.resolve(name).source.description
285+ return slots[key]?.waiters.count ?? 0
286+ }
287+
288+ /// Sources of the models currently loaded, as `ModelReference.description`.
289+ public func loadedSources() -> Set<String> {
290+ Set(slots.filter { $0.value.engine != nil }.keys)
291+ }
292+}
new file mode 100644
@@ -0,0 +1,292 @@
1+import Foundation
2+import Logging
3+import RazorbillCore
4+
5+/// Why a request could not get its model.
6+public enum ModelManagerError: Error, Sendable, Equatable, CustomStringConvertible {
7+ /// `limit` requests are already waiting for this model.
8+ case queueFull(model: String, limit: Int)
9+ /// Every loaded model is busy, so none can be unloaded to make room.
10+ case allModelsBusy(model: String)
11+ /// The model does not fit in the memory razorbill may use, even after unloading idle models.
12+ case insufficientMemory(model: String, needed: Int64, available: Int64)
13+ /// The engine failed to download or load the model.
14+ case loadFailed(model: String, reason: String)
15+
16+ public var description: String {
17+ switch self {
18+ case .queueFull(let model, let limit):
19+ "too many requests waiting for '\(model)' (max_queue: \(limit)); retry later"
20+ case .allModelsBusy(let model):
21+ "cannot load '\(model)': every loaded model is busy (max_loaded_models reached); retry later"
22+ case .insufficientMemory(let model, let needed, let available):
23+ "'\(model)' needs about \(Self.gigabytes(needed)) of memory, "
24+ + "only \(Self.gigabytes(available)) can be freed for it"
25+ case .loadFailed(let model, let reason):
26+ "cannot load '\(model)': \(reason)"
27+ }
28+ }
29+
30+ static func gigabytes(_ bytes: Int64) -> String {
31+ String(format: "%.1f GB", Double(bytes) / 1_073_741_824)
32+ }
33+}
34+
35+/// The right to use one loaded model. Requests for the same model run one at a time: release
36+/// the lease when the answer is complete so the next request can start.
37+public struct ModelLease: Sendable {
38+ public let model: ResolvedModel
39+ public let engine: any InferenceEngine
40+ let key: String
41+ let manager: ModelManager
42+
43+ public func release() async {
44+ await manager.release(key)
45+ }
46+}
47+
48+/// Loads models on demand and keeps the server within its limits (ticket #34).
49+///
50+/// - A model is loaded on its first request (or at start-up with `preload`), once, and shared.
51+/// - Requests for one model are served one at a time, in arrival order; at most
52+/// `limits.maxQueue` wait, the next ones get ``ModelManagerError/queueFull(model:limit:)``.
53+/// - Beyond `limits.maxLoadedModels`, or when memory runs short, the least recently used idle
54+/// model is unloaded first.
55+/// - ``unloadIdle(now:)`` unloads models unused for `limits.keepAlive`.
56+///
57+/// ```swift
58+/// let lease = try await manager.acquire("qwen3")
59+/// defer { Task { await lease.release() } }
60+/// let session = try await lease.engine.makeSession(setup)
61+/// ```
62+public actor ModelManager {
63+ public typealias EngineFactory = @Sendable () throws -> any InferenceEngine
64+
65+ public nonisolated let catalog: ModelCatalog
66+ let limits: ServerLimits
67+ let makeEngine: EngineFactory
68+ let memoryBudget: Int64
69+ let logger: Logger
70+
71+ private var slots: [String: Slot] = [:]
72+
73+ /// A request waiting for its turn.
74+ private typealias Waiter = CheckedContinuation<Void, any Error>
75+
76+ /// One model, loaded or not, with its queue.
77+ private struct Slot {
78+ var model: ResolvedModel
79+ var engine: (any InferenceEngine)?
80+ /// Bytes of weights, when known.
81+ var size: Int64 = 0
82+ /// A request holds the model (loading it or generating).
83+ var busy = false
84+ var waiters: [(id: UUID, continuation: Waiter)] = []
85+ var lastUsed = ContinuousClock.now
86+
87+ var isIdle: Bool { !busy && waiters.isEmpty }
88+ }
89+
90+ /// - Parameter memoryBudget: bytes of model weights razorbill may keep loaded; default 75 %
91+ /// of the physical memory (Apple Silicon shares it between CPU and GPU).
92+ public init(
93+ catalog: ModelCatalog, limits: ServerLimits, memoryBudget: Int64? = nil,
94+ logger: Logger = Logger(label: "rzb"), makeEngine: @escaping EngineFactory
95+ ) {
96+ self.catalog = catalog
97+ self.limits = limits
98+ self.memoryBudget = memoryBudget ?? Int64(ProcessInfo.processInfo.physicalMemory / 4 * 3)
99+ self.logger = logger
100+ self.makeEngine = makeEngine
101+ }
102+
103+ // MARK: Requests
104+
105+ /// Waits for the model's turn, loads it if needed and hands it over. Cancelling the calling
106+ /// task while it waits removes it from the queue.
107+ public func acquire(_ name: String) async throws -> ModelLease {
108+ let model = try catalog.resolve(name)
109+ let key = model.source.description
110+ try await takeTurn(key: key, model: model)
111+ do {
112+ let engine = try await loadedEngine(key: key)
113+ return ModelLease(model: model, engine: engine, key: key, manager: self)
114+ } catch {
115+ release(key)
116+ throw error
117+ }
118+ }
119+
120+ /// Runs `body` with the model, releasing it afterwards.
121+ public func withModel<T: Sendable>(
122+ _ name: String, _ body: @Sendable (ModelLease) async throws -> T
123+ ) async throws -> T {
124+ let lease = try await acquire(name)
125+ do {
126+ let result = try await body(lease)
127+ await lease.release()
128+ return result
129+ } catch {
130+ await lease.release()
131+ throw error
132+ }
133+ }
134+
135+ /// Ends a turn: the next waiting request gets the model, or it becomes idle.
136+ func release(_ key: String) {
137+ guard var slot = slots[key] else { return }
138+ slot.lastUsed = .now
139+ if slot.waiters.isEmpty {
140+ slot.busy = false
141+ slots[key] = slot
142+ } else {
143+ let next = slot.waiters.removeFirst()
144+ slots[key] = slot
145+ next.continuation.resume()
146+ }
147+ }
148+
149+ private func takeTurn(key: String, model: ResolvedModel) async throws {
150+ var slot = slots[key] ?? Slot(model: model)
151+ guard slot.busy else {
152+ slot.busy = true
153+ slots[key] = slot
154+ return
155+ }
156+ guard slot.waiters.count < limits.maxQueue else {
157+ throw ModelManagerError.queueFull(model: model.name, limit: limits.maxQueue)
158+ }
159+ let id = UUID()
160+ try await withTaskCancellationHandler {
161+ try await withCheckedThrowingContinuation { (continuation: Waiter) in
162+ enqueue(key: key, id: id, continuation: continuation)
163+ }
164+ } onCancel: {
165+ Task { await self.cancelWaiter(key: key, id: id) }
166+ }
167+ }
168+
169+ /// Adds a waiter, unless its task was cancelled before it could be queued.
170+ private func enqueue(key: String, id: UUID, continuation: Waiter) {
171+ if Task.isCancelled {
172+ continuation.resume(throwing: CancellationError())
173+ } else {
174+ slots[key]?.waiters.append((id, continuation))
175+ }
176+ }
177+
178+ private func cancelWaiter(key: String, id: UUID) {
179+ guard let index = slots[key]?.waiters.firstIndex(where: { $0.id == id }) else { return }
180+ let waiter = slots[key]?.waiters.remove(at: index)
181+ waiter?.continuation.resume(throwing: CancellationError())
182+ }
183+
184+ // MARK: Loading
185+
186+ /// The slot's engine, loading the model first when needed. Called while holding the turn.
187+ private func loadedEngine(key: String) async throws -> any InferenceEngine {
188+ guard let slot = slots[key] else { throw CancellationError() }
189+ if let engine = slot.engine { return engine }
190+ let model = slot.model
191+ let size = catalog.store.weightsSize(of: model.source) ?? 0
192+ try await makeRoom(for: key, model: model.name, size: size)
193+ let engine: any InferenceEngine
194+ do {
195+ engine = try makeEngine()
196+ let start = ContinuousClock.now
197+ try await engine.load(model.source, offline: false) { _ in }
198+ logger.info("loaded \(model.source) in \(ContinuousClock.now - start)")
199+ } catch {
200+ throw loadError(error, model: model)
201+ }
202+ slots[key]?.engine = engine
203+ // Downloaded just now: its size is known only after the download.
204+ slots[key]?.size = catalog.store.weightsSize(of: model.source) ?? size
205+ return engine
206+ }
207+
208+ /// Unloads least recently used idle models until `key` fits, or fails.
209+ private func makeRoom(for key: String, model: String, size: Int64) async throws {
210+ if size > memoryBudget {
211+ throw ModelManagerError.insufficientMemory(
212+ model: model, needed: size, available: memoryBudget)
213+ }
214+ while true {
215+ let loaded = slots.filter { $0.key != key && $0.value.engine != nil }
216+ let used = loaded.values.reduce(Int64(0)) { $0 + $1.size }
217+ let fits = loaded.count < limits.maxLoadedModels && used + size <= memoryBudget
218+ if fits { return }
219+ let idle = loaded.filter { $0.value.isIdle }
220+ guard let victim = idle.min(by: { $0.value.lastUsed < $1.value.lastUsed })?.key else {
221+ if loaded.count >= limits.maxLoadedModels {
222+ throw ModelManagerError.allModelsBusy(model: model)
223+ }
224+ throw ModelManagerError.insufficientMemory(
225+ model: model, needed: size, available: memoryBudget - used)
226+ }
227+ await unload(victim, reason: "to make room for \(model)")
228+ }
229+ }
230+
231+ private func loadError(_ error: any Error, model: ResolvedModel) -> any Error {
232+ if error is CancellationError { return error }
233+ if case .huggingFace(let id, _) = model.source, catalog.store.lacksMLXWeights(id: id) {
234+ return ModelResolutionError.notMLX(id)
235+ }
236+ return ModelManagerError.loadFailed(model: model.name, reason: "\(error)")
237+ }
238+
239+ private func unload(_ key: String, reason: String) async {
240+ guard let engine = slots[key]?.engine else { return }
241+ slots[key]?.engine = nil
242+ slots[key]?.size = 0
243+ if slots[key]?.isIdle == true {
244+ slots[key] = nil
245+ }
246+ await engine.unload()
247+ logger.info("unloaded \(key) (\(reason))")
248+ }
249+
250+ // MARK: Housekeeping
251+
252+ /// Loads the declared models marked `preload`. Failures are logged, not fatal.
253+ public func preload() async {
254+ for entry in catalog.config.models where entry.preload {
255+ do {
256+ let lease = try await acquire(entry.id)
257+ await lease.release()
258+ } catch {
259+ logger.error("cannot preload \(entry.id): \(error)")
260+ }
261+ }
262+ }
263+
264+ /// Unloads the models idle for at least `limits.keepAlive`.
265+ public func unloadIdle(now: ContinuousClock.Instant = .now) async {
266+ let expired = slots.filter { slot in
267+ slot.value.engine != nil && slot.value.isIdle
268+ && now - slot.value.lastUsed >= limits.keepAlive
269+ }
270+ for key in expired.keys {
271+ await unload(key, reason: "idle for \(limits.keepAlive)")
272+ }
273+ }
274+
275+ /// Unloads everything (server shutdown).
276+ public func unloadAll() async {
277+ for key in slots.keys where slots[key]?.engine != nil {
278+ await unload(key, reason: "shutdown")
279+ }
280+ }
281+
282+ /// Requests waiting for `name` (tests and diagnostics).
283+ func queueLength(_ name: String) throws -> Int {
284+ let key = try catalog.resolve(name).source.description
285+ return slots[key]?.waiters.count ?? 0
286+ }
287+
288+ /// Sources of the models currently loaded, as `ModelReference.description`.
289+ public func loadedSources() -> Set<String> {
290+ Set(slots.filter { $0.value.engine != nil }.keys)
291+ }
292+}
added Sources/RazorbillServer/ModelRoutes.swift +77 -0
new file mode 100644
@@ -0,0 +1,77 @@
1+import Foundation
2+import Hummingbird
3+import RazorbillCore
4+
5+/// One entry of `GET /v1/models`, in OpenAI's shape plus razorbill's `loaded` and `kind`.
6+struct ModelObject: Encodable, Equatable {
7+ let id: String
8+ var object = "model"
9+ let created: Int
10+ var ownedBy = "razorbill"
11+ let loaded: Bool
12+ let kind: String
13+
14+ enum CodingKeys: String, CodingKey {
15+ case id, object, created, loaded, kind
16+ case ownedBy = "owned_by"
17+ }
18+}
19+
20+/// `GET /v1/models`: `{"object": "list", "data": [...]}`.
21+struct ModelList: Encodable {
22+ var object = "list"
23+ let data: [ModelObject]
24+}
25+
26+/// `GET /v1/models` and `GET /v1/models/{id}` (ids may contain `/`).
27+///
28+/// Lists the declared models, then every MLX model already in the Hugging Face cache (any of
29+/// them can be requested by its repository id), each with whether it is loaded right now.
30+struct ModelRoutes {
31+ let models: ModelManager
32+ /// Reported as `created` (Unix seconds): razorbill has no real creation date for a model.
33+ let created = Int(Date().timeIntervalSince1970)
34+
35+ func add(to router: Router<ServerContext>) {
36+ router.get("/v1/models") { _, _ in
37+ try jsonResponse(ModelList(data: await list()))
38+ }
39+ router.get("/v1/models/**") { _, context in
40+ let id = context.parameters.getCatchAll().joined(separator: "/")
41+ guard let model = await list().first(where: { $0.id == id }) else {
42+ throw OpenAIError.modelNotFound(id)
43+ }
44+ return try jsonResponse(model)
45+ }
46+ }
47+
48+ func list() async -> [ModelObject] {
49+ let loaded = await models.loadedSources()
50+ let config = models.catalog.config
51+ var result = config.models.map { entry in
52+ ModelObject(
53+ id: entry.id, created: created, loaded: loaded.contains(entry.source.description),
54+ kind: entry.kind.rawValue)
55+ }
56+ var listed = Set(result.map(\.id))
57+ let cached = ((try? models.catalog.store.list()) ?? []).filter(\.isLoadable).map(\.id)
58+ // Loaded undeclared models pinned to a revision (`org/name@rev`) are not in the cache
59+ // list; loaded declared models are already listed under their declared id.
60+ let declaredSources = Set(config.models.map(\.source.description))
61+ let loadedUndeclared = loaded.subtracting(declaredSources).sorted()
62+ for id in cached + loadedUndeclared where listed.insert(id).inserted {
63+ result.append(
64+ ModelObject(id: id, created: created, loaded: loaded.contains(id), kind: "chat"))
65+ }
66+ return result
67+ }
68+}
69+
70+/// A JSON response encoded like every other razorbill answer (sorted keys).
71+func jsonResponse(_ value: some Encodable, status: HTTPResponse.Status = .ok) throws -> Response {
72+ var headers = HTTPFields()
73+ headers[.contentType] = "application/json; charset=utf-8"
74+ let data = try JSONEncoder.openAI.encode(value)
75+ return Response(
76+ status: status, headers: headers, body: .init(byteBuffer: ByteBuffer(bytes: data)))
77+}
new file mode 100644
@@ -0,0 +1,77 @@
1+import Foundation
2+import Hummingbird
3+import RazorbillCore
4+
5+/// One entry of `GET /v1/models`, in OpenAI's shape plus razorbill's `loaded` and `kind`.
6+struct ModelObject: Encodable, Equatable {
7+ let id: String
8+ var object = "model"
9+ let created: Int
10+ var ownedBy = "razorbill"
11+ let loaded: Bool
12+ let kind: String
13+
14+ enum CodingKeys: String, CodingKey {
15+ case id, object, created, loaded, kind
16+ case ownedBy = "owned_by"
17+ }
18+}
19+
20+/// `GET /v1/models`: `{"object": "list", "data": [...]}`.
21+struct ModelList: Encodable {
22+ var object = "list"
23+ let data: [ModelObject]
24+}
25+
26+/// `GET /v1/models` and `GET /v1/models/{id}` (ids may contain `/`).
27+///
28+/// Lists the declared models, then every MLX model already in the Hugging Face cache (any of
29+/// them can be requested by its repository id), each with whether it is loaded right now.
30+struct ModelRoutes {
31+ let models: ModelManager
32+ /// Reported as `created` (Unix seconds): razorbill has no real creation date for a model.
33+ let created = Int(Date().timeIntervalSince1970)
34+
35+ func add(to router: Router<ServerContext>) {
36+ router.get("/v1/models") { _, _ in
37+ try jsonResponse(ModelList(data: await list()))
38+ }
39+ router.get("/v1/models/**") { _, context in
40+ let id = context.parameters.getCatchAll().joined(separator: "/")
41+ guard let model = await list().first(where: { $0.id == id }) else {
42+ throw OpenAIError.modelNotFound(id)
43+ }
44+ return try jsonResponse(model)
45+ }
46+ }
47+
48+ func list() async -> [ModelObject] {
49+ let loaded = await models.loadedSources()
50+ let config = models.catalog.config
51+ var result = config.models.map { entry in
52+ ModelObject(
53+ id: entry.id, created: created, loaded: loaded.contains(entry.source.description),
54+ kind: entry.kind.rawValue)
55+ }
56+ var listed = Set(result.map(\.id))
57+ let cached = ((try? models.catalog.store.list()) ?? []).filter(\.isLoadable).map(\.id)
58+ // Loaded undeclared models pinned to a revision (`org/name@rev`) are not in the cache
59+ // list; loaded declared models are already listed under their declared id.
60+ let declaredSources = Set(config.models.map(\.source.description))
61+ let loadedUndeclared = loaded.subtracting(declaredSources).sorted()
62+ for id in cached + loadedUndeclared where listed.insert(id).inserted {
63+ result.append(
64+ ModelObject(id: id, created: created, loaded: loaded.contains(id), kind: "chat"))
65+ }
66+ return result
67+ }
68+}
69+
70+/// A JSON response encoded like every other razorbill answer (sorted keys).
71+func jsonResponse(_ value: some Encodable, status: HTTPResponse.Status = .ok) throws -> Response {
72+ var headers = HTTPFields()
73+ headers[.contentType] = "application/json; charset=utf-8"
74+ let data = try JSONEncoder.openAI.encode(value)
75+ return Response(
76+ status: status, headers: headers, body: .init(byteBuffer: ByteBuffer(bytes: data)))
77+}
modified Sources/RazorbillServer/OpenAIError.swift +33 -0
@@ -1,5 +1,6 @@
11 import Foundation
22 import Hummingbird
3+import RazorbillCore
34
45 /// An error answered in OpenAI's format, so that OpenAI clients show the message:
56 ///
@@ -125,6 +126,10 @@ extension OpenAIError {
125126 switch error {
126127 case let error as OpenAIError:
127128 return error
129+ case let error as ModelResolutionError:
130+ return OpenAIError(model: error)
131+ case let error as ModelManagerError:
132+ return OpenAIError(manager: error)
128133 case let error as HTTPError:
129134 return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)
130135 case let error as any HTTPResponseError where error.status == .contentTooLarge:
@@ -137,6 +142,34 @@ extension OpenAIError {
137142 }
138143 }
139144
145+extension OpenAIError {
146+ /// 404 for an unknown model, 400 for a model that is not in MLX format.
147+ init(model error: ModelResolutionError) {
148+ switch error {
149+ case .unknown(let name):
150+ self = .modelNotFound(name)
151+ case .notMLX:
152+ self.init(
153+ .badRequest, message: error.description, param: "model",
154+ code: "model_not_supported")
155+ }
156+ }
157+
158+ /// 429 when the queue is full, 503 when the server cannot make room, 500 when loading fails.
159+ init(manager error: ModelManagerError) {
160+ switch error {
161+ case .queueFull:
162+ self.init(.tooManyRequests, message: error.description, code: "queue_full")
163+ case .allModelsBusy:
164+ self.init(.serviceUnavailable, message: error.description, code: "server_busy")
165+ case .insufficientMemory:
166+ self.init(.serviceUnavailable, message: error.description, code: "insufficient_memory")
167+ case .loadFailed:
168+ self.init(.internalServerError, message: error.description, code: "model_load_failed")
169+ }
170+ }
171+}
172+
140173 extension JSONEncoder {
141174 /// Encoder for API responses: stable key order, slashes left as they are.
142175 static var openAI: JSONEncoder {
@@ -1,5 +1,6 @@
1 import Foundation1 import Foundation
2 import Hummingbird2 import Hummingbird
3+import RazorbillCore
3 4
4 /// An error answered in OpenAI's format, so that OpenAI clients show the message:5 /// An error answered in OpenAI's format, so that OpenAI clients show the message:
5 ///6 ///
@@ -125,6 +126,10 @@ extension OpenAIError {
125 switch error {126 switch error {
126 case let error as OpenAIError:127 case let error as OpenAIError:
127 return error128 return error
129+ case let error as ModelResolutionError:
130+ return OpenAIError(model: error)
131+ case let error as ModelManagerError:
132+ return OpenAIError(manager: error)
128 case let error as HTTPError:133 case let error as HTTPError:
129 return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)134 return OpenAIError(error.status, message: error.body ?? error.status.reasonPhrase)
130 case let error as any HTTPResponseError where error.status == .contentTooLarge:135 case let error as any HTTPResponseError where error.status == .contentTooLarge:
@@ -137,6 +142,34 @@ extension OpenAIError {
137 }142 }
138 }143 }
139 144
145+extension OpenAIError {
146+ /// 404 for an unknown model, 400 for a model that is not in MLX format.
147+ init(model error: ModelResolutionError) {
148+ switch error {
149+ case .unknown(let name):
150+ self = .modelNotFound(name)
151+ case .notMLX:
152+ self.init(
153+ .badRequest, message: error.description, param: "model",
154+ code: "model_not_supported")
155+ }
156+ }
157+
158+ /// 429 when the queue is full, 503 when the server cannot make room, 500 when loading fails.
159+ init(manager error: ModelManagerError) {
160+ switch error {
161+ case .queueFull:
162+ self.init(.tooManyRequests, message: error.description, code: "queue_full")
163+ case .allModelsBusy:
164+ self.init(.serviceUnavailable, message: error.description, code: "server_busy")
165+ case .insufficientMemory:
166+ self.init(.serviceUnavailable, message: error.description, code: "insufficient_memory")
167+ case .loadFailed:
168+ self.init(.internalServerError, message: error.description, code: "model_load_failed")
169+ }
170+ }
171+}
172+
140 extension JSONEncoder {173 extension JSONEncoder {
141 /// Encoder for API responses: stable key order, slashes left as they are.174 /// Encoder for API responses: stable key order, slashes left as they are.
142 static var openAI: JSONEncoder {175 static var openAI: JSONEncoder {
modified Sources/RazorbillServer/RazorbillServer.swift +32 -11
@@ -1,18 +1,21 @@
11 import Hummingbird
22 import Logging
3+import RazorbillCore
4+import ServiceLifecycle
35
46 /// The OpenAI-compatible HTTP server behind `rzb serve`.
57 ///
68 /// ```swift
7-/// try await RazorbillServer.run(ServerSettings(port: 8080), logger: logger) { port in
8-/// print("listening on \(port)")
9-/// }
9+/// try await RazorbillServer.run(
10+/// ServerSettings(port: 8080), engines: engines, store: ModelStore(), logger: logger
11+/// ) { port in print("listening on \(port)") }
1012 /// ```
1113 ///
1214 /// Tests build the application themselves, to add routes or start it on a random port:
1315 ///
1416 /// ```swift
15-/// let router = RazorbillServer.makeRouter(settings)
17+/// let models = RazorbillServer.makeModelManager(settings, engines: engines, store: store, logger: logger)
18+/// let router = RazorbillServer.makeRouter(settings, models: models)
1619 /// let app = RazorbillServer.makeApplication(router: router, settings: settings, logger: logger)
1720 /// try await app.test(.live) { client in … }
1821 /// ```
@@ -21,7 +24,9 @@ public enum RazorbillServer {
2124 ///
2225 /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key.
2326 /// The error envelope sits inside CORS so browser clients can read error bodies too.
24- public static func makeRouter(_ settings: ServerSettings) -> Router<ServerContext> {
27+ public static func makeRouter(
28+ _ settings: ServerSettings, models: ModelManager
29+ ) -> Router<ServerContext> {
2530 let router = Router(context: ServerContext.self)
2631 router.middlewares.add(RequestLogMiddleware())
2732 if let origin = settings.corsOrigin {
@@ -33,18 +38,31 @@ public enum RazorbillServer {
3338 router.middlewares.add(APIKeyMiddleware(key: key))
3439 }
3540 addHealthRoute(to: router)
41+ ModelRoutes(models: models).add(to: router)
3642 return router
3743 }
3844
39- /// The application, not started.
45+ /// The models of `settings.config`, loaded with the default engine of `engines`.
46+ public static func makeModelManager(
47+ _ settings: ServerSettings, engines: EngineRegistry, store: ModelStore, logger: Logger
48+ ) -> ModelManager {
49+ ModelManager(
50+ catalog: ModelCatalog(config: settings.config, store: store),
51+ limits: settings.config.limits, logger: logger
52+ ) { try engines.make() }
53+ }
54+
55+ /// The application, not started. `models` is preloaded, swept for idle models and unloaded
56+ /// at shutdown alongside the server.
4057 public static func makeApplication(
41- router: Router<ServerContext>, settings: ServerSettings, logger: Logger,
42- onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
58+ router: Router<ServerContext>, settings: ServerSettings, models: ModelManager,
59+ logger: Logger, onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
4360 ) -> some ApplicationProtocol {
4461 Application(
4562 router: router,
4663 configuration: .init(
4764 address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),
65+ services: [ModelLifecycleService(models: models)],
4866 onServerRunning: { channel in
4967 await onRunning(channel.localAddress?.port ?? settings.port)
5068 },
@@ -55,12 +73,15 @@ public enum RazorbillServer {
5573 /// Starts the server and returns once it has stopped (SIGINT or SIGTERM: requests in
5674 /// flight are finished or cancelled, then the server exits). `onRunning` receives the port.
5775 public static func run(
58- _ settings: ServerSettings, logger: Logger,
76+ _ settings: ServerSettings, engines: EngineRegistry, store: ModelStore, logger: Logger,
5977 onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
6078 ) async throws {
61- let router = makeRouter(settings)
79+ _ = try engines.make() // fail now, not on the first request, when no engine exists
80+ let models = makeModelManager(settings, engines: engines, store: store, logger: logger)
81+ let router = makeRouter(settings, models: models)
6282 let app = makeApplication(
63- router: router, settings: settings, logger: logger, onRunning: onRunning)
83+ router: router, settings: settings, models: models, logger: logger,
84+ onRunning: onRunning)
6485 try await app.runService()
6586 }
6687
@@ -1,18 +1,21 @@
1 import Hummingbird1 import Hummingbird
2 import Logging2 import Logging
3+import RazorbillCore
4+import ServiceLifecycle
3 5
4 /// The OpenAI-compatible HTTP server behind `rzb serve`.6 /// The OpenAI-compatible HTTP server behind `rzb serve`.
5 ///7 ///
6 /// ```swift8 /// ```swift
7-/// try await RazorbillServer.run(ServerSettings(port: 8080), logger: logger) { port in9+/// try await RazorbillServer.run(
8-/// print("listening on \(port)")10+/// ServerSettings(port: 8080), engines: engines, store: ModelStore(), logger: logger
9-/// }11+/// ) { port in print("listening on \(port)") }
10 /// ```12 /// ```
11 ///13 ///
12 /// Tests build the application themselves, to add routes or start it on a random port:14 /// Tests build the application themselves, to add routes or start it on a random port:
13 ///15 ///
14 /// ```swift16 /// ```swift
15-/// let router = RazorbillServer.makeRouter(settings)17+/// let models = RazorbillServer.makeModelManager(settings, engines: engines, store: store, logger: logger)
18+/// let router = RazorbillServer.makeRouter(settings, models: models)
16 /// let app = RazorbillServer.makeApplication(router: router, settings: settings, logger: logger)19 /// let app = RazorbillServer.makeApplication(router: router, settings: settings, logger: logger)
17 /// try await app.test(.live) { client in … }20 /// try await app.test(.live) { client in … }
18 /// ```21 /// ```
@@ -21,7 +24,9 @@ public enum RazorbillServer {
21 ///24 ///
22 /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key.25 /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key.
23 /// The error envelope sits inside CORS so browser clients can read error bodies too.26 /// The error envelope sits inside CORS so browser clients can read error bodies too.
24- public static func makeRouter(_ settings: ServerSettings) -> Router<ServerContext> {27+ public static func makeRouter(
28+ _ settings: ServerSettings, models: ModelManager
29+ ) -> Router<ServerContext> {
25 let router = Router(context: ServerContext.self)30 let router = Router(context: ServerContext.self)
26 router.middlewares.add(RequestLogMiddleware())31 router.middlewares.add(RequestLogMiddleware())
27 if let origin = settings.corsOrigin {32 if let origin = settings.corsOrigin {
@@ -33,18 +38,31 @@ public enum RazorbillServer {
33 router.middlewares.add(APIKeyMiddleware(key: key))38 router.middlewares.add(APIKeyMiddleware(key: key))
34 }39 }
35 addHealthRoute(to: router)40 addHealthRoute(to: router)
41+ ModelRoutes(models: models).add(to: router)
36 return router42 return router
37 }43 }
38 44
39- /// The application, not started.45+ /// The models of `settings.config`, loaded with the default engine of `engines`.
46+ public static func makeModelManager(
47+ _ settings: ServerSettings, engines: EngineRegistry, store: ModelStore, logger: Logger
48+ ) -> ModelManager {
49+ ModelManager(
50+ catalog: ModelCatalog(config: settings.config, store: store),
51+ limits: settings.config.limits, logger: logger
52+ ) { try engines.make() }
53+ }
54+
55+ /// The application, not started. `models` is preloaded, swept for idle models and unloaded
56+ /// at shutdown alongside the server.
40 public static func makeApplication(57 public static func makeApplication(
41- router: Router<ServerContext>, settings: ServerSettings, logger: Logger,58+ router: Router<ServerContext>, settings: ServerSettings, models: ModelManager,
42- onRunning: @escaping @Sendable (Int) async -> Void = { _ in }59+ logger: Logger, onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
43 ) -> some ApplicationProtocol {60 ) -> some ApplicationProtocol {
44 Application(61 Application(
45 router: router,62 router: router,
46 configuration: .init(63 configuration: .init(
47 address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),64 address: .hostname(settings.host, port: settings.port), serverName: "razorbill"),
65+ services: [ModelLifecycleService(models: models)],
48 onServerRunning: { channel in66 onServerRunning: { channel in
49 await onRunning(channel.localAddress?.port ?? settings.port)67 await onRunning(channel.localAddress?.port ?? settings.port)
50 },68 },
@@ -55,12 +73,15 @@ public enum RazorbillServer {
55 /// Starts the server and returns once it has stopped (SIGINT or SIGTERM: requests in73 /// Starts the server and returns once it has stopped (SIGINT or SIGTERM: requests in
56 /// flight are finished or cancelled, then the server exits). `onRunning` receives the port.74 /// flight are finished or cancelled, then the server exits). `onRunning` receives the port.
57 public static func run(75 public static func run(
58- _ settings: ServerSettings, logger: Logger,76+ _ settings: ServerSettings, engines: EngineRegistry, store: ModelStore, logger: Logger,
59 onRunning: @escaping @Sendable (Int) async -> Void = { _ in }77 onRunning: @escaping @Sendable (Int) async -> Void = { _ in }
60 ) async throws {78 ) async throws {
61- let router = makeRouter(settings)79+ _ = try engines.make() // fail now, not on the first request, when no engine exists
80+ let models = makeModelManager(settings, engines: engines, store: store, logger: logger)
81+ let router = makeRouter(settings, models: models)
62 let app = makeApplication(82 let app = makeApplication(
63- router: router, settings: settings, logger: logger, onRunning: onRunning)83+ router: router, settings: settings, models: models, logger: logger,
84+ onRunning: onRunning)
64 try await app.runService()85 try await app.runService()
65 }86 }
66 87
added Tests/RazorbillServerTests/ModelManagerTests.swift +251 -0
new file mode 100644
@@ -0,0 +1,251 @@
1+import Foundation
2+import RazorbillCore
3+import Testing
4+
5+@testable import RazorbillServer
6+
7+/// Engines that record what they load and unload, and can be told to fail.
8+final class TestEngines: @unchecked Sendable {
9+ private let lock = NSLock()
10+ private var storedEvents: [String] = []
11+ private var failures: [String: any Error] = [:]
12+
13+ /// `load <model>` / `unload <model>`, in order.
14+ var events: [String] { lock.withLock { storedEvents } }
15+ var loads: Int { events.filter { $0.hasPrefix("load ") }.count }
16+
17+ func failLoading(_ model: String, with error: any Error) {
18+ lock.withLock { failures[model] = error }
19+ }
20+
21+ func record(_ event: String) { lock.withLock { storedEvents.append(event) } }
22+ func failure(for model: String) -> (any Error)? {
23+ lock.withLock { failures.removeValue(forKey: model) }
24+ }
25+
26+ var make: ModelManager.EngineFactory {
27+ { [self] in Engine(owner: self) }
28+ }
29+
30+ final class Engine: InferenceEngine, @unchecked Sendable {
31+ let name = "test"
32+ let owner: TestEngines
33+ private let lock = NSLock()
34+ private var model = ""
35+
36+ init(owner: TestEngines) { self.owner = owner }
37+
38+ func load(
39+ _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void
40+ ) async throws {
41+ if let error = owner.failure(for: model.description) { throw error }
42+ lock.withLock { self.model = model.description }
43+ owner.record("load \(model)")
44+ }
45+
46+ func download(
47+ _ model: ModelReference, progress: @escaping @Sendable (Double) -> Void
48+ ) async throws {}
49+
50+ func makeSession(_ setup: SessionSetup) async throws -> any EngineSession {
51+ try await FakeEngine().makeSession(setup)
52+ }
53+
54+ func unload() async {
55+ owner.record("unload \(lock.withLock { model })")
56+ }
57+ }
58+}
59+
60+struct LoadBroke: Error, CustomStringConvertible {
61+ var description: String { "disk on fire" }
62+}
63+
64+@Suite struct ModelManagerTests {
65+ let engines = TestEngines()
66+ let cache = URL(fileURLWithPath: NSTemporaryDirectory())
67+ .appendingPathComponent("rzb-manager-\(UUID().uuidString)")
68+
69+ func manager(
70+ _ limits: ServerLimits = ServerLimits(), models: [ModelEntry] = [],
71+ budget: Int64 = 1 << 40
72+ ) -> ModelManager {
73+ let config = ServerConfig(models: models, limits: limits)
74+ return ModelManager(
75+ catalog: ModelCatalog(config: config, store: ModelStore(cacheDirectory: cache)),
76+ limits: limits, memoryBudget: budget, makeEngine: engines.make)
77+ }
78+
79+ /// Puts `size` bytes of safetensors weights for `id` in the cache.
80+ func cacheModel(_ id: String, size: Int, safetensors: Bool = true) throws {
81+ let snapshot = ModelStore(cacheDirectory: cache).directory(for: id)
82+ .appendingPathComponent("snapshots/c1")
83+ let refs = snapshot.deletingLastPathComponent().deletingLastPathComponent()
84+ .appendingPathComponent("refs")
85+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
86+ try FileManager.default.createDirectory(at: refs, withIntermediateDirectories: true)
87+ try "c1".write(to: refs.appendingPathComponent("main"), atomically: true, encoding: .utf8)
88+ try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json"))
89+ if safetensors {
90+ try Data(count: size).write(to: snapshot.appendingPathComponent("model.safetensors"))
91+ }
92+ }
93+
94+ /// Waits until `name` has `count` requests queued.
95+ func waitForQueue(_ manager: ModelManager, _ name: String, count: Int) async throws {
96+ for _ in 0 ..< 500 where try await manager.queueLength(name) != count {
97+ try await Task.sleep(for: .milliseconds(2))
98+ }
99+ #expect(try await manager.queueLength(name) == count)
100+ }
101+
102+ @Test func loadsOnFirstRequestAndReuses() async throws {
103+ let manager = manager()
104+ for _ in 0 ..< 3 {
105+ let lease = try await manager.acquire("org/a")
106+ #expect(lease.model.name == "org/a")
107+ await lease.release()
108+ }
109+ #expect(engines.events == ["load org/a"])
110+ #expect(await manager.loadedSources() == ["org/a"])
111+ }
112+
113+ @Test func declaredNameAndRepositoryIdShareOneLoad() async throws {
114+ let manager = manager(models: [
115+ ModelEntry(id: "a", source: .huggingFace(id: "org/a", revision: "main"))
116+ ])
117+ try await manager.withModel("a") { _ in }
118+ try await manager.withModel("org/a") { _ in }
119+ #expect(engines.loads == 1)
120+ }
121+
122+ @Test func requestsForOneModelRunInOrder() async throws {
123+ let manager = manager()
124+ let first = try await manager.acquire("org/a")
125+ let second = Task { try await manager.acquire("org/a") }
126+ try await waitForQueue(manager, "org/a", count: 1)
127+ await first.release()
128+ let lease = try await second.value
129+ #expect(try await manager.queueLength("org/a") == 0)
130+ await lease.release()
131+ #expect(engines.loads == 1)
132+ }
133+
134+ @Test func fullQueueIsRefused() async throws {
135+ let manager = manager(ServerLimits(maxQueue: 1))
136+ let first = try await manager.acquire("org/a")
137+ let waiting = Task { try await manager.acquire("org/a") }
138+ try await waitForQueue(manager, "org/a", count: 1)
139+ await #expect(throws: ModelManagerError.queueFull(model: "org/a", limit: 1)) {
140+ try await manager.acquire("org/a")
141+ }
142+ await first.release()
143+ await try waiting.value.release()
144+ }
145+
146+ @Test func cancelledWaiterLeavesTheQueue() async throws {
147+ let manager = manager(ServerLimits(maxQueue: 1))
148+ let first = try await manager.acquire("org/a")
149+ let waiting = Task { try await manager.acquire("org/a") }
150+ try await waitForQueue(manager, "org/a", count: 1)
151+ waiting.cancel()
152+ await #expect(throws: CancellationError.self) { try await waiting.value }
153+ try await waitForQueue(manager, "org/a", count: 0)
154+ await first.release()
155+ try await manager.withModel("org/a") { _ in }
156+ }
157+
158+ @Test func leastRecentlyUsedIdleModelMakesRoom() async throws {
159+ let manager = manager(ServerLimits(maxLoadedModels: 2))
160+ try await manager.withModel("org/a") { _ in }
161+ try await manager.withModel("org/b") { _ in }
162+ try await manager.withModel("org/a") { _ in } // b is now the least recently used
163+ try await manager.withModel("org/c") { _ in }
164+ #expect(engines.events == ["load org/a", "load org/b", "unload org/b", "load org/c"])
165+ #expect(await manager.loadedSources() == ["org/a", "org/c"])
166+ }
167+
168+ @Test func busyModelsAreNeverUnloaded() async throws {
169+ let manager = manager(ServerLimits(maxLoadedModels: 1))
170+ let lease = try await manager.acquire("org/a")
171+ await #expect(throws: ModelManagerError.allModelsBusy(model: "org/b")) {
172+ try await manager.acquire("org/b")
173+ }
174+ await lease.release()
175+ try await manager.withModel("org/b") { _ in }
176+ #expect(engines.events == ["load org/a", "unload org/a", "load org/b"])
177+ }
178+
179+ @Test func idleModelsAreUnloadedAfterKeepAlive() async throws {
180+ let manager = manager(ServerLimits(keepAlive: .seconds(60)))
181+ try await manager.withModel("org/a") { _ in }
182+ await manager.unloadIdle()
183+ #expect(await manager.loadedSources() == ["org/a"])
184+ await manager.unloadIdle(now: .now + .seconds(61))
185+ #expect(await manager.loadedSources().isEmpty)
186+ #expect(engines.events == ["load org/a", "unload org/a"])
187+ }
188+
189+ @Test func modelsThatDoNotFitAreRefusedAfterUnloadingIdleOnes() async throws {
190+ try cacheModel("org/big", size: 3000)
191+ try cacheModel("org/small", size: 600)
192+ try cacheModel("org/medium", size: 500)
193+ let manager = manager(ServerLimits(maxLoadedModels: 5), budget: 1000)
194+ await #expect(
195+ throws: ModelManagerError.insufficientMemory(
196+ model: "org/big", needed: 3000, available: 1000)
197+ ) { try await manager.acquire("org/big") }
198+
199+ try await manager.withModel("org/small") { _ in }
200+ try await manager.withModel("org/medium") { _ in } // 600 + 500 > 1000: small goes
201+ #expect(engines.events == ["load org/small", "unload org/small", "load org/medium"])
202+
203+ let medium = try await manager.acquire("org/medium")
204+ await #expect(
205+ throws: ModelManagerError.insufficientMemory(
206+ model: "org/small", needed: 600, available: 500)
207+ ) { try await manager.acquire("org/small") }
208+ await medium.release()
209+ }
210+
211+ @Test func loadFailureIsReportedAndTheNextRequestRetries() async throws {
212+ let manager = manager()
213+ engines.failLoading("org/a", with: LoadBroke())
214+ await #expect(throws: ModelManagerError.loadFailed(model: "org/a", reason: "disk on fire"))
215+ {
216+ try await manager.acquire("org/a")
217+ }
218+ try await manager.withModel("org/a") { _ in }
219+ #expect(engines.events == ["load org/a"])
220+ }
221+
222+ @Test func repositoryWithoutSafetensorsIsNotMLX() async throws {
223+ try cacheModel("org/gguf", size: 0, safetensors: false)
224+ engines.failLoading("org/gguf", with: LoadBroke())
225+ await #expect(throws: ModelResolutionError.notMLX("org/gguf")) {
226+ try await manager().acquire("org/gguf")
227+ }
228+ }
229+
230+ @Test func unknownNamesAreRejectedBeforeLoading() async throws {
231+ await #expect(throws: ModelResolutionError.unknown("gpt-4o")) {
232+ try await manager().acquire("gpt-4o")
233+ }
234+ #expect(engines.events.isEmpty)
235+ }
236+
237+ @Test func preloadAndUnloadAll() async throws {
238+ let manager = manager(
239+ ServerLimits(maxLoadedModels: 3),
240+ models: [
241+ ModelEntry(
242+ id: "a", source: .huggingFace(id: "org/a", revision: "main"), preload: true),
243+ ModelEntry(id: "b", source: .huggingFace(id: "org/b", revision: "main")),
244+ ])
245+ await manager.preload()
246+ #expect(engines.events == ["load org/a"])
247+ await manager.unloadAll()
248+ #expect(engines.events == ["load org/a", "unload org/a"])
249+ #expect(await manager.loadedSources().isEmpty)
250+ }
251+}
new file mode 100644
@@ -0,0 +1,251 @@
1+import Foundation
2+import RazorbillCore
3+import Testing
4+
5+@testable import RazorbillServer
6+
7+/// Engines that record what they load and unload, and can be told to fail.
8+final class TestEngines: @unchecked Sendable {
9+ private let lock = NSLock()
10+ private var storedEvents: [String] = []
11+ private var failures: [String: any Error] = [:]
12+
13+ /// `load <model>` / `unload <model>`, in order.
14+ var events: [String] { lock.withLock { storedEvents } }
15+ var loads: Int { events.filter { $0.hasPrefix("load ") }.count }
16+
17+ func failLoading(_ model: String, with error: any Error) {
18+ lock.withLock { failures[model] = error }
19+ }
20+
21+ func record(_ event: String) { lock.withLock { storedEvents.append(event) } }
22+ func failure(for model: String) -> (any Error)? {
23+ lock.withLock { failures.removeValue(forKey: model) }
24+ }
25+
26+ var make: ModelManager.EngineFactory {
27+ { [self] in Engine(owner: self) }
28+ }
29+
30+ final class Engine: InferenceEngine, @unchecked Sendable {
31+ let name = "test"
32+ let owner: TestEngines
33+ private let lock = NSLock()
34+ private var model = ""
35+
36+ init(owner: TestEngines) { self.owner = owner }
37+
38+ func load(
39+ _ model: ModelReference, offline: Bool, progress: @escaping @Sendable (Double) -> Void
40+ ) async throws {
41+ if let error = owner.failure(for: model.description) { throw error }
42+ lock.withLock { self.model = model.description }
43+ owner.record("load \(model)")
44+ }
45+
46+ func download(
47+ _ model: ModelReference, progress: @escaping @Sendable (Double) -> Void
48+ ) async throws {}
49+
50+ func makeSession(_ setup: SessionSetup) async throws -> any EngineSession {
51+ try await FakeEngine().makeSession(setup)
52+ }
53+
54+ func unload() async {
55+ owner.record("unload \(lock.withLock { model })")
56+ }
57+ }
58+}
59+
60+struct LoadBroke: Error, CustomStringConvertible {
61+ var description: String { "disk on fire" }
62+}
63+
64+@Suite struct ModelManagerTests {
65+ let engines = TestEngines()
66+ let cache = URL(fileURLWithPath: NSTemporaryDirectory())
67+ .appendingPathComponent("rzb-manager-\(UUID().uuidString)")
68+
69+ func manager(
70+ _ limits: ServerLimits = ServerLimits(), models: [ModelEntry] = [],
71+ budget: Int64 = 1 << 40
72+ ) -> ModelManager {
73+ let config = ServerConfig(models: models, limits: limits)
74+ return ModelManager(
75+ catalog: ModelCatalog(config: config, store: ModelStore(cacheDirectory: cache)),
76+ limits: limits, memoryBudget: budget, makeEngine: engines.make)
77+ }
78+
79+ /// Puts `size` bytes of safetensors weights for `id` in the cache.
80+ func cacheModel(_ id: String, size: Int, safetensors: Bool = true) throws {
81+ let snapshot = ModelStore(cacheDirectory: cache).directory(for: id)
82+ .appendingPathComponent("snapshots/c1")
83+ let refs = snapshot.deletingLastPathComponent().deletingLastPathComponent()
84+ .appendingPathComponent("refs")
85+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
86+ try FileManager.default.createDirectory(at: refs, withIntermediateDirectories: true)
87+ try "c1".write(to: refs.appendingPathComponent("main"), atomically: true, encoding: .utf8)
88+ try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json"))
89+ if safetensors {
90+ try Data(count: size).write(to: snapshot.appendingPathComponent("model.safetensors"))
91+ }
92+ }
93+
94+ /// Waits until `name` has `count` requests queued.
95+ func waitForQueue(_ manager: ModelManager, _ name: String, count: Int) async throws {
96+ for _ in 0 ..< 500 where try await manager.queueLength(name) != count {
97+ try await Task.sleep(for: .milliseconds(2))
98+ }
99+ #expect(try await manager.queueLength(name) == count)
100+ }
101+
102+ @Test func loadsOnFirstRequestAndReuses() async throws {
103+ let manager = manager()
104+ for _ in 0 ..< 3 {
105+ let lease = try await manager.acquire("org/a")
106+ #expect(lease.model.name == "org/a")
107+ await lease.release()
108+ }
109+ #expect(engines.events == ["load org/a"])
110+ #expect(await manager.loadedSources() == ["org/a"])
111+ }
112+
113+ @Test func declaredNameAndRepositoryIdShareOneLoad() async throws {
114+ let manager = manager(models: [
115+ ModelEntry(id: "a", source: .huggingFace(id: "org/a", revision: "main"))
116+ ])
117+ try await manager.withModel("a") { _ in }
118+ try await manager.withModel("org/a") { _ in }
119+ #expect(engines.loads == 1)
120+ }
121+
122+ @Test func requestsForOneModelRunInOrder() async throws {
123+ let manager = manager()
124+ let first = try await manager.acquire("org/a")
125+ let second = Task { try await manager.acquire("org/a") }
126+ try await waitForQueue(manager, "org/a", count: 1)
127+ await first.release()
128+ let lease = try await second.value
129+ #expect(try await manager.queueLength("org/a") == 0)
130+ await lease.release()
131+ #expect(engines.loads == 1)
132+ }
133+
134+ @Test func fullQueueIsRefused() async throws {
135+ let manager = manager(ServerLimits(maxQueue: 1))
136+ let first = try await manager.acquire("org/a")
137+ let waiting = Task { try await manager.acquire("org/a") }
138+ try await waitForQueue(manager, "org/a", count: 1)
139+ await #expect(throws: ModelManagerError.queueFull(model: "org/a", limit: 1)) {
140+ try await manager.acquire("org/a")
141+ }
142+ await first.release()
143+ await try waiting.value.release()
144+ }
145+
146+ @Test func cancelledWaiterLeavesTheQueue() async throws {
147+ let manager = manager(ServerLimits(maxQueue: 1))
148+ let first = try await manager.acquire("org/a")
149+ let waiting = Task { try await manager.acquire("org/a") }
150+ try await waitForQueue(manager, "org/a", count: 1)
151+ waiting.cancel()
152+ await #expect(throws: CancellationError.self) { try await waiting.value }
153+ try await waitForQueue(manager, "org/a", count: 0)
154+ await first.release()
155+ try await manager.withModel("org/a") { _ in }
156+ }
157+
158+ @Test func leastRecentlyUsedIdleModelMakesRoom() async throws {
159+ let manager = manager(ServerLimits(maxLoadedModels: 2))
160+ try await manager.withModel("org/a") { _ in }
161+ try await manager.withModel("org/b") { _ in }
162+ try await manager.withModel("org/a") { _ in } // b is now the least recently used
163+ try await manager.withModel("org/c") { _ in }
164+ #expect(engines.events == ["load org/a", "load org/b", "unload org/b", "load org/c"])
165+ #expect(await manager.loadedSources() == ["org/a", "org/c"])
166+ }
167+
168+ @Test func busyModelsAreNeverUnloaded() async throws {
169+ let manager = manager(ServerLimits(maxLoadedModels: 1))
170+ let lease = try await manager.acquire("org/a")
171+ await #expect(throws: ModelManagerError.allModelsBusy(model: "org/b")) {
172+ try await manager.acquire("org/b")
173+ }
174+ await lease.release()
175+ try await manager.withModel("org/b") { _ in }
176+ #expect(engines.events == ["load org/a", "unload org/a", "load org/b"])
177+ }
178+
179+ @Test func idleModelsAreUnloadedAfterKeepAlive() async throws {
180+ let manager = manager(ServerLimits(keepAlive: .seconds(60)))
181+ try await manager.withModel("org/a") { _ in }
182+ await manager.unloadIdle()
183+ #expect(await manager.loadedSources() == ["org/a"])
184+ await manager.unloadIdle(now: .now + .seconds(61))
185+ #expect(await manager.loadedSources().isEmpty)
186+ #expect(engines.events == ["load org/a", "unload org/a"])
187+ }
188+
189+ @Test func modelsThatDoNotFitAreRefusedAfterUnloadingIdleOnes() async throws {
190+ try cacheModel("org/big", size: 3000)
191+ try cacheModel("org/small", size: 600)
192+ try cacheModel("org/medium", size: 500)
193+ let manager = manager(ServerLimits(maxLoadedModels: 5), budget: 1000)
194+ await #expect(
195+ throws: ModelManagerError.insufficientMemory(
196+ model: "org/big", needed: 3000, available: 1000)
197+ ) { try await manager.acquire("org/big") }
198+
199+ try await manager.withModel("org/small") { _ in }
200+ try await manager.withModel("org/medium") { _ in } // 600 + 500 > 1000: small goes
201+ #expect(engines.events == ["load org/small", "unload org/small", "load org/medium"])
202+
203+ let medium = try await manager.acquire("org/medium")
204+ await #expect(
205+ throws: ModelManagerError.insufficientMemory(
206+ model: "org/small", needed: 600, available: 500)
207+ ) { try await manager.acquire("org/small") }
208+ await medium.release()
209+ }
210+
211+ @Test func loadFailureIsReportedAndTheNextRequestRetries() async throws {
212+ let manager = manager()
213+ engines.failLoading("org/a", with: LoadBroke())
214+ await #expect(throws: ModelManagerError.loadFailed(model: "org/a", reason: "disk on fire"))
215+ {
216+ try await manager.acquire("org/a")
217+ }
218+ try await manager.withModel("org/a") { _ in }
219+ #expect(engines.events == ["load org/a"])
220+ }
221+
222+ @Test func repositoryWithoutSafetensorsIsNotMLX() async throws {
223+ try cacheModel("org/gguf", size: 0, safetensors: false)
224+ engines.failLoading("org/gguf", with: LoadBroke())
225+ await #expect(throws: ModelResolutionError.notMLX("org/gguf")) {
226+ try await manager().acquire("org/gguf")
227+ }
228+ }
229+
230+ @Test func unknownNamesAreRejectedBeforeLoading() async throws {
231+ await #expect(throws: ModelResolutionError.unknown("gpt-4o")) {
232+ try await manager().acquire("gpt-4o")
233+ }
234+ #expect(engines.events.isEmpty)
235+ }
236+
237+ @Test func preloadAndUnloadAll() async throws {
238+ let manager = manager(
239+ ServerLimits(maxLoadedModels: 3),
240+ models: [
241+ ModelEntry(
242+ id: "a", source: .huggingFace(id: "org/a", revision: "main"), preload: true),
243+ ModelEntry(id: "b", source: .huggingFace(id: "org/b", revision: "main")),
244+ ])
245+ await manager.preload()
246+ #expect(engines.events == ["load org/a"])
247+ await manager.unloadAll()
248+ #expect(engines.events == ["load org/a", "unload org/a"])
249+ #expect(await manager.loadedSources().isEmpty)
250+ }
251+}
added Tests/RazorbillServerTests/ModelRoutesTests.swift +119 -0
new file mode 100644
@@ -0,0 +1,119 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import RazorbillCore
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+/// An entry of `GET /v1/models`, decoded.
10+struct ModelItem: Decodable, Equatable {
11+ let id: String
12+ var object = "model"
13+ var ownedBy = "razorbill"
14+ let loaded: Bool
15+ let kind: String
16+
17+ enum CodingKeys: String, CodingKey {
18+ case id, object, loaded, kind
19+ case ownedBy = "owned_by"
20+ }
21+}
22+
23+@Suite struct ModelRoutesTests {
24+ struct ListBody: Decodable {
25+ let object: String
26+ let data: [ModelItem]
27+ }
28+
29+ func setUp() throws -> (ModelManager, Router<ServerContext>) {
30+ let cache = URL(fileURLWithPath: NSTemporaryDirectory())
31+ .appendingPathComponent("rzb-routes-\(UUID().uuidString)")
32+ let store = ModelStore(cacheDirectory: cache)
33+ for (id, weights) in [("org/cached", "model.safetensors"), ("org/gguf", "m.gguf")] {
34+ let snapshot = store.directory(for: id).appendingPathComponent("snapshots/c1")
35+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
36+ try FileManager.default.createDirectory(
37+ at: store.directory(for: id).appendingPathComponent("refs"),
38+ withIntermediateDirectories: true)
39+ try "c1".write(
40+ to: store.directory(for: id).appendingPathComponent("refs/main"), atomically: true,
41+ encoding: .utf8)
42+ try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json"))
43+ try Data().write(to: snapshot.appendingPathComponent(weights))
44+ }
45+ let config = ServerConfig(models: [
46+ ModelEntry(id: "qwen3", source: .huggingFace(id: "org/q", revision: "main")),
47+ ModelEntry(
48+ id: "embed", source: .huggingFace(id: "org/e", revision: "main"), kind: .embedding),
49+ ])
50+ let models = ModelManager(
51+ catalog: ModelCatalog(config: config, store: store), limits: config.limits,
52+ memoryBudget: 1 << 40, makeEngine: TestEngines().make)
53+ return (models, testRouter(models: models))
54+ }
55+
56+ @Test func listsDeclaredThenCachedMLXModelsWithTheirState() async throws {
57+ let (models, router) = try setUp()
58+ try await models.withModel("qwen3") { _ in }
59+ try await withLiveServer(router: router) { client in
60+ try await client.execute(uri: "/v1/models", method: .get) { response in
61+ #expect(response.status == .ok)
62+ let body = try JSONDecoder().decode(
63+ ListBody.self, from: Data(buffer: response.body))
64+ #expect(body.object == "list")
65+ let expected = [
66+ ModelItem(id: "qwen3", loaded: true, kind: "chat"),
67+ ModelItem(id: "embed", loaded: false, kind: "embedding"),
68+ ModelItem(id: "org/cached", loaded: false, kind: "chat"),
69+ ]
70+ #expect(body.data == expected)
71+ }
72+ }
73+ }
74+
75+ @Test func oneModelByIdEvenWithASlash() async throws {
76+ let (_, router) = try setUp()
77+ try await withLiveServer(router: router) { client in
78+ try await client.execute(uri: "/v1/models/org/cached", method: .get) { response in
79+ #expect(response.status == .ok)
80+ #expect(String(buffer: response.body).contains(#""id":"org/cached""#))
81+ }
82+ try await client.execute(uri: "/v1/models/nope", method: .get) { response in
83+ #expect(response.status == .notFound)
84+ let error = try ErrorBody(response).error
85+ #expect(error.code == "model_not_found")
86+ }
87+ }
88+ }
89+
90+ @Test func managerErrorsMapToOpenAIStatuses() async throws {
91+ let router = testRouter()
92+ let cases: [(String, any Error)] = [
93+ ("queue", ModelManagerError.queueFull(model: "m", limit: 1)),
94+ ("busy", ModelManagerError.allModelsBusy(model: "m")),
95+ ("memory", ModelManagerError.insufficientMemory(model: "m", needed: 2, available: 1)),
96+ ("load", ModelManagerError.loadFailed(model: "m", reason: "x")),
97+ ("unknown", ModelResolutionError.unknown("m")),
98+ ("gguf", ModelResolutionError.notMLX("o/m")),
99+ ]
100+ for (path, error) in cases {
101+ router.get("/v1/fail/\(path)") { _, _ -> String in throw error }
102+ }
103+ let expected: [String: (HTTPResponse.Status, String)] = [
104+ "queue": (.tooManyRequests, "queue_full"), "busy": (.serviceUnavailable, "server_busy"),
105+ "memory": (.serviceUnavailable, "insufficient_memory"),
106+ "load": (.internalServerError, "model_load_failed"),
107+ "unknown": (.notFound, "model_not_found"), "gguf": (.badRequest, "model_not_supported"),
108+ ]
109+ try await withLiveServer(router: router) { client in
110+ for (path, (status, code)) in expected {
111+ try await client.execute(uri: "/v1/fail/\(path)", method: .get) { response in
112+ #expect(response.status == status, "\(path)")
113+ let error = try ErrorBody(response).error
114+ #expect(error.code == code, "\(path)")
115+ }
116+ }
117+ }
118+ }
119+}
new file mode 100644
@@ -0,0 +1,119 @@
1+import Foundation
2+import Hummingbird
3+import HummingbirdTesting
4+import RazorbillCore
5+import Testing
6+
7+@testable import RazorbillServer
8+
9+/// An entry of `GET /v1/models`, decoded.
10+struct ModelItem: Decodable, Equatable {
11+ let id: String
12+ var object = "model"
13+ var ownedBy = "razorbill"
14+ let loaded: Bool
15+ let kind: String
16+
17+ enum CodingKeys: String, CodingKey {
18+ case id, object, loaded, kind
19+ case ownedBy = "owned_by"
20+ }
21+}
22+
23+@Suite struct ModelRoutesTests {
24+ struct ListBody: Decodable {
25+ let object: String
26+ let data: [ModelItem]
27+ }
28+
29+ func setUp() throws -> (ModelManager, Router<ServerContext>) {
30+ let cache = URL(fileURLWithPath: NSTemporaryDirectory())
31+ .appendingPathComponent("rzb-routes-\(UUID().uuidString)")
32+ let store = ModelStore(cacheDirectory: cache)
33+ for (id, weights) in [("org/cached", "model.safetensors"), ("org/gguf", "m.gguf")] {
34+ let snapshot = store.directory(for: id).appendingPathComponent("snapshots/c1")
35+ try FileManager.default.createDirectory(at: snapshot, withIntermediateDirectories: true)
36+ try FileManager.default.createDirectory(
37+ at: store.directory(for: id).appendingPathComponent("refs"),
38+ withIntermediateDirectories: true)
39+ try "c1".write(
40+ to: store.directory(for: id).appendingPathComponent("refs/main"), atomically: true,
41+ encoding: .utf8)
42+ try Data("{}".utf8).write(to: snapshot.appendingPathComponent("config.json"))
43+ try Data().write(to: snapshot.appendingPathComponent(weights))
44+ }
45+ let config = ServerConfig(models: [
46+ ModelEntry(id: "qwen3", source: .huggingFace(id: "org/q", revision: "main")),
47+ ModelEntry(
48+ id: "embed", source: .huggingFace(id: "org/e", revision: "main"), kind: .embedding),
49+ ])
50+ let models = ModelManager(
51+ catalog: ModelCatalog(config: config, store: store), limits: config.limits,
52+ memoryBudget: 1 << 40, makeEngine: TestEngines().make)
53+ return (models, testRouter(models: models))
54+ }
55+
56+ @Test func listsDeclaredThenCachedMLXModelsWithTheirState() async throws {
57+ let (models, router) = try setUp()
58+ try await models.withModel("qwen3") { _ in }
59+ try await withLiveServer(router: router) { client in
60+ try await client.execute(uri: "/v1/models", method: .get) { response in
61+ #expect(response.status == .ok)
62+ let body = try JSONDecoder().decode(
63+ ListBody.self, from: Data(buffer: response.body))
64+ #expect(body.object == "list")
65+ let expected = [
66+ ModelItem(id: "qwen3", loaded: true, kind: "chat"),
67+ ModelItem(id: "embed", loaded: false, kind: "embedding"),
68+ ModelItem(id: "org/cached", loaded: false, kind: "chat"),
69+ ]
70+ #expect(body.data == expected)
71+ }
72+ }
73+ }
74+
75+ @Test func oneModelByIdEvenWithASlash() async throws {
76+ let (_, router) = try setUp()
77+ try await withLiveServer(router: router) { client in
78+ try await client.execute(uri: "/v1/models/org/cached", method: .get) { response in
79+ #expect(response.status == .ok)
80+ #expect(String(buffer: response.body).contains(#""id":"org/cached""#))
81+ }
82+ try await client.execute(uri: "/v1/models/nope", method: .get) { response in
83+ #expect(response.status == .notFound)
84+ let error = try ErrorBody(response).error
85+ #expect(error.code == "model_not_found")
86+ }
87+ }
88+ }
89+
90+ @Test func managerErrorsMapToOpenAIStatuses() async throws {
91+ let router = testRouter()
92+ let cases: [(String, any Error)] = [
93+ ("queue", ModelManagerError.queueFull(model: "m", limit: 1)),
94+ ("busy", ModelManagerError.allModelsBusy(model: "m")),
95+ ("memory", ModelManagerError.insufficientMemory(model: "m", needed: 2, available: 1)),
96+ ("load", ModelManagerError.loadFailed(model: "m", reason: "x")),
97+ ("unknown", ModelResolutionError.unknown("m")),
98+ ("gguf", ModelResolutionError.notMLX("o/m")),
99+ ]
100+ for (path, error) in cases {
101+ router.get("/v1/fail/\(path)") { _, _ -> String in throw error }
102+ }
103+ let expected: [String: (HTTPResponse.Status, String)] = [
104+ "queue": (.tooManyRequests, "queue_full"), "busy": (.serviceUnavailable, "server_busy"),
105+ "memory": (.serviceUnavailable, "insufficient_memory"),
106+ "load": (.internalServerError, "model_load_failed"),
107+ "unknown": (.notFound, "model_not_found"), "gguf": (.badRequest, "model_not_supported"),
108+ ]
109+ try await withLiveServer(router: router) { client in
110+ for (path, (status, code)) in expected {
111+ try await client.execute(uri: "/v1/fail/\(path)", method: .get) { response in
112+ #expect(response.status == status, "\(path)")
113+ let error = try ErrorBody(response).error
114+ #expect(error.code == code, "\(path)")
115+ }
116+ }
117+ }
118+ }
119+}
modified Tests/RazorbillServerTests/ServerTests.swift +18 -6
@@ -2,6 +2,7 @@ import Foundation
22 import Hummingbird
33 import HummingbirdTesting
44 import Logging
5+import RazorbillCore
56 import Testing
67
78 @testable import RazorbillServer
@@ -9,9 +10,20 @@ import Testing
910 /// Settings for a server on a random port.
1011 let testSettings = ServerSettings(port: 0)
1112
13+/// A model manager on an empty temporary cache with fake engines.
14+func testModels(
15+ _ settings: ServerSettings = testSettings, engines: TestEngines = TestEngines()
16+) -> ModelManager {
17+ let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
18+ "rzb-server-\(UUID().uuidString)")
19+ return ModelManager(
20+ catalog: ModelCatalog(config: settings.config, store: ModelStore(cacheDirectory: cache)),
21+ limits: settings.config.limits, memoryBudget: 1 << 40, makeEngine: engines.make)
22+}
23+
1224 /// razorbill's router, to which a test adds its own routes before ``withLiveServer``.
13-func testRouter() -> Router<ServerContext> {
14- RazorbillServer.makeRouter(testSettings)
25+func testRouter(models: ModelManager = testModels()) -> Router<ServerContext> {
26+ RazorbillServer.makeRouter(testSettings, models: models)
1527 }
1628
1729 /// Starts the server on a random port and calls it over real HTTP.
@@ -21,9 +33,10 @@ func withLiveServer(
2133 logs: LogCapture = LogCapture(),
2234 _ test: @Sendable (any TestClientProtocol) async throws -> Void
2335 ) async throws {
24- let router = router ?? RazorbillServer.makeRouter(settings)
36+ let models = testModels(settings)
37+ let router = router ?? RazorbillServer.makeRouter(settings, models: models)
2538 let app = RazorbillServer.makeApplication(
26- router: router, settings: settings, logger: logs.logger)
39+ router: router, settings: settings, models: models, logger: logs.logger)
2740 try await app.test(.live) { client in try await test(client) }
2841 }
2942
@@ -164,9 +177,8 @@ struct ErrorBody: Decodable {
164177 @Test func rightKeyPassesAndHealthIsOpen() async throws {
165178 try await withLiveServer(settings) { client in
166179 let right: HTTPFields = [.authorization: "Bearer s3cret"]
167- // Authenticated, so the request reaches the router: unknown route.
168180 try await client.execute(uri: "/v1/models", method: .get, headers: right) { response in
169- #expect(response.status == .notFound)
181+ #expect(response.status == .ok)
170182 }
171183 try await client.execute(uri: "/health", method: .get) { response in
172184 #expect(response.status == .ok)
@@ -2,6 +2,7 @@ import Foundation
2 import Hummingbird2 import Hummingbird
3 import HummingbirdTesting3 import HummingbirdTesting
4 import Logging4 import Logging
5+import RazorbillCore
5 import Testing6 import Testing
6 7
7 @testable import RazorbillServer8 @testable import RazorbillServer
@@ -9,9 +10,20 @@ import Testing
9 /// Settings for a server on a random port.10 /// Settings for a server on a random port.
10 let testSettings = ServerSettings(port: 0)11 let testSettings = ServerSettings(port: 0)
11 12
13+/// A model manager on an empty temporary cache with fake engines.
14+func testModels(
15+ _ settings: ServerSettings = testSettings, engines: TestEngines = TestEngines()
16+) -> ModelManager {
17+ let cache = FileManager.default.temporaryDirectory.appendingPathComponent(
18+ "rzb-server-\(UUID().uuidString)")
19+ return ModelManager(
20+ catalog: ModelCatalog(config: settings.config, store: ModelStore(cacheDirectory: cache)),
21+ limits: settings.config.limits, memoryBudget: 1 << 40, makeEngine: engines.make)
22+}
23+
12 /// razorbill's router, to which a test adds its own routes before ``withLiveServer``.24 /// razorbill's router, to which a test adds its own routes before ``withLiveServer``.
13-func testRouter() -> Router<ServerContext> {25+func testRouter(models: ModelManager = testModels()) -> Router<ServerContext> {
14- RazorbillServer.makeRouter(testSettings)26+ RazorbillServer.makeRouter(testSettings, models: models)
15 }27 }
16 28
17 /// Starts the server on a random port and calls it over real HTTP.29 /// Starts the server on a random port and calls it over real HTTP.
@@ -21,9 +33,10 @@ func withLiveServer(
21 logs: LogCapture = LogCapture(),33 logs: LogCapture = LogCapture(),
22 _ test: @Sendable (any TestClientProtocol) async throws -> Void34 _ test: @Sendable (any TestClientProtocol) async throws -> Void
23 ) async throws {35 ) async throws {
24- let router = router ?? RazorbillServer.makeRouter(settings)36+ let models = testModels(settings)
37+ let router = router ?? RazorbillServer.makeRouter(settings, models: models)
25 let app = RazorbillServer.makeApplication(38 let app = RazorbillServer.makeApplication(
26- router: router, settings: settings, logger: logs.logger)39+ router: router, settings: settings, models: models, logger: logs.logger)
27 try await app.test(.live) { client in try await test(client) }40 try await app.test(.live) { client in try await test(client) }
28 }41 }
29 42
@@ -164,9 +177,8 @@ struct ErrorBody: Decodable {
164 @Test func rightKeyPassesAndHealthIsOpen() async throws {177 @Test func rightKeyPassesAndHealthIsOpen() async throws {
165 try await withLiveServer(settings) { client in178 try await withLiveServer(settings) { client in
166 let right: HTTPFields = [.authorization: "Bearer s3cret"]179 let right: HTTPFields = [.authorization: "Bearer s3cret"]
167- // Authenticated, so the request reaches the router: unknown route.
168 try await client.execute(uri: "/v1/models", method: .get, headers: right) { response in180 try await client.execute(uri: "/v1/models", method: .get, headers: right) { response in
169- #expect(response.status == .notFound)181+ #expect(response.status == .ok)
170 }182 }
171 try await client.execute(uri: "/health", method: .get) { response in183 try await client.execute(uri: "/health", method: .get) { response in
172 #expect(response.status == .ok)184 #expect(response.status == .ok)