Skip to content

feat: add adaptive provider batching capacity - #181

Merged
Gajesh2007 merged 6 commits into
worktree-swift-multi-modelfrom
feat/adaptive-batching-routing
May 18, 2026
Merged

Gajesh2007 merged 6 commits into
worktree-swift-multi-modelfrom
feat/adaptive-batching-routing

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented May 18, 2026 •

Copy link
Copy Markdown
Member

Summary

This PR adds provider-reported adaptive batching capacity on top of the multi-model Swift provider branch.

  • Swift BatchScheduler keeps a hard engine slot ceiling and learns an effective per-model concurrency cap from observed per-batch decode TPS.
  • Swift admission remains KV-aware: a request must fit the model's token budget, and pending-to-active promotion re-checks active reserved tokens before allocating a row.
  • Swift heartbeats now report per-slot max_concurrency, active/queued token budgets, observed TPS, and KV bytes per token.
  • Coordinator routing consumes positive per-slot max_concurrency for model-aware headroom checks while preserving legacy fallback for omitted/zero values.
  • Coordinator model capacity snapshots and routing gates now treat saturated per-model slots as capacity-limited rather than structurally ineligible.

Before

flowchart TD
    A[Consumer request] --> B[Coordinator selects provider]
    B --> C{Provider-wide cap}
    C -->|Default or memory tier| D[Route to provider]
    D --> E[Swift ProviderLoop]
    E --> F[BatchScheduler]
    F --> G{Fixed active rows = 4}
    G -->|free row| H[BatchGenerator active batch]
    G -->|no row| I[Provider pending queue]
    H --> J[Decode]
    I --> H

    K[KV/token budget] -. checked at submit .-> F
    L[Actual per-batch TPS] -. not used for cap .-> F
    M[Multi-model slots] -. coordinator sees provider-wide cap .-> C
Loading

After

flowchart TD
    A[Consumer request] --> B[Coordinator preflight and routing]
    B --> C{Per-model slot cap reported?}
    C -->|yes| D[Use slot max_concurrency]
    C -->|no or zero| E[Legacy provider-wide fallback]
    D --> F{Provider-wide safety cap also has headroom?}
    E --> F
    F -->|headroom| G[Route to provider]
    F -->|full| Q[Capacity rejection / queue]

    G --> H[Swift ProviderLoop]
    H --> I[BatchScheduler]
    I --> J{Request fits token budget alone?}
    J -->|no| R[token_budget_exhausted]
    J -->|yes| K[Pending queue]

    K --> L{Active rows below dynamic cap?}
    L -->|yes| M{Active reserved tokens + request <= live KV budget?}
    M -->|yes| N[Promote to BatchGenerator]
    M -->|no| K
    L -->|no| K
    N --> O[Decode burst]
    O --> P[Record batch-size TPS EWMA]
    P --> S[Expand or shrink dynamic cap]
    S --> T[Heartbeat backend_capacity slot max_concurrency]
    T --> B
Loading

Testing

  • cd coordinator && go test ./...
  • git diff --check

Swift verification is blocked in this worktree because local path dependencies are absent:

  • libs/mlx-swift/Package.swift
  • libs/mlx-swift-lm/Package.swift

Review Notes

Focused review passes were run for Swift scheduling, coordinator routing, and test coverage. Follow-up fixes addressed submit-time over-rejection, mixed-size pending promotion, fast detached task completion, model capacity readiness, capacity rejection accounting, backend-reported load saturation, and provider-wide safety headroom.


View in Codesmith
Need help on this PR? Tag @codesmith with what you need.

  • Let Codesmith autofix CI failures and bot reviews

@vercel

vercel Bot commented May 18, 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 18, 2026 10:46pm
d-inference-console-ui-dev Ready Ready Preview May 18, 2026 10:46pm
d-inference-landing Ready Ready Preview May 18, 2026 10:46pm

Request Review

Comment on lines +363 to +365
p.mu.Lock()
defer p.mu.Unlock()
return p.maxConcurrencyForModelLocked(model)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@claude is this a block or non-blocking read mutex?

@claude claude Bot May 18, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude finished @ethenotethan's task in 38s —— View job


Mutex analysis for registry.go:365

  • Read the file and identify the mutex type

It's a blocking exclusive lock — not a read mutex.

At line 363–364:

p.mu.Lock()
defer p.mu.Unlock()

p.mu is declared as sync.Mutex (line 209), not sync.RWMutex. A plain sync.Mutex only has Lock()/Unlock() — there's no concept of a read lock here. The call blocks until no other goroutine holds the lock, then takes exclusive ownership.

Potential improvement: Since MaxConcurrencyForModel is read-only (it doesn't mutate any fields), this could benefit from using sync.RWMutex with RLock()/RUnlock(), which would allow multiple concurrent readers without blocking each other. Under high routing load, many goroutines may call this simultaneously to check per-model headroom, so the exclusive lock is a potential bottleneck. Fix this →

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.

It’s an exclusive sync.Mutex, matching the existing Provider locking pattern. The critical section is tiny and protects concurrent reads of BackendCapacity / pending request state while heartbeats and routing paths mutate them. We could move Provider.mu to sync.RWMutex later if profiling shows contention, but a plain mutex is the safer/simple production-grade default here.

@Gajesh2007

Copy link
Copy Markdown
Member Author

@codex are there any logical flaws in this or something that might break the system completely or not perform what is being requested?

@hankbobtheresearchoor hankbobtheresearchoor left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review Summary

This is a well-structured PR. The core idea — letting the Swift provider dynamically learn per-model throughput limits and report them to the coordinator for per-model routing — is a genuine improvement over the old flat provider-wide cap. The two-sided implementation (Swift adaptive caps + Go per-model gates) is coherent.

Verdict: Approve — no blocking issues. A few suggestions below.

What works well

  • The dual-gate in routing: per-slot cap AND provider-wide safety cap. Protects against both model-level saturation and provider-level overload.
  • The completedBeforeTaskRegistration race fix in ProviderLoop — handles the edge case correctly without adding complexity.
  • The clamp on MaxConcurrency (0–24) in the coordinator prevents malicious heartbeat values.
  • Good test coverage: 4 new Go scheduler tests + updated clamp tests + Swift forward/backward compat tests.
  • The EWMA in BatchPerformanceBucket uses alpha=0.25 which gives reasonable reactivity for an inference workload.

Suggestions (see inline comments)

  • 🟡 hasConcurrencyHeadroomForModelLocked name is misleading — it gates on provider-wide cap too
  • 🔵 pendingLoadForModelLocked break after first matching slot
  • 🔵 capacityRefreshTask queries all slots regardless of which changed

— reviewed by Hermes

return load
}

func (p *Provider) hasConcurrencyHeadroomForModelLocked(model string) bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Suggestion: The name implies a model-level-only check, but the function also gates on the provider-wide . This double-gate is deliberate and correct — it prevents a model-level green light from accidentally overloading the provider. Consider adding a brief doc comment explaining the dual purpose: the second term is the provider-wide safety valve, not redundant with the per-slot cap.

return load
}

func (p *Provider) hasConcurrencyHeadroomForModelLocked(model string) bool {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Suggestion: The name hasConcurrencyHeadroomForModelLocked implies a model-level-only check, but the function also gates on the provider-wide pendingCount() < maxConcurrency(). This double-gate is deliberate and correct — it prevents a model-level green light from accidentally overloading the provider. Consider adding a brief doc comment explaining that the second term is the provider-wide safety valve.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

ℹ️ 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".

if backendLoad > load {
load = backendLoad
}
break

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Observation: pendingLoadForModelLocked uses break after matching the first slot for a model. If a provider ever reports duplicate model entries across multiple slots, only the first slot’s backend load would be considered. This is fine for the current single-slot-per-model architecture, but a comment noting the assumption would help future readers.


// MARK: - Capacity Refresh

private func startCapacityRefreshMonitor() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Observation: capacityRefreshTask calls updateAggregateCapacity() at half the heartbeat interval, which queries all model slots’ schedulers for capacity. For a provider with many loaded models, most slots haven’t changed state between refreshes. Consider passing the affected model ID and only refreshing that slot — or keep the full refresh since it’s cheap (just reading actor properties) and simpler.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

iiuc this is adding a self reporting mechanism to the provider where the provider self-determines its concurrency limits based on constant profiling of token throughput wrt decode rates, GPU availability, memory bandwidth, etc. ran some q&a using agents to understand how variability in prompt sizes could impact the self reporting which is claimed to be handled. also looked at the variables we're profiling and they seem correct for profiling in-time token throughput capabilities.

@hankbobtheresearchoor approved after reviewing. I pre-embedded him with repo context and an llm-wiki that's enriched with theoretical context.

have open questions about how this handles all different token generation architectures (e.g, spec-decoding with MTP drafters vs single target model next token prediction) and race conditions but will leave those for another day. otherwise approving on intuition, a few hours of layman analysis, and vibes.

iiuc there is some synchronization risk since the heartbeats are done on 5 second interval but rabbit hole for another day

Comment on lines +887 to +888
if s.MaxConcurrency < 0 {
s.MaxConcurrency = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

think it'd be easiest to set MaxConcurrency a non-negative variable to avoid <0 expressions ever being possible

Comment on lines +820 to +827
maxDecodeTPS = 500.0
maxPrefillTPS = 5000.0
maxMemoryBandwidthGBs = 2000.0
maxMemoryGB = 1024
maxMemoryGBFloat = 1024.0
maxReportedMaxConcurrency = 24
maxTokensPotential = 1_000_000
maxTokenBudgetCap int64 = 10_000_000_000 // 10 billion — generous safety valve for total token budget capacity

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

One thing worth noting: if we ever need to change these values, it would require having to upgrade the provider binary. Meaning that these expressions are tightly coupled with a particular provider release. If that's undesired, we could parameterize these via the coordinator admin and update them unilaterally.

@github-actions

github-actions Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Benchmark Results

Runner: macos-15 (M1 Virtual) | Date: 2026-05-18 22:53 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 9.008s
Throughput 0.4 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 3.807s 3.807s 3.807s 3.807s
parse 4 91µs 169µs 177µs 177µs
reserve 4 9ms 10ms 11ms 11ms
route 4 290µs 297µs 404µs 404µs
encrypt 4 149µs 153µs 160µs 160µs
dispatch 4 29µs 39µs 39µs 39µs
coordinator_to_provider 4 3.783s 3.784s 3.786s 3.786s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=91.25µs (threshold=1ms)
parse:p95<=5ms PASS p95=177µs (threshold=5ms)
reserve:mean<=50ms PASS mean=9.096ms (threshold=50ms)
reserve:p95<=200ms PASS p95=10.914ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=148.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=160µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=28.75µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=39µ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 5.002s
Throughput 0.8 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 4.998s 4.998s 5.001s 5.001s
parse 4 73µs 58µs 197µs 197µs
reserve 4 40ms 48ms 64ms 64ms
route 4 1ms 1ms 2ms 2ms
encrypt 4 179µs 169µs 239µs 239µs
dispatch 4 77µs 87µs 93µs 93µs
coordinator_to_provider 4 3.82s 3.828s 3.845s 3.845s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=72.5µs (threshold=1ms)
parse:p95<=5ms PASS p95=197µs (threshold=5ms)
reserve:mean<=50ms PASS mean=39.868ms (threshold=50ms)
reserve:p95<=200ms PASS p95=63.942ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=178.75µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=239µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=76.5µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=93µ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 39
Errors 11
Total Duration 52.116s
Throughput 0.7 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 39 4.686s 16ms 27.756s 29.874s
parse 38 0s 0s 0s 13ms
reserve 38 6ms 2ms 27ms 27ms
route 38 398ms 1ms 5.027s 10.049s
encrypt 39 0s 0s 0s 1ms
dispatch 39 64µs 47µs 144µs 339µs
coordinator_to_provider 39 4.217s 5ms 27.711s 29.81s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=397.605µs (threshold=1ms)
parse:p95<=5ms PASS p95=211µs (threshold=5ms)
reserve:mean<=50ms PASS mean=6.314894ms (threshold=50ms)
reserve:p95<=200ms PASS p95=26.97ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=226.897µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=497µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=64.076µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=144µ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 7.871s
Throughput 1.5 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 12 4.662s 4.635s 4.759s 4.759s
parse 12 43µs 30µs 101µs 101µs
reserve 12 34ms 35ms 49ms 49ms
route 12 5ms 4ms 13ms 13ms
encrypt 12 254µs 218µs 533µs 533µs
dispatch 12 66µs 45µs 171µs 171µs
coordinator_to_provider 12 4.597s 4.584s 4.713s 4.713s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=42.5µs (threshold=1ms)
parse:p95<=5ms PASS p95=101µs (threshold=5ms)
reserve:mean<=50ms PASS mean=33.5005ms (threshold=50ms)
reserve:p95<=200ms PASS p95=48.724ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=253.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=533µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=66.083µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=171µ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 5.44s
Throughput 0.7 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 4.288s 4.288s 4.289s 4.289s
parse 4 45µs 32µs 111µs 111µs
reserve 4 10ms 10ms 11ms 11ms
route 4 3ms 4ms 4ms 4ms
encrypt 4 153µs 169µs 169µs 169µs
dispatch 4 28µs 33µs 40µs 40µs
coordinator_to_provider 4 4.26s 4.26s 4.264s 4.264s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=45µs (threshold=1ms)
parse:p95<=5ms PASS p95=111µs (threshold=5ms)
reserve:mean<=50ms PASS mean=10.14675ms (threshold=50ms)
reserve:p95<=200ms PASS p95=10.558ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=153µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=169µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=27.75µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=40µ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 6
Errors 54
Total Duration 7.26s
Throughput 0.8 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 6 4.433s 5.305s 5.366s 5.366s
parse 6 21µs 28µs 33µs 33µs
reserve 6 13ms 12ms 18ms 18ms
route 6 1.683s 2ms 5.048s 5.048s
encrypt 6 168µs 137µs 310µs 310µs
dispatch 6 65µs 41µs 174µs 174µs
coordinator_to_provider 6 2.722s 5.175s 5.303s 5.303s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=21µs (threshold=1ms)
parse:p95<=5ms PASS p95=33µs (threshold=5ms)
reserve:mean<=50ms PASS mean=12.653ms (threshold=50ms)
reserve:p95<=200ms PASS p95=18.203ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=168.333µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=310µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=64.833µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=174µ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 4.099s
Throughput 1.0 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 4 3.24s 3.24s 3.24s 3.24s
parse 4 31µs 36µs 67µs 67µs
reserve 4 8ms 8ms 9ms 9ms
route 4 2ms 2ms 2ms 2ms
encrypt 4 137µs 138µs 157µs 157µs
dispatch 4 25µs 31µs 32µs 32µs
coordinator_to_provider 4 3.224s 3.224s 3.226s 3.226s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=31.25µs (threshold=1ms)
parse:p95<=5ms PASS p95=67µs (threshold=5ms)
reserve:mean<=50ms PASS mean=8.0265ms (threshold=50ms)
reserve:p95<=200ms PASS p95=8.614ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=136.5µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=157µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=25µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=32µ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 9.603s
Throughput 3.1 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 30 1.574s 36ms 4.692s 4.692s
parse 30 40µs 34µs 91µs 162µs
reserve 30 7ms 6ms 19ms 23ms
route 30 2ms 1ms 6ms 8ms
encrypt 30 215µs 146µs 575µs 604µs
dispatch 30 49µs 41µs 111µs 131µs
coordinator_to_provider 30 1.558s 26ms 4.661s 4.676s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=39.833µs (threshold=1ms)
parse:p95<=5ms PASS p95=91µs (threshold=5ms)
reserve:mean<=50ms PASS mean=7.423733ms (threshold=50ms)
reserve:p95<=200ms PASS p95=19.381ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=215.3µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=575µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=49.066µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=111µ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 25
Errors 5
Total Duration 15.379s
Throughput 1.6 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 25 2.844s 26ms 9.607s 9.869s
parse 25 36µs 23µs 54µs 295µs
reserve 25 4ms 2ms 12ms 23ms
route 25 1ms 0s 2ms 9ms
encrypt 25 161µs 142µs 328µs 395µs
dispatch 25 42µs 32µs 121µs 123µs
coordinator_to_provider 25 2.835s 12ms 9.593s 9.854s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=35.8µs (threshold=1ms)
parse:p95<=5ms PASS p95=54µs (threshold=5ms)
reserve:mean<=50ms PASS mean=4.04732ms (threshold=50ms)
reserve:p95<=200ms PASS p95=12.008ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=161.28µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=328µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=42.16µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=121µ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 8.057s
Throughput 1.5 req/s

Latency Decomposition

Segment Count Mean P50 P95 Max
total_e2e 12 5.308s 5.296s 5.498s 5.498s
parse 12 134µs 118µs 222µs 222µs
reserve 12 19ms 20ms 21ms 21ms
route 12 28ms 28ms 31ms 31ms
encrypt 12 197µs 181µs 271µs 271µs
dispatch 12 79µs 70µs 171µs 171µs
coordinator_to_provider 12 5.211s 5.194s 5.4s 5.4s

Assertion Report: PASS

Assertion Result Detail
parse:mean<=1ms PASS mean=133.583µs (threshold=1ms)
parse:p95<=5ms PASS p95=222µs (threshold=5ms)
reserve:mean<=50ms PASS mean=19.351583ms (threshold=50ms)
reserve:p95<=200ms PASS p95=20.557ms (threshold=200ms)
encrypt:mean<=5ms PASS mean=196.666µs (threshold=5ms)
encrypt:p95<=50ms PASS p95=271µs (threshold=50ms)
dispatch:mean<=5ms PASS mean=78.833µs (threshold=5ms)
dispatch:p95<=50ms PASS p95=171µs (threshold=50ms)

@Gajesh2007
Gajesh2007 merged commit fc803d2 into worktree-swift-multi-model May 18, 2026
15 checks passed
Gajesh2007 added a commit that referenced this pull request May 23, 2026
* feat(provider-swift): multi-model concurrent serving

Replace single-model-at-a-time architecture with per-model inference
slots. Each loaded model gets its own BatchScheduler and worker task,
matching the Rust provider's multi-model behavior. Models load on-demand
and stay warm in memory for fast coordinator routing.

- Per-model idle timeout with independent eviction
- LRU eviction loop when memory pressure requires freeing GPU memory
- Continuation-based concurrent load guard prevents duplicate loads
- Aggregate capacity reporting across all loaded model slots
- StandaloneServer lazy-loads models on first request

* fix: revalidate in-flight state before each eviction/idle unload

Both evictUntilAvailable and tickIdleMonitor snapshot requestToModel
once then await unloadModel in a loop. Since the actor is reentrant
across await, new requests can arrive between iterations making the
snapshot stale. Re-check in-flight state before each unload to avoid
evicting models that just became active.

* fix: address PR review — memory estimation, capacity sync, preload lifecycle

- Apply 0.7x safety factor and subtract MLX cache from available memory
  estimate to avoid OOM from overestimating GPU headroom
- Call updateAggregateCapacity() after model load so heartbeats
  immediately reflect the new slot (symmetric with unload path)
- Track preload Tasks and cancel them on shutdown so a mid-flight
  preload cannot insert into modelSlots after the cleanup sweep

* fix: address threat model review findings

- SEC-016: Make encryption failure fail-closed. On encrypt error, send
  inference_error instead of falling back to plaintext in the data field.
- Add max model slots cap (bounded by advertised model count) to prevent
  coordinator-driven OOM from unbounded load_model messages.
- Serialize model loads through a global gate so concurrent loads for
  different models don't interleave eviction decisions and overcommit
  unified GPU memory.

* fix: budget 3x model weight size for 128k context KV cache

KV cache at 128k context with GQA is roughly equal to weight size per
request. With 4 concurrent requests under continuous batching, worst
case KV is ~4x weights. Budget 3x as practical middle ground since
not all requests hit 128k simultaneously.

* fix: address remaining PR review comments

- Mark request in-flight before await suspension so eviction sees the
  model as active (prevents evicting a model mid-request)
- Re-check slot limit after load gate wait (prevents exceeding max slots
  when concurrent loads both pass the initial check)
- Return 5xx for runtime model load failures in StandaloneServer, 404
  only for model-not-found
- Extract scheduler constants (maxConcurrent, pendingTimeout,
  defaultMaxTokens) to named statics instead of magic numbers

* fix: fail request cleanly on insufficient memory, bound standalone model cache

- evictUntilAvailable now throws InferenceError.modelLoadFailed when no
  idle models can be evicted and memory target cannot be met, preventing
  OOM crashes under live traffic.
- StandaloneServer now caps warm-model cache at 3 entries with LRU
  eviction, preventing unbounded memory growth in --local mode.

* fix: serialize standalone loads, abort on encryption failure, fix preload race and test assertion

- StandaloneServer: add global load gate (isLoadingAny + loadGateWaiters)
  so only one model loads at a time, preventing interleaved OOM.
- ProviderLoop: emitSSE now returns Bool; callers abort the inference task
  immediately on encryption failure instead of continuing to generate.
- ProviderLoop: preload tasks use UUID ownership tokens so deferred
  cleanup cannot remove a newer task's entry. Old preloads are cancelled
  before overwriting.
- StandaloneServerTests: fix assertion to match actual error message
  ('not found locally' not 'not available').

* fix: skip LRU eviction for active schedulers, honor cancellation at load gate

- StandaloneServer: LRU eviction now queries scheduler.capacity() and
  skips models with activeRequests > 0 or pendingRequests > 0, preventing
  truncated responses from mid-stream eviction.
- ProviderLoop: added Task.checkCancellation() after resuming from the
  load gate, so cancelled preload tasks (e.g. during shutdown) exit
  instead of proceeding to load.

* feat: add adaptive provider batching capacity (#181)

* feat: add adaptive provider batching capacity

* test: cover adaptive batching routing

* test: add adaptive capacity integration coverage

* test: link e2e providers to payout accounts

* fix: return default provider auth token path

* fix: record chat routing timing before encryption

* fix: address multi-model concurrency review

* fix: harden multi-model edge cases

* fix: clear cancelled requests from reported capacity

* test: cover live multi-model mlx serving

* test: cover live load-model coalescing

* fix: clean up standalone disconnects

* fix: harden swift multi-model races

* fix: track standalone eviction until unload

* fix: honor standalone model slot config

This branch was successfully deployed

3 active deployments
Preview – d-inference-console-ui-dev — b6c0397a Deployed May 18, 2026 by vercel[bot]
Preview – d-inference — b6c0397a Deployed May 18, 2026 by vercel[bot]
Preview – d-inference-landing — b6c0397a Deployed May 18, 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.

3 participants