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

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

Download ZIP

v0.2 step 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>
k33g committed 2026-11-25T13:43:11+01:00 Browse files
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)
22
33 ## State
44 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).
55 Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).
66 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).
78 Branch `feature/v0.2-openai-server`: step 1 (agent code removed) committed as `132c60f`; #32 (HTTP
89 server foundation, `rzb serve`) implemented, tested (Linux 55, Mac 60), quality gate PASS, ticket
910 closed. `razorbill.yaml` (old agent file) deleted with the user's agreement; #17's last task
1011 closed. Nothing pushed.
1112
1213 ## 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.
2123
2224 ## Watch out for
2325 - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns
@@ -47,6 +49,8 @@ closed. Nothing pushed.
4749 `localhost` (getaddrinfo), not hard-code 127.0.0.1.
4850 - `@Suite(.enabled(if: Type.member))` referencing its own type is a "circular reference" error:
4951 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).
5054 - `ModelManager` keys slots by `ModelReference.description` (`org/name`, or `org/name@rev`), not by
5155 the requested name.
5256 - 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 ## State3 ## State
4 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).4 Update after #33: `--config` file, `rzb config validate`, `ModelCatalog` done (Linux 73, Mac 78).
5 Update after #34: `ModelManager`, `/v1/models` done (Linux 89, Mac 94).5 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 (HTTP8 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, ticket9 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 task10 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 steps13 ## Next steps
13-1. #36 streaming: in `ChatCompletionRoute.answer`, when `plan.stream`, return14+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 chunk16+ (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 is17+ 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 for24 ## Watch out for
23 - Hummingbird's own 404 is `HTTPError(.notFound)` with no body; `OpenAIError.converting` turns25 - 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 by54 - `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 @@
166166 model configuration (shared container). Tests Linux 106, Mac 114 incl. real-model smoke tests;
167167 openai Python SDK verified against the Linux binary. Quality gate PASS (run #9, after splitting a
168168 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 a167 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 @@
77 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in
88 tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code
99 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
1111 Architecture). Decided by the user (#31): the
1212 agent code goes (run/chat/tui/init, agent loop, bash tool, TUI) but model list/pull/rm, ModelStore,
1313 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
4444 demand, per-model turn queue, LRU/memory eviction of idle models, keep_alive; `ModelLifecycleService`
4545 for preload / idle sweep / unload at shutdown; `GET /v1/models[/{id}]`; `Chat/`:
4646 `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`,
4849 `models list|pull|rm`, `version`; `CLIEnvironment` carries `variables` and a replaceable `serve`
4950 runner for tests; `ServerSettings.config` carries the loaded file to the server).
5051 `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()`)
5455 registry's default (`mlx` on the Mac, `fake` on Linux). Chat requests are stateless (fresh session,
5556 whole conversation each time, system messages through the template); stop sequences are applied
5657 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).
5861
5962 ## Architecture of v0.1 (agent, removed on the v0.2 branch)
6063
@@ -142,7 +145,7 @@ razorbill`, `host.sh run . rzb <args>` (no TTY: `rzb run` only); host-runner tes
142145 (`@testable import`). Sandbox started on the Mac with `sbx env run --force` (`sbxenv.yaml`).
143146 Lint: `swiftlint lint --quiet Sources Tests` and `swift-format` (4 spaces); keep wrapped
144147 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
146149 Qwen3-0.6B-4bit through ModelManager + MLXEngine, enabled only when the model is in the HF cache).
147150 Server tests start the real server on a random port (`HummingbirdTesting` `.live`).
148151
@@ -7,7 +7,7 @@
7 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in7 and reasoning, structured output, function calling, embeddings; "decision models" later). Planned in
8 tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code8 tickets #31–#47 (milestones v0.2 / v0.3). Done on branch `feature/v0.2-openai-server`: agent code
9 removed (`132c60f`), HTTP server foundation #32 (`rzb serve`), server configuration file #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 (see10+model lifecycle + `/v1/models` #34, `POST /v1/chat/completions` #35 and its streaming #36 (see
11 Architecture). Decided by the user (#31): the11 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 applied56 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 answer57 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 wrapped146 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`: real148+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 @@
88 {"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"}
99 {"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"}
1010 {"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
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `4d3623e` on `feature/v0.2-openai-server`
4+- **Commit**: `6a3f52a` on `feature/v0.2-openai-server`
55 - **qlty**: qlty 0.672.0 linux-arm64 (4362b62 2026-11-20)
66 - **swiftlint**: 0.65.1 (run directly, merged into lint issues)
7-- **Run**: #10 (previous: 2026-11-25T12:29:03Z)
7+- **Run**: #11 (previous: 2026-11-25T12:29:06Z)
88
99 ## Lint issues (`qlty check`)
1010
@@ -28,14 +28,14 @@ _none_
2828
2929 | metric | total | vs previous |
3030 |---|---|---|
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 |
3939
4040 ### Most complex files
4141
@@ -45,23 +45,22 @@ _none_
4545 | tools/host-runner/host_runner.py | 22 | 22 | 141 |
4646 | Sources/RazorbillMLX/MLXEngine.swift | 21 | 33 | 204 |
4747 | 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 |
4950 | 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 |
5153 | Sources/RazorbillCLI/Commands/ServeCommand.swift | 10 | 7 | 79 |
5254 | Sources/RazorbillCore/Config/GenerationOverrides.swift | 10 | 11 | 47 |
5355 | Sources/RazorbillCore/Engine/ThinkingSplitter.swift | 10 | 8 | 54 |
5456 | Sources/RazorbillCore/Config/ConfigReader.swift | 9 | 14 | 89 |
5557 | 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 |
5959
6060 ## Trend
6161
6262 | run | timestamp | error | warning | smells | complex | gate |
6363 |---|---|---|---|---|---|---|
64-| 1 | 2026-11-24T05:51:46Z | 0 | 1 | 15 | 523 | FAIL |
6564 | 2 | 2026-11-24T05:52:09Z | 0 | 0 | 14 | 518 | FAIL |
6665 | 3 | 2026-11-24T05:57:47Z | 0 | 0 | 0 | 358 | PASS |
6766 | 4 | 2026-11-25T07:51:14Z | 0 | 0 | 0 | 153 | PASS |
@@ -71,3 +70,4 @@ _none_
7170 | 8 | 2026-11-25T12:28:48Z | 0 | 1 | 0 | 296 | FAIL |
7271 | 9 | 2026-11-25T12:29:03Z | 0 | 0 | 0 | 296 | PASS |
7372 | 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:06Z1+# 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 files40 ### 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 ## Trend60 ## 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 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 36
33 title: "Chat completions streaming (SSE, stream_options, cancellation)"
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z
9+updatedAt: 2026-11-25T12:45:00.000Z
1010 labels:
1111 - "kind::feature"
1212 - "area::server"
@@ -27,42 +27,65 @@ body: |
2727 tasks:
2828 - id: 1
2929 title: "SSE writer with flushing"
30- state: open
30+ state: closed
3131 priority: high
3232 author:
3333 name: k33g
3434 email: ph.charriere@gmail.com
3535 createdAt: 2026-11-24T21:17:08.000Z
36+ updatedAt: 2026-11-25T12:45:00.000Z
37+ closedAt: 2026-11-25T12:45:00.000Z
3638 - id: 2
3739 title: "Chunk sequence: role, content deltas, finish_reason, [DONE]"
38- state: open
40+ state: closed
3941 priority: high
4042 author:
4143 name: k33g
4244 email: ph.charriere@gmail.com
4345 createdAt: 2026-11-24T21:17:08.000Z
46+ updatedAt: 2026-11-25T12:45:00.000Z
47+ closedAt: 2026-11-25T12:45:00.000Z
4448 - id: 3
4549 title: "stream_options.include_usage"
46- state: open
50+ state: closed
4751 priority: medium
4852 author:
4953 name: k33g
5054 email: ph.charriere@gmail.com
5155 createdAt: 2026-11-24T21:17:08.000Z
56+ updatedAt: 2026-11-25T12:45:00.000Z
57+ closedAt: 2026-11-25T12:45:00.000Z
5258 - id: 4
5359 title: "Error event after the stream started"
54- state: open
60+ state: closed
5561 priority: medium
5662 author:
5763 name: k33g
5864 email: ph.charriere@gmail.com
5965 createdAt: 2026-11-24T21:17:08.000Z
66+ updatedAt: 2026-11-25T12:45:00.000Z
67+ closedAt: 2026-11-25T12:45:00.000Z
6068 - id: 5
6169 title: "Tests: chunk order and content reassembly"
62- state: open
70+ state: closed
6371 priority: high
6472 author:
6573 name: k33g
6674 email: ph.charriere@gmail.com
6775 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: 362 id: 36
3 title: "Chat completions streaming (SSE, stream_options, cancellation)"3 title: "Chat completions streaming (SSE, stream_options, cancellation)"
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-11-24T21:17:08.000Z8 createdAt: 2026-11-24T21:17:08.000Z
9-updatedAt: 2026-11-24T21:17:08.000Z9+updatedAt: 2026-11-25T12: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: 128 - id: 1
29 title: "SSE writer with flushing"29 title: "SSE writer with flushing"
30- state: open30+ state: closed
31 priority: high31 priority: high
32 author:32 author:
33 name: k33g33 name: k33g
34 email: ph.charriere@gmail.com34 email: ph.charriere@gmail.com
35 createdAt: 2026-11-24T21:17:08.000Z35 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: 238 - id: 2
37 title: "Chunk sequence: role, content deltas, finish_reason, [DONE]"39 title: "Chunk sequence: role, content deltas, finish_reason, [DONE]"
38- state: open40+ state: closed
39 priority: high41 priority: high
40 author:42 author:
41 name: k33g43 name: k33g
42 email: ph.charriere@gmail.com44 email: ph.charriere@gmail.com
43 createdAt: 2026-11-24T21:17:08.000Z45 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: 348 - id: 3
45 title: "stream_options.include_usage"49 title: "stream_options.include_usage"
46- state: open50+ state: closed
47 priority: medium51 priority: medium
48 author:52 author:
49 name: k33g53 name: k33g
50 email: ph.charriere@gmail.com54 email: ph.charriere@gmail.com
51 createdAt: 2026-11-24T21:17:08.000Z55 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: 458 - id: 4
53 title: "Error event after the stream started"59 title: "Error event after the stream started"
54- state: open60+ state: closed
55 priority: medium61 priority: medium
56 author:62 author:
57 name: k33g63 name: k33g
58 email: ph.charriere@gmail.com64 email: ph.charriere@gmail.com
59 createdAt: 2026-11-24T21:17:08.000Z65 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: 568 - id: 5
61 title: "Tests: chunk order and content reassembly"69 title: "Tests: chunk order and content reassembly"
62- state: open70+ state: closed
63 priority: high71 priority: high
64 author:72 author:
65 name: k33g73 name: k33g
66 email: ph.charriere@gmail.com74 email: ph.charriere@gmail.com
67 createdAt: 2026-11-24T21:17:08.000Z75 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 {
1717 var presencePenalty: Double?
1818 var frequencyPenalty: Double?
1919 var stream: Bool?
20+ var streamOptions: StreamOptions?
2021 var logprobs: Bool?
2122 var tools: ConfigValue?
2223 var responseFormat: ConfigValue?
@@ -30,6 +31,7 @@ struct ChatCompletionRequest: Decodable, Sendable {
3031 case presencePenalty = "presence_penalty"
3132 case frequencyPenalty = "frequency_penalty"
3233 case responseFormat = "response_format"
34+ case streamOptions = "stream_options"
3335 }
3436
3537 /// Decodes a request body; malformed JSON or wrong types become a 400 naming the field.
@@ -44,6 +46,15 @@ struct ChatCompletionRequest: Decodable, Sendable {
4446 }
4547 }
4648
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+
4758 /// `stop`: one string or a list of strings.
4859 struct StopField: Decodable, Sendable {
4960 let values: [String]
@@ -117,6 +128,8 @@ struct ChatPlan: Sendable {
117128 var frequencyPenalty: Double?
118129 var stops: [String]
119130 var stream: Bool
131+ /// `stream_options.include_usage`: a last chunk with the token counts.
132+ var includeUsage = false
120133
121134 /// The settings for `model`: its defaults, then the client's values, then its locks.
122135 func settings(for model: ResolvedModel) -> GenerationSettings {
@@ -150,7 +163,8 @@ extension ChatCompletionRequest {
150163 client: GenerationOverrides(temperature: temperature, topP: topP, maxTokens: limit),
151164 seed: seed.map { UInt64(bitPattern: $0) },
152165 presencePenalty: presencePenalty, frequencyPenalty: frequencyPenalty,
153- stops: stops, stream: stream ?? false)
166+ stops: stops, stream: stream ?? false,
167+ includeUsage: streamOptions?.includeUsage ?? false)
154168 }
155169
156170 /// 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: Bool130 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 {
5858 /// until the answer is complete. If the client disconnects, the generation is cancelled.
5959 struct ChatCompletionRoute {
6060 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)
6163
6264 func add(to router: Router<ServerContext>) {
6365 router.post("/v1/chat/completions") { request, context in
@@ -81,9 +83,8 @@ struct ChatCompletionRoute {
8183 func answer(_ body: RequestBody, context: ServerContext) async throws -> Response {
8284 let buffer = try await body.collect(upTo: context.maxUploadSize)
8385 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)
8788 }
8889 let response = try await complete(plan)
8990 context.usage.record(
@@ -92,6 +93,25 @@ struct ChatCompletionRoute {
9293 return try jsonResponse(response)
9394 }
9495
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+
95115 func complete(_ plan: ChatPlan) async throws -> ChatCompletionResponse {
96116 try await models.withModel(plan.model) { lease in
97117 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: ModelManager60 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 in65 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 in116 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 {
285285 return slots[key]?.waiters.count ?? 0
286286 }
287287
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+
288294 /// Sources of the models currently loaded, as `ModelReference.description`.
289295 public func loadedSources() -> Set<String> {
290296 Set(slots.filter { $0.value.engine != nil }.keys)
@@ -285,6 +285,12 @@ public actor ModelManager {
285 return slots[key]?.waiters.count ?? 0285 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 {
2424 ///
2525 /// Middleware order, outermost first: request log, CORS, OpenAI error envelope, API key.
2626 /// 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.
2729 public static func makeRouter(
28- _ settings: ServerSettings, models: ModelManager
30+ _ settings: ServerSettings, models: ModelManager, streamKeepAlive: Duration = .seconds(5)
2931 ) -> Router<ServerContext> {
3032 let router = Router(context: ServerContext.self)
3133 router.middlewares.add(RequestLogMiddleware())
@@ -39,7 +41,7 @@ public enum RazorbillServer {
3941 }
4042 addHealthRoute(to: router)
4143 ModelRoutes(models: models).add(to: router)
42- ChatCompletionRoute(models: models).add(to: router)
44+ ChatCompletionRoute(models: models, streamKeepAlive: streamKeepAlive).add(to: router)
4345 return router
4446 }
4547
@@ -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: ModelManager30+ _ 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 router45 return router
44 }46 }
45 47
modified Sources/RazorbillServer/ServerSentEvents.swift +40 -14
@@ -11,36 +11,62 @@ import Hummingbird
1111 /// ```
1212 ///
1313 /// 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.
1620 ///
1721 /// ```swift
1822 /// return ServerSentEvents.response(chunks) // chunks: AsyncThrowingStream<Chunk, Error>
1923 /// ```
2024 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 {
2328 var headers = HTTPFields()
2429 headers[.contentType] = "text/event-stream; charset=utf-8"
2530 headers[.cacheControl] = "no-cache"
2631 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"))
3138 }
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
3846 }
3947 try await writer.finish(nil)
4048 }
4149 return Response(status: .ok, headers: headers, body: body)
4250 }
4351
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+
4470 /// `data: <payload>\n\n`
4571 static func frame(_ payload: Data) -> ByteBuffer {
4672 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 it14+/// `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 /// ```swift21 /// ```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) -> Response25+ 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 in31 let body = ResponseBody { writer in
27- let encoder = JSONEncoder.openAI32+ 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(
1616 @Suite(.serialized, .enabled(if: smokeModelIsCached))
1717 struct ChatSmokeTests {
1818
19+ let models = ModelManager(
20+ catalog: ModelCatalog(config: ServerConfig(), store: ModelStore()), limits: ServerLimits()
21+ ) { MLXEngine() }
22+
1923 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)
2325 }
2426
2527 func plan(_ prompt: String, maxTokens: Int = 64, stops: [String] = []) -> ChatPlan {
@@ -48,6 +50,27 @@ struct ChatSmokeTests {
4850 #expect(response.usage.completionTokens == 8)
4951 }
5052
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+
5174 @Test func stopSequenceCutsTheAnswer() async throws {
5275 let response = try await route().complete(
5376 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
177177 (simpleRequest(extra: #","top_p":"high""#), "top_p"),
178178 (simpleRequest(extra: #","max_tokens":0"#), "max_tokens"),
179179 (simpleRequest(extra: #","n":2"#), "n"),
180- (simpleRequest(extra: #","stream":true"#), "stream"),
181180 (simpleRequest(extra: #","tools":[]"#), "tools"),
182181 (simpleRequest(extra: #","stop":["a","b","c","d","e"]"#), "stop"),
183182 (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 {
1515 let hang: Bool
1616 private var cancelled = 0
1717
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+ ) {
1925 fake = FakeEngine(script: script)
2026 self.hang = hang
27+ self.failure = failure
2128 }
2229
2330 var cancelledGenerations: Int { lock.withLock { cancelled } }
@@ -61,7 +68,11 @@ final class TestEngines: @unchecked Sendable {
6168 ) async throws {}
6269
6370 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)
6576 }
6677
6778 func unload() async {
@@ -83,6 +94,19 @@ struct HangingSession: EngineSession {
8394 }
8495 }
8596
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+
86110 struct LoadBroke: Error, CustomStringConvertible {
87111 var description: String { "disk on fire" }
88112 }
@@ -15,9 +15,16 @@ final class TestEngines: @unchecked Sendable {
15 let hang: Bool15 let hang: Bool
16 private var cancelled = 016 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 = hang26 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+}