Repository navigation
feat: add adaptive provider batching capacity - #181
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
| p.mu.Lock() | ||
| defer p.mu.Unlock() | ||
| return p.maxConcurrencyForModelLocked(model) |
There was a problem hiding this comment.
@claude is this a block or non-blocking read mutex?
There was a problem hiding this comment.
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 →
There was a problem hiding this comment.
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.
|
@codex are there any logical flaws in this or something that might break the system completely or not perform what is being requested? |
hankbobtheresearchoor
left a comment
There was a problem hiding this comment.
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
completedBeforeTaskRegistrationrace fix inProviderLoop— 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
BatchPerformanceBucketusesalpha=0.25which gives reasonable reactivity for an inference workload.
Suggestions (see inline comments)
- 🟡
hasConcurrencyHeadroomForModelLockedname is misleading — it gates on provider-wide cap too - 🔵
pendingLoadForModelLockedbreakafter first matching slot - 🔵
capacityRefreshTaskqueries all slots regardless of which changed
— reviewed by Hermes
| return load | ||
| } | ||
|
|
||
| func (p *Provider) hasConcurrencyHeadroomForModelLocked(model string) bool { |
There was a problem hiding this comment.
🟡 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 { |
There was a problem hiding this comment.
🟡 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.
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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 |
There was a problem hiding this comment.
🔵 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() { |
There was a problem hiding this comment.
🔵 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
left a comment
There was a problem hiding this comment.
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
| if s.MaxConcurrency < 0 { | ||
| s.MaxConcurrency = 0 |
There was a problem hiding this comment.
think it'd be easiest to set MaxConcurrency a non-negative variable to avoid <0 expressions ever being possible
| 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 |
There was a problem hiding this comment.
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.
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: PASS
|
* 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
Summary
This PR adds provider-reported adaptive batching capacity on top of the multi-model Swift provider branch.
BatchSchedulerkeeps a hard engine slot ceiling and learns an effective per-model concurrency cap from observed per-batch decode TPS.max_concurrency, active/queued token budgets, observed TPS, and KV bytes per token.max_concurrencyfor model-aware headroom checks while preserving legacy fallback for omitted/zero values.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 .-> CAfter
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 --> BTesting
cd coordinator && go test ./...git diff --checkSwift verification is blocked in this worktree because local path dependencies are absent:
libs/mlx-swift/Package.swiftlibs/mlx-swift-lm/Package.swiftReview 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.
Need help on this PR? Tag
@codesmithwith what you need.