Skip to content

feat(provider-swift): adopt MLXLMServer for OpenAI protocol + parsers - #208

Merged
Gajesh2007 merged 1 commit into
masterfrom
feat/mlxlm-server-adoption
May 25, 2026
Merged

Gajesh2007 merged 1 commit into
masterfrom
feat/mlxlm-server-adoption

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented May 24, 2026 •

Copy link
Copy Markdown
Member

Stacked on PR #207 (feat/batched-engine-migration). Base is set to PR #207's branch so the diff shows only this PR's changes. When PR #207 merges to master, GitHub will auto-rebase the base to master. This PR also depends on upstream Layr-Labs/mlx-swift-lm#30 for the MLXBatchedEngineServerEngine it consumes.

Summary

Replaces our hand-rolled OpenAI server plumbing with upstream MLXLMServer while preserving every Darkbloom-specific security/operational layer. We gain reasoning parsing (<think>, Harmony channels), per-model tool-call parsing (9 formats), /v1/responses, JSON-schema response_format, embeddings hook, and /v1/chat/completions/batch for 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 --> BE
Loading

After (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 --> BE
Loading

Legend: green = new (this PR), blue = upstream (MLXLMServer / Hummingbird), grey = unchanged, red = deleted

What moved where

Concern Before After
OpenAI request decoding hand-rolled ChatRequest.swift upstream OpenAIChatCompletionRequest (legacy fallback retained)
SSE chunk encoding OpenAIFormatter.swift (deleted) upstream ServerSentEventEncoder inside MLXOpenAIService
Reasoning parsing none upstream StreamingReasoningParser (streaming-aware, mlx-swift-lm PR #28)
Tool-call parsing none upstream ToolCallProcessor + per-model ToolCallFormat.infer (9 formats)
/v1/responses API none upstream MLXOpenAIService.createResponse/retrieveResponse/cancelResponse
JSON-schema response_format none upstream OpenAIResponseFormatSupport
Embeddings endpoint none upstream MLXEmbeddingServerEngine hook (off today)
HTTP routes ServerRoutes.swift + hand-rolled handlers in StandaloneServer.swift upstream MLXServerApplication.buildRouter(service:)
Continuous batching BatchScheduler → BatchedEngine (PR #207) unchanged
KV byte budget (cross-model) GlobalKVCacheBudget in our code unchanged
Adaptive concurrency cap AdaptiveBatchCapPolicy in our code → engine.setMaxNumSeqs (mlx-swift-lm PR #27) unchanged
Multi-model LRU + headroom + reservation StandaloneServer.swift unchanged (compacted into ~250 LoC)
Attestation flow ProviderLoop registration + 5-min challenge unchanged
Per-chunk NaCl encryption ProviderLoop wraps each SSE frame unchanged (now wraps upstream-emitted frames)
Idle timeout / unload IdleTimeoutPolicy unchanged
GPU enforcement / SIP / Hardened Runtime GPUEnforcement.requireMetal unchanged

File changes

File Status LoC
Sources/ProviderCore/Inference/MultiModelBatchSchedulerEngine.swift NEW +424
Sources/ProviderCore/Inference/OpenAIFormatter.swift DELETED −124
Sources/ProviderCore/Server/ServerRoutes.swift DELETED −90
Sources/ProviderCore/Server/StandaloneServer.swift rewritten 636 → 411 (−225)
Sources/ProviderCore/ProviderLoop.swift modified +244 / −167 (net +77)
Package.swift modified +1
Tests/ProviderCoreTests/MultiModelBatchSchedulerEngineTests.swift NEW +152
Tests/ProviderCoreTests/ProviderLoopStreamChunkTests.swift NEW +171
Tests/ProviderCoreTests/StandaloneServerTests.swift rewritten −7
Tests/ProviderCoreTests/BatchSchedulerEngineIntegrationTests.swift modified +137 (2 new live tests)

What we kept (Darkbloom-specific, NOT in MLXLMServer)

  • Attestation flow (registration, challenge-response, SE-signed status) — untouched
  • Per-chunk NaCl crypto_box encryption boundary — preserved 1:1
  • Multi-model serving + LRU eviction + memory-headroom gating + reservation counters
  • GlobalKVCacheBudget cross-model byte-level reservation
  • AdaptiveBatchCapPolicy runtime concurrency adjustment (uses upstream PR Large Models Failing To Download Due To Download Retries Exausted #27's setMaxNumSeqs)
  • 120s pending-queue timeout
  • Idle timeout + model unload
  • GPU enforcement / Hardened Runtime preflight
  • BatchScheduler public surface — zero changes

Critical fixes applied during review

The first impl pass had three critical regressions caught by the review sub-agent:

  1. Billing zero: ProviderLoop forced stream: true but didn't force streamOptions.includeUsage: true → every consumer request reported promptTokens=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).

  2. SE attestation hash domain divergence: fullResponseText accumulated only delta.content. When upstream's reasoning parser runs, it strips <think> blocks from delta.content and routes them to delta.reasoning_content — so the hash would commit to a different byte sequence than what the consumer reassembles. Fixed: accumulate content + reasoning_content from each chunk in the order emitted; inline TB-007 comment documents the domain.

  3. No real test coverage of the new path: Existing CoordinatorIntegrationTests stubs the engine. Fixed: added 12 unit tests against parseStreamChunk with wire-faithful SSE frames generated via upstream's ServerSentEventEncoder (including a billing-regression guard for the usage chunk), plus 2 live tests gated on DARKBLOOM_LIVE_MLX_TESTS=1 that drive the full BatchScheduler → MultiModelBatchSchedulerEngine → MLXOpenAIService chain end-to-end.

Plus three important fixes:

  1. Eviction race in StandaloneServer: Previously three actor hops (ensureLoaded → registryProvider → reserveModel) — a concurrent eviction could pick the just-loaded model in between. Fixed: single acquire(modelId:) actor-isolated method does load + lookup + reserve atomically in one critical section, with reservation rollback on lookup failure.

  2. Hardcoded 500 status for upstream errors: Fixed: mapInferenceErrorToStatus switch maps MLXOpenAIServiceError and MultiModelBatchSchedulerEngineError cases to appropriate 4xx/5xx codes (422 / 501 / 404 / 400 / 500).

  3. Brittle SSE parser: Old parseStreamChunk used frame.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

Check Result
swift build clean (only pre-existing MLX.GPU.* deprecation warnings)
swift test (full non-live) 233/233 pass (baseline 219 + 14 new this PR)
git grep OpenAIFormatter provider-swift/ 0 hits ✓
git diff -- provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift empty ✓
git grep \"container.perform\" provider-swift/Sources/ 5 hits (the 3 pre-existing + 2 added for tokenizer extraction at model-load time; documented)

Live tests recommended before merge

cd provider-swift
DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter BatchSchedulerEngineIntegrationTests
# Asserts usage.promptTokens > 0 && usage.completionTokens > 0 (C1 regression guard)
# Asserts cancellation frees scheduler slot

DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter ContinuousBatchingLiveTests
DARKBLOOM_LIVE_MLX_TESTS=1 swift test --filter PerformanceLiveTests

Wire compatibility

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 coordinator/api/consumer.go:2478-2562 handles 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)

  1. 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 keep BatchScheduler's sacred surface untouched in this PR.

  2. Upstream Hummingbird error envelope. MLXServerApplication doesn't wrap thrown engine errors into OpenAIErrorResponse JSON; clients see empty 5xx bodies. Standalone server is dev-only on 127.0.0.1 so the priority is low; file an upstream issue.

  3. Lossy legacy decode fallback (Reviewer I4). Documented in code; future PR should reject unknown legacy fields explicitly.

  4. /v1/models semantics flipped from "advertised" to "currently loaded." Behavior change documented in tests; consider owned_by/ready annotations if we want to preserve the advertised-list shape.

Reviewer trail (per AGENTS.md)

  1. Pre-implementation audit: only 3 container.perform sites in production code, all safe to run alongside engine-owned model execution.
  2. Implementation sub-agent: built adapter + rewrites + tests.
  3. Review sub-agent: BLOCK verdict — 3 critical (C1 billing, C2 hash, C3 coverage) + 3 important (I1 race, I2 status, I3 parser).
  4. Fixup sub-agent: all critical + important issues addressed.
  5. Build + test green; this PR incorporates the fixed state.

@vercel

vercel Bot commented May 24, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview May 25, 2026 1:22am
d-inference-console-ui-dev Ready Ready Preview May 25, 2026 1:22am
d-inference-landing Ready Ready Preview May 25, 2026 1:22am

Request Review

@github-actions

github-actions Bot commented May 24, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results

Runner: macos-15 (M1 Virtual) | Date: 2026-05-25 01:10 UTC

1-provider-streaming

1 providers, 1 users, 30 requests, concurrency=5, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 30
Success 4
Errors 26
Total Duration 4.966s
Throughput 0.8 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 1.752s 1.752s 1.753s 1.753s
parse 4 127µs 92µs 342µs 342µs
reserve 4 8ms 10ms 10ms 10ms
route 4 31µs 28µs 58µs 58µs
encrypt 4 761µs 838µs 875µs 875µs
dispatch 4 66µs 72µs 87µs 87µs
coordinator_to_provider 4 1.732s 1.733s 1.735s 1.735s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=126.5µs (threshold=1ms)
parse:p95<=5ms PASS p95=342µs (threshold=5ms)
reserve:mean<=50ms PASS mean=7.8875ms (threshold=50ms)
reserve:p95<=200ms PASS p95=10.357ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=760.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=875µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=66.25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=87µs (threshold=50ms)

1-provider-non-streaming

1 providers, 1 users, 20 requests, concurrency=5, streaming=false

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 20
Success 4
Errors 16
Total Duration 3.313s
Throughput 1.2 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 3.309s 3.309s 3.313s 3.313s
parse 4 22µs 25µs 25µs 25µs
reserve 4 4ms 5ms 6ms 6ms
route 4 15µs 19µs 21µs 21µs
encrypt 4 576µs 578µs 627µs 627µs
dispatch 4 34µs 36µs 36µs 36µs
coordinator_to_provider 4 1.731s 1.732s 1.734s 1.734s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=22.25µs (threshold=1ms)
parse:p95<=5ms PASS p95=25µs (threshold=5ms)
reserve:mean<=50ms PASS mean=4.14975ms (threshold=50ms)
reserve:p95<=200ms PASS p95=6.296ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=575.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=627µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=33.75µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=36µs (threshold=50ms)

7-provider-multi-model

7 providers, 5 users, 50 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 4 0.5 GB
mlx-community/gemma-3-270m-4bit 3 0.2 GB
Metric Value
Total Requests 50
Success 50
Errors 0
Total Duration 17.492s
Throughput 2.9 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 50 724ms 185ms 3.901s 4.1s
parse 49 29µs 19µs 47µs 457µs
reserve 49 2ms 1ms 2ms 3ms
route 49 29µs 24µs 66µs 103µs
encrypt 50 505µs 482µs 759µs 934µs
dispatch 50 42µs 36µs 102µs 116µs
coordinator_to_provider 50 670ms 182ms 3.848s 4.094s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=29.428µs (threshold=1ms)
parse:p95<=5ms PASS p95=47µs (threshold=5ms)
reserve:mean<=50ms PASS mean=1.538428ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.348ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=504.66µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=759µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=42.42µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=102µs (threshold=50ms)

3-provider-high-concurrency

3 providers, 10 users, 60 requests, concurrency=20, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 60
Success 12
Errors 48
Total Duration 3.997s
Throughput 3.0 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 12 2.34s 2.344s 2.346s 2.346s
parse 12 19µs 18µs 49µs 49µs
reserve 12 3ms 4ms 4ms 4ms
route 12 15µs 13µs 31µs 31µs
encrypt 12 1ms 1ms 1ms 1ms
dispatch 12 44µs 25µs 134µs 134µs
coordinator_to_provider 12 2.329s 2.334s 2.337s 2.337s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=19.083µs (threshold=1ms)
parse:p95<=5ms PASS p95=49µs (threshold=5ms)
reserve:mean<=50ms PASS mean=3.41125ms (threshold=50ms)
reserve:p95<=200ms PASS p95=4.198ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=739.75µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=1.078ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=43.5µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=134µs (threshold=50ms)

1-provider-queue-saturation

1 providers, 10 users, 40 requests, concurrency=15, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 40
Success 4
Errors 36
Total Duration 3.918s
Throughput 1.0 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 2.38s 2.38s 2.38s 2.38s
parse 4 25µs 27µs 33µs 33µs
reserve 4 2ms 2ms 3ms 3ms
route 4 13µs 13µs 15µs 15µs
encrypt 4 495µs 510µs 543µs 543µs
dispatch 4 30µs 37µs 39µs 39µs
coordinator_to_provider 4 2.373s 2.374s 2.374s 2.374s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=24.75µs (threshold=1ms)
parse:p95<=5ms PASS p95=33µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.37025ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.554ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=494.75µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=543µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=30.25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=39µs (threshold=50ms)

3-provider-20-users

3 providers, 20 users, 60 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 60
Success 60
Errors 0
Total Duration 9.767s
Throughput 6.1 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 60 429ms 77ms 2.297s 2.298s
parse 60 17µs 15µs 35µs 67µs
reserve 60 1ms 1ms 3ms 4ms
route 60 16µs 15µs 32µs 44µs
encrypt 60 0s 0s 1ms 1ms
dispatch 60 35µs 24µs 86µs 327µs
coordinator_to_provider 60 425ms 74ms 2.29s 2.292s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=17.466µs (threshold=1ms)
parse:p95<=5ms PASS p95=35µs (threshold=5ms)
reserve:mean<=50ms PASS mean=1.449883ms (threshold=50ms)
reserve:p95<=200ms PASS p95=3.022ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=411.366µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=820µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=34.933µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=86µs (threshold=50ms)

1-provider-scaling

1 providers, 5 users, 30 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 30
Success 4
Errors 26
Total Duration 3.435s
Throughput 1.2 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 2.149s 2.149s 2.149s 2.149s
parse 4 22µs 28µs 29µs 29µs
reserve 4 2ms 2ms 3ms 3ms
route 4 12µs 11µs 19µs 19µs
encrypt 4 506µs 525µs 579µs 579µs
dispatch 4 37µs 46µs 62µs 62µs
coordinator_to_provider 4 2.143s 2.144s 2.144s 2.144s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=22.25µs (threshold=1ms)
parse:p95<=5ms PASS p95=29µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.335ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.654ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=506.25µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=579µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=37.25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=62µs (threshold=50ms)

3-provider-scaling

3 providers, 5 users, 30 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 30
Success 30
Errors 0
Total Duration 6.101s
Throughput 4.9 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 30 784ms 139ms 2.226s 2.226s
parse 30 18µs 14µs 32µs 51µs
reserve 30 2ms 1ms 3ms 3ms
route 30 16µs 14µs 35µs 50µs
encrypt 30 0s 0s 1ms 1ms
dispatch 30 33µs 23µs 127µs 146µs
coordinator_to_provider 30 780ms 137ms 2.219s 2.22s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=17.566µs (threshold=1ms)
parse:p95<=5ms PASS p95=32µs (threshold=5ms)
reserve:mean<=50ms PASS mean=1.682066ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.986ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=482.933µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=906µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=32.866µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=127µs (threshold=50ms)

5-provider-scaling

5 providers, 5 users, 30 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 5 0.5 GB
Metric Value
Total Requests 30
Success 30
Errors 0
Total Duration 6.824s
Throughput 4.4 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 30 862ms 158ms 2.529s 2.529s
parse 30 22µs 18µs 50µs 55µs
reserve 30 2ms 2ms 3ms 4ms
route 30 26µs 21µs 58µs 109µs
encrypt 30 1ms 0s 1ms 2ms
dispatch 30 43µs 33µs 125µs 243µs
coordinator_to_provider 30 858ms 155ms 2.521s 2.523s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=21.966µs (threshold=1ms)
parse:p95<=5ms PASS p95=50µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.0359ms (threshold=50ms)
reserve:p95<=200ms PASS p95=3.284ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=587.433µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=1.001ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=43.033µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=125µs (threshold=50ms)

3-provider-heavy-100conc-10kb

3 providers, 20 users, 100 requests, concurrency=100, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 100
Success 12
Errors 88
Total Duration 3.879s
Throughput 3.1 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 12 2.152s 2.167s 2.169s 2.169s
parse 12 118µs 87µs 458µs 458µs
reserve 12 9ms 9ms 11ms 11ms
route 12 14µs 12µs 25µs 25µs
encrypt 12 17ms 18ms 18ms 18ms
dispatch 12 63µs 52µs 146µs 146µs
coordinator_to_provider 12 2.117s 2.131s 2.144s 2.144s

Assertion Report: FAIL

Assertion Result Detail
parse:mean<=1ms PASS mean=118.333µs (threshold=1ms)
parse:p95<=5ms PASS p95=458µs (threshold=5ms)
reserve:mean<=50ms PASS mean=9.233583ms (threshold=50ms)
reserve:p95<=200ms PASS p95=11.438ms (threshold=200ms)
encrypt:mean<=5ms FAIL mean=16.968583ms (threshold=5ms)
encrypt:p95<=50ms PASS p95=18.487ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=62.833µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=146µs (threshold=50ms)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment on lines +760 to +763
} catch {
log.error("[\(requestId)] Generation error: \(error)")
let statusCode = Self.mapInferenceErrorToStatus(error)
send.send(.inferenceError(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +208 to +212
let requestId = "req-\(UUID().uuidString.prefix(12))"
let upstream = await scheduler.submit(
request: ourRequest,
requestId: requestId
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +1472 to +1473
let role = OpenAIRole(rawValue: msg.role) ?? .user
return OpenAIChatMessage(role: role, content: .text(msg.content))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +247 to +252
if let failed {
await releaseBox.fire()
continuation.finish(
throwing: MultiModelBatchSchedulerEngineError
.generationFailed(failed)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +181 to +184
/// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +1529 to +1531
if rawLine.hasPrefix("data:") {
dataLine = rawLine.dropFirst("data:".count)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +747 to +751
if let content = parsed.contentDelta {
fullResponseText += content
}
if let reasoning = parsed.reasoningDelta {
fullResponseText += reasoning

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +212 to +215
availableModels: { [weak self] in
guard let self else { return [] }
return await self.loadedModelIds()
},

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +120 to +124
let choice = chunk.choices.first
return StreamChunkExtract(
contentDelta: choice?.delta.content,
reasoningDelta: choice?.delta.reasoningContent,
toolCallsDelta: choice?.delta.toolCalls,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +83 to +87
if lowercased.contains("token_budget_exhausted")
|| lowercased.contains("timed out waiting for capacity")
|| lowercased.contains("insufficient global kv cache headroom")
{
return .tokenBudgetExhausted(message)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +364 to +365
} catch StandaloneServerError.modelNotFound {
// P2 #4: standalone's lazy loader rejects an unknown model

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

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.
@github-actions

github-actions Bot commented May 25, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results

Runner: macos-15 (M1 Virtual) | Date: 2026-05-25 01:24 UTC

1-provider-streaming

1 providers, 1 users, 30 requests, concurrency=5, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 30
Success 4
Errors 26
Total Duration 4.943s
Throughput 0.8 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 1.764s 1.764s 1.764s 1.764s
parse 4 47µs 33µs 99µs 99µs
reserve 4 6ms 7ms 8ms 8ms
route 4 26µs 27µs 59µs 59µs
encrypt 4 579µs 550µs 734µs 734µs
dispatch 4 55µs 44µs 97µs 97µs
coordinator_to_provider 4 1.746s 1.746s 1.748s 1.748s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=46.5µs (threshold=1ms)
parse:p95<=5ms PASS p95=99µs (threshold=5ms)
reserve:mean<=50ms PASS mean=6.05425ms (threshold=50ms)
reserve:p95<=200ms PASS p95=8.052ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=578.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=734µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=55.25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=97µs (threshold=50ms)

1-provider-non-streaming

1 providers, 1 users, 20 requests, concurrency=5, streaming=false

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 20
Success 4
Errors 16
Total Duration 3.55s
Throughput 1.1 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 3.544s 3.545s 3.549s 3.549s
parse 4 15µs 16µs 17µs 17µs
reserve 4 3ms 3ms 4ms 4ms
route 4 12µs 12µs 19µs 19µs
encrypt 4 378µs 374µs 478µs 478µs
dispatch 4 36µs 32µs 62µs 62µs
coordinator_to_provider 4 1.852s 1.852s 1.853s 1.853s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=14.75µs (threshold=1ms)
parse:p95<=5ms PASS p95=17µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.95075ms (threshold=50ms)
reserve:p95<=200ms PASS p95=4.261ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=378µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=478µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=36µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=62µs (threshold=50ms)

7-provider-multi-model

7 providers, 5 users, 50 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 4 0.5 GB
mlx-community/gemma-3-270m-4bit 3 0.2 GB
Metric Value
Total Requests 50
Success 50
Errors 0
Total Duration 14.273s
Throughput 3.5 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 50 718ms 182ms 3.82s 3.82s
parse 48 23µs 20µs 46µs 61µs
reserve 48 2ms 1ms 6ms 8ms
route 48 32µs 24µs 67µs 210µs
encrypt 50 1ms 0s 1ms 1ms
dispatch 50 47µs 36µs 115µs 194µs
coordinator_to_provider 50 611ms 179ms 3.687s 3.801s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=23.229µs (threshold=1ms)
parse:p95<=5ms PASS p95=46µs (threshold=5ms)
reserve:mean<=50ms PASS mean=1.992729ms (threshold=50ms)
reserve:p95<=200ms PASS p95=6.205ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=539.26µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=986µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=46.52µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=115µs (threshold=50ms)

3-provider-high-concurrency

3 providers, 10 users, 60 requests, concurrency=20, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 60
Success 12
Errors 48
Total Duration 3.725s
Throughput 3.2 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 12 2.141s 2.141s 2.148s 2.148s
parse 12 18µs 15µs 50µs 50µs
reserve 12 2ms 3ms 3ms 3ms
route 12 14µs 13µs 25µs 25µs
encrypt 12 1ms 1ms 1ms 1ms
dispatch 12 25µs 19µs 62µs 62µs
coordinator_to_provider 12 2.133s 2.134s 2.14s 2.14s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=17.583µs (threshold=1ms)
parse:p95<=5ms PASS p95=50µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.3305ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.986ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=581.916µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=1.094ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=25.25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=62µs (threshold=50ms)

1-provider-queue-saturation

1 providers, 10 users, 40 requests, concurrency=15, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 40
Success 4
Errors 36
Total Duration 3.478s
Throughput 1.2 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 1.983s 1.983s 1.983s 1.983s
parse 4 15µs 18µs 24µs 24µs
reserve 4 2ms 2ms 2ms 2ms
route 4 14µs 16µs 18µs 18µs
encrypt 4 1ms 1ms 1ms 1ms
dispatch 4 27µs 28µs 43µs 43µs
coordinator_to_provider 4 1.977s 1.976s 1.977s 1.977s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=15.25µs (threshold=1ms)
parse:p95<=5ms PASS p95=24µs (threshold=5ms)
reserve:mean<=50ms PASS mean=1.97775ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.119ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=699.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=1.015ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=27.25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=43µs (threshold=50ms)

3-provider-20-users

3 providers, 20 users, 60 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 60
Success 60
Errors 0
Total Duration 10.112s
Throughput 5.9 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 60 425ms 77ms 2.25s 2.25s
parse 60 18µs 17µs 34µs 77µs
reserve 60 1ms 1ms 3ms 3ms
route 60 25µs 19µs 60µs 243µs
encrypt 60 0s 0s 1ms 1ms
dispatch 60 36µs 31µs 84µs 94µs
coordinator_to_provider 60 421ms 75ms 2.242s 2.244s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=18.45µs (threshold=1ms)
parse:p95<=5ms PASS p95=34µs (threshold=5ms)
reserve:mean<=50ms PASS mean=1.320516ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.677ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=402.066µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=705µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=35.85µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=84µs (threshold=50ms)

1-provider-scaling

1 providers, 5 users, 30 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 1 0.5 GB
Metric Value
Total Requests 30
Success 4
Errors 26
Total Duration 3.566s
Throughput 1.1 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 2.05s 2.05s 2.051s 2.051s
parse 4 14µs 12µs 22µs 22µs
reserve 4 2ms 2ms 2ms 2ms
route 4 29µs 28µs 60µs 60µs
encrypt 4 499µs 518µs 563µs 563µs
dispatch 4 24µs 28µs 33µs 33µs
coordinator_to_provider 4 2.045s 2.046s 2.046s 2.046s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=13.5µs (threshold=1ms)
parse:p95<=5ms PASS p95=22µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.048ms (threshold=50ms)
reserve:p95<=200ms PASS p95=2.097ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=498.75µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=563µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=23.75µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=33µs (threshold=50ms)

3-provider-scaling

3 providers, 5 users, 30 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 30
Success 30
Errors 0
Total Duration 6.004s
Throughput 5.0 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 30 743ms 81ms 2.154s 2.155s
parse 30 38µs 15µs 267µs 329µs
reserve 30 2ms 2ms 5ms 12ms
route 30 19µs 19µs 36µs 37µs
encrypt 30 1ms 0s 1ms 3ms
dispatch 30 42µs 22µs 107µs 390µs
coordinator_to_provider 30 738ms 79ms 2.148s 2.15s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=38.433µs (threshold=1ms)
parse:p95<=5ms PASS p95=267µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.2424ms (threshold=50ms)
reserve:p95<=200ms PASS p95=5.011ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=528.633µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=1.009ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=41.5µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=107µs (threshold=50ms)

5-provider-scaling

5 providers, 5 users, 30 requests, concurrency=10, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 5 0.5 GB
Metric Value
Total Requests 30
Success 30
Errors 0
Total Duration 6.828s
Throughput 4.4 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 30 826ms 13ms 2.471s 2.471s
parse 30 24µs 20µs 61µs 89µs
reserve 30 3ms 2ms 7ms 8ms
route 30 35µs 22µs 132µs 169µs
encrypt 30 1ms 1ms 2ms 2ms
dispatch 30 40µs 26µs 113µs 198µs
coordinator_to_provider 30 821ms 5ms 2.463s 2.466s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=23.533µs (threshold=1ms)
parse:p95<=5ms PASS p95=61µs (threshold=5ms)
reserve:mean<=50ms PASS mean=2.699033ms (threshold=50ms)
reserve:p95<=200ms PASS p95=7.087ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=665.4µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=1.942ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=39.633µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=113µs (threshold=50ms)

3-provider-heavy-100conc-10kb

3 providers, 20 users, 100 requests, concurrency=100, streaming=true

Model Providers RAM
mlx-community/Qwen3.5-0.8B-MLX-4bit 3 0.5 GB
Metric Value
Total Requests 100
Success 12
Errors 88
Total Duration 3.871s
Throughput 3.1 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 12 2.185s 2.188s 2.205s 2.205s
parse 12 108µs 92µs 243µs 243µs
reserve 12 7ms 7ms 8ms 8ms
route 12 16µs 13µs 26µs 26µs
encrypt 12 15ms 19ms 20ms 20ms
dispatch 12 45µs 40µs 93µs 93µs
coordinator_to_provider 12 2.154s 2.158s 2.18s 2.18s

Assertion Report: FAIL

Assertion Result Detail
parse:mean<=1ms PASS mean=108.166µs (threshold=1ms)
parse:p95<=5ms PASS p95=243µs (threshold=5ms)
reserve:mean<=50ms PASS mean=6.97125ms (threshold=50ms)
reserve:p95<=200ms PASS p95=7.58ms (threshold=200ms)
encrypt:mean<=5ms FAIL mean=15.268ms (threshold=5ms)
encrypt:p95<=50ms PASS p95=19.893ms (threshold=50ms)
dispatch:mean<=5ms PASS mean=44.75µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=93µs (threshold=50ms)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +53 to +54
case .requestRejected:
return 503

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment on lines +135 to +136
contentDelta: contentParts.isEmpty ? nil : contentParts.joined(),
reasoningDelta: reasoningParts.isEmpty ? nil : reasoningParts.joined(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

This branch was successfully deployed

3 active deployments
Preview – d-inference — 247f5130 Deployed May 25, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 247f5130 Deployed May 25, 2026 by vercel[bot]
Preview – d-inference-landing — 247f5130 Deployed May 25, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant