v0.2 step 6 — streamed chat completions (#36)
stream: true returns chat.completion.chunk events in OpenAI's order (role, content or tool-call deltas, finish_reason, [DONE]), with stream_options.include_usage. Errors before the first byte stay plain JSON errors; later ones become an error event. The model is held for the whole stream and released when it ends or is cancelled. SSE keep-alive comments every 5 s let the server notice a vanished caller even while the model is silent, which cancels the generation. Tests: Linux 113, Mac 122 (real-model streaming smoke test); the openai Python SDK streams against the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
d8981f3 parent: 6a3f52a modified
.memory/handoffs/2026-11-25-v0-2-server-foundation.md +13 -9 | @@ -1,23 +1,25 @@ | ||
| 1 | -# Handoff — 2026-11-25 — v0.2: server foundation (#32), config (#33), models (#34), chat (#35) | |
| 1 | +# Handoff — 2026-11-25 — v0.2: server (#32), config (#33), models (#34), chat (#35), streaming (#36) | |
| 2 | 2 | |
| 3 | 3 | ## State |
| 4 | 4 | Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78). |
| 5 | 5 | Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94). |
| 6 | 6 | Update after #35: non-streaming chat completions done (Linux 106, Mac 114, real-model smoke tests). |
| 7 | +Update after #36: streaming done (Linux 113, Mac 122). | |
| 7 | 8 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 8 | 9 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 9 | 10 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 10 | 11 | closed. Nothing pushed. |
| 11 | 12 | |
| 12 | 13 | ## Next steps |
| 13 | -1. #36 streaming: in `ChatCompletionRoute.answer`, when `plan.stream`, return | |
| 14 | - `ServerSentEvents.response(...)` over `CompletionStream.pieces` mapped to `chat.completion.chunk` | |
| 15 | - (first chunk `delta.role`, then `delta.content`, last with `finish_reason`, optional usage chunk | |
| 16 | - with `stream_options.include_usage`). The lease must be released when the stream ends or is | |
| 17 | - cancelled — `withModel` cannot wrap a streamed body: acquire, and release in the body writer. | |
| 18 | -2. #37 reasoning: `CompletionPiece.reasoning` is already produced and dropped in `complete`. | |
| 19 | -3. User check on the Mac: `rzb serve` + openai SDK or curl against a real model over HTTP. | |
| 20 | -4. Open point: a network-exposed server accepting any HF id lets clients trigger downloads. | |
| 14 | +1. #37 reasoning over the API: `CompletionPiece.reasoning` is produced and dropped in | |
| 15 | + `ChatCompletionRoute.complete` and `ChunkBuilder.chunks` — map it to `reasoning_content` | |
| 16 | + (message and `delta`); decide how a request turns thinking on/off (`reasoning_effort`?) on top of | |
| 17 | + the config's `thinking` default. | |
| 18 | +2. Then by milestone order: #38 spike constrained decoding, #39 structured output, #40/#41 tools, | |
| 19 | + #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; the agent docs | |
| 20 | + are still in docs/). | |
| 21 | +3. User check on the Mac: `rzb serve` + a real model over HTTP (streaming with `curl -N`). | |
| 22 | +4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. | |
| 21 | 23 | |
| 22 | 24 | ## Watch out for |
| 23 | 25 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -47,6 +49,8 @@ closed. Nothing pushed. | ||
| 47 | 49 | `localhost` (getaddrinfo), not hard-code 127.0.0.1. |
| 48 | 50 | - `@Suite(.enabled(if: Type.member))` referencing its own type is a "circular reference" error: |
| 49 | 51 | use a file-level constant. |
| 52 | +- Ticket comments: build the author block from the ticket file's own `author:` (the privacy hook | |
| 53 | + refuses commands that contain the account e-mail). | |
| 50 | 54 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 51 | 55 | the requested name. |
| 52 | 56 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
| @@ -1,23 +1,25 @@ | |||
| 1 | -# Handoff — 2026-11-25 — v0.2: server foundation (#32), config (#33), models (#34), chat (#35) | 1 | +# Handoff — 2026-11-25 — v0.2: server (#32), config (#33), models (#34), chat (#35), streaming (#36) |
| 2 | 2 | ||
| 3 | ## State | 3 | ## 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 | Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94). |
| 6 | Update after #35: non-streaming chat completions done (Linux 106, Mac 114, real-model smoke tests). | 6 | Update after #35: non-streaming chat completions done (Linux 106, Mac 114, real-model smoke tests). |
| 7 | +Update after #36: streaming done (Linux 113, Mac 122). | ||
| 7 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP | 8 | Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP |
| 8 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket | 9 | server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket |
| 9 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task | 10 | closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task |
| 10 | closed. Nothing pushed. | 11 | closed. Nothing pushed. |
| 11 | 12 | ||
| 12 | ## Next steps | 13 | ## Next steps |
| 13 | -1. #36 streaming: in `ChatCompletionRoute.answer`, when `plan.stream`, return | 14 | +1. #37 reasoning over the API: `CompletionPiece.reasoning` is produced and dropped in |
| 14 | - `ServerSentEvents.response(...)` over `CompletionStream.pieces` mapped to `chat.completion.chunk` | 15 | + `ChatCompletionRoute.complete` and `ChunkBuilder.chunks` — map it to `reasoning_content` |
| 15 | - (first chunk `delta.role`, then `delta.content`, last with `finish_reason`, optional usage chunk | 16 | + (message and `delta`); decide how a request turns thinking on/off (`reasoning_effort`?) on top of |
| 16 | - with `stream_options.include_usage`). The lease must be released when the stream ends or is | 17 | + the config's `thinking` default. |
| 17 | - cancelled — `withModel` cannot wrap a streamed body: acquire, and release in the body writer. | 18 | +2. Then by milestone order: #38 spike constrained decoding, #39 structured output, #40/#41 tools, |
| 18 | -2. #37 reasoning: `CompletionPiece.reasoning` is already produced and dropped in `complete`. | 19 | + #42 embeddings, #43 compatibility suite, #44 legacy completions, #45 docs (EN+FR; the agent docs |
| 19 | -3. User check on the Mac: `rzb serve` + openai SDK or curl against a real model over HTTP. | 20 | + are still in docs/). |
| 20 | -4. Open point: a network-exposed server accepting any HF id lets clients trigger downloads. | 21 | +3. User check on the Mac: `rzb serve` + a real model over HTTP (streaming with `curl -N`). |
| 22 | +4. Open point: a network-exposed server accepting any HF id lets callers trigger downloads. | ||
| 21 | 23 | ||
| 22 | ## Watch out for | 24 | ## Watch out for |
| 23 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns | 25 | - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns |
| @@ -47,6 +49,8 @@ closed. Nothing pushed. | |||
| 47 | `localhost` (getaddrinfo), not hard-code 127.0.0.1. | 49 | `localhost` (getaddrinfo), not hard-code 127.0.0.1. |
| 48 | - `@Suite(.enabled(if: Type.member))` referencing its own type is a "circular reference" error: | 50 | - `@Suite(.enabled(if: Type.member))` referencing its own type is a "circular reference" error: |
| 49 | use a file-level constant. | 51 | use a file-level constant. |
| 52 | +- Ticket comments: build the author block from the ticket file's own `author:` (the privacy hook | ||
| 53 | + refuses commands that contain the account e-mail). | ||
| 50 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by | 54 | - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by |
| 51 | the requested name. | 55 | the requested name. |
| 52 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. | 56 | - Docs/README still describe the agent; rewritten in #45 at the end of v0.2. |
modified
.memory/history.md +9 -0 | @@ -166,3 +166,12 @@ | ||
| 166 | 166 | model configuration (shared container). Tests Linux 106, Mac 114 incl. real-model smoke tests; |
| 167 | 167 | openai Python SDK verified against the Linux binary. Quality gate PASS (run #9, after splitting a |
| 168 | 168 | nested if-chain in ConfigValue decoding). #35 closed. |
| 169 | +- #36: streaming chat completions (OpenAI chunk order, include_usage, tool-call deltas, error event | |
| 170 | + after the start, plain JSON errors before it). Lease held for the stream's life and released in the | |
| 171 | + chunk task. Found while designing: the inbound-close watch ends when the handler returns, so a | |
| 172 | + streaming caller that vanishes is only seen on a failed write → SSE keep-alive comments every 5 s | |
| 173 | + (rejected: doing the whole request inside the response body writer, which would turn validation | |
| 174 | + errors into 200 + error events). Tests Linux 113, Mac 122 (real-model streaming smoke test); Python | |
| 175 | + SDK `stream=True` and `curl -N` checked. Gate PASS (run #11). #36 closed. | |
| 176 | +- Trap: the privacy hook refuses a command whose text holds the account e-mail (e.g. a ticket | |
| 177 | + author block written inline); copy the author block from the ticket file instead. | |
| @@ -166,3 +166,12 @@ | |||
| 166 | model configuration (shared container). Tests Linux 106, Mac 114 incl. real-model smoke tests; | 166 | model configuration (shared container). Tests Linux 106, Mac 114 incl. real-model smoke tests; |
| 167 | openai Python SDK verified against the Linux binary. Quality gate PASS (run #9, after splitting a | 167 | openai Python SDK verified against the Linux binary. Quality gate PASS (run #9, after splitting a |
| 168 | nested if-chain in ConfigValue decoding). #35 closed. | 168 | nested if-chain in ConfigValue decoding). #35 closed. |
| 169 | +- #36: streaming chat completions (OpenAI chunk order, include_usage, tool-call deltas, error event | ||
| 170 | + after the start, plain JSON errors before it). Lease held for the stream's life and released in the | ||
| 171 | + chunk task. Found while designing: the inbound-close watch ends when the handler returns, so a | ||
| 172 | + streaming caller that vanishes is only seen on a failed write → SSE keep-alive comments every 5 s | ||
| 173 | + (rejected: doing the whole request inside the response body writer, which would turn validation | ||
| 174 | + errors into 200 + error events). Tests Linux 113, Mac 122 (real-model streaming smoke test); Python | ||
| 175 | + SDK `stream=True` and `curl -N` checked. Gate PASS (run #11). #36 closed. | ||
| 176 | +- Trap: the privacy hook refuses a command whose text holds the account e-mail (e.g. a ticket | ||
| 177 | + author block written inline); copy the author block from the ticket file instead. | ||
modified
.memory/summary.md +7 -4 | @@ -7,7 +7,7 @@ | ||
| 7 | 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in |
| 8 | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, |
| 10 | -model lifecycle + `/v1/models` #34, non-streaming `POST /v1/chat/completions` #35 (see | |
| 10 | +model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35 and its streaming #36 (see | |
| 11 | 11 | Architecture). Decided by the user (#31): the |
| 12 | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 13 | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| @@ -44,7 +44,8 @@ error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelMana | ||
| 44 | 44 | demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService` |
| 45 | 45 | for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`; `Chat/`: |
| 46 | 46 | `ChatCompletionRequest` → `ChatPlan`, `CompletionStream` (engine events → content / reasoning / |
| 47 | -tool calls / finish + usage, stop sequences), `ChatCompletionRoute`), `RazorbillCLI` (`serve`, | |
| 47 | +tool calls / finish + usage, stop sequences), `ChatCompletionRoute` (plain + streamed), | |
| 48 | +`ChatCompletionChunk`/`ChunkBuilder`), `RazorbillCLI` (`serve`, | |
| 48 | 49 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` |
| 49 | 50 | runner for tests; `ServerSettings.config` carries the loaded file to the server). |
| 50 | 51 | `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` |
| @@ -54,7 +55,9 @@ the variable). One engine instance per loaded model (`InferenceEngine.unload()`) | ||
| 54 | 55 | registry's default (`mlx` on the Mac, `fake` on Linux). Chat requests are stateless (fresh session, |
| 55 | 56 | whole conversation each time, system messages through the template); stop sequences are applied |
| 56 | 57 | server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer |
| 57 | -(`Connection: close`) because it watches for client hang-ups. Next: streaming (#36). | |
| 58 | +(`Connection: close`) because it watches for client hang-ups. Streams hold the model lease until the | |
| 59 | +stream ends; a vanished streaming client is noticed by a failed write, so SSE sends a `: keep-alive` | |
| 60 | +comment every 5 s. Next: reasoning over the API (#37). | |
| 58 | 61 | |
| 59 | 62 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 60 | 63 | |
| @@ -142,7 +145,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | ||
| 142 | 145 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 143 | 146 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 144 | 147 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 145 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #35): Linux 106, Mac 114 (incl. `ChatSmokeTests`: real | |
| 148 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #36): Linux 113, Mac 122 (incl. `ChatSmokeTests`: real | |
| 146 | 149 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 147 | 150 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 148 | 151 | |
| @@ -7,7 +7,7 @@ | |||
| 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in | 7 | and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in |
| 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code | 8 | tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code |
| 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, | 9 | removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #33, |
| 10 | -model lifecycle + `/v1/models` #34, non-streaming `POST /v1/chat/completions` #35 (see | 10 | +model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35 and its streaming #36 (see |
| 11 | Architecture). Decided by the user (#31): the | 11 | Architecture). Decided by the user (#31): the |
| 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, | 12 | agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore, |
| 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` | 13 | MLX loading, thinking handling, FakeEngine and the YAML loader are reused; binary stays `rzb` |
| @@ -44,7 +44,8 @@ error envelope → API key, `GET /health`, `ServerSentEvents` helper; `ModelMana | |||
| 44 | demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService` | 44 | demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService` |
| 45 | for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`; `Chat/`: | 45 | for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`; `Chat/`: |
| 46 | `ChatCompletionRequest` → `ChatPlan`, `CompletionStream` (engine events → content / reasoning / | 46 | `ChatCompletionRequest` → `ChatPlan`, `CompletionStream` (engine events → content / reasoning / |
| 47 | -tool calls / finish + usage, stop sequences), `ChatCompletionRoute`), `RazorbillCLI` (`serve`, | 47 | +tool calls / finish + usage, stop sequences), `ChatCompletionRoute` (plain + streamed), |
| 48 | +`ChatCompletionChunk`/`ChunkBuilder`), `RazorbillCLI` (`serve`, | ||
| 48 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` | 49 | `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve` |
| 49 | runner for tests; `ServerSettings.config` carries the loaded file to the server). | 50 | runner for tests; `ServerSettings.config` carries the loaded file to the server). |
| 50 | `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` | 51 | `rzb serve [--config file] --host 127.0.0.1 --port 8080 --api-key-env RZB_API_KEY --cors-origin` |
| @@ -54,7 +55,9 @@ the variable). One engine instance per loaded model (`InferenceEngine.unload()`) | |||
| 54 | registry's default (`mlx` on the Mac, `fake` on Linux). Chat requests are stateless (fresh session, | 55 | registry's default (`mlx` on the Mac, `fake` on Linux). Chat requests are stateless (fresh session, |
| 55 | whole conversation each time, system messages through the template); stop sequences are applied | 56 | whole conversation each time, system messages through the template); stop sequences are applied |
| 56 | server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer | 57 | server side (`StopSequenceFilter` in Core); the chat route closes the connection after each answer |
| 57 | -(`Connection: close`) because it watches for client hang-ups. Next: streaming (#36). | 58 | +(`Connection: close`) because it watches for client hang-ups. Streams hold the model lease until the |
| 59 | +stream ends; a vanished streaming client is noticed by a failed write, so SSE sends a `: keep-alive` | ||
| 60 | +comment every 5 s. Next: reasoning over the API (#37). | ||
| 58 | 61 | ||
| 59 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) | 62 | ## Architecture of v0.1 (agent, removed on the v0.2 branch) |
| 60 | 63 | ||
| @@ -142,7 +145,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes | |||
| 142 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). | 145 | (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`). |
| 143 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped | 146 | Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped |
| 144 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). | 147 | signatures as `) throws -> T {` or on one line (the two tools fight over brace placement). |
| 145 | -Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #35): Linux 106, Mac 114 (incl. `ChatSmokeTests`: real | 148 | +Tests 2026-11-24 (v0.1): Linux 121, Mac 126. Tests 2026-11-25 (v0.2 after #36): Linux 113, Mac 122 (incl. `ChatSmokeTests`: real |
| 146 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). | 149 | Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache). |
| 147 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). | 150 | Server tests start the real server on a random port (`HummingbirdTesting` `.live`). |
| 148 | 151 | ||
modified
.quality/history.jsonl +1 -0 | @@ -8,3 +8,4 @@ | ||
| 8 | 8 | {"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "4d3623e", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 8, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:48Z"} |
| 9 | 9 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 9, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:03Z"} |
| 10 | 10 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 10, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:06Z"} |
| 11 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "6a3f52a", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 169, "complex": 325, "cyclo": 390, "fields": 725, "funcs": 372, "lcom": 75, "lines": 6771, "loc": 5299}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 11, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:38:59Z"} | |
| @@ -8,3 +8,4 @@ | |||
| 8 | {"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "4d3623e", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 8, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:48Z"} | 8 | {"branch": "feature/v0.2-openai-server", "breaches": ["warning-level issues: 1 (max 0)"], "commit": "4d3623e", "counts": {"warning": 1}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 8, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:28:48Z"} |
| 9 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 9, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:03Z"} | 9 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 9, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:03Z"} |
| 10 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 10, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:06Z"} | 10 | {"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "4d3623e", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 156, "complex": 296, "cyclo": 369, "fields": 670, "funcs": 349, "lcom": 73, "lines": 6345, "loc": 4948}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 10, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:29:06Z"} |
| 11 | +{"branch": "feature/v0.2-openai-server", "breaches": [], "commit": "6a3f52a", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 169, "complex": 325, "cyclo": 390, "fields": 725, "funcs": 372, "lcom": 75, "lines": 6771, "loc": 5299}, "qlty_version": "qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)", "run": 11, "smells": 0, "swiftlint_version": "0.65.1", "timestamp": "2026-11-25T12:38:59Z"} | ||
added
.quality/report-20261125T123859Z.md +73 -0 | new file mode 100644 | ||
| @@ -0,0 +1,73 @@ | ||
| 1 | +# Quality report — 2026-11-25T12:38:59Z | |
| 2 | + | |
| 3 | +- **Gate**: ✅ **PASS** | |
| 4 | +- **Commit**: `6a3f52a` 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**: #11 (previous: 2026-11-25T12:29:06Z) | |
| 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 | 372 | +23 | | |
| 32 | +| classes | 169 | +13 | | |
| 33 | +| fields | 725 | +55 | | |
| 34 | +| cyclo | 390 | +21 | | |
| 35 | +| complex | 325 | +29 | | |
| 36 | +| lcom | 75 | +2 | | |
| 37 | +| lines | 6771 | +426 | | |
| 38 | +| loc | 5299 | +351 | | |
| 39 | + | |
| 40 | +### Most complex files | |
| 41 | + | |
| 42 | +| file | complex | cyclo | loc | | |
| 43 | +|---|---|---|---| | |
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | |
| 45 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | |
| 46 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | |
| 47 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | |
| 48 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 131 | | |
| 49 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 50 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | |
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 241 | | |
| 52 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | |
| 53 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | |
| 54 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | |
| 55 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | |
| 56 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | |
| 57 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | |
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 9 | 11 | 127 | | |
| 59 | + | |
| 60 | +## Trend | |
| 61 | + | |
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | |
| 63 | +|---|---|---|---|---|---|---| | |
| 64 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | |
| 65 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | |
| 66 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | |
| 67 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | |
| 68 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | |
| 69 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | |
| 70 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | |
| 71 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | |
| 72 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | |
| 73 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| new file mode 100644 | |||
| @@ -0,0 +1,73 @@ | |||
| 1 | +# Quality report — 2026-11-25T12:38:59Z | ||
| 2 | + | ||
| 3 | +- **Gate**: ✅ **PASS** | ||
| 4 | +- **Commit**: `6a3f52a` 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**: #11 (previous: 2026-11-25T12:29:06Z) | ||
| 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 | 372 | +23 | | ||
| 32 | +| classes | 169 | +13 | | ||
| 33 | +| fields | 725 | +55 | | ||
| 34 | +| cyclo | 390 | +21 | | ||
| 35 | +| complex | 325 | +29 | | ||
| 36 | +| lcom | 75 | +2 | | ||
| 37 | +| lines | 6771 | +426 | | ||
| 38 | +| loc | 5299 | +351 | | ||
| 39 | + | ||
| 40 | +### Most complex files | ||
| 41 | + | ||
| 42 | +| file | complex | cyclo | loc | | ||
| 43 | +|---|---|---|---| | ||
| 44 | +| Sources/RazorbillServer/Chat/CompletionStream.swift | 24 | 15 | 92 | | ||
| 45 | +| tools/host-runner/host_runner.py | 22 | 22 | 141 | | ||
| 46 | +| Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | ||
| 47 | +| Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | ||
| 48 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 131 | | ||
| 49 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 50 | +| Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | ||
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 241 | | ||
| 52 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | ||
| 53 | +| Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | ||
| 54 | +| Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | ||
| 55 | +| Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | ||
| 56 | +| Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | ||
| 57 | +| Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | ||
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 9 | 11 | 127 | | ||
| 59 | + | ||
| 60 | +## Trend | ||
| 61 | + | ||
| 62 | +| run | timestamp | error | warning | smells | complex | gate | | ||
| 63 | +|---|---|---|---|---|---|---| | ||
| 64 | +| 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | | ||
| 65 | +| 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | ||
| 66 | +| 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | ||
| 67 | +| 5 | 2026-11-25T08:05:17Z | 0 | 0 | 0 | 198 | PASS | | ||
| 68 | +| 6 | 2026-11-25T12:12:54Z | 0 | 0 | 0 | 228 | PASS | | ||
| 69 | +| 7 | 2026-11-25T12:28:23Z | 0 | 0 | 1 | 311 | FAIL | | ||
| 70 | +| 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | ||
| 71 | +| 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | ||
| 72 | +| 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | ||
| 73 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
modified
.quality/report-latest.md +17 -17 | @@ -1,10 +1,10 @@ | ||
| 1 | -# Quality report — 2026-11-25T12:29:06Z | |
| 1 | +# Quality report — 2026-11-25T12:38:59Z | |
| 2 | 2 | |
| 3 | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `4d3623e` on `feature/v0.2-openai-server` | |
| 4 | +- **Commit**: `6a3f52a` on `feature/v0.2-openai-server` | |
| 5 | 5 | - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20) |
| 6 | 6 | - **swiftlint**: 0.65.1 (run directly, merged into lint issues) |
| 7 | -- **Run**: #10 (previous: 2026-11-25T12:29:03Z) | |
| 7 | +- **Run**: #11 (previous: 2026-11-25T12:29:06Z) | |
| 8 | 8 | |
| 9 | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | |
| @@ -28,14 +28,14 @@ _none_ | ||
| 28 | 28 | |
| 29 | 29 | | metric | total | vs previous | |
| 30 | 30 | |---|---|---| |
| 31 | -| funcs | 349 | ±0 | | |
| 32 | -| classes | 156 | ±0 | | |
| 33 | -| fields | 670 | ±0 | | |
| 34 | -| cyclo | 369 | ±0 | | |
| 35 | -| complex | 296 | ±0 | | |
| 36 | -| lcom | 73 | ±0 | | |
| 37 | -| lines | 6345 | ±0 | | |
| 38 | -| loc | 4948 | ±0 | | |
| 31 | +| funcs | 372 | +23 | | |
| 32 | +| classes | 169 | +13 | | |
| 33 | +| fields | 725 | +55 | | |
| 34 | +| cyclo | 390 | +21 | | |
| 35 | +| complex | 325 | +29 | | |
| 36 | +| lcom | 75 | +2 | | |
| 37 | +| lines | 6771 | +426 | | |
| 38 | +| loc | 5299 | +351 | | |
| 39 | 39 | |
| 40 | 40 | ### Most complex files |
| 41 | 41 | |
| @@ -45,23 +45,22 @@ _none_ | ||
| 45 | 45 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 46 | 46 | | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | |
| 47 | 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | |
| 48 | -| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | |
| 48 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 131 | | |
| 49 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | |
| 49 | 50 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 50 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | |
| 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 241 | | |
| 52 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | |
| 51 | 53 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 52 | 54 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | |
| 53 | 55 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 54 | 56 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | |
| 55 | 57 | | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | |
| 56 | -| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | |
| 57 | -| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | |
| 58 | -| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | |
| 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 9 | 11 | 127 | | |
| 59 | 59 | |
| 60 | 60 | ## Trend |
| 61 | 61 | |
| 62 | 62 | | run | timestamp | error | warning | smells | complex | gate | |
| 63 | 63 | |---|---|---|---|---|---|---| |
| 64 | -| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL | | |
| 65 | 64 | | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | |
| 66 | 65 | | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | |
| 67 | 66 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | |
| @@ -71,3 +70,4 @@ _none_ | ||
| 71 | 70 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | |
| 72 | 71 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | |
| 73 | 72 | | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | |
| 73 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | |
| @@ -1,10 +1,10 @@ | |||
| 1 | -# Quality report — 2026-11-25T12:29:06Z | 1 | +# Quality report — 2026-11-25T12:38:59Z |
| 2 | 2 | ||
| 3 | - **Gate**: ✅ **PASS** | 3 | - **Gate**: ✅ **PASS** |
| 4 | -- **Commit**: `4d3623e` on `feature/v0.2-openai-server` | 4 | +- **Commit**: `6a3f52a` 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**: #10 (previous: 2026-11-25T12:29:03Z) | 7 | +- **Run**: #11 (previous: 2026-11-25T12:29:06Z) |
| 8 | 8 | ||
| 9 | ## Lint issues (`qlty check`) | 9 | ## Lint issues (`qlty check`) |
| 10 | 10 | ||
| @@ -28,14 +28,14 @@ _none_ | |||
| 28 | 28 | ||
| 29 | | metric | total | vs previous | | 29 | | metric | total | vs previous | |
| 30 | |---|---|---| | 30 | |---|---|---| |
| 31 | -| funcs | 349 | ±0 | | 31 | +| funcs | 372 | +23 | |
| 32 | -| classes | 156 | ±0 | | 32 | +| classes | 169 | +13 | |
| 33 | -| fields | 670 | ±0 | | 33 | +| fields | 725 | +55 | |
| 34 | -| cyclo | 369 | ±0 | | 34 | +| cyclo | 390 | +21 | |
| 35 | -| complex | 296 | ±0 | | 35 | +| complex | 325 | +29 | |
| 36 | -| lcom | 73 | ±0 | | 36 | +| lcom | 75 | +2 | |
| 37 | -| lines | 6345 | ±0 | | 37 | +| lines | 6771 | +426 | |
| 38 | -| loc | 4948 | ±0 | | 38 | +| loc | 5299 | +351 | |
| 39 | 39 | ||
| 40 | ### Most complex files | 40 | ### Most complex files |
| 41 | 41 | ||
| @@ -45,23 +45,22 @@ _none_ | |||
| 45 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | | 45 | | tools/host-runner/host_runner.py | 22 | 22 | 141 | |
| 46 | | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | | 46 | | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 | |
| 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | | 47 | | Sources/RazorbillCore/Config/ServerConfigLoader.swift | 20 | 17 | 214 | |
| 48 | -| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 216 | | 48 | +| Sources/RazorbillServer/Chat/ChatCompletionChunk.swift | 16 | 11 | 131 | |
| 49 | +| Sources/RazorbillServer/ModelManager.swift | 16 | 22 | 220 | | ||
| 49 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | | 50 | | Sources/RazorbillCLI/Commands/ModelsCommand.swift | 13 | 7 | 100 | |
| 50 | -| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 231 | | 51 | +| Sources/RazorbillServer/Chat/ChatCompletionRequest.swift | 13 | 21 | 241 | |
| 52 | +| Tests/RazorbillServerTests/ModelManagerTests.swift | 11 | 9 | 253 | | ||
| 51 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | | 53 | | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 | |
| 52 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | | 54 | | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 | |
| 53 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | | 55 | | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 | |
| 54 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | | 56 | | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 | |
| 55 | | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | | 57 | | Sources/RazorbillCore/Models/ModelCatalog.swift | 9 | 9 | 77 | |
| 56 | -| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 8 | 9 | 112 | | 58 | +| Sources/RazorbillServer/Chat/ChatCompletionRoute.swift | 9 | 11 | 127 | |
| 57 | -| Sources/RazorbillServer/Middlewares.swift | 8 | 8 | 66 | | ||
| 58 | -| Tests/RazorbillServerTests/ModelManagerTests.swift | 8 | 7 | 234 | | ||
| 59 | 59 | ||
| 60 | ## Trend | 60 | ## Trend |
| 61 | 61 | ||
| 62 | | run | timestamp | error | warning | smells | complex | gate | | 62 | | run | timestamp | error | warning | smells | complex | gate | |
| 63 | |---|---|---|---|---|---|---| | 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 | | 64 | | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL | |
| 66 | | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | | 65 | | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS | |
| 67 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | | 66 | | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS | |
| @@ -71,3 +70,4 @@ _none_ | |||
| 71 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | | 70 | | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL | |
| 72 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | | 71 | | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS | |
| 73 | | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | | 72 | | 10 | 2026-11-25T12:29:06Z | 0 | 0 | 0 | 296 | PASS | |
| 73 | +| 11 | 2026-11-25T12:38:59Z | 0 | 0 | 0 | 325 | PASS | | ||
modified
.tickets/issues/0036-chat-completions-streaming-sse-stream-options-ca.yaml +31 -8 | @@ -1,12 +1,12 @@ | ||
| 1 | 1 | # Managed by IssueSpec. Hand edits are welcome; keep the schema valid. |
| 2 | 2 | id: 36 |
| 3 | 3 | title: "Chat completions streaming (SSE, stream_options, cancellation)" |
| 4 | -state: open | |
| 4 | +state: closed | |
| 5 | 5 | author: |
| 6 | 6 | name: k33g |
| 7 | 7 | email: ph.charriere@gmail.com |
| 8 | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | |
| 9 | +updatedAt: 2026-11-25T12:45:00.000Z | |
| 10 | 10 | labels: |
| 11 | 11 | - "kind::feature" |
| 12 | 12 | - "area::server" |
| @@ -27,42 +27,65 @@ body: | | ||
| 27 | 27 | tasks: |
| 28 | 28 | - id: 1 |
| 29 | 29 | title: "SSE writer with flushing" |
| 30 | - state: open | |
| 30 | + state: closed | |
| 31 | 31 | priority: high |
| 32 | 32 | author: |
| 33 | 33 | name: k33g |
| 34 | 34 | email: ph.charriere@gmail.com |
| 35 | 35 | createdAt: 2026-11-24T21:17:08.000Z |
| 36 | + updatedAt: 2026-11-25T12:45:00.000Z | |
| 37 | + closedAt: 2026-11-25T12:45:00.000Z | |
| 36 | 38 | - id: 2 |
| 37 | 39 | title: "Chunk sequence: role, content deltas, finish_reason, [DONE]" |
| 38 | - state: open | |
| 40 | + state: closed | |
| 39 | 41 | priority: high |
| 40 | 42 | author: |
| 41 | 43 | name: k33g |
| 42 | 44 | email: ph.charriere@gmail.com |
| 43 | 45 | createdAt: 2026-11-24T21:17:08.000Z |
| 46 | + updatedAt: 2026-11-25T12:45:00.000Z | |
| 47 | + closedAt: 2026-11-25T12:45:00.000Z | |
| 44 | 48 | - id: 3 |
| 45 | 49 | title: "stream_options.include_usage" |
| 46 | - state: open | |
| 50 | + state: closed | |
| 47 | 51 | priority: medium |
| 48 | 52 | author: |
| 49 | 53 | name: k33g |
| 50 | 54 | email: ph.charriere@gmail.com |
| 51 | 55 | createdAt: 2026-11-24T21:17:08.000Z |
| 56 | + updatedAt: 2026-11-25T12:45:00.000Z | |
| 57 | + closedAt: 2026-11-25T12:45:00.000Z | |
| 52 | 58 | - id: 4 |
| 53 | 59 | title: "Error event after the stream started" |
| 54 | - state: open | |
| 60 | + state: closed | |
| 55 | 61 | priority: medium |
| 56 | 62 | author: |
| 57 | 63 | name: k33g |
| 58 | 64 | email: ph.charriere@gmail.com |
| 59 | 65 | createdAt: 2026-11-24T21:17:08.000Z |
| 66 | + updatedAt: 2026-11-25T12:45:00.000Z | |
| 67 | + closedAt: 2026-11-25T12:45:00.000Z | |
| 60 | 68 | - id: 5 |
| 61 | 69 | title: "Tests: chunk order and content reassembly" |
| 62 | - state: open | |
| 70 | + state: closed | |
| 63 | 71 | priority: high |
| 64 | 72 | author: |
| 65 | 73 | name: k33g |
| 66 | 74 | email: ph.charriere@gmail.com |
| 67 | 75 | createdAt: 2026-11-24T21:17:08.000Z |
| 68 | -comments: [] | |
| 76 | + updatedAt: 2026-11-25T12:45:00.000Z | |
| 77 | + closedAt: 2026-11-25T12:45:00.000Z | |
| 78 | +comments: | |
| 79 | + - id: 1 | |
| 80 | + author: | |
| 81 | + name: k33g | |
| 82 | + email: ph.charriere@gmail.com | |
| 83 | + createdAt: 2026-11-25T12:45:00.000Z | |
| 84 | + body: | | |
| 85 | + Done: `stream: true` on `POST /v1/chat/completions`. | |
| 86 | + - Chunks in OpenAI's order: `delta.role` (+ empty content), `delta.content` pieces (or `delta.tool_calls` with `index`), an empty delta with `finish_reason`, then `data: [DONE]`. `stream_options.include_usage` → `"usage": null` on every chunk and a last chunk with empty `choices` and the usage. Stop sequences apply as in #35. | |
| 87 | + - Errors before the first byte (unknown model, full queue, load failure) are plain JSON errors with their status; after it, a `data: {"error": …}` event and no `[DONE]`. | |
| 88 | + - The model is held (`ModelManager.acquire`) until the stream ends, fails or is cancelled, then released; one log line per stream (`stream <id> model=… stop tokens=p+c`). | |
| 89 | + - Vanished caller: the handler returns before the body is written, so Hummingbird's inbound-close watch does not cover the stream. `ServerSentEvents.response` writes a `: keep-alive` SSE comment every 5 s (`streamKeepAlive`); the write to a closed connection fails, which cancels the events and the generation, so a hang-up is noticed within ~5 s even while the model is silent (long prompt, thinking). | |
| 90 | + Tests: 7 streaming tests (order, usage, stop/tool calls, error event, errors before start, lease release, hang-up cancels and frees the model) + Mac smoke test streaming a real Qwen3-0.6B answer token by token. Python SDK `stream=True` (with include_usage) and `curl -N` checked against the Linux binary. Linux 113, Mac 122, quality gate PASS. | |
| 91 | + | |
| @@ -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: 36 | 2 | id: 36 |
| 3 | title: "Chat completions streaming (SSE, stream_options, cancellation)" | 3 | title: "Chat completions streaming (SSE, stream_options, cancellation)" |
| 4 | -state: open | 4 | +state: closed |
| 5 | author: | 5 | author: |
| 6 | name: k33g | 6 | name: k33g |
| 7 | email: ph.charriere@gmail.com | 7 | email: ph.charriere@gmail.com |
| 8 | createdAt: 2026-11-24T21:17:08.000Z | 8 | createdAt: 2026-11-24T21:17:08.000Z |
| 9 | -updatedAt: 2026-11-24T21:17:08.000Z | 9 | +updatedAt: 2026-11-25T12:45:00.000Z |
| 10 | labels: | 10 | labels: |
| 11 | - "kind::feature" | 11 | - "kind::feature" |
| 12 | - "area::server" | 12 | - "area::server" |
| @@ -27,42 +27,65 @@ body: | | |||
| 27 | tasks: | 27 | tasks: |
| 28 | - id: 1 | 28 | - id: 1 |
| 29 | title: "SSE writer with flushing" | 29 | title: "SSE writer with flushing" |
| 30 | - state: open | 30 | + state: closed |
| 31 | priority: high | 31 | priority: high |
| 32 | author: | 32 | author: |
| 33 | name: k33g | 33 | name: k33g |
| 34 | email: ph.charriere@gmail.com | 34 | email: ph.charriere@gmail.com |
| 35 | createdAt: 2026-11-24T21:17:08.000Z | 35 | createdAt: 2026-11-24T21:17:08.000Z |
| 36 | + updatedAt: 2026-11-25T12:45:00.000Z | ||
| 37 | + closedAt: 2026-11-25T12:45:00.000Z | ||
| 36 | - id: 2 | 38 | - id: 2 |
| 37 | title: "Chunk sequence: role, content deltas, finish_reason, [DONE]" | 39 | title: "Chunk sequence: role, content deltas, finish_reason, [DONE]" |
| 38 | - state: open | 40 | + state: closed |
| 39 | priority: high | 41 | priority: high |
| 40 | author: | 42 | author: |
| 41 | name: k33g | 43 | name: k33g |
| 42 | email: ph.charriere@gmail.com | 44 | email: ph.charriere@gmail.com |
| 43 | createdAt: 2026-11-24T21:17:08.000Z | 45 | createdAt: 2026-11-24T21:17:08.000Z |
| 46 | + updatedAt: 2026-11-25T12:45:00.000Z | ||
| 47 | + closedAt: 2026-11-25T12:45:00.000Z | ||
| 44 | - id: 3 | 48 | - id: 3 |
| 45 | title: "stream_options.include_usage" | 49 | title: "stream_options.include_usage" |
| 46 | - state: open | 50 | + state: closed |
| 47 | priority: medium | 51 | priority: medium |
| 48 | author: | 52 | author: |
| 49 | name: k33g | 53 | name: k33g |
| 50 | email: ph.charriere@gmail.com | 54 | email: ph.charriere@gmail.com |
| 51 | createdAt: 2026-11-24T21:17:08.000Z | 55 | createdAt: 2026-11-24T21:17:08.000Z |
| 56 | + updatedAt: 2026-11-25T12:45:00.000Z | ||
| 57 | + closedAt: 2026-11-25T12:45:00.000Z | ||
| 52 | - id: 4 | 58 | - id: 4 |
| 53 | title: "Error event after the stream started" | 59 | title: "Error event after the stream started" |
| 54 | - state: open | 60 | + state: closed |
| 55 | priority: medium | 61 | priority: medium |
| 56 | author: | 62 | author: |
| 57 | name: k33g | 63 | name: k33g |
| 58 | email: ph.charriere@gmail.com | 64 | email: ph.charriere@gmail.com |
| 59 | createdAt: 2026-11-24T21:17:08.000Z | 65 | createdAt: 2026-11-24T21:17:08.000Z |
| 66 | + updatedAt: 2026-11-25T12:45:00.000Z | ||
| 67 | + closedAt: 2026-11-25T12:45:00.000Z | ||
| 60 | - id: 5 | 68 | - id: 5 |
| 61 | title: "Tests: chunk order and content reassembly" | 69 | title: "Tests: chunk order and content reassembly" |
| 62 | - state: open | 70 | + state: closed |
| 63 | priority: high | 71 | priority: high |
| 64 | author: | 72 | author: |
| 65 | name: k33g | 73 | name: k33g |
| 66 | email: ph.charriere@gmail.com | 74 | email: ph.charriere@gmail.com |
| 67 | createdAt: 2026-11-24T21:17:08.000Z | 75 | createdAt: 2026-11-24T21:17:08.000Z |
| 68 | -comments: [] | 76 | + updatedAt: 2026-11-25T12:45:00.000Z |
| 77 | + closedAt: 2026-11-25T12:45:00.000Z | ||
| 78 | +comments: | ||
| 79 | + - id: 1 | ||
| 80 | + author: | ||
| 81 | + name: k33g | ||
| 82 | + email: ph.charriere@gmail.com | ||
| 83 | + createdAt: 2026-11-25T12:45:00.000Z | ||
| 84 | + body: | | ||
| 85 | + Done: `stream: true` on `POST /v1/chat/completions`. | ||
| 86 | + - Chunks in OpenAI's order: `delta.role` (+ empty content), `delta.content` pieces (or `delta.tool_calls` with `index`), an empty delta with `finish_reason`, then `data: [DONE]`. `stream_options.include_usage` → `"usage": null` on every chunk and a last chunk with empty `choices` and the usage. Stop sequences apply as in #35. | ||
| 87 | + - Errors before the first byte (unknown model, full queue, load failure) are plain JSON errors with their status; after it, a `data: {"error": …}` event and no `[DONE]`. | ||
| 88 | + - The model is held (`ModelManager.acquire`) until the stream ends, fails or is cancelled, then released; one log line per stream (`stream <id> model=… stop tokens=p+c`). | ||
| 89 | + - Vanished caller: the handler returns before the body is written, so Hummingbird's inbound-close watch does not cover the stream. `ServerSentEvents.response` writes a `: keep-alive` SSE comment every 5 s (`streamKeepAlive`); the write to a closed connection fails, which cancels the events and the generation, so a hang-up is noticed within ~5 s even while the model is silent (long prompt, thinking). | ||
| 90 | + Tests: 7 streaming tests (order, usage, stop/tool calls, error event, errors before start, lease release, hang-up cancels and frees the model) + Mac smoke test streaming a real Qwen3-0.6B answer token by token. Python SDK `stream=True` (with include_usage) and `curl -N` checked against the Linux binary. Linux 113, Mac 122, quality gate PASS. | ||
| 91 | + | ||
added
Sources/RazorbillServer/Chat/ChatCompletionChunk.swift +163 -0 | new file mode 100644 | ||
| @@ -0,0 +1,163 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Logging | |
| 3 | +import RazorbillCore | |
| 4 | + | |
| 5 | +/// `chat.completion.chunk`: one event of a streamed answer. | |
| 6 | +/// | |
| 7 | +/// The sequence is OpenAI's: a first chunk with `delta.role`, then `delta.content` (or | |
| 8 | +/// `delta.tool_calls`) pieces, then a chunk with an empty delta and `finish_reason`; with | |
| 9 | +/// `stream_options.include_usage`, a last chunk with empty `choices` and the `usage` (every other | |
| 10 | +/// chunk then carries `"usage": null`). | |
| 11 | +struct ChatCompletionChunk: Encodable, Sendable { | |
| 12 | + let id: String | |
| 13 | + let created: Int | |
| 14 | + let model: String | |
| 15 | + let choices: [ChunkChoice] | |
| 16 | + /// `nil` and not written unless usage was requested; then `null` until the last chunk. | |
| 17 | + let usage: Usage? | |
| 18 | + let includesUsage: Bool | |
| 19 | + | |
| 20 | + enum CodingKeys: String, CodingKey { | |
| 21 | + case id, object, created, model, choices, usage | |
| 22 | + } | |
| 23 | + | |
| 24 | + func encode(to encoder: any Encoder) throws { | |
| 25 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 26 | + try container.encode(id, forKey: .id) | |
| 27 | + try container.encode("chat.completion.chunk", forKey: .object) | |
| 28 | + try container.encode(created, forKey: .created) | |
| 29 | + try container.encode(model, forKey: .model) | |
| 30 | + try container.encode(choices, forKey: .choices) | |
| 31 | + if includesUsage { try container.encode(usage, forKey: .usage) } | |
| 32 | + } | |
| 33 | +} | |
| 34 | + | |
| 35 | +/// The one choice of a chunk. | |
| 36 | +struct ChunkChoice: Encodable, Sendable { | |
| 37 | + let delta: ChunkDelta | |
| 38 | + let finishReason: FinishReason? | |
| 39 | + | |
| 40 | + enum CodingKeys: String, CodingKey { | |
| 41 | + case index, delta, logprobs | |
| 42 | + case finishReason = "finish_reason" | |
| 43 | + } | |
| 44 | + | |
| 45 | + func encode(to encoder: any Encoder) throws { | |
| 46 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 47 | + try container.encode(0, forKey: .index) | |
| 48 | + try container.encode(delta, forKey: .delta) | |
| 49 | + try container.encodeNil(forKey: .logprobs) | |
| 50 | + try container.encode(finishReason, forKey: .finishReason) | |
| 51 | + } | |
| 52 | +} | |
| 53 | + | |
| 54 | +/// What a chunk adds to the message; absent fields are not written. | |
| 55 | +struct ChunkDelta: Encodable, Sendable { | |
| 56 | + var role: String? | |
| 57 | + var content: String? | |
| 58 | + var toolCalls: [IndexedToolCall]? | |
| 59 | + | |
| 60 | + enum CodingKeys: String, CodingKey { | |
| 61 | + case role, content | |
| 62 | + case toolCalls = "tool_calls" | |
| 63 | + } | |
| 64 | +} | |
| 65 | + | |
| 66 | +/// A streamed tool call: OpenAI numbers them with `index`. | |
| 67 | +struct IndexedToolCall: Encodable, Sendable { | |
| 68 | + let index: Int | |
| 69 | + let call: WireToolCall | |
| 70 | + | |
| 71 | + enum CodingKeys: String, CodingKey { | |
| 72 | + case index, id, type, function | |
| 73 | + } | |
| 74 | + | |
| 75 | + func encode(to encoder: any Encoder) throws { | |
| 76 | + var container = encoder.container(keyedBy: CodingKeys.self) | |
| 77 | + try container.encode(index, forKey: .index) | |
| 78 | + try container.encode(call.id, forKey: .id) | |
| 79 | + try container.encode(call.type, forKey: .type) | |
| 80 | + try container.encode(call.function, forKey: .function) | |
| 81 | + } | |
| 82 | +} | |
| 83 | + | |
| 84 | +/// Builds the chunks of one streamed answer. | |
| 85 | +struct ChunkBuilder: Sendable { | |
| 86 | + let id = ChatCompletionRoute.newID() | |
| 87 | + let created = Int(Date().timeIntervalSince1970) | |
| 88 | + let model: String | |
| 89 | + let includeUsage: Bool | |
| 90 | + private var toolCallCount = 0 | |
| 91 | + | |
| 92 | + init(model: String, includeUsage: Bool) { | |
| 93 | + self.model = model | |
| 94 | + self.includeUsage = includeUsage | |
| 95 | + } | |
| 96 | + | |
| 97 | + /// The first chunk: the assistant's role and empty content. | |
| 98 | + func start() -> ChatCompletionChunk { | |
| 99 | + chunk(ChunkDelta(role: "assistant", content: "")) | |
| 100 | + } | |
| 101 | + | |
| 102 | + mutating func chunks(for piece: CompletionPiece) -> [ChatCompletionChunk] { | |
| 103 | + switch piece { | |
| 104 | + case .content(let text): | |
| 105 | + return [chunk(ChunkDelta(content: text))] | |
| 106 | + case .reasoning: | |
| 107 | + return [] // reasoning_content comes with ticket #37 | |
| 108 | + case .toolCall(let call): | |
| 109 | + defer { toolCallCount += 1 } | |
| 110 | + let indexed = IndexedToolCall(index: toolCallCount, call: WireToolCall(call)) | |
| 111 | + return [chunk(ChunkDelta(toolCalls: [indexed]))] | |
| 112 | + case .finished(let reason, let usage): | |
| 113 | + let last = chunk(ChunkDelta(), finishReason: reason) | |
| 114 | + guard includeUsage else { return [last] } | |
| 115 | + let usageChunk = ChatCompletionChunk( | |
| 116 | + id: id, created: created, model: model, choices: [], usage: usage, | |
| 117 | + includesUsage: true) | |
| 118 | + return [last, usageChunk] | |
| 119 | + } | |
| 120 | + } | |
| 121 | + | |
| 122 | + private func chunk( | |
| 123 | + _ delta: ChunkDelta, finishReason: FinishReason? = nil | |
| 124 | + ) -> ChatCompletionChunk { | |
| 125 | + ChatCompletionChunk( | |
| 126 | + id: id, created: created, model: model, | |
| 127 | + choices: [ChunkChoice(delta: delta, finishReason: finishReason)], usage: nil, | |
| 128 | + includesUsage: includeUsage) | |
| 129 | + } | |
| 130 | +} | |
| 131 | + | |
| 132 | +extension ChatCompletionRoute { | |
| 133 | + /// The chunks of a streamed answer. The model stays held until the stream ends, fails or is | |
| 134 | + /// cancelled (client gone); then the lease is released and a summary is logged. | |
| 135 | + static func chunks( | |
| 136 | + _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, plan: ChatPlan, | |
| 137 | + logger: Logger | |
| 138 | + ) -> AsyncThrowingStream<ChatCompletionChunk, Error> { | |
| 139 | + AsyncThrowingStream { continuation in | |
| 140 | + let task = Task { | |
| 141 | + var builder = ChunkBuilder(model: plan.model, includeUsage: plan.includeUsage) | |
| 142 | + var outcome = "cancelled" | |
| 143 | + continuation.yield(builder.start()) | |
| 144 | + do { | |
| 145 | + for try await piece in pieces { | |
| 146 | + if case .finished(let reason, let usage) = piece { | |
| 147 | + outcome = | |
| 148 | + "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | |
| 149 | + } | |
| 150 | + for chunk in builder.chunks(for: piece) { continuation.yield(chunk) } | |
| 151 | + } | |
| 152 | + continuation.finish() | |
| 153 | + } catch { | |
| 154 | + if !(error is CancellationError) { outcome = "failed: \(error)" } | |
| 155 | + continuation.finish(throwing: error) | |
| 156 | + } | |
| 157 | + await lease.release() | |
| 158 | + logger.info("stream \(builder.id) model=\(plan.model) \(outcome)") | |
| 159 | + } | |
| 160 | + continuation.onTermination = { _ in task.cancel() } | |
| 161 | + } | |
| 162 | + } | |
| 163 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,163 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Logging | ||
| 3 | +import RazorbillCore | ||
| 4 | + | ||
| 5 | +/// `chat.completion.chunk`: one event of a streamed answer. | ||
| 6 | +/// | ||
| 7 | +/// The sequence is OpenAI's: a first chunk with `delta.role`, then `delta.content` (or | ||
| 8 | +/// `delta.tool_calls`) pieces, then a chunk with an empty delta and `finish_reason`; with | ||
| 9 | +/// `stream_options.include_usage`, a last chunk with empty `choices` and the `usage` (every other | ||
| 10 | +/// chunk then carries `"usage": null`). | ||
| 11 | +struct ChatCompletionChunk: Encodable, Sendable { | ||
| 12 | + let id: String | ||
| 13 | + let created: Int | ||
| 14 | + let model: String | ||
| 15 | + let choices: [ChunkChoice] | ||
| 16 | + /// `nil` and not written unless usage was requested; then `null` until the last chunk. | ||
| 17 | + let usage: Usage? | ||
| 18 | + let includesUsage: Bool | ||
| 19 | + | ||
| 20 | + enum CodingKeys: String, CodingKey { | ||
| 21 | + case id, object, created, model, choices, usage | ||
| 22 | + } | ||
| 23 | + | ||
| 24 | + func encode(to encoder: any Encoder) throws { | ||
| 25 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 26 | + try container.encode(id, forKey: .id) | ||
| 27 | + try container.encode("chat.completion.chunk", forKey: .object) | ||
| 28 | + try container.encode(created, forKey: .created) | ||
| 29 | + try container.encode(model, forKey: .model) | ||
| 30 | + try container.encode(choices, forKey: .choices) | ||
| 31 | + if includesUsage { try container.encode(usage, forKey: .usage) } | ||
| 32 | + } | ||
| 33 | +} | ||
| 34 | + | ||
| 35 | +/// The one choice of a chunk. | ||
| 36 | +struct ChunkChoice: Encodable, Sendable { | ||
| 37 | + let delta: ChunkDelta | ||
| 38 | + let finishReason: FinishReason? | ||
| 39 | + | ||
| 40 | + enum CodingKeys: String, CodingKey { | ||
| 41 | + case index, delta, logprobs | ||
| 42 | + case finishReason = "finish_reason" | ||
| 43 | + } | ||
| 44 | + | ||
| 45 | + func encode(to encoder: any Encoder) throws { | ||
| 46 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 47 | + try container.encode(0, forKey: .index) | ||
| 48 | + try container.encode(delta, forKey: .delta) | ||
| 49 | + try container.encodeNil(forKey: .logprobs) | ||
| 50 | + try container.encode(finishReason, forKey: .finishReason) | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// What a chunk adds to the message; absent fields are not written. | ||
| 55 | +struct ChunkDelta: Encodable, Sendable { | ||
| 56 | + var role: String? | ||
| 57 | + var content: String? | ||
| 58 | + var toolCalls: [IndexedToolCall]? | ||
| 59 | + | ||
| 60 | + enum CodingKeys: String, CodingKey { | ||
| 61 | + case role, content | ||
| 62 | + case toolCalls = "tool_calls" | ||
| 63 | + } | ||
| 64 | +} | ||
| 65 | + | ||
| 66 | +/// A streamed tool call: OpenAI numbers them with `index`. | ||
| 67 | +struct IndexedToolCall: Encodable, Sendable { | ||
| 68 | + let index: Int | ||
| 69 | + let call: WireToolCall | ||
| 70 | + | ||
| 71 | + enum CodingKeys: String, CodingKey { | ||
| 72 | + case index, id, type, function | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + func encode(to encoder: any Encoder) throws { | ||
| 76 | + var container = encoder.container(keyedBy: CodingKeys.self) | ||
| 77 | + try container.encode(index, forKey: .index) | ||
| 78 | + try container.encode(call.id, forKey: .id) | ||
| 79 | + try container.encode(call.type, forKey: .type) | ||
| 80 | + try container.encode(call.function, forKey: .function) | ||
| 81 | + } | ||
| 82 | +} | ||
| 83 | + | ||
| 84 | +/// Builds the chunks of one streamed answer. | ||
| 85 | +struct ChunkBuilder: Sendable { | ||
| 86 | + let id = ChatCompletionRoute.newID() | ||
| 87 | + let created = Int(Date().timeIntervalSince1970) | ||
| 88 | + let model: String | ||
| 89 | + let includeUsage: Bool | ||
| 90 | + private var toolCallCount = 0 | ||
| 91 | + | ||
| 92 | + init(model: String, includeUsage: Bool) { | ||
| 93 | + self.model = model | ||
| 94 | + self.includeUsage = includeUsage | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + /// The first chunk: the assistant's role and empty content. | ||
| 98 | + func start() -> ChatCompletionChunk { | ||
| 99 | + chunk(ChunkDelta(role: "assistant", content: "")) | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + mutating func chunks(for piece: CompletionPiece) -> [ChatCompletionChunk] { | ||
| 103 | + switch piece { | ||
| 104 | + case .content(let text): | ||
| 105 | + return [chunk(ChunkDelta(content: text))] | ||
| 106 | + case .reasoning: | ||
| 107 | + return [] // reasoning_content comes with ticket #37 | ||
| 108 | + case .toolCall(let call): | ||
| 109 | + defer { toolCallCount += 1 } | ||
| 110 | + let indexed = IndexedToolCall(index: toolCallCount, call: WireToolCall(call)) | ||
| 111 | + return [chunk(ChunkDelta(toolCalls: [indexed]))] | ||
| 112 | + case .finished(let reason, let usage): | ||
| 113 | + let last = chunk(ChunkDelta(), finishReason: reason) | ||
| 114 | + guard includeUsage else { return [last] } | ||
| 115 | + let usageChunk = ChatCompletionChunk( | ||
| 116 | + id: id, created: created, model: model, choices: [], usage: usage, | ||
| 117 | + includesUsage: true) | ||
| 118 | + return [last, usageChunk] | ||
| 119 | + } | ||
| 120 | + } | ||
| 121 | + | ||
| 122 | + private func chunk( | ||
| 123 | + _ delta: ChunkDelta, finishReason: FinishReason? = nil | ||
| 124 | + ) -> ChatCompletionChunk { | ||
| 125 | + ChatCompletionChunk( | ||
| 126 | + id: id, created: created, model: model, | ||
| 127 | + choices: [ChunkChoice(delta: delta, finishReason: finishReason)], usage: nil, | ||
| 128 | + includesUsage: includeUsage) | ||
| 129 | + } | ||
| 130 | +} | ||
| 131 | + | ||
| 132 | +extension ChatCompletionRoute { | ||
| 133 | + /// The chunks of a streamed answer. The model stays held until the stream ends, fails or is | ||
| 134 | + /// cancelled (client gone); then the lease is released and a summary is logged. | ||
| 135 | + static func chunks( | ||
| 136 | + _ pieces: AsyncThrowingStream<CompletionPiece, Error>, lease: ModelLease, plan: ChatPlan, | ||
| 137 | + logger: Logger | ||
| 138 | + ) -> AsyncThrowingStream<ChatCompletionChunk, Error> { | ||
| 139 | + AsyncThrowingStream { continuation in | ||
| 140 | + let task = Task { | ||
| 141 | + var builder = ChunkBuilder(model: plan.model, includeUsage: plan.includeUsage) | ||
| 142 | + var outcome = "cancelled" | ||
| 143 | + continuation.yield(builder.start()) | ||
| 144 | + do { | ||
| 145 | + for try await piece in pieces { | ||
| 146 | + if case .finished(let reason, let usage) = piece { | ||
| 147 | + outcome = | ||
| 148 | + "\(reason.rawValue) tokens=\(usage.promptTokens)+\(usage.completionTokens)" | ||
| 149 | + } | ||
| 150 | + for chunk in builder.chunks(for: piece) { continuation.yield(chunk) } | ||
| 151 | + } | ||
| 152 | + continuation.finish() | ||
| 153 | + } catch { | ||
| 154 | + if !(error is CancellationError) { outcome = "failed: \(error)" } | ||
| 155 | + continuation.finish(throwing: error) | ||
| 156 | + } | ||
| 157 | + await lease.release() | ||
| 158 | + logger.info("stream \(builder.id) model=\(plan.model) \(outcome)") | ||
| 159 | + } | ||
| 160 | + continuation.onTermination = { _ in task.cancel() } | ||
| 161 | + } | ||
| 162 | + } | ||
| 163 | +} | ||
modified
Sources/RazorbillServer/Chat/ChatCompletionRequest.swift +15 -1 | @@ -17,6 +17,7 @@ struct ChatCompletionRequest: Decodable, Sendable { | ||
| 17 | 17 | var presencePenalty: Double? |
| 18 | 18 | var frequencyPenalty: Double? |
| 19 | 19 | var stream: Bool? |
| 20 | + var streamOptions: StreamOptions? | |
| 20 | 21 | var logprobs: Bool? |
| 21 | 22 | var tools: ConfigValue? |
| 22 | 23 | var responseFormat: ConfigValue? |
| @@ -30,6 +31,7 @@ struct ChatCompletionRequest: Decodable, Sendable { | ||
| 30 | 31 | case presencePenalty = "presence_penalty" |
| 31 | 32 | case frequencyPenalty = "frequency_penalty" |
| 32 | 33 | case responseFormat = "response_format" |
| 34 | + case streamOptions = "stream_options" | |
| 33 | 35 | } |
| 34 | 36 | |
| 35 | 37 | /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. |
| @@ -44,6 +46,15 @@ struct ChatCompletionRequest: Decodable, Sendable { | ||
| 44 | 46 | } |
| 45 | 47 | } |
| 46 | 48 | |
| 49 | +/// `stream_options`. | |
| 50 | +struct StreamOptions: Decodable, Sendable { | |
| 51 | + var includeUsage: Bool? | |
| 52 | + | |
| 53 | + enum CodingKeys: String, CodingKey { | |
| 54 | + case includeUsage = "include_usage" | |
| 55 | + } | |
| 56 | +} | |
| 57 | + | |
| 47 | 58 | /// `stop`: one string or a list of strings. |
| 48 | 59 | struct StopField: Decodable, Sendable { |
| 49 | 60 | let values: [String] |
| @@ -117,6 +128,8 @@ struct ChatPlan: Sendable { | ||
| 117 | 128 | var frequencyPenalty: Double? |
| 118 | 129 | var stops: [String] |
| 119 | 130 | var stream: Bool |
| 131 | + /// `stream_options.include_usage`: a last chunk with the token counts. | |
| 132 | + var includeUsage = false | |
| 120 | 133 | |
| 121 | 134 | /// The settings for `model`: its defaults, then the client's values, then its locks. |
| 122 | 135 | func settings(for model: ResolvedModel) -> GenerationSettings { |
| @@ -150,7 +163,8 @@ extension ChatCompletionRequest { | ||
| 150 | 163 | client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit), |
| 151 | 164 | seed: seed.map { UInt64(bitPattern: $0) }, |
| 152 | 165 | presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, |
| 153 | - stops: stops, stream: stream ?? false) | |
| 166 | + stops: stops, stream: stream ?? false, | |
| 167 | + includeUsage: streamOptions?.includeUsage ?? false) | |
| 154 | 168 | } |
| 155 | 169 | |
| 156 | 170 | /// Fields razorbill does not handle yet: refused rather than silently ignored. |
| @@ -17,6 +17,7 @@ struct ChatCompletionRequest: Decodable, Sendable { | |||
| 17 | var presencePenalty: Double? | 17 | var presencePenalty: Double? |
| 18 | var frequencyPenalty: Double? | 18 | var frequencyPenalty: Double? |
| 19 | var stream: Bool? | 19 | var stream: Bool? |
| 20 | + var streamOptions: StreamOptions? | ||
| 20 | var logprobs: Bool? | 21 | var logprobs: Bool? |
| 21 | var tools: ConfigValue? | 22 | var tools: ConfigValue? |
| 22 | var responseFormat: ConfigValue? | 23 | var responseFormat: ConfigValue? |
| @@ -30,6 +31,7 @@ struct ChatCompletionRequest: Decodable, Sendable { | |||
| 30 | case presencePenalty = "presence_penalty" | 31 | case presencePenalty = "presence_penalty" |
| 31 | case frequencyPenalty = "frequency_penalty" | 32 | case frequencyPenalty = "frequency_penalty" |
| 32 | case responseFormat = "response_format" | 33 | case responseFormat = "response_format" |
| 34 | + case streamOptions = "stream_options" | ||
| 33 | } | 35 | } |
| 34 | 36 | ||
| 35 | /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. | 37 | /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field. |
| @@ -44,6 +46,15 @@ struct ChatCompletionRequest: Decodable, Sendable { | |||
| 44 | } | 46 | } |
| 45 | } | 47 | } |
| 46 | 48 | ||
| 49 | +/// `stream_options`. | ||
| 50 | +struct StreamOptions: Decodable, Sendable { | ||
| 51 | + var includeUsage: Bool? | ||
| 52 | + | ||
| 53 | + enum CodingKeys: String, CodingKey { | ||
| 54 | + case includeUsage = "include_usage" | ||
| 55 | + } | ||
| 56 | +} | ||
| 57 | + | ||
| 47 | /// `stop`: one string or a list of strings. | 58 | /// `stop`: one string or a list of strings. |
| 48 | struct StopField: Decodable, Sendable { | 59 | struct StopField: Decodable, Sendable { |
| 49 | let values: [String] | 60 | let values: [String] |
| @@ -117,6 +128,8 @@ struct ChatPlan: Sendable { | |||
| 117 | var frequencyPenalty: Double? | 128 | var frequencyPenalty: Double? |
| 118 | var stops: [String] | 129 | var stops: [String] |
| 119 | var stream: Bool | 130 | var stream: Bool |
| 131 | + /// `stream_options.include_usage`: a last chunk with the token counts. | ||
| 132 | + var includeUsage = false | ||
| 120 | 133 | ||
| 121 | /// The settings for `model`: its defaults, then the client's values, then its locks. | 134 | /// The settings for `model`: its defaults, then the client's values, then its locks. |
| 122 | func settings(for model: ResolvedModel) -> GenerationSettings { | 135 | func settings(for model: ResolvedModel) -> GenerationSettings { |
| @@ -150,7 +163,8 @@ extension ChatCompletionRequest { | |||
| 150 | client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit), | 163 | client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit), |
| 151 | seed: seed.map { UInt64(bitPattern: $0) }, | 164 | seed: seed.map { UInt64(bitPattern: $0) }, |
| 152 | presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, | 165 | presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty, |
| 153 | - stops: stops, stream: stream ?? false) | 166 | + stops: stops, stream: stream ?? false, |
| 167 | + includeUsage: streamOptions?.includeUsage ?? false) | ||
| 154 | } | 168 | } |
| 155 | 169 | ||
| 156 | /// Fields razorbill does not handle yet: refused rather than silently ignored. | 170 | /// Fields razorbill does not handle yet: refused rather than silently ignored. |
modified
Sources/RazorbillServer/Chat/ChatCompletionRoute.swift +23 -3 | @@ -58,6 +58,8 @@ struct AssistantMessage: Encodable, Sendable { | ||
| 58 | 58 | /// until the answer is complete. If the client disconnects, the generation is cancelled. |
| 59 | 59 | struct ChatCompletionRoute { |
| 60 | 60 | let models: ModelManager |
| 61 | + /// How often a streamed answer writes a `: keep-alive` comment while the model is silent. | |
| 62 | + var streamKeepAlive: Duration = .seconds(5) | |
| 61 | 63 | |
| 62 | 64 | func add(to router: Router<ServerContext>) { |
| 63 | 65 | router.post("/v1/chat/completions") { request, context in |
| @@ -81,9 +83,8 @@ struct ChatCompletionRoute { | ||
| 81 | 83 | func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { |
| 82 | 84 | let buffer = try await body.collect(upTo: context.maxUploadSize) |
| 83 | 85 | let plan = try ChatCompletionRequest.decode(Data(buffer: buffer)).validated() |
| 84 | - guard !plan.stream else { | |
| 85 | - throw OpenAIError( | |
| 86 | - .badRequest, message: "stream: true is not supported yet.", param: "stream") | |
| 86 | + if plan.stream { | |
| 87 | + return try await stream(plan, context: context) | |
| 87 | 88 | } |
| 88 | 89 | let response = try await complete(plan) |
| 89 | 90 | context.usage.record( |
| @@ -92,6 +93,25 @@ struct ChatCompletionRoute { | ||
| 92 | 93 | return try jsonResponse(response) |
| 93 | 94 | } |
| 94 | 95 | |
| 96 | + /// Errors up to the first byte (unknown model, full queue, load failure) are plain JSON | |
| 97 | + /// errors with their status; later ones become an error event in the stream. | |
| 98 | + func stream(_ plan: ChatPlan, context: ServerContext) async throws -> Response { | |
| 99 | + let lease = try await models.acquire(plan.model) | |
| 100 | + let pieces: AsyncThrowingStream<CompletionPiece, Error> | |
| 101 | + do { | |
| 102 | + let setup = SessionSetup( | |
| 103 | + system: "", tools: [], generation: plan.settings(for: lease.model)) | |
| 104 | + let session = try await lease.engine.makeSession(setup) | |
| 105 | + pieces = CompletionStream.pieces(from: session.send(plan.messages), stops: plan.stops) | |
| 106 | + } catch { | |
| 107 | + await lease.release() | |
| 108 | + throw error | |
| 109 | + } | |
| 110 | + context.usage.record(model: plan.model) | |
| 111 | + let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger) | |
| 112 | + return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive) | |
| 113 | + } | |
| 114 | + | |
| 95 | 115 | func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { |
| 96 | 116 | try await models.withModel(plan.model) { lease in |
| 97 | 117 | let setup = SessionSetup( |
| @@ -58,6 +58,8 @@ struct AssistantMessage: Encodable, Sendable { | |||
| 58 | /// until the answer is complete. If the client disconnects, the generation is cancelled. | 58 | /// until the answer is complete. If the client disconnects, the generation is cancelled. |
| 59 | struct ChatCompletionRoute { | 59 | struct ChatCompletionRoute { |
| 60 | let models: ModelManager | 60 | let models: ModelManager |
| 61 | + /// How often a streamed answer writes a `: keep-alive` comment while the model is silent. | ||
| 62 | + var streamKeepAlive: Duration = .seconds(5) | ||
| 61 | 63 | ||
| 62 | func add(to router: Router<ServerContext>) { | 64 | func add(to router: Router<ServerContext>) { |
| 63 | router.post("/v1/chat/completions") { request, context in | 65 | router.post("/v1/chat/completions") { request, context in |
| @@ -81,9 +83,8 @@ struct ChatCompletionRoute { | |||
| 81 | func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { | 83 | func answer(_ body: RequestBody, context: ServerContext) async throws -> Response { |
| 82 | let buffer = try await body.collect(upTo: context.maxUploadSize) | 84 | let buffer = try await body.collect(upTo: context.maxUploadSize) |
| 83 | let plan = try ChatCompletionRequest.decode(Data(buffer: buffer)).validated() | 85 | let plan = try ChatCompletionRequest.decode(Data(buffer: buffer)).validated() |
| 84 | - guard !plan.stream else { | 86 | + if plan.stream { |
| 85 | - throw OpenAIError( | 87 | + return try await stream(plan, context: context) |
| 86 | - .badRequest, message: "stream: true is not supported yet.", param: "stream") | ||
| 87 | } | 88 | } |
| 88 | let response = try await complete(plan) | 89 | let response = try await complete(plan) |
| 89 | context.usage.record( | 90 | context.usage.record( |
| @@ -92,6 +93,25 @@ struct ChatCompletionRoute { | |||
| 92 | return try jsonResponse(response) | 93 | return try jsonResponse(response) |
| 93 | } | 94 | } |
| 94 | 95 | ||
| 96 | + /// Errors up to the first byte (unknown model, full queue, load failure) are plain JSON | ||
| 97 | + /// errors with their status; later ones become an error event in the stream. | ||
| 98 | + func stream(_ plan: ChatPlan, context: ServerContext) async throws -> Response { | ||
| 99 | + let lease = try await models.acquire(plan.model) | ||
| 100 | + let pieces: AsyncThrowingStream<CompletionPiece, Error> | ||
| 101 | + do { | ||
| 102 | + let setup = SessionSetup( | ||
| 103 | + system: "", tools: [], generation: plan.settings(for: lease.model)) | ||
| 104 | + let session = try await lease.engine.makeSession(setup) | ||
| 105 | + pieces = CompletionStream.pieces(from: session.send(plan.messages), stops: plan.stops) | ||
| 106 | + } catch { | ||
| 107 | + await lease.release() | ||
| 108 | + throw error | ||
| 109 | + } | ||
| 110 | + context.usage.record(model: plan.model) | ||
| 111 | + let chunks = Self.chunks(pieces, lease: lease, plan: plan, logger: context.logger) | ||
| 112 | + return ServerSentEvents.response(chunks, keepAlive: streamKeepAlive) | ||
| 113 | + } | ||
| 114 | + | ||
| 95 | func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { | 115 | func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse { |
| 96 | try await models.withModel(plan.model) { lease in | 116 | try await models.withModel(plan.model) { lease in |
| 97 | let setup = SessionSetup( | 117 | let setup = SessionSetup( |
modified
Sources/RazorbillServer/ModelManager.swift +6 -0 | @@ -285,6 +285,12 @@ public actor ModelManager { | ||
| 285 | 285 | return slots[key]?.waiters.count ?? 0 |
| 286 | 286 | } |
| 287 | 287 | |
| 288 | + /// A request holds `name` right now (tests and diagnostics). | |
| 289 | + func isBusy(_ name: String) throws -> Bool { | |
| 290 | + let key = try catalog.resolve(name).source.description | |
| 291 | + return slots[key]?.busy ?? false | |
| 292 | + } | |
| 293 | + | |
| 288 | 294 | /// Sources of the models currently loaded, as `ModelReference.description`. |
| 289 | 295 | public func loadedSources() -> Set<String> { |
| 290 | 296 | Set(slots.filter { $0.value.engine != nil }.keys) |
| @@ -285,6 +285,12 @@ public actor ModelManager { | |||
| 285 | return slots[key]?.waiters.count ?? 0 | 285 | return slots[key]?.waiters.count ?? 0 |
| 286 | } | 286 | } |
| 287 | 287 | ||
| 288 | + /// A request holds `name` right now (tests and diagnostics). | ||
| 289 | + func isBusy(_ name: String) throws -> Bool { | ||
| 290 | + let key = try catalog.resolve(name).source.description | ||
| 291 | + return slots[key]?.busy ?? false | ||
| 292 | + } | ||
| 293 | + | ||
| 288 | /// Sources of the models currently loaded, as `ModelReference.description`. | 294 | /// Sources of the models currently loaded, as `ModelReference.description`. |
| 289 | public func loadedSources() -> Set<String> { | 295 | public func loadedSources() -> Set<String> { |
| 290 | Set(slots.filter { $0.value.engine != nil }.keys) | 296 | Set(slots.filter { $0.value.engine != nil }.keys) |
modified
Sources/RazorbillServer/RazorbillServer.swift +4 -2 | @@ -24,8 +24,10 @@ public enum RazorbillServer { | ||
| 24 | 24 | /// |
| 25 | 25 | /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key. |
| 26 | 26 | /// The error envelope sits inside CORS so browser clients can read error bodies too. |
| 27 | + /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model | |
| 28 | + /// is silent, which is also how fast a vanished client is noticed. | |
| 27 | 29 | public static func makeRouter( |
| 28 | - _ settings: ServerSettings, models: ModelManager | |
| 30 | + _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5) | |
| 29 | 31 | ) -> Router<ServerContext> { |
| 30 | 32 | let router = Router(context: ServerContext.self) |
| 31 | 33 | router.middlewares.add(RequestLogMiddleware()) |
| @@ -39,7 +41,7 @@ public enum RazorbillServer { | ||
| 39 | 41 | } |
| 40 | 42 | addHealthRoute(to: router) |
| 41 | 43 | ModelRoutes(models: models).add(to: router) |
| 42 | - ChatCompletionRoute(models: models).add(to: router) | |
| 44 | + ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) | |
| 43 | 45 | return router |
| 44 | 46 | } |
| 45 | 47 | |
| @@ -24,8 +24,10 @@ public enum RazorbillServer { | |||
| 24 | /// | 24 | /// |
| 25 | /// 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. |
| 26 | /// 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. |
| 27 | + /// `streamKeepAlive`: how often streamed answers write a keep-alive comment while the model | ||
| 28 | + /// is silent, which is also how fast a vanished client is noticed. | ||
| 27 | public static func makeRouter( | 29 | public static func makeRouter( |
| 28 | - _ settings: ServerSettings, models: ModelManager | 30 | + _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5) |
| 29 | ) -> Router<ServerContext> { | 31 | ) -> Router<ServerContext> { |
| 30 | let router = Router(context: ServerContext.self) | 32 | let router = Router(context: ServerContext.self) |
| 31 | router.middlewares.add(RequestLogMiddleware()) | 33 | router.middlewares.add(RequestLogMiddleware()) |
| @@ -39,7 +41,7 @@ public enum RazorbillServer { | |||
| 39 | } | 41 | } |
| 40 | addHealthRoute(to: router) | 42 | addHealthRoute(to: router) |
| 41 | ModelRoutes(models: models).add(to: router) | 43 | ModelRoutes(models: models).add(to: router) |
| 42 | - ChatCompletionRoute(models: models).add(to: router) | 44 | + ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router) |
| 43 | return router | 45 | return router |
| 44 | } | 46 | } |
| 45 | 47 | ||
modified
Sources/RazorbillServer/ServerSentEvents.swift +40 -14 | @@ -11,36 +11,62 @@ import Hummingbird | ||
| 11 | 11 | /// ``` |
| 12 | 12 | /// |
| 13 | 13 | /// An error thrown by the sequence after the stream started is sent as one last event, |
| 14 | -/// `data: {"error": {…}}`, and the stream closes without `[DONE]`. Each event is flushed as it | |
| 15 | -/// is produced (no buffering). Cancelling the request (client gone) cancels the iteration. | |
| 14 | +/// `data: {"error": {…}}`, and the stream closes without `[DONE]`. Each event is written as soon | |
| 15 | +/// as it is produced (no buffering). | |
| 16 | +/// | |
| 17 | +/// While no event comes, a `: keep-alive` comment (ignored by SSE clients) is written every | |
| 18 | +/// `keepAlive`: a client that went away is only noticed when a write fails, so this bounds how | |
| 19 | +/// long a generation runs for nobody. Once the client is gone, the events are cancelled. | |
| 16 | 20 | /// |
| 17 | 21 | /// ```swift |
| 18 | 22 | /// return ServerSentEvents.response(chunks) // chunks: AsyncThrowingStream<Chunk, Error> |
| 19 | 23 | /// ``` |
| 20 | 24 | public enum ServerSentEvents { |
| 21 | - public static func response<Events: AsyncSequence & Sendable>(_ events: Events) -> Response | |
| 22 | - where Events.Element: Encodable { | |
| 25 | + public static func response<Events: AsyncSequence & Sendable>( | |
| 26 | + _ events: Events, keepAlive: Duration = .seconds(5) | |
| 27 | + ) -> Response where Events.Element: Encodable { | |
| 23 | 28 | var headers = HTTPFields() |
| 24 | 29 | headers[.contentType] = "text/event-stream; charset=utf-8" |
| 25 | 30 | headers[.cacheControl] = "no-cache" |
| 26 | 31 | let body = ResponseBody { writer in |
| 27 | - let encoder = JSONEncoder.openAI | |
| 28 | - do { | |
| 29 | - for try await event in events { | |
| 30 | - try await writer.write(frame(encoder.encode(event))) | |
| 32 | + let (frames, output) = AsyncStream<ByteBuffer>.makeStream() | |
| 33 | + let producer = Task { await produce(events, into: output) } | |
| 34 | + let ticker = Task { | |
| 35 | + while !Task.isCancelled { | |
| 36 | + try? await Task.sleep(for: keepAlive) | |
| 37 | + output.yield(ByteBuffer(string: ": keep-alive\n\n")) | |
| 31 | 38 | } |
| 32 | - try await writer.write(frame(Data("[DONE]".utf8))) | |
| 33 | - } catch is CancellationError { | |
| 34 | - // The client went away: nothing left to tell it. | |
| 35 | - } catch { | |
| 36 | - let converted = OpenAIError.converting(error, for: nil) | |
| 37 | - try await writer.write(frame(converted.json())) | |
| 39 | + } | |
| 40 | + defer { | |
| 41 | + producer.cancel() | |
| 42 | + ticker.cancel() | |
| 43 | + } | |
| 44 | + for await frame in frames { | |
| 45 | + try await writer.write(frame) // throws once the client is gone | |
| 38 | 46 | } |
| 39 | 47 | try await writer.finish(nil) |
| 40 | 48 | } |
| 41 | 49 | return Response(status: .ok, headers: headers, body: body) |
| 42 | 50 | } |
| 43 | 51 | |
| 52 | + /// Encodes every event into `output`, then `[DONE]` or an error event, then finishes it. | |
| 53 | + static func produce<Events: AsyncSequence>( | |
| 54 | + _ events: Events, into output: AsyncStream<ByteBuffer>.Continuation | |
| 55 | + ) async where Events.Element: Encodable { | |
| 56 | + let encoder = JSONEncoder.openAI | |
| 57 | + do { | |
| 58 | + for try await event in events { | |
| 59 | + output.yield(frame(try encoder.encode(event))) | |
| 60 | + } | |
| 61 | + output.yield(frame(Data("[DONE]".utf8))) | |
| 62 | + } catch is CancellationError { | |
| 63 | + // The client went away: nothing left to tell it. | |
| 64 | + } catch { | |
| 65 | + output.yield(frame(OpenAIError.converting(error, for: nil).json())) | |
| 66 | + } | |
| 67 | + output.finish() | |
| 68 | + } | |
| 69 | + | |
| 44 | 70 | /// `data: <payload>\n\n` |
| 45 | 71 | static func frame(_ payload: Data) -> ByteBuffer { |
| 46 | 72 | var buffer = ByteBuffer() |
| @@ -11,36 +11,62 @@ import Hummingbird | |||
| 11 | /// ``` | 11 | /// ``` |
| 12 | /// | 12 | /// |
| 13 | /// An error thrown by the sequence after the stream started is sent as one last event, | 13 | /// An error thrown by the sequence after the stream started is sent as one last event, |
| 14 | -/// `data: {"error": {…}}`, and the stream closes without `[DONE]`. Each event is flushed as it | 14 | +/// `data: {"error": {…}}`, and the stream closes without `[DONE]`. Each event is written as soon |
| 15 | -/// is produced (no buffering). Cancelling the request (client gone) cancels the iteration. | 15 | +/// as it is produced (no buffering). |
| 16 | +/// | ||
| 17 | +/// While no event comes, a `: keep-alive` comment (ignored by SSE clients) is written every | ||
| 18 | +/// `keepAlive`: a client that went away is only noticed when a write fails, so this bounds how | ||
| 19 | +/// long a generation runs for nobody. Once the client is gone, the events are cancelled. | ||
| 16 | /// | 20 | /// |
| 17 | /// ```swift | 21 | /// ```swift |
| 18 | /// return ServerSentEvents.response(chunks) // chunks: AsyncThrowingStream<Chunk, Error> | 22 | /// return ServerSentEvents.response(chunks) // chunks: AsyncThrowingStream<Chunk, Error> |
| 19 | /// ``` | 23 | /// ``` |
| 20 | public enum ServerSentEvents { | 24 | public enum ServerSentEvents { |
| 21 | - public static func response<Events: AsyncSequence & Sendable>(_ events: Events) -> Response | 25 | + public static func response<Events: AsyncSequence & Sendable>( |
| 22 | - where Events.Element: Encodable { | 26 | + _ events: Events, keepAlive: Duration = .seconds(5) |
| 27 | + ) -> Response where Events.Element: Encodable { | ||
| 23 | var headers = HTTPFields() | 28 | var headers = HTTPFields() |
| 24 | headers[.contentType] = "text/event-stream; charset=utf-8" | 29 | headers[.contentType] = "text/event-stream; charset=utf-8" |
| 25 | headers[.cacheControl] = "no-cache" | 30 | headers[.cacheControl] = "no-cache" |
| 26 | let body = ResponseBody { writer in | 31 | let body = ResponseBody { writer in |
| 27 | - let encoder = JSONEncoder.openAI | 32 | + let (frames, output) = AsyncStream<ByteBuffer>.makeStream() |
| 28 | - do { | 33 | + let producer = Task { await produce(events, into: output) } |
| 29 | - for try await event in events { | 34 | + let ticker = Task { |
| 30 | - try await writer.write(frame(encoder.encode(event))) | 35 | + while !Task.isCancelled { |
| 36 | + try? await Task.sleep(for: keepAlive) | ||
| 37 | + output.yield(ByteBuffer(string: ": keep-alive\n\n")) | ||
| 31 | } | 38 | } |
| 32 | - try await writer.write(frame(Data("[DONE]".utf8))) | 39 | + } |
| 33 | - } catch is CancellationError { | 40 | + defer { |
| 34 | - // The client went away: nothing left to tell it. | 41 | + producer.cancel() |
| 35 | - } catch { | 42 | + ticker.cancel() |
| 36 | - let converted = OpenAIError.converting(error, for: nil) | 43 | + } |
| 37 | - try await writer.write(frame(converted.json())) | 44 | + for await frame in frames { |
| 45 | + try await writer.write(frame) // throws once the client is gone | ||
| 38 | } | 46 | } |
| 39 | try await writer.finish(nil) | 47 | try await writer.finish(nil) |
| 40 | } | 48 | } |
| 41 | return Response(status: .ok, headers: headers, body: body) | 49 | return Response(status: .ok, headers: headers, body: body) |
| 42 | } | 50 | } |
| 43 | 51 | ||
| 52 | + /// Encodes every event into `output`, then `[DONE]` or an error event, then finishes it. | ||
| 53 | + static func produce<Events: AsyncSequence>( | ||
| 54 | + _ events: Events, into output: AsyncStream<ByteBuffer>.Continuation | ||
| 55 | + ) async where Events.Element: Encodable { | ||
| 56 | + let encoder = JSONEncoder.openAI | ||
| 57 | + do { | ||
| 58 | + for try await event in events { | ||
| 59 | + output.yield(frame(try encoder.encode(event))) | ||
| 60 | + } | ||
| 61 | + output.yield(frame(Data("[DONE]".utf8))) | ||
| 62 | + } catch is CancellationError { | ||
| 63 | + // The client went away: nothing left to tell it. | ||
| 64 | + } catch { | ||
| 65 | + output.yield(frame(OpenAIError.converting(error, for: nil).json())) | ||
| 66 | + } | ||
| 67 | + output.finish() | ||
| 68 | + } | ||
| 69 | + | ||
| 44 | /// `data: <payload>\n\n` | 70 | /// `data: <payload>\n\n` |
| 45 | static func frame(_ payload: Data) -> ByteBuffer { | 71 | static func frame(_ payload: Data) -> ByteBuffer { |
| 46 | var buffer = ByteBuffer() | 72 | var buffer = ByteBuffer() |
modified
Tests/RazorbillMLXTests/ChatSmokeTests.swift +26 -3 | @@ -16,10 +16,12 @@ let smokeModelIsCached = ModelStore().isAvailableLocally( | ||
| 16 | 16 | @Suite(.serialized, .enabled(if: smokeModelIsCached)) |
| 17 | 17 | struct ChatSmokeTests { |
| 18 | 18 | |
| 19 | + let models = ModelManager( | |
| 20 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() | |
| 21 | + ) { MLXEngine() } | |
| 22 | + | |
| 19 | 23 | func route() -> ChatCompletionRoute { |
| 20 | - let catalog = ModelCatalog(config: ServerConfig(), store: ModelStore()) | |
| 21 | - let models = ModelManager(catalog: catalog, limits: ServerLimits()) { MLXEngine() } | |
| 22 | - return ChatCompletionRoute(models: models) | |
| 24 | + ChatCompletionRoute(models: models) | |
| 23 | 25 | } |
| 24 | 26 | |
| 25 | 27 | func plan(_ prompt: String, maxTokens: Int = 64, stops: [String] = []) -> ChatPlan { |
| @@ -48,6 +50,27 @@ struct ChatSmokeTests { | ||
| 48 | 50 | #expect(response.usage.completionTokens == 8) |
| 49 | 51 | } |
| 50 | 52 | |
| 53 | + @Test func streamsTheAnswerInManyChunks() async throws { | |
| 54 | + var streaming = plan("What is the capital of France?") | |
| 55 | + streaming.includeUsage = true | |
| 56 | + let lease = try await models.acquire(smokeModel) | |
| 57 | + let session = try await lease.engine.makeSession( | |
| 58 | + SessionSetup(system: "", tools: [], generation: streaming.settings(for: lease.model))) | |
| 59 | + let pieces = CompletionStream.pieces(from: session.send(streaming.messages), stops: []) | |
| 60 | + var contents: [String] = [] | |
| 61 | + var usage: Usage? | |
| 62 | + let chunks = ChatCompletionRoute.chunks( | |
| 63 | + pieces, lease: lease, plan: streaming, logger: .init(label: "test")) | |
| 64 | + for try await chunk in chunks { | |
| 65 | + contents += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty } | |
| 66 | + usage = chunk.usage ?? usage | |
| 67 | + } | |
| 68 | + #expect(contents.count > 3) // token by token, not one block | |
| 69 | + #expect(contents.joined().contains("Paris")) | |
| 70 | + #expect((usage?.completionTokens ?? 0) > 0) | |
| 71 | + #expect(try await models.isBusy(smokeModel) == false) | |
| 72 | + } | |
| 73 | + | |
| 51 | 74 | @Test func stopSequenceCutsTheAnswer() async throws { |
| 52 | 75 | let response = try await route().complete( |
| 53 | 76 | plan("List the numbers from 1 to 10, separated by commas.", stops: ["5"])) |
| @@ -16,10 +16,12 @@ let smokeModelIsCached = ModelStore().isAvailableLocally( | |||
| 16 | @Suite(.serialized, .enabled(if: smokeModelIsCached)) | 16 | @Suite(.serialized, .enabled(if: smokeModelIsCached)) |
| 17 | struct ChatSmokeTests { | 17 | struct ChatSmokeTests { |
| 18 | 18 | ||
| 19 | + let models = ModelManager( | ||
| 20 | + catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits() | ||
| 21 | + ) { MLXEngine() } | ||
| 22 | + | ||
| 19 | func route() -> ChatCompletionRoute { | 23 | func route() -> ChatCompletionRoute { |
| 20 | - let catalog = ModelCatalog(config: ServerConfig(), store: ModelStore()) | 24 | + ChatCompletionRoute(models: models) |
| 21 | - let models = ModelManager(catalog: catalog, limits: ServerLimits()) { MLXEngine() } | ||
| 22 | - return ChatCompletionRoute(models: models) | ||
| 23 | } | 25 | } |
| 24 | 26 | ||
| 25 | func plan(_ prompt: String, maxTokens: Int = 64, stops: [String] = []) -> ChatPlan { | 27 | func plan(_ prompt: String, maxTokens: Int = 64, stops: [String] = []) -> ChatPlan { |
| @@ -48,6 +50,27 @@ struct ChatSmokeTests { | |||
| 48 | #expect(response.usage.completionTokens == 8) | 50 | #expect(response.usage.completionTokens == 8) |
| 49 | } | 51 | } |
| 50 | 52 | ||
| 53 | + @Test func streamsTheAnswerInManyChunks() async throws { | ||
| 54 | + var streaming = plan("What is the capital of France?") | ||
| 55 | + streaming.includeUsage = true | ||
| 56 | + let lease = try await models.acquire(smokeModel) | ||
| 57 | + let session = try await lease.engine.makeSession( | ||
| 58 | + SessionSetup(system: "", tools: [], generation: streaming.settings(for: lease.model))) | ||
| 59 | + let pieces = CompletionStream.pieces(from: session.send(streaming.messages), stops: []) | ||
| 60 | + var contents: [String] = [] | ||
| 61 | + var usage: Usage? | ||
| 62 | + let chunks = ChatCompletionRoute.chunks( | ||
| 63 | + pieces, lease: lease, plan: streaming, logger: .init(label: "test")) | ||
| 64 | + for try await chunk in chunks { | ||
| 65 | + contents += chunk.choices.compactMap(\.delta.content).filter { !$0.isEmpty } | ||
| 66 | + usage = chunk.usage ?? usage | ||
| 67 | + } | ||
| 68 | + #expect(contents.count > 3) // token by token, not one block | ||
| 69 | + #expect(contents.joined().contains("Paris")) | ||
| 70 | + #expect((usage?.completionTokens ?? 0) > 0) | ||
| 71 | + #expect(try await models.isBusy(smokeModel) == false) | ||
| 72 | + } | ||
| 73 | + | ||
| 51 | @Test func stopSequenceCutsTheAnswer() async throws { | 74 | @Test func stopSequenceCutsTheAnswer() async throws { |
| 52 | let response = try await route().complete( | 75 | let response = try await route().complete( |
| 53 | plan("List the numbers from 1 to 10, separated by commas.", stops: ["5"])) | 76 | plan("List the numbers from 1 to 10, separated by commas.", stops: ["5"])) |
modified
Tests/RazorbillServerTests/ChatCompletionTests.swift +0 -1 | @@ -177,7 +177,6 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri | ||
| 177 | 177 | (simpleRequest(extra: #","top_p":"high""#), "top_p"), |
| 178 | 178 | (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), |
| 179 | 179 | (simpleRequest(extra: #","n":2"#), "n"), |
| 180 | - (simpleRequest(extra: #","stream":true"#), "stream"), | |
| 181 | 180 | (simpleRequest(extra: #","tools":[]"#), "tools"), |
| 182 | 181 | (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), |
| 183 | 182 | (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), |
| @@ -177,7 +177,6 @@ func simpleRequest(_ model: String = "org/m", content: String = "x", extra: Stri | |||
| 177 | (simpleRequest(extra: #","top_p":"high""#), "top_p"), | 177 | (simpleRequest(extra: #","top_p":"high""#), "top_p"), |
| 178 | (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), | 178 | (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"), |
| 179 | (simpleRequest(extra: #","n":2"#), "n"), | 179 | (simpleRequest(extra: #","n":2"#), "n"), |
| 180 | - (simpleRequest(extra: #","stream":true"#), "stream"), | ||
| 181 | (simpleRequest(extra: #","tools":[]"#), "tools"), | 180 | (simpleRequest(extra: #","tools":[]"#), "tools"), |
| 182 | (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), | 181 | (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"), |
| 183 | (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), | 182 | (simpleRequest(extra: #","response_format":{"type":"json_object"}"#), "response_format"), |
modified
Tests/RazorbillServerTests/ModelManagerTests.swift +26 -2 | @@ -15,9 +15,16 @@ final class TestEngines: @unchecked Sendable { | ||
| 15 | 15 | let hang: Bool |
| 16 | 16 | private var cancelled = 0 |
| 17 | 17 | |
| 18 | - init(script: [[EngineEvent]] = [], hang: Bool = false) { | |
| 18 | + /// Sessions stream these events, then throw this error. | |
| 19 | + let failure: (events: [EngineEvent], error: any Error)? | |
| 20 | + | |
| 21 | + init( | |
| 22 | + script: [[EngineEvent]] = [], hang: Bool = false, | |
| 23 | + failure: (events: [EngineEvent], error: any Error)? = nil | |
| 24 | + ) { | |
| 19 | 25 | fake = FakeEngine(script: script) |
| 20 | 26 | self.hang = hang |
| 27 | + self.failure = failure | |
| 21 | 28 | } |
| 22 | 29 | |
| 23 | 30 | var cancelledGenerations: Int { lock.withLock { cancelled } } |
| @@ -61,7 +68,11 @@ final class TestEngines: @unchecked Sendable { | ||
| 61 | 68 | ) async throws {} |
| 62 | 69 | |
| 63 | 70 | func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 64 | - owner.hang ? HangingSession(owner: owner) : try await owner.fake.makeSession(setup) | |
| 71 | + if let failure = owner.failure { | |
| 72 | + return FailingSession(events: failure.events, error: failure.error) | |
| 73 | + } | |
| 74 | + return owner.hang | |
| 75 | + ? HangingSession(owner: owner) : try await owner.fake.makeSession(setup) | |
| 65 | 76 | } |
| 66 | 77 | |
| 67 | 78 | func unload() async { |
| @@ -83,6 +94,19 @@ struct HangingSession: EngineSession { | ||
| 83 | 94 | } |
| 84 | 95 | } |
| 85 | 96 | |
| 97 | +/// Streams some events, then fails. | |
| 98 | +struct FailingSession: EngineSession, @unchecked Sendable { | |
| 99 | + let events: [EngineEvent] | |
| 100 | + let error: any Error | |
| 101 | + | |
| 102 | + func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | |
| 103 | + AsyncThrowingStream { continuation in | |
| 104 | + for event in events { continuation.yield(event) } | |
| 105 | + continuation.finish(throwing: error) | |
| 106 | + } | |
| 107 | + } | |
| 108 | +} | |
| 109 | + | |
| 86 | 110 | struct LoadBroke: Error, CustomStringConvertible { |
| 87 | 111 | var description: String { "disk on fire" } |
| 88 | 112 | } |
| @@ -15,9 +15,16 @@ final class TestEngines: @unchecked Sendable { | |||
| 15 | let hang: Bool | 15 | let hang: Bool |
| 16 | private var cancelled = 0 | 16 | private var cancelled = 0 |
| 17 | 17 | ||
| 18 | - init(script: [[EngineEvent]] = [], hang: Bool = false) { | 18 | + /// Sessions stream these events, then throw this error. |
| 19 | + let failure: (events: [EngineEvent], error: any Error)? | ||
| 20 | + | ||
| 21 | + init( | ||
| 22 | + script: [[EngineEvent]] = [], hang: Bool = false, | ||
| 23 | + failure: (events: [EngineEvent], error: any Error)? = nil | ||
| 24 | + ) { | ||
| 19 | fake = FakeEngine(script: script) | 25 | fake = FakeEngine(script: script) |
| 20 | self.hang = hang | 26 | self.hang = hang |
| 27 | + self.failure = failure | ||
| 21 | } | 28 | } |
| 22 | 29 | ||
| 23 | var cancelledGenerations: Int { lock.withLock { cancelled } } | 30 | var cancelledGenerations: Int { lock.withLock { cancelled } } |
| @@ -61,7 +68,11 @@ final class TestEngines: @unchecked Sendable { | |||
| 61 | ) async throws {} | 68 | ) async throws {} |
| 62 | 69 | ||
| 63 | func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { | 70 | func makeSession(_ setup: SessionSetup) async throws -> any EngineSession { |
| 64 | - owner.hang ? HangingSession(owner: owner) : try await owner.fake.makeSession(setup) | 71 | + if let failure = owner.failure { |
| 72 | + return FailingSession(events: failure.events, error: failure.error) | ||
| 73 | + } | ||
| 74 | + return owner.hang | ||
| 75 | + ? HangingSession(owner: owner) : try await owner.fake.makeSession(setup) | ||
| 65 | } | 76 | } |
| 66 | 77 | ||
| 67 | func unload() async { | 78 | func unload() async { |
| @@ -83,6 +94,19 @@ struct HangingSession: EngineSession { | |||
| 83 | } | 94 | } |
| 84 | } | 95 | } |
| 85 | 96 | ||
| 97 | +/// Streams some events, then fails. | ||
| 98 | +struct FailingSession: EngineSession, @unchecked Sendable { | ||
| 99 | + let events: [EngineEvent] | ||
| 100 | + let error: any Error | ||
| 101 | + | ||
| 102 | + func send(_ messages: [ChatMessage]) -> AsyncThrowingStream<EngineEvent, Error> { | ||
| 103 | + AsyncThrowingStream { continuation in | ||
| 104 | + for event in events { continuation.yield(event) } | ||
| 105 | + continuation.finish(throwing: error) | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | +} | ||
| 109 | + | ||
| 86 | struct LoadBroke: Error, CustomStringConvertible { | 110 | struct LoadBroke: Error, CustomStringConvertible { |
| 87 | var description: String { "disk on fire" } | 111 | var description: String { "disk on fire" } |
| 88 | } | 112 | } |
added
Tests/RazorbillServerTests/StreamingTests.swift +149 -0 | new file mode 100644 | ||
| @@ -0,0 +1,149 @@ | ||
| 1 | +import Foundation | |
| 2 | +import Hummingbird | |
| 3 | +import HummingbirdTesting | |
| 4 | +import RazorbillCore | |
| 5 | +import Testing | |
| 6 | + | |
| 7 | +@testable import RazorbillServer | |
| 8 | + | |
| 9 | +/// The `data:` payloads of an SSE body, keep-alive comments left out. | |
| 10 | +func events(_ response: TestResponse) -> [String] { | |
| 11 | + String(buffer: response.body).components(separatedBy: "\n\n").compactMap { block in | |
| 12 | + block.hasPrefix("data: ") ? String(block.dropFirst("data: ".count)) : nil | |
| 13 | + } | |
| 14 | +} | |
| 15 | + | |
| 16 | +/// The JSON objects of an SSE body (all events but `[DONE]`). | |
| 17 | +func chunks(_ response: TestResponse) throws -> [[String: Any]] { | |
| 18 | + try events(response).filter { $0 != "[DONE]" }.map { payload in | |
| 19 | + try #require(try JSONSerialization.jsonObject(with: Data(payload.utf8)) as? [String: Any]) | |
| 20 | + } | |
| 21 | +} | |
| 22 | + | |
| 23 | +/// `choices[0].delta` of a chunk. | |
| 24 | +func delta(_ chunk: [String: Any]) -> [String: Any]? { | |
| 25 | + ((chunk["choices"] as? [[String: Any]])?.first)?["delta"] as? [String: Any] | |
| 26 | +} | |
| 27 | + | |
| 28 | +/// `choices[0].finish_reason` of a chunk, `nil` when it is JSON null or absent. | |
| 29 | +func finishReason(_ chunk: [String: Any]) -> String? { | |
| 30 | + ((chunk["choices"] as? [[String: Any]])?.first)?["finish_reason"] as? String | |
| 31 | +} | |
| 32 | + | |
| 33 | +@Suite struct StreamingTests { | |
| 34 | + static let streamed = #","stream":true"# | |
| 35 | + | |
| 36 | + @Test func chunksComeInOpenAIOrder() async throws { | |
| 37 | + let stats = GenerationStats(promptTokens: 5, generatedTokens: 2, tokensPerSecond: 1) | |
| 38 | + let engines = TestEngines(script: [[.text("Hel"), .text("lo"), .stats(stats)]]) | |
| 39 | + try await withLiveServer(engines: engines) { client in | |
| 40 | + let response = try await post(client, simpleRequest(extra: Self.streamed)) | |
| 41 | + #expect(response.status == .ok) | |
| 42 | + #expect(response.headers[.contentType]?.hasPrefix("text/event-stream") == true) | |
| 43 | + #expect(events(response).last == "[DONE]") | |
| 44 | + let all = try chunks(response) | |
| 45 | + #expect(all.count == 4) | |
| 46 | + #expect(all.allSatisfy { $0["object"] as? String == "chat.completion.chunk" }) | |
| 47 | + #expect(Set(all.compactMap { $0["id"] as? String }).count == 1) | |
| 48 | + #expect(all.allSatisfy { $0["usage"] == nil }) | |
| 49 | + #expect(delta(all[0])?["role"] as? String == "assistant") | |
| 50 | + #expect( | |
| 51 | + all.dropFirst().compactMap { delta($0)?["content"] as? String } == ["Hel", "lo"]) | |
| 52 | + #expect(all.dropLast().allSatisfy { finishReason($0) == nil }) | |
| 53 | + #expect(finishReason(all[3]) == "stop") | |
| 54 | + #expect(delta(all[3])?.isEmpty == true) | |
| 55 | + } | |
| 56 | + } | |
| 57 | + | |
| 58 | + @Test func includeUsageAddsAFinalUsageChunk() async throws { | |
| 59 | + let stats = GenerationStats(promptTokens: 5, generatedTokens: 2, tokensPerSecond: 1) | |
| 60 | + let engines = TestEngines(script: [[.text("Hi"), .stats(stats)]]) | |
| 61 | + let extra = Self.streamed + #","stream_options":{"include_usage":true}"# | |
| 62 | + try await withLiveServer(engines: engines) { client in | |
| 63 | + let all = try chunks(try await post(client, simpleRequest(extra: extra))) | |
| 64 | + #expect(all.count == 4) | |
| 65 | + #expect(all.dropLast().allSatisfy { $0["usage"] is NSNull }) | |
| 66 | + let last = try #require(all.last) | |
| 67 | + #expect((last["choices"] as? [Any])?.isEmpty == true) | |
| 68 | + let usage = try #require(last["usage"] as? [String: Int]) | |
| 69 | + #expect(usage == ["prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7]) | |
| 70 | + } | |
| 71 | + } | |
| 72 | + | |
| 73 | + @Test func stopSequencesAndToolCallsStreamToo() async throws { | |
| 74 | + let call = ToolCall(id: "c1", name: "f", arguments: ["a": .int(1)]) | |
| 75 | + let engines = TestEngines(script: [[.toolCall(call)], [.text("one EN"), .text("D two")]]) | |
| 76 | + try await withLiveServer(engines: engines) { client in | |
| 77 | + let calls = try chunks(try await post(client, simpleRequest(extra: Self.streamed))) | |
| 78 | + let streamedCall = try #require( | |
| 79 | + (delta(calls[1])?["tool_calls"] as? [[String: Any]])?.first) | |
| 80 | + #expect(streamedCall["index"] as? Int == 0 && streamedCall["id"] as? String == "c1") | |
| 81 | + #expect(finishReason(calls[2]) == "tool_calls") | |
| 82 | + } | |
| 83 | + try await withLiveServer(engines: engines) { client in | |
| 84 | + let extra = Self.streamed + #","stop":"END""# | |
| 85 | + let cut = try chunks(try await post(client, simpleRequest(extra: extra))) | |
| 86 | + #expect(cut.compactMap { delta($0)?["content"] as? String }.joined() == "one ") | |
| 87 | + #expect(finishReason(cut.last ?? [:]) == "stop") | |
| 88 | + } | |
| 89 | + } | |
| 90 | + | |
| 91 | + @Test func errorAfterTheStartIsAnErrorEvent() async throws { | |
| 92 | + let engines = TestEngines( | |
| 93 | + failure: ( | |
| 94 | + [.text("partial")], ModelManagerError.loadFailed(model: "m", reason: "GPU gone") | |
| 95 | + )) | |
| 96 | + try await withLiveServer(engines: engines) { client in | |
| 97 | + let response = try await post(client, simpleRequest(extra: Self.streamed)) | |
| 98 | + #expect(response.status == .ok) | |
| 99 | + let payloads = events(response) | |
| 100 | + #expect(!payloads.contains("[DONE]")) | |
| 101 | + let error = try #require(try chunks(response).last?["error"] as? [String: Any]) | |
| 102 | + #expect(error["code"] as? String == "model_load_failed") | |
| 103 | + #expect((error["message"] as? String)?.contains("GPU gone") == true) | |
| 104 | + } | |
| 105 | + } | |
| 106 | + | |
| 107 | + @Test func errorsBeforeTheStartArePlainJSON() async throws { | |
| 108 | + try await withLiveServer { client in | |
| 109 | + let response = try await post(client, simpleRequest("gpt-4o", extra: Self.streamed)) | |
| 110 | + #expect(response.status == .notFound) | |
| 111 | + let error = try ErrorBody(response).error | |
| 112 | + #expect(error.code == "model_not_found") | |
| 113 | + } | |
| 114 | + } | |
| 115 | + | |
| 116 | + @Test func theModelIsReleasedWhenTheStreamEnds() async throws { | |
| 117 | + let engines = TestEngines() | |
| 118 | + let models = testModels(engines: engines) | |
| 119 | + try await withLiveServer(router: testRouter(models: models), engines: engines) { client in | |
| 120 | + _ = try await post(client, simpleRequest(extra: Self.streamed)) | |
| 121 | + } | |
| 122 | + for _ in 0 ..< 100 where try await models.isBusy("org/m") { | |
| 123 | + try await Task.sleep(for: .milliseconds(5)) | |
| 124 | + } | |
| 125 | + #expect(try await models.isBusy("org/m") == false) | |
| 126 | + } | |
| 127 | + | |
| 128 | + @Test func vanishedClientCancelsTheGenerationAndFreesTheModel() async throws { | |
| 129 | + let engines = TestEngines(hang: true) | |
| 130 | + let models = testModels(engines: engines) | |
| 131 | + let router = RazorbillServer.makeRouter( | |
| 132 | + testSettings, models: models, streamKeepAlive: .milliseconds(20)) | |
| 133 | + try await withLiveServer(router: router, engines: engines) { client in | |
| 134 | + let body = simpleRequest(extra: Self.streamed) | |
| 135 | + let socket = try RawConnection(port: try #require(client.port)) | |
| 136 | + socket.send( | |
| 137 | + "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n" | |
| 138 | + + "Content-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)" | |
| 139 | + ) | |
| 140 | + try await Task.sleep(for: .milliseconds(200)) // streaming, the model is silent | |
| 141 | + socket.close() | |
| 142 | + for _ in 0 ..< 300 where engines.cancelledGenerations == 0 { | |
| 143 | + try await Task.sleep(for: .milliseconds(10)) | |
| 144 | + } | |
| 145 | + } | |
| 146 | + #expect(engines.cancelledGenerations == 1) | |
| 147 | + #expect(try await models.isBusy("org/m") == false) | |
| 148 | + } | |
| 149 | +} | |
| new file mode 100644 | |||
| @@ -0,0 +1,149 @@ | |||
| 1 | +import Foundation | ||
| 2 | +import Hummingbird | ||
| 3 | +import HummingbirdTesting | ||
| 4 | +import RazorbillCore | ||
| 5 | +import Testing | ||
| 6 | + | ||
| 7 | +@testable import RazorbillServer | ||
| 8 | + | ||
| 9 | +/// The `data:` payloads of an SSE body, keep-alive comments left out. | ||
| 10 | +func events(_ response: TestResponse) -> [String] { | ||
| 11 | + String(buffer: response.body).components(separatedBy: "\n\n").compactMap { block in | ||
| 12 | + block.hasPrefix("data: ") ? String(block.dropFirst("data: ".count)) : nil | ||
| 13 | + } | ||
| 14 | +} | ||
| 15 | + | ||
| 16 | +/// The JSON objects of an SSE body (all events but `[DONE]`). | ||
| 17 | +func chunks(_ response: TestResponse) throws -> [[String: Any]] { | ||
| 18 | + try events(response).filter { $0 != "[DONE]" }.map { payload in | ||
| 19 | + try #require(try JSONSerialization.jsonObject(with: Data(payload.utf8)) as? [String: Any]) | ||
| 20 | + } | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +/// `choices[0].delta` of a chunk. | ||
| 24 | +func delta(_ chunk: [String: Any]) -> [String: Any]? { | ||
| 25 | + ((chunk["choices"] as? [[String: Any]])?.first)?["delta"] as? [String: Any] | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +/// `choices[0].finish_reason` of a chunk, `nil` when it is JSON null or absent. | ||
| 29 | +func finishReason(_ chunk: [String: Any]) -> String? { | ||
| 30 | + ((chunk["choices"] as? [[String: Any]])?.first)?["finish_reason"] as? String | ||
| 31 | +} | ||
| 32 | + | ||
| 33 | +@Suite struct StreamingTests { | ||
| 34 | + static let streamed = #","stream":true"# | ||
| 35 | + | ||
| 36 | + @Test func chunksComeInOpenAIOrder() async throws { | ||
| 37 | + let stats = GenerationStats(promptTokens: 5, generatedTokens: 2, tokensPerSecond: 1) | ||
| 38 | + let engines = TestEngines(script: [[.text("Hel"), .text("lo"), .stats(stats)]]) | ||
| 39 | + try await withLiveServer(engines: engines) { client in | ||
| 40 | + let response = try await post(client, simpleRequest(extra: Self.streamed)) | ||
| 41 | + #expect(response.status == .ok) | ||
| 42 | + #expect(response.headers[.contentType]?.hasPrefix("text/event-stream") == true) | ||
| 43 | + #expect(events(response).last == "[DONE]") | ||
| 44 | + let all = try chunks(response) | ||
| 45 | + #expect(all.count == 4) | ||
| 46 | + #expect(all.allSatisfy { $0["object"] as? String == "chat.completion.chunk" }) | ||
| 47 | + #expect(Set(all.compactMap { $0["id"] as? String }).count == 1) | ||
| 48 | + #expect(all.allSatisfy { $0["usage"] == nil }) | ||
| 49 | + #expect(delta(all[0])?["role"] as? String == "assistant") | ||
| 50 | + #expect( | ||
| 51 | + all.dropFirst().compactMap { delta($0)?["content"] as? String } == ["Hel", "lo"]) | ||
| 52 | + #expect(all.dropLast().allSatisfy { finishReason($0) == nil }) | ||
| 53 | + #expect(finishReason(all[3]) == "stop") | ||
| 54 | + #expect(delta(all[3])?.isEmpty == true) | ||
| 55 | + } | ||
| 56 | + } | ||
| 57 | + | ||
| 58 | + @Test func includeUsageAddsAFinalUsageChunk() async throws { | ||
| 59 | + let stats = GenerationStats(promptTokens: 5, generatedTokens: 2, tokensPerSecond: 1) | ||
| 60 | + let engines = TestEngines(script: [[.text("Hi"), .stats(stats)]]) | ||
| 61 | + let extra = Self.streamed + #","stream_options":{"include_usage":true}"# | ||
| 62 | + try await withLiveServer(engines: engines) { client in | ||
| 63 | + let all = try chunks(try await post(client, simpleRequest(extra: extra))) | ||
| 64 | + #expect(all.count == 4) | ||
| 65 | + #expect(all.dropLast().allSatisfy { $0["usage"] is NSNull }) | ||
| 66 | + let last = try #require(all.last) | ||
| 67 | + #expect((last["choices"] as? [Any])?.isEmpty == true) | ||
| 68 | + let usage = try #require(last["usage"] as? [String: Int]) | ||
| 69 | + #expect(usage == ["prompt_tokens": 5, "completion_tokens": 2, "total_tokens": 7]) | ||
| 70 | + } | ||
| 71 | + } | ||
| 72 | + | ||
| 73 | + @Test func stopSequencesAndToolCallsStreamToo() async throws { | ||
| 74 | + let call = ToolCall(id: "c1", name: "f", arguments: ["a": .int(1)]) | ||
| 75 | + let engines = TestEngines(script: [[.toolCall(call)], [.text("one EN"), .text("D two")]]) | ||
| 76 | + try await withLiveServer(engines: engines) { client in | ||
| 77 | + let calls = try chunks(try await post(client, simpleRequest(extra: Self.streamed))) | ||
| 78 | + let streamedCall = try #require( | ||
| 79 | + (delta(calls[1])?["tool_calls"] as? [[String: Any]])?.first) | ||
| 80 | + #expect(streamedCall["index"] as? Int == 0 && streamedCall["id"] as? String == "c1") | ||
| 81 | + #expect(finishReason(calls[2]) == "tool_calls") | ||
| 82 | + } | ||
| 83 | + try await withLiveServer(engines: engines) { client in | ||
| 84 | + let extra = Self.streamed + #","stop":"END""# | ||
| 85 | + let cut = try chunks(try await post(client, simpleRequest(extra: extra))) | ||
| 86 | + #expect(cut.compactMap { delta($0)?["content"] as? String }.joined() == "one ") | ||
| 87 | + #expect(finishReason(cut.last ?? [:]) == "stop") | ||
| 88 | + } | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + @Test func errorAfterTheStartIsAnErrorEvent() async throws { | ||
| 92 | + let engines = TestEngines( | ||
| 93 | + failure: ( | ||
| 94 | + [.text("partial")], ModelManagerError.loadFailed(model: "m", reason: "GPU gone") | ||
| 95 | + )) | ||
| 96 | + try await withLiveServer(engines: engines) { client in | ||
| 97 | + let response = try await post(client, simpleRequest(extra: Self.streamed)) | ||
| 98 | + #expect(response.status == .ok) | ||
| 99 | + let payloads = events(response) | ||
| 100 | + #expect(!payloads.contains("[DONE]")) | ||
| 101 | + let error = try #require(try chunks(response).last?["error"] as? [String: Any]) | ||
| 102 | + #expect(error["code"] as? String == "model_load_failed") | ||
| 103 | + #expect((error["message"] as? String)?.contains("GPU gone") == true) | ||
| 104 | + } | ||
| 105 | + } | ||
| 106 | + | ||
| 107 | + @Test func errorsBeforeTheStartArePlainJSON() async throws { | ||
| 108 | + try await withLiveServer { client in | ||
| 109 | + let response = try await post(client, simpleRequest("gpt-4o", extra: Self.streamed)) | ||
| 110 | + #expect(response.status == .notFound) | ||
| 111 | + let error = try ErrorBody(response).error | ||
| 112 | + #expect(error.code == "model_not_found") | ||
| 113 | + } | ||
| 114 | + } | ||
| 115 | + | ||
| 116 | + @Test func theModelIsReleasedWhenTheStreamEnds() async throws { | ||
| 117 | + let engines = TestEngines() | ||
| 118 | + let models = testModels(engines: engines) | ||
| 119 | + try await withLiveServer(router: testRouter(models: models), engines: engines) { client in | ||
| 120 | + _ = try await post(client, simpleRequest(extra: Self.streamed)) | ||
| 121 | + } | ||
| 122 | + for _ in 0 ..< 100 where try await models.isBusy("org/m") { | ||
| 123 | + try await Task.sleep(for: .milliseconds(5)) | ||
| 124 | + } | ||
| 125 | + #expect(try await models.isBusy("org/m") == false) | ||
| 126 | + } | ||
| 127 | + | ||
| 128 | + @Test func vanishedClientCancelsTheGenerationAndFreesTheModel() async throws { | ||
| 129 | + let engines = TestEngines(hang: true) | ||
| 130 | + let models = testModels(engines: engines) | ||
| 131 | + let router = RazorbillServer.makeRouter( | ||
| 132 | + testSettings, models: models, streamKeepAlive: .milliseconds(20)) | ||
| 133 | + try await withLiveServer(router: router, engines: engines) { client in | ||
| 134 | + let body = simpleRequest(extra: Self.streamed) | ||
| 135 | + let socket = try RawConnection(port: try #require(client.port)) | ||
| 136 | + socket.send( | ||
| 137 | + "POST /v1/chat/completions HTTP/1.1\r\nHost: localhost\r\n" | ||
| 138 | + + "Content-Type: application/json\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)" | ||
| 139 | + ) | ||
| 140 | + try await Task.sleep(for: .milliseconds(200)) // streaming, the model is silent | ||
| 141 | + socket.close() | ||
| 142 | + for _ in 0 ..< 300 where engines.cancelledGenerations == 0 { | ||
| 143 | + try await Task.sleep(for: .milliseconds(10)) | ||
| 144 | + } | ||
| 145 | + } | ||
| 146 | + #expect(engines.cancelledGenerations == 1) | ||
| 147 | + #expect(try await models.isBusy("org/m") == false) | ||
| 148 | + } | ||
| 149 | +} | ||