Repository navigation
feat(provider-swift): adopt MLXLMServer for OpenAI protocol + parsers - #208
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 9fd43ab7f9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| frequency_penalty: request.frequencyPenalty, | ||
| stream: request.stream, | ||
| stop: stop, | ||
| seed: nil, |
There was a problem hiding this comment.
Forward seed into scheduler request translation
translate(openAIRequest:) hard-codes seed: nil, so any caller-provided seed is dropped before BatchScheduler.submit. This regresses deterministic sampling: repeated requests with the same prompt/seed can now produce different outputs, which breaks reproducibility for benchmarking and tests that rely on seeded runs.
Useful? React with 👍 / 👎.
| } catch { | ||
| log.error("[\(requestId)] Generation error: \(error)") | ||
| let statusCode = Self.mapInferenceErrorToStatus(error) | ||
| send.send(.inferenceError( |
There was a problem hiding this comment.
Treat stream cancellation as HTTP 499 instead of 500
The for try await frame in frames loop can exit through this catch with CancellationError when the inference task is cancelled; that path currently maps to a generic server error and sends status 500. In cancellation scenarios that occur while waiting for the next frame (before the explicit token.isCancelled branch runs), clients will see a spurious 500 instead of the expected cancel semantics (499), and cancellation telemetry becomes misleading.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this commit — the catch block now checks if error is CancellationError first and sends statusCode: 499 with "request cancelled" body, matching the explicit token.isCancelled branch above. Only non-cancellation errors fall through to the generic mapping.
| let requestId = "req-\(UUID().uuidString.prefix(12))" | ||
| let upstream = await scheduler.submit( | ||
| request: ourRequest, | ||
| requestId: requestId | ||
| ) |
There was a problem hiding this comment.
Preserve coordinator request IDs for scheduler cancellation
This generates a new internal request ID before scheduler.submit, but ProviderLoop.handleCancellation still calls scheduler.cancel(requestId: <coordinator request id>). After this change those IDs no longer match, so coordinator-driven cancels can miss the active scheduler job and let generation continue until stream teardown/on-termination cleanup runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this commit — ProviderLoop.handleCancellation no longer calls scheduler.cancel(<coordinator id>) directly. Cancellation propagates via task.cancel() → AsyncThrowingStream teardown → MLXOpenAIService.onTermination → MultiModelBatchSchedulerEngine.onTermination → scheduler.cancel(<internal id>). The internal request ID match is correct because the same engine instance issued it. Covered by consumerCancellationReachesEngineOnTermination test.
| /// reservation if the lookup somehow fails so a partial-acquire | ||
| /// doesn't pin a missing model forever. | ||
| fileprivate func acquireModel(_ modelId: String) async throws -> MultiModelBatchSchedulerEngine.AcquiredModel { | ||
| try await ensureModelLoaded(modelId) |
There was a problem hiding this comment.
Return 404 for unknown standalone models
acquireModel forwards ensureModelLoaded errors directly, including StandaloneServerError.modelNotFound. In the new MLX router path these thrown errors are no longer mapped to OpenAI-style 404 responses, so unknown model IDs can surface as generic 5xx responses instead of the previous 404 contract.
Useful? React with 👍 / 👎.
| let role = OpenAIRole(rawValue: msg.role) ?? .user | ||
| return OpenAIChatMessage(role: role, content: .text(msg.content)) |
There was a problem hiding this comment.
Avoid coercing unknown legacy roles to user
The legacy fallback rewrites any unrecognized role to .user rather than rejecting the request. When fallback decoding is used, this silently changes prompt semantics (for example tool/developer-like roles) and can produce materially different model behavior instead of returning a clear client error.
Useful? React with 👍 / 👎.
| if let failed { | ||
| await releaseBox.fire() | ||
| continuation.finish( | ||
| throwing: MultiModelBatchSchedulerEngineError | ||
| .generationFailed(failed) | ||
| ) |
There was a problem hiding this comment.
Preserve scheduler admission status codes in standalone mode
Scheduler failures are collapsed into generationFailed(String), which strips error category information before it reaches HTTP handling. In standalone mode this regresses prior behavior that mapped queue/capacity/admission failures (for example token_budget_exhausted and queue full) to 429/503-style responses, so clients now receive generic server errors and lose retry/backoff semantics.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in this commit — fromSchedulerMessage(_:) parses BatchScheduler's structured error strings (token_budget_exhausted: ..., request queue full, etc.) into typed cases (tokenBudgetExhausted, queueFull, requestRejected) which map to 429/503 in mapInferenceErrorToStatus. See MultiModelBatchSchedulerEngineTests.fromSchedulerMessage* for the 5 mapping cases.
| /// CORS headers that the pre-MLXLMServer implementation pinned on every | ||
| /// response are dropped in this version — see the rewrite report for | ||
| /// the deviation note. The standalone server is dev-only (`darkbloom | ||
| /// start --local`) and is reached over `127.0.0.1`, where browsers do |
There was a problem hiding this comment.
Restore CORS handling for standalone local API
This rewrite explicitly drops the previous CORS middleware and preflight handling, so browser-based tools running on a different localhost origin (different port) can no longer call /v1/* endpoints. That is a functional regression from the prior standalone server behavior, which returned permissive Access-Control-Allow-* headers for local integrations.
Useful? React with 👍 / 👎.
a39cf75 to
ddd538e
Compare
9fd43ab to
5a43af1
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5a43af16b9
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| /// reservation if the lookup somehow fails so a partial-acquire | ||
| /// doesn't pin a missing model forever. | ||
| fileprivate func acquireModel(_ modelId: String) async throws -> MultiModelBatchSchedulerEngine.AcquiredModel { | ||
| try await ensureModelLoaded(modelId) |
There was a problem hiding this comment.
Map standalone capacity errors to 503
acquireModel now forwards ensureModelLoaded failures directly, so StandaloneServerError.capacityUnavailable (thrown when cache slots are all busy or memory headroom is insufficient) bubbles out as a generic upstream error. In the new MLX router path, uncategorized thrown errors are surfaced as 500s, which regresses the previous 503/retry contract for temporary capacity conditions and makes clients treat backpressure as server faults.
Useful? React with 👍 / 👎.
| if rawLine.hasPrefix("data:") { | ||
| dataLine = rawLine.dropFirst("data:".count) | ||
| } |
There was a problem hiding this comment.
Concatenate all SSE data lines before JSON decode
parseStreamChunk overwrites dataLine on each data: field and only decodes the last one, but SSE permits payloads to be split across multiple data: lines in a single event. In that valid frame shape, this parser drops earlier fragments, the JSON decode fails, and usage/content extraction silently stops, which can undercount billing and produce an attestation hash that no longer matches the streamed assistant output.
Useful? React with 👍 / 👎.
| if let content = parsed.contentDelta { | ||
| fullResponseText += content | ||
| } | ||
| if let reasoning = parsed.reasoningDelta { | ||
| fullResponseText += reasoning |
There was a problem hiding this comment.
Include tool-call deltas in attestation hash input
The attestation input is built from fullResponseText, but the stream parser only appends content and reasoning_content and ignores tool-call deltas. With the new MLX tool-calling path, responses that primarily emit tool_calls can produce materially different client-visible outputs while hashing the same body (often empty), so the emitted response_hash no longer commits to the full assistant response for tool-calling requests.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed — tool-call deltas now folded into attestation hash via encodeToolCallsForHash at ProviderLoop+SSEParser.swift:124. Hash domain is content + reasoning_content + tool_calls (canonicalized). See ProviderLoopStreamChunkTests.parseStreamChunk extracts tool_calls delta.
5a43af1 to
1303611
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1303611eb6
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| availableModels: { [weak self] in | ||
| guard let self else { return [] } | ||
| return await self.loadedModelIds() | ||
| }, |
There was a problem hiding this comment.
Restore advertised model catalog in /v1/models
makeApplication() wires availableModels to loadedModelIds(), so /v1/models now returns only currently resident schedulers instead of the configured model catalog. This makes setModels(_:) ineffective for discovery after rescans and returns an empty list at startup until something is loaded through another path, which breaks clients that rely on /v1/models to choose valid model IDs before their first request.
Useful? React with 👍 / 👎.
ddd538e to
77989fa
Compare
1303611 to
1f2243d
Compare
99e2cd4 to
cc8c973
Compare
1f2243d to
4a13844
Compare
cc8c973 to
77989fa
Compare
4a13844 to
23688e0
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 23688e0e37
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| let choice = chunk.choices.first | ||
| return StreamChunkExtract( | ||
| contentDelta: choice?.delta.content, | ||
| reasoningDelta: choice?.delta.reasoningContent, | ||
| toolCallsDelta: choice?.delta.toolCalls, |
There was a problem hiding this comment.
Parse all choices when accumulating streamed deltas
parseStreamChunk only reads chunk.choices.first, so if the upstream stream contains multiple choices (for example when a request asks for more than one completion), deltas from the remaining choices are ignored. In this path, ProviderLoop still forwards the full SSE frame to clients, but the attestation accumulator only includes the first choice, so response_hash no longer commits to all returned assistant output for multi-choice responses.
Useful? React with 👍 / 👎.
| if lowercased.contains("token_budget_exhausted") | ||
| || lowercased.contains("timed out waiting for capacity") | ||
| || lowercased.contains("insufficient global kv cache headroom") | ||
| { | ||
| return .tokenBudgetExhausted(message) |
There was a problem hiding this comment.
Preserve 400 mapping for invalid planner rejections
fromSchedulerMessage classifies every token_budget_exhausted:* string as .tokenBudgetExhausted (503), which also captures planner errors like invalid token count, duplicate request ID, and request exceeds batch token budget. Those are request-shape/admission validation failures, not transient capacity exhaustion, so returning 503 regresses client semantics and retry behavior compared with the prior standalone mapping that treated these as 400-class input errors.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed — fromSchedulerMessage now distinguishes validation errors (invalid token count, duplicate request ID, exceeds batch token budget) → .requestRejected (400) from capacity errors → .tokenBudgetExhausted (503). See MultiModelBatchSchedulerEngineError.swift:87-95.
| } catch StandaloneServerError.modelNotFound { | ||
| // P2 #4: standalone's lazy loader rejects an unknown model |
There was a problem hiding this comment.
Map standalone capacity failures to a typed engine error
acquireModel translates only modelNotFound into a MultiModelBatchSchedulerEngineError and lets StandaloneServerError.capacityUnavailable escape unchanged. In the new router path, CORSResponder only maps MLXOpenAIServiceError and MultiModelBatchSchedulerEngineError, so capacity/backpressure conditions (full cache slots or insufficient headroom) can still bubble out as generic 500s instead of a retryable 503 contract.
Useful? React with 👍 / 👎.
9e96606 to
529b911
Compare
529b911 to
72c1392
Compare
cc8c973 to
512fa03
Compare
72c1392 to
1766b8d
Compare
Replaces our hand-rolled OpenAI server plumbing with upstream MLXLMServer (introduced in mlx-swift-lm PR #26, enhanced with batched engine in PR #30). Preserves every Darkbloom-specific security/operational layer (attestation, NaCl per-chunk encryption, multi-model LRU + memory headroom + reservation, GlobalKVCacheBudget, AdaptiveBatchCapPolicy, idle timeout, GPU enforcement) while inheriting upstream-maintained reasoning parsing, tool calling, /v1/responses, JSON-schema response_format, and embeddings hook. Submodule bump: libs/mlx-swift-lm: 3f2795a -> 7dc38801 (PR-A: feat/batched-engine- server-engine, the companion upstream PR adding MLXBatchedEngineServerEngine to MLXLMServer). Before this PR merges, the submodule pointer should be advanced to whatever commit PR-A merges to on mlx-swift-lm main. Companion PR: Layr-Labs/mlx-swift-lm#30 Architecture after the swap: Coordinator WebSocket -> ProviderLoop.handleInferenceRequest | decrypts ciphertext (NaCl crypto_box) | decodes OpenAIChatCompletionRequest | (with legacy ChatCompletionRequest fallback for single-string | stop and other pre-OpenAI-strict-types wire shapes) | forces stream=true AND streamOptions.includeUsage=true v MLXOpenAIService.streamChatCompletionFrames | (single-model registry view bound to this scheduler) v MultiModelBatchSchedulerEngine.streamChatCompletion (new adapter) | translates OpenAI <-> our ChatCompletionRequest | onTermination -> scheduler.cancel(requestId) v BatchScheduler.submit (UNCHANGED, sacred surface) v MLXLMCommon.BatchedEngine Standalone (darkbloom start --local): HTTP -> MLXServerApplication.buildRouter(service:) (upstream Hummingbird) v MLXOpenAIService v MultiModelBatchSchedulerEngine (acquire closure: load + lookup + reserve atomically inside the StandaloneServer actor) v BatchScheduler per model (UNCHANGED) New files: ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift (+424 LOC) Conforms to MLXLMServer.MLXServerEngine. Dispatches by request.model to the right BatchScheduler. Two inits: (a) one-shot 'acquire' closure (atomic load+reserve under one actor hop, used by StandaloneServer); (b) legacy three-closure (used by ProviderLoop which pre-pins via requestToModel). Cancellation propagates through onTermination -> scheduler.cancel. Lossy translations (seed/tools/tool_choice/ response_format/user) documented inline. Tests/ProviderCoreTests/MultiModelBatchSchedulerEngineTests.swift (+152) 7 unit tests: registry empty path, ensureLoaded sequencing, model-not-loaded error, tokenize-without-model error, translate field mapping, empty-stop handling, sorted available models. Tests/ProviderCoreTests/ProviderLoopStreamChunkTests.swift (+171) 12 unit tests against parseStreamChunk feeding wire-faithful SSE frames generated via upstream's ServerSentEventEncoder. Covers role/ content/reasoning/finish/usage/[DONE]/comments/event-prefix/garbage/ empty frames. Critically: 'parseStreamChunk extracts usage block (C1 billing-regression guard)' pins the include_usage contract. Modified: ProviderCore/ProviderLoop.swift (+244/-167, net +77) Inference handler rewrite: - Decode OpenAIChatCompletionRequest (legacy ChatCompletionRequest fallback retained for backward compat). - Force stream=true AND streamOptions.includeUsage=true. The include_usage flag is REQUIRED: upstream MLXOpenAIService.streamChatCompletionFrames only emits the usage chunk when this is set. Without it, every consumer request would report promptTokens=0 and completionTokens=0 - a revenue-zero regression (see Reviewer C1). - For each SSE frame: encrypt with NaCl crypto_box, send as inferenceChunk over WS. Per-chunk encryption boundary unchanged. - parseStreamChunk: defensive SSE parser handling comments (':'), event-type lines ('event:'), data: lines. Extracts content, reasoning_content, usage, finish_reason, role into StreamChunkExtract. - fullResponseText accumulator: content + reasoning_content (TB-007 hash domain matches engine output and consumer reassembly). - mapInferenceErrorToStatus: structured status code mapping for MLXOpenAIServiceError + MultiModelBatchSchedulerEngineError (422/501/404 instead of always 500). - CRITICAL log + telemetry warning when parsed token counts are zero (catches future upstream drift before billing is affected). ProviderCore/Server/StandaloneServer.swift (636 -> 411, -225) Drops hand-rolled Hummingbird routes, request decoders, SSE writers, non-streaming response assembly. Uses MLXServerApplication.buildRouter (service:) to mount upstream routes. KEEPS LRU + memory-headroom gating + reservation counters + idle timeout + per-model BatchScheduler + shared GlobalKVCacheBudget. New 'acquire(modelId:)' actor-isolated method does load + lookup + reserve atomically inside one critical section, closing the eviction-race window in the multi-model dispatch path (Reviewer I1). Package.swift (+1) Adds MLXLMServer product to ProviderCore deps. Deleted: ProviderCore/Inference/OpenAIFormatter.swift (-124) SSE chunk formatting moved upstream (ServerSentEventEncoder + MLXOpenAIService.streamChatCompletionFrames). ProviderCore/Server/ServerRoutes.swift (-90) Hummingbird route helpers, only used by the old standalone routes. Wire-format compatibility (verified): Upstream emits SSE frames as 'data: <json>\n\n' via JSONEncoder with .sortedKeys + .withoutEscapingSlashes. Nil fields are omitted (not emitted as explicit 'null'). Coordinator's normalizeSSEChunk in consumer.go:2478-2562 handles both shapes. No coordinator change required. Security verification (TB-007): - BatchScheduler public surface UNCHANGED (git diff empty). - prefixCacheConfig: nil and prefixCache: nil PRESERVED at BatchScheduler load (cross-tenant data persistence still off). - Per-chunk NaCl encryption boundary unchanged (each upstream SSE frame -> crypto_box -> inferenceChunk over WS). - SE response attestation hash domain documented and now includes both delta.content AND delta.reasoning_content so the hash commits to the bytes the consumer reassembles (was a latent bug; surfaces now that upstream's reasoning parser is wired). - Zero new disk writes, sockets, IPC, sub-processes in MultiModelBatchSchedulerEngine.swift (verified by grep). - Zero logging of decoded text or token IDs in any new file. - Attestation flow (registration, challenge-response, SE-signed status) untouched in ProviderLoop above the inference handler. Verification: swift build (provider-swift): PASS (clean; pre-existing MLX.GPU.* deprecation warnings only) swift test (full non-live suite): 233/233 PASS (baseline was 219; +14 new this PR) git grep OpenAIFormatter provider-swift/ -> 0 hits git diff BatchScheduler.swift -> empty container.perform sites -> 5 (added 2 in this PR for tokenizer extraction at model load; documented as a deviation from the original 3 because we cannot expose tokenizer on BatchScheduler's sacred surface) Live tests recommended on real hardware (DARKBLOOM_LIVE_MLX_TESTS=1): cd provider-swift DARKBLOOM_LIVE_MLX_TESTS=1 swift test \ --filter BatchSchedulerEngineIntegrationTests # Asserts usage.promptTokens > 0 AND usage.completionTokens > 0 against # a real Qwen3-0.6B-8bit model (regression guard for C1 billing zero). DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter ContinuousBatchingLiveTests Open follow-ups (NOT blockers for this PR): - Authoritative billing counts. The brief allowed substituting a CRITICAL log for engine-authoritative token counts because exposing them would expand BatchScheduler's sacred surface. A future PR should add BatchScheduler.lastCompletedRequestTokens(_:) and prefer that over parsing the SSE wire. - Upstream Hummingbird error envelope. MLXServerApplication does not wrap thrown engine errors into OpenAIErrorResponse JSON bodies; clients see empty 5xx bodies. Standalone server is dev-only over 127.0.0.1 so the priority is low; worth a follow-up issue to upstream. - Lossy legacy decode fallback (Reviewer I4): OpenAIRole.function -> user, plus seed/tools/tool_choice/response_format/user are dropped. Document in API surface; reject unknown roles in a follow-up. - /v1/models semantics: upstream returns currently-loaded models. Standalone server inherits this. Pre-rewrite returned advertised list. Behavior change; documented but not reverted. Reviewer trail (run by sub-agents per AGENTS.md): - Pre-impl audit: ProviderLoop concurrent-access (3 container.perform sites, all safe). - Impl sub-agent: built the adapter + rewrites + tests. - Review sub-agent: BLOCK verdict on C1 (billing zero), C2 (hash divergence), C3 (no real test coverage of new path), plus I1-I6. - Fixup sub-agent: applied all critical + 3 important fixes. - Build + test green; this commit incorporates the fixed state.
1766b8d to
247f513
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: PASS
7-provider-multi-model7 providers, 5 users, 50 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-high-concurrency3 providers, 10 users, 60 requests, concurrency=20, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 247f51301d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| case .requestRejected: | ||
| return 503 |
There was a problem hiding this comment.
Map requestRejected errors to HTTP 400
fromSchedulerMessage classifies planner validation failures like "invalid token count", "duplicate request id", and "exceeds batch token budget" as .requestRejected, but this mapper currently returns 503 for that case, so malformed requests are reported as transient capacity failures and can be retried indefinitely instead of being fixed by the caller. Fresh evidence against the earlier "fixed" thread claim: in this commit, .requestRejected still maps to 503 here, which conflicts with StandaloneServer.schedulerErrorStatus and the inline contract comments describing these as bad-request semantics.
Useful? React with 👍 / 👎.
| contentDelta: contentParts.isEmpty ? nil : contentParts.joined(), | ||
| reasoningDelta: reasoningParts.isEmpty ? nil : reasoningParts.joined(), |
There was a problem hiding this comment.
Delimit per-choice deltas in hash accumulation
parseStreamChunk concatenates deltas from all choices with plain .joined() and no choice boundary markers, so different multi-choice outputs can collapse to the same accumulator bytes (for example choice deltas ["ab","c"] and ["a","bc"] both become "abc"). Since ProviderLoop hashes this accumulated string for response_hash, attestation no longer uniquely commits to the full streamed response when n > 1.
Useful? React with 👍 / 👎.
Summary
Replaces our hand-rolled OpenAI server plumbing with upstream
MLXLMServerwhile preserving every Darkbloom-specific security/operational layer. We gain reasoning parsing (<think>, Harmony channels), per-model tool-call parsing (9 formats),/v1/responses, JSON-schemaresponse_format, embeddings hook, and/v1/chat/completions/batchfor free.Architecture — before vs after
Before (master @ PR #207)
flowchart LR classDef deleted fill:#ffd5d5,stroke:#c00000,color:#000000 classDef unchanged fill:#e8e8e8,stroke:#888888,color:#000000 WS_in["Coordinator WebSocket"]:::unchanged PL["ProviderLoop<br>decrypt -> decode -> format -> encrypt"]:::unchanged OF["OpenAIFormatter<br>124 LoC SSE chunks"]:::deleted BS["BatchScheduler<br>continuous batching"]:::unchanged BE["MLXLMCommon BatchedEngine"]:::unchanged HTTP_in["HTTP client<br>darkbloom start --local"]:::unchanged SS["StandaloneServer<br>636 LoC routes + LRU + headroom"]:::deleted SR["ServerRoutes.swift<br>90 LoC helpers"]:::deleted WS_in --> PL PL --> OF OF --> PL PL --> BS HTTP_in --> SS SS --> SR SR --> OF SS --> BS BS --> BEAfter (this PR)
flowchart LR classDef new fill:#d5ffd5,stroke:#00aa00,color:#000000 classDef upstream fill:#d5e8ff,stroke:#0066cc,color:#000000 classDef unchanged fill:#e8e8e8,stroke:#888888,color:#000000 WS_in["Coordinator WebSocket"]:::unchanged PL["ProviderLoop<br>decrypt + encrypt only"]:::unchanged MLX["MLXOpenAIService<br>UPSTREAM<br>reasoning + tools + SSE + responses API"]:::upstream ADAPTER["MultiModelBatchSchedulerEngine<br>NEW 424 LoC<br>MLXServerEngine adapter<br>dispatch by request.model"]:::new BS["BatchScheduler<br>UNCHANGED sacred surface"]:::unchanged BE["MLXLMCommon BatchedEngine"]:::unchanged HTTP_in["HTTP client<br>darkbloom start --local"]:::unchanged HB["MLXServerApplication.buildRouter<br>UPSTREAM Hummingbird"]:::upstream SS["StandaloneServer<br>411 LoC<br>LRU + headroom + reservation + idle ONLY"]:::unchanged WS_in --> PL PL --> MLX MLX --> ADAPTER ADAPTER --> BS HTTP_in --> HB HB --> MLX SS -.acquire/release.-> ADAPTER BS --> BELegend: green = new (this PR), blue = upstream (MLXLMServer / Hummingbird), grey = unchanged, red = deleted
What moved where
ChatRequest.swiftOpenAIChatCompletionRequest(legacy fallback retained)OpenAIFormatter.swift(deleted)ServerSentEventEncoderinsideMLXOpenAIServiceStreamingReasoningParser(streaming-aware, mlx-swift-lm PR #28)ToolCallProcessor+ per-modelToolCallFormat.infer(9 formats)/v1/responsesAPIMLXOpenAIService.createResponse/retrieveResponse/cancelResponseresponse_formatOpenAIResponseFormatSupportMLXEmbeddingServerEnginehook (off today)ServerRoutes.swift+ hand-rolled handlers inStandaloneServer.swiftMLXServerApplication.buildRouter(service:)BatchScheduler→BatchedEngine(PR #207)GlobalKVCacheBudgetin our codeAdaptiveBatchCapPolicyin our code →engine.setMaxNumSeqs(mlx-swift-lm PR #27)StandaloneServer.swiftProviderLoopregistration + 5-min challengeProviderLoopwraps each SSE frameIdleTimeoutPolicyGPUEnforcement.requireMetalFile changes
Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swiftSources/ProviderCore/Inference/OpenAIFormatter.swiftSources/ProviderCore/Server/ServerRoutes.swiftSources/ProviderCore/Server/StandaloneServer.swiftSources/ProviderCore/ProviderLoop.swiftPackage.swiftTests/ProviderCoreTests/MultiModelBatchSchedulerEngineTests.swiftTests/ProviderCoreTests/ProviderLoopStreamChunkTests.swiftTests/ProviderCoreTests/StandaloneServerTests.swiftTests/ProviderCoreTests/BatchSchedulerEngineIntegrationTests.swiftWhat we kept (Darkbloom-specific, NOT in MLXLMServer)
crypto_boxencryption boundary — preserved 1:1GlobalKVCacheBudgetcross-model byte-level reservationAdaptiveBatchCapPolicyruntime concurrency adjustment (uses upstream PR Large Models Failing To Download Due To Download Retries Exausted #27'ssetMaxNumSeqs)BatchSchedulerpublic surface — zero changesCritical fixes applied during review
The first impl pass had three critical regressions caught by the review sub-agent:
Billing zero: ProviderLoop forced
stream: truebut didn't forcestreamOptions.includeUsage: true→ every consumer request reportedpromptTokens=0, completionTokens=0→ coordinator would bill $0 for everything. Fixed: force both, plus CRITICAL log + telemetry alert if parsed counts ever come back zero (defense in depth against future upstream drift).SE attestation hash domain divergence:
fullResponseTextaccumulated onlydelta.content. When upstream's reasoning parser runs, it strips<think>blocks fromdelta.contentand routes them todelta.reasoning_content— so the hash would commit to a different byte sequence than what the consumer reassembles. Fixed: accumulatecontent + reasoning_contentfrom each chunk in the order emitted; inline TB-007 comment documents the domain.No real test coverage of the new path: Existing
CoordinatorIntegrationTestsstubs the engine. Fixed: added 12 unit tests againstparseStreamChunkwith wire-faithful SSE frames generated via upstream'sServerSentEventEncoder(including a billing-regression guard for the usage chunk), plus 2 live tests gated onDARKBLOOM_LIVE_MLX_TESTS=1that drive the fullBatchScheduler → MultiModelBatchSchedulerEngine → MLXOpenAIServicechain end-to-end.Plus three important fixes:
Eviction race in
StandaloneServer: Previously three actor hops (ensureLoaded→registryProvider→reserveModel) — a concurrent eviction could pick the just-loaded model in between. Fixed: singleacquire(modelId:)actor-isolated method does load + lookup + reserve atomically in one critical section, with reservation rollback on lookup failure.Hardcoded 500 status for upstream errors: Fixed:
mapInferenceErrorToStatusswitch mapsMLXOpenAIServiceErrorandMultiModelBatchSchedulerEngineErrorcases to appropriate 4xx/5xx codes (422 / 501 / 404 / 400 / 500).Brittle SSE parser: Old
parseStreamChunkusedframe.range(of: \"data: \")— would silently return nil on SSE comments or event-type lines. Fixed: line-by-line parse handling:comments,event:lines,data:payloads; logs WARN on truly unparseable frames.Verification
swift buildMLX.GPU.*deprecation warnings)swift test(full non-live)git grep OpenAIFormatter provider-swift/git diff -- provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swiftgit grep \"container.perform\" provider-swift/Sources/Live tests recommended before merge
Wire compatibility
Upstream emits SSE frames as
\"data: <json>\\n\\n\"viaJSONEncoderwith.sortedKeys + .withoutEscapingSlashes. Nil fields are omitted (not emitted as explicitnull). Coordinator'snormalizeSSEChunkincoordinator/api/consumer.go:2478-2562handles both shapes. No coordinator change required. A follow-up wire-format e2e test on the coordinator side is recommended (out of scope here).Open follow-ups (NOT blocking)
Authoritative billing counts. Today we parse the SSE wire for token counts (with a CRITICAL log guard if it returns zero). A future small PR should add
BatchScheduler.lastCompletedRequestTokens(_:)and prefer that. Out of scope to keepBatchScheduler's sacred surface untouched in this PR.Upstream Hummingbird error envelope.
MLXServerApplicationdoesn't wrap thrown engine errors intoOpenAIErrorResponseJSON; clients see empty 5xx bodies. Standalone server is dev-only on127.0.0.1so the priority is low; file an upstream issue.Lossy legacy decode fallback (Reviewer I4). Documented in code; future PR should reject unknown legacy fields explicitly.
/v1/modelssemantics flipped from "advertised" to "currently loaded." Behavior change documented in tests; considerowned_by/readyannotations if we want to preserve the advertised-list shape.Reviewer trail (per AGENTS.md)
container.performsites in production code, all safe to run alongside engine-owned model execution.