Repository navigation
feat: multi-model swap — download multiple models, serve one at a time - #225
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: FAIL
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: FAIL
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
Providers can now select and download multiple models even when their combined size exceeds available RAM. Only one model is warm (loaded in GPU memory) at a time; the coordinator manages demand-driven model swaps via the existing load_model protocol. Provider (Swift): - TUI picker: removed simultaneous memory budget constraint; each model only needs to individually fit. Shows 'one model active at a time (swap on demand)' when total exceeds RAM. - Fixed pre-existing download resume bug: range-resumption (HTTP 206) now appends to the partial file instead of replacing it. Coordinator (Go): - Cold-start routing: freeMemoryAdmits now admits idle providers that have the model on disk but not loaded, accounting for LRU eviction. - Raised cold-start penalty from 2.5s to 30s (realistic for model swap times of 15–60s) so warm providers are strongly preferred. - Proactive model swap: TriggerModelSwaps sends load_model to idle cold providers when queued requests have no warm provider. Includes deduplication (2-min cooldown per provider+model pair), one-provider- per-pass selection, and full routing safety gates (trust, runtime, privacy, challenge freshness, catalog). - SendLoadModel, ClearPendingModelLoad, QueuedModels helpers.
007fce7 to
dade28d
Compare
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: FAIL
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: FAIL
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 007fce7f6b
ℹ️ 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 p.Status == StatusOffline || p.Status == StatusUntrusted { | ||
| return false | ||
| } |
There was a problem hiding this comment.
Apply routing gates before treating a provider as warm
TriggerModelSwaps skips swap planning whenever hasWarmProviderLocked finds any warm copy, but this helper only excludes offline/untrusted providers and does not apply the same routability checks used elsewhere (runtime verified, challenge freshness, privacy capability, min trust). In a case where the only warm provider has stale attestation (or otherwise fails scheduler gates), queued requests for that model will never trigger load_model on eligible cold providers, so requests can sit in queue until timeout even though a routable provider exists.
Useful? React with 👍 / 👎.
| for _, warmModel := range p.WarmModels { | ||
| if warmModel == model { | ||
| return true | ||
| } |
There was a problem hiding this comment.
Stop using stale WarmModels to suppress model swaps
The new warm check falls back to p.WarmModels, but this list is not reliably cleared when a provider has no warm models (heartbeats can omit warm_models when empty), so stale entries can persist after unload. With that stale state, hasWarmProviderLocked returns true and TriggerModelSwaps skips sending load_model, leaving queued requests for that model stuck until timeout despite no provider actually running it.
Useful? React with 👍 / 👎.
| if !r.providerServesCatalogModelLocked(p, model) { | ||
| return 0, false | ||
| } | ||
| return p.pendingCount(), true |
There was a problem hiding this comment.
Restrict proactive model loads to idle providers
The swap planner can pick providers that still have in-flight work because modelLoadCandidatePendingLocked returns pendingCount as eligible regardless of whether it is zero, and bestModelLoadProviderLocked accepts that candidate. In a common single-slot case, sending load_model while another model is actively serving causes the provider to fail the preload (all model slots are active), then the coordinator clears pending and retries on subsequent heartbeats, creating repeated failed swaps and delaying useful warm-up.
Useful? React with 👍 / 👎.
| if http.statusCode == 206 { | ||
| try Self.appendDownloadedRange(tempFile, to: partial, label: label) | ||
| } else { |
There was a problem hiding this comment.
Validate Content-Range before appending resumed bytes
On HTTP 206 responses, the downloader always appends the returned temp file to the existing .part without checking that the server actually started at the requested offset. If an origin/proxy returns a mismatched range, this appends duplicate or shifted bytes; for legacy CDN downloads that pass expectedSHA256: nil, that corruption is not detected before promotion to the final model file.
Useful? React with 👍 / 👎.
…idle-only swaps, Content-Range validation - hasWarmProviderLocked now applies full routing gates (trust, runtime, privacy, challenge freshness) so stale-attested providers don't suppress model swaps - Heartbeat always overwrites WarmModels (including empty) to clear stale entries after model unload - bestModelLoadProviderLocked only selects idle providers (pendingCount == 0) to avoid failed load_model on busy single-slot providers - Download resume validates Content-Range start offset before appending; falls back to full re-download on mismatch
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: FAIL
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: FAIL
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 33c25dab4a
ℹ️ 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".
|
|
||
| slotStatePenaltyRunning = 0.0 | ||
| slotStatePenaltyUnknown = 2_500.0 | ||
| slotStatePenaltyUnknown = 30_000.0 |
There was a problem hiding this comment.
Treat idle warm slots as running
When a model is loaded but has no active requests, the Swift provider reports the slot state as idle (BatchScheduler+Telemetry.backendCapacity uses activeRequests > 0 ? "running" : "idle"). Since slotStatePenalty still falls through unknown states to slotStatePenaltyUnknown, raising this value to 30s now charges already-resident idle models the full cold-swap penalty. In a mixed fleet this can make the scheduler prefer an actually cold provider over a warm idle one, causing unnecessary model loads and much worse TTFT.
Useful? React with 👍 / 👎.
| if let rangeStart = Self.parseContentRangeStart(contentRange), | ||
| rangeStart != expectedStart { | ||
| // Range mismatch: discard partial and re-download fully. | ||
| try? fm.removeItem(at: partial) | ||
| try fm.moveItem(at: tempFile, to: partial) |
There was a problem hiding this comment.
Discard mismatched 206 ranges instead of promoting them
Fresh evidence: the new mismatch branch detects a Content-Range start that differs from the requested resume offset, but then removes the old .part and promotes the mismatched range body as the new partial, which is immediately moved to the final destination below. If an origin/proxy returns a shifted 206 response and expectedSHA256 is nil (the legacy download path), this can install a truncated or shifted model file instead of retrying a full download.
Useful? React with 👍 / 👎.
| if _, pending := r.pendingModelLoads[modelLoadKey(id, model)]; pending { | ||
| continue |
There was a problem hiding this comment.
Block providers with any pending model load
When multiple models are queued for the same idle machine, this only suppresses a duplicate (provider, same model) load; on the next heartbeat, while the first load_model is still pending and no inference is in pendingReqs, the same provider can be selected for a different model. The Swift provider serializes those loads, so the second preload can immediately evict or supersede the first before queued requests for the first model are drained, producing repeated swap oscillation or queue timeouts on single-provider/low-memory setups.
Useful? React with 👍 / 👎.
| } else { | ||
| // No Content-Range header: cannot verify, append optimistically. | ||
| try Self.appendDownloadedRange(tempFile, to: partial, label: label) |
There was a problem hiding this comment.
Reject unverifiable 206 resume responses
Fresh evidence: although the code now detects some mismatched Content-Range starts, it still appends the resumed bytes when a 206 response omits Content-Range or has a malformed value that parseContentRangeStart returns nil for. In that proxy/origin failure mode the coordinator cannot prove the returned bytes start at existingBytes, and for downloads without expectedSHA256 the corrupted .part is promoted to the final model file.
Useful? React with 👍 / 👎.
| // AND passes the same routing safety gates used by the scheduler. A provider | ||
| // with stale attestation or failed privacy checks should not suppress swap | ||
| // planning. Caller must hold p.mu. Caller must hold r.mu (read or write). | ||
| func (r *Registry) providerHasWarmModelLocked(p *Provider, model string, now time.Time) bool { |
There was a problem hiding this comment.
Apply the catalog gate before suppressing swaps
Fresh evidence: the warm-provider helper now applies the trust/runtime/privacy/freshness gates, but it still never calls providerServesCatalogModelLocked. If a provider has the requested ID warm but is no longer catalog-routable for that ID (for example a weight-hash mismatch after a catalog update), it can make TriggerModelSwaps skip loading the model on an eligible cold provider, while the normal scheduler will refuse to route to the warm provider.
Useful? React with 👍 / 👎.
…trictness, load oscillation, catalog gate - slotStatePenalty: handle 'idle' state as running (0ms) — provider reports 'idle' for warm-but-no-active-requests models - Content-Range: discard partial on missing/unparseable header instead of appending optimistically; test mock now sends Content-Range - bestModelLoadProviderLocked: skip providers with ANY pending load_model (providerHasPendingLoad) to prevent swap oscillation - providerHasWarmModelLocked: add catalog gate so retired/hash-changed models don't suppress swap planning
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: FAIL
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: FAIL
3-provider-20-users3 providers, 20 users, 60 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
1-provider-scaling1 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 354cd7148a
ℹ️ 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".
| key := modelLoadKey(action.providerID, action.modelID) | ||
| if _, pending := r.pendingModelLoads[key]; pending { | ||
| continue | ||
| } | ||
| r.pendingModelLoads[key] = now | ||
| reserved = append(reserved, action) |
There was a problem hiding this comment.
Reserve model loads per provider
When two provider heartbeat goroutines call TriggerModelSwaps concurrently while different models are queued, both can plan against an empty pendingModelLoads map under the read lock, and this reservation step only rejects the exact (provider, model) key. Fresh evidence beyond the earlier heartbeat-ordering concern is that the write-side reservation still allows the second concurrent plan to reserve the same provider for a different model, so a single idle machine can receive overlapping load_model commands for A and B before either pending entry is visible to planning; the Swift provider serializes/evicts these loads, which can undo the first warm-up and leave queued requests timing out on low-capacity setups.
Useful? React with 👍 / 👎.
| if statusMsg.Status == protocol.LoadModelStatusSucceeded || | ||
| statusMsg.Status == protocol.LoadModelStatusFailed { | ||
| s.registry.ClearPendingModelLoad(providerID, statusMsg.ModelID) |
There was a problem hiding this comment.
Drain queued requests when preloads succeed
When a demand-driven load_model finishes close to the queue timeout, this handler only clears the pending-load marker and then waits for a future heartbeat to report the model as warm before queued requests are drained. In the inspected provider loop, load_model_status: succeeded is sent immediately after ensureModelLoaded, so a request can still time out during the heartbeat gap even though the model was loaded in time; drain or otherwise wake the queue on terminal success for statusMsg.ModelID.
Useful? React with 👍 / 👎.
| for _, model := range queuedModels { | ||
| if r.hasWarmProviderLocked(model, now) { | ||
| continue | ||
| } | ||
|
|
||
| providerID := r.bestModelLoadProviderLocked(model, now, selectedProviders) |
There was a problem hiding this comment.
Plan swaps with request serial constraints
When a queued request has AllowedProviderSerials, this model-only planning can select and warm any provider for the model, but the queue drain later calls ReserveProviderEx with the original request and will still reject providers outside the allowed serial set. If the wrong provider becomes warm first, hasWarmProviderLocked suppresses further swaps for that model, so a serial-pinned request can time out even though an allowed cold provider could have loaded the model.
Useful? React with 👍 / 👎.
- reservePendingModelLoads: check providerHasPendingLoad (not just per-key) to prevent concurrent heartbeat goroutines from reserving the same idle provider for different models - load_model_status handler: drain queued requests immediately on success instead of waiting for next heartbeat (up to 5s)
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
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: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: dd7f43d780
ℹ️ 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 !found { | ||
| p.BackendCapacity.Slots = append(p.BackendCapacity.Slots, protocol.BackendSlotCapacity{ | ||
| Model: modelID, | ||
| State: "idle", | ||
| }) |
There was a problem hiding this comment.
Clear evicted slots when marking the new model warm
When a load_model_status:succeeded arrives after a preload that evicted the previous idle model, this only appends a synthetic slot for the new model and leaves the old BackendCapacity.Slots entries in place until the next heartbeat. In that pre-heartbeat window the scheduler and hasWarmProviderLocked still treat the evicted model as warm, so requests for the old model can be routed/swap-suppressed based on stale capacity state instead of warming a real provider for that model.
Useful? React with 👍 / 👎.
| candidates, capacityRejections := r.QuickCapacityCheck(modelID, 500, defaultRequestedMaxTokens) | ||
| if candidates > 0 || capacityRejections > 0 { | ||
| return |
There was a problem hiding this comment.
Ignore failed preload providers when deciding to fail the queue
When the only provider reports load_model_status:failed for a model (for example because its local weights are corrupt), this check still calls QuickCapacityCheck, which only sees that the same provider advertises the model and has theoretical capacity. Because the failed path deliberately keeps the pending-load entry as a cooldown, the queue is not rejected and no other provider can be selected, so consumers wait for the 120s timeout and the coordinator repeats the failed preload after the TTL instead of failing fast when there is no usable alternative.
Useful? React with 👍 / 👎.
When a swap evicts model A and loads model B, stale 'running'/'idle' slots for A remained in BackendCapacity until the next heartbeat, causing the scheduler to treat A as still warm. Now drops all warm slots except the newly loaded model.
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: da353a853c
ℹ️ 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 slot.State == "running" || slot.State == "idle" { | ||
| continue // evicted — drop stale warm slot |
There was a problem hiding this comment.
Preserve warm slots when no eviction occurred
When a preload succeeds while the provider still has spare model slots, ensureModelLoaded does not evict existing models (it only evicts once modelSlots.count >= maxModelSlots), but this synthetic capacity update drops every other running/idle slot anyway. Until the next heartbeat, BackendCapacity is authoritative, so still-loaded models disappear from scheduler/warm-provider checks and can be treated as cold, causing unnecessary swaps or routing away from a provider that is already warm.
Useful? React with 👍 / 👎.
Provider may have multiple model slots loaded simultaneously (maxModelSlots=3). Only add/update the new model's slot; leave existing slots untouched. Next heartbeat provides authoritative state.
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
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: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
Documents the overlapping state views (BackendCapacity vs WarmModels vs CurrentModel vs pendingModelLoads), their precedence rules, and a 5-point checklist for mutating provider state. Learned from 10 fix iterations on the multi-model swap feature.
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: FAIL
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: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
Benchmark ResultsRunner: 1-provider-streaming1 providers, 1 users, 30 requests, concurrency=5, streaming=true
Latency Decomposition
Assertion Report: FAIL
1-provider-non-streaming1 providers, 1 users, 20 requests, concurrency=5, streaming=false
Latency Decomposition
Assertion Report: FAIL
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: FAIL
1-provider-queue-saturation1 providers, 10 users, 40 requests, concurrency=15, streaming=true
Latency Decomposition
Assertion Report: FAIL
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: FAIL
3-provider-scaling3 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
5-provider-scaling5 providers, 5 users, 30 requests, concurrency=10, streaming=true
Latency Decomposition
Assertion Report: PASS
3-provider-heavy-100conc-10kb3 providers, 20 users, 100 requests, concurrency=100, streaming=true
Latency Decomposition
Assertion Report: FAIL
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d3955b8404
ℹ️ 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".
| } | ||
| } | ||
| snap.modelLoaded = snap.slotState == "running" | ||
| snap.availableOnDisk = !snap.modelLoaded |
There was a problem hiding this comment.
Treat idle slots as loaded before cold admission
When a Swift provider reports the requested model in an idle slot, this new availableOnDisk flag still becomes true because modelLoaded only recognizes running. In the no-token-budget/backward-compatible path, freeMemoryAdmits then takes the cold-swap branch for an already-loaded idle model and ignores gpuMemoryActiveGB; with multiple idle models filling memory, a request can be routed even when there is not enough free memory for its KV cache, leading to provider-side OOM/failure. Mark idle as loaded here (as slotStatePenalty now does) so loaded models use the normal free-memory check.
Useful? React with 👍 / 👎.
| // alongside active models. | ||
| if snap.availableOnDisk && !snap.modelLoaded && snap.totalPending == 0 { | ||
| const osReserveGB = 4.0 | ||
| return snap.modelSizeGB+kvCacheGB+osReserveGB <= snap.totalMemoryGB |
There was a problem hiding this comment.
Use the provider's load headroom for cold routes
For an idle provider that only has the model on disk, this new admission path accepts the route when catalog disk size plus KV plus 4 GB fits in total RAM, but the Swift provider's actual ensureModelLoaded gate requires modelInfo.estimatedMemoryGb * 3.0 headroom before loading. In the common case where a large model satisfies this coordinator check but fails the provider's stricter load gate, direct cold requests are routed to a provider that immediately errors instead of staying queued/trying another capable machine; the cold-route check needs to mirror the provider load headroom (or otherwise exclude models the provider will reject).
Useful? React with 👍 / 👎.
| case protocol.LoadModelStatusFailed: | ||
| // Keep the pending entry (TTL cooldown suppresses retry storms). | ||
| // If no other provider can serve this model, reject queued | ||
| // requests immediately rather than making them wait 120s. | ||
| s.registry.RejectUnservableQueuedRequests(statusMsg.ModelID) |
There was a problem hiding this comment.
Honor preload cooldown during direct routing
When a preload fails, this branch intentionally leaves the pending-load entry in place as a cooldown, but that state is only consulted by TriggerModelSwaps; ReserveProviderEx/QuickCapacityCheck still see the same idle provider as routable. A new direct request for the same cold model during the TTL can therefore be sent right back to the provider that just failed to load it, producing an immediate provider-side 500 instead of suppressing that provider until the cooldown expires or another provider is chosen.
Useful? React with 👍 / 👎.
Layr-Labs#225) * feat: multi-model swap — download multiple models, serve one at a time Providers can now select and download multiple models even when their combined size exceeds available RAM. Only one model is warm (loaded in GPU memory) at a time; the coordinator manages demand-driven model swaps via the existing load_model protocol. Provider (Swift): - TUI picker: removed simultaneous memory budget constraint; each model only needs to individually fit. Shows 'one model active at a time (swap on demand)' when total exceeds RAM. - Fixed pre-existing download resume bug: range-resumption (HTTP 206) now appends to the partial file instead of replacing it. Coordinator (Go): - Cold-start routing: freeMemoryAdmits now admits idle providers that have the model on disk but not loaded, accounting for LRU eviction. - Raised cold-start penalty from 2.5s to 30s (realistic for model swap times of 15–60s) so warm providers are strongly preferred. - Proactive model swap: TriggerModelSwaps sends load_model to idle cold providers when queued requests have no warm provider. Includes deduplication (2-min cooldown per provider+model pair), one-provider- per-pass selection, and full routing safety gates (trust, runtime, privacy, challenge freshness, catalog). - SendLoadModel, ClearPendingModelLoad, QueuedModels helpers. * chore: gofmt billing_handlers.go and pricing_test.go * fix: address review — routing gates on warm check, stale WarmModels, idle-only swaps, Content-Range validation - hasWarmProviderLocked now applies full routing gates (trust, runtime, privacy, challenge freshness) so stale-attested providers don't suppress model swaps - Heartbeat always overwrites WarmModels (including empty) to clear stale entries after model unload - bestModelLoadProviderLocked only selects idle providers (pendingCount == 0) to avoid failed load_model on busy single-slot providers - Download resume validates Content-Range start offset before appending; falls back to full re-download on mismatch * fix: address second review round — idle slot penalty, Content-Range strictness, load oscillation, catalog gate - slotStatePenalty: handle 'idle' state as running (0ms) — provider reports 'idle' for warm-but-no-active-requests models - Content-Range: discard partial on missing/unparseable header instead of appending optimistically; test mock now sends Content-Range - bestModelLoadProviderLocked: skip providers with ANY pending load_model (providerHasPendingLoad) to prevent swap oscillation - providerHasWarmModelLocked: add catalog gate so retired/hash-changed models don't suppress swap planning * fix: per-provider reservation race + drain queue on load success - reservePendingModelLoads: check providerHasPendingLoad (not just per-key) to prevent concurrent heartbeat goroutines from reserving the same idle provider for different models - load_model_status handler: drain queued requests immediately on success instead of waiting for next heartbeat (up to 5s) * fix: adversarial review — BackendCapacity authority, load failure backoff, disconnect cleanup, TUI preselect - providerHasWarmModelLocked: BackendCapacity is authoritative when present; only 'running'/'idle' slots count as warm. Prevents crashed slots from suppressing needed model swaps via stale WarmModels. - load_model_status: only clear pendingModelLoads on success. Failures retain the 2-min cooldown to prevent retry storms against providers that consistently fail (deleted files, OOM). - Disconnect: clear pendingModelLoads entries for the disconnected provider to prevent stale entries from blocking future swaps. - TUI preselect: check canFitIndividually before preselecting a downloaded model. * feat: reject queued requests immediately when model is unservable When load_model fails and no other provider can serve the model, queued requests are now rejected immediately with a fast error instead of waiting 120 seconds for the queue timeout. - FailQueuedRequestsForModel: sends nil to all ResponseChs, causing waiters to receive ErrQueueTimeout - RejectUnservableQueuedRequests: checks QuickCapacityCheck after a load failure; if no eligible provider exists, flushes the queue - Wired into load_model_status handler alongside the existing success/drain path * fix: clear stale CurrentModel on nil heartbeat, mark provider warm before queue drain - Heartbeat: clear CurrentModel when active_model is nil/omitted, preventing attestation challenges from comparing against unloaded models - load_model_status:succeeded: call MarkModelWarm before draining so the scheduler sees the provider as warm immediately, not after the next heartbeat (up to 5s delay) * fix: RejectUnservableQueuedRequests must check capacityRejections Only reject queued requests when NO provider serves the model at all. If providers exist but are temporarily at capacity, requests should wait — those providers may finish current work and become available. * fix: MarkModelWarm injects synthetic BackendCapacity slot The scheduler uses BackendCapacity.Slots (not WarmModels) for Swift providers. When load_model_status:succeeded arrives before the next heartbeat, the model had no slot so the scheduler still saw it as cold/unknown. Now injects an 'idle' slot so DrainQueuedRequestsForModel immediately routes to the just-warmed provider. * fix: MarkModelWarm clears stale evicted slots from BackendCapacity When a swap evicts model A and loads model B, stale 'running'/'idle' slots for A remained in BackendCapacity until the next heartbeat, causing the scheduler to treat A as still warm. Now drops all warm slots except the newly loaded model. * fix: MarkModelWarm preserves existing warm slots Provider may have multiple model slots loaded simultaneously (maxModelSlots=3). Only add/update the new model's slot; leave existing slots untouched. Next heartbeat provides authoritative state. * docs: add coordinator state model and mutation checklist to AGENTS.md Documents the overlapping state views (BackendCapacity vs WarmModels vs CurrentModel vs pendingModelLoads), their precedence rules, and a 5-point checklist for mutating provider state. Learned from 10 fix iterations on the multi-model swap feature. * docs: fix WarmModels reader list — include legacy ScoreProvider and /v1/me/providers
* refactor: extract per-package config structs from main.go Each package now owns its Config struct and ReadConfig() function with env var constants scoped to the package that consumes them: - coordinator/config: AppConfig composition + shared helpers - coordinator/store: database URL / memory store selection - coordinator/billing: Stripe, mnemonic, referral, mock mode - coordinator/auth: Privy app ID, verification key, app secret - coordinator/ratelimit: consumer + financial rate limits - coordinator/registry: min trust level - coordinator/mdm: MDM URL + API key - coordinator/api: ServerConfig (port, URLs, CORS, min version) main.go goes from ~40 inline os.Getenv() calls to a single config.ReadAppConfig() call, with all env reads scoped to the package that owns each config domain. Pattern adapted from: https://github.com/Layr-Labs/eigenda-proxy * fix: move Config structs into config.go, add Check methods - billing.Config moved from billing.go to config.go - auth.Config moved from privy.go to config.go - Added Check() to billing, auth, registry, mdm, datadog Configs - Fixed config/app_config.go to use correct function names - Removed duplicate Config from ratelimit/ratelimit.go * refactor: inject config structs through constructors - store.NewPostgres(ctx, cfg store.Config) — replaces connString param - store.NewMemory(cfg store.Config) — replaces adminKey param - mdm.NewClient(cfg mdm.Config, logger) — replaces baseURL/apiKey params - api.NewServer(reg, st, cfg api.ServerConfig, logger) — injects cfg fields Added AdminKey to store.Config and ServerConfig (AdminKey/AdminEmails/ReleaseKey). Updated all 117 NewMemory call sites, 2 NewPostgres callers, 1 mdm.NewClient, 1 api.NewServer in main.go, and ~20 api.NewServer test callers via testServer helper. All tests pass (go test -race ./...). * fix: update e2e testbed for new constructor signatures - store/config.go: pass AdminKey in ReadConfig - e2e/testbed/coordinator.go: use store.Config for NewMemory/NewPostgres - e2e/testbed/suite.go: pass api.ServerConfig to NewServer * fix: use shared env.EnvPrefix in ratelimit config Create coordinator/env/ package with shared EnvPrefix constant so that ratelimit/config.go can reference it without creating an import cycle (config->ratelimit would conflict with ratelimit->config). config/app_config.go now defines EnvPrefix = env.EnvPrefix as a package-level alias. ratelimit/config.go imports env and uses env.EnvPrefix+"_RATE_LIMIT_RPS" etc. * fix: wire env prefix + deduplicate NewServer wiring Addresses review feedback on PR #187: 1. All per-package configs now use env.EnvPrefix instead of hardcoded "EIGENINFERENCE" strings. Previously only ratelimit/ used it; now store/, billing/, auth/, mdm/, registry/, and api/server_config do too. No import cycles — all packages import coordinator/env. 2. NewServer now applies same trimming as the Set* methods: - strings.TrimRight for baseURL, r2CDNURL, r2SitePackagesCDNURL - strings.TrimSpace for minProviderVersion - strings.ToLower(strings.TrimSpace) for admin emails This fixes an inconsistency where NewServer left URLs untrimmed but the Set* calls in main.go would trim them later. 3. Removed redundant Set* calls from main.go. NewServer already sets all ServerConfig fields, so the conditional SetConsoleURL / SetCORSOrigin / SetBaseURL / SetMinProviderVersion / SetR2CDNURL / SetR2SitePackagesCDNURL / SetReleaseKey / SetAdminKey blocks were duplicate work. * chore: add TODO for admin email storage antipattern (PR feedback) * ratelimit: reuse env helpers instead of local duplicates Move EnvFloat/EnvInt/EnvOr/FirstNonEmpty from coordinator/config to coordinator/env so they're accessible without import cycles. coordinator/config now forwards to env for backward compatibility. ratelimit/config.go now calls env.EnvFloat/env.EnvInt directly instead of defining its own duplicate helpers. Fixes: config→app_config→api→ratelimit import cycle that prevented ratelimit from importing coordinator/config directly. * fix: reuse env.EnvOr/env.FirstNonEmpty instead of local helpers * registry: validate MinTrustLevel is a recognized value in Check() * fix(billing): add MockMode+StripeSecretKey mutual exclusion to Check() * fix: guard threat-model-review for fork PRs where ANTHROPIC_API_KEY unavailable Two-part fix: 1. Workflow: add `if: github.event.pull_request.head.repo.full_name == github.repository` to skip the entire job for fork PRs (secrets not shared with forks). 2. Script: handle missing ANTHROPIC_API_KEY env var gracefully by returning a skip message instead of crashing. * Revert guard block from threat-model-review.py per review feedback * revert: remove out-of-scope workflow guard from config refactor PR * feat(coordinator): use registry max_output_length for default max_tokens bound The coordinator was hardcoding defaultMaxOutputTokens=8192 for all models when the consumer didn't specify max_tokens. Now it looks up the model's max_output_length from the registry (set at registration) and uses that as the bound. Falls back to 8192 for models not in the registry. GPT-OSS 20B and Gemma 4 both support 32K output, so consumers that omit max_tokens now get up to 32K instead of being capped at 8K. The registry lookup piggybacks on the existing GetModelRegistryRecord call used for reasoning_parser injection -- no additional DB query. * fix(provider-swift): exclude sliding attention layers from per-token KV cost Sliding-attention layers have a fixed KV cache bounded by the window size (e.g. 128 tokens for GPT-OSS 20B). Their memory does not grow with sequence length, so counting them in kvBytesPerToken overestimates the per-token cost and underestimates the token budget by up to 2x. GPT-OSS 20B: 12 full + 12 sliding layers. Before: 48 KB/token, budget ~2.1M tokens on 128GB. After: 24 KB/token, budget ~4.2M tokens. Gemma 4 has a similar hybrid layout and benefits equally. * fix: update test files for store.Config and ServerConfig signatures * rebrand: research preview -> public alpha (#220) Rename all instances of 'Research Preview' and 'research project' to 'Public Alpha' across UI, landing page, legal terms, and README. - console-ui: sidebar label, footer disclaimer, login page, provider setup, LLM system prompt - landing: banner tag (now 'Low-cost private inference on idle Macs'), marketing copy (3 sections), terms.html (6 clauses) - docs: terms-of-service.md (6 matching clauses) - README: top-level callout No legal meaning changed -- the existing ToS already listed 'alpha' as a valid label. CSS class names (.research-tag) left unchanged. * feat: add Vercel Web Analytics to console-ui and landing page (#221) * feat: add Vercel Web Analytics to console-ui and landing page Install @vercel/analytics alongside existing Google Analytics on both surfaces. Vercel Analytics is cookieless and collects only anonymized page-view data, so no consent banner is required. console-ui (Next.js): - Added @vercel/analytics dependency - Added <Analytics /> component to root layout (imported from @vercel/analytics/next for automatic route tracking) landing (plain HTML): - Added va queue shim + deferred script tag pointing at /_vercel/insights/script.js Google Analytics remains untouched -- both systems run in parallel. Vercel Analytics tracks by default; GA continues to be consent-gated. Note: Web Analytics must also be enabled in the Vercel project dashboard for data to start flowing. * feat: mirror custom events to Vercel Analytics Add Vercel track() call inside the existing trackEvent() function so all 45 custom event call sites automatically send to both GA and Vercel Analytics with zero call-site changes. Vercel track() fires unconditionally (cookieless, always-on). GA continues to be consent-gated. Vercel track() limits: string values only and max 5 key-value pairs per event, so we convert and cap. * feat: add landing page funnel tracking with Vercel Analytics Add scroll-based section visibility and CTA click tracking to landing/index.html using Vercel Analytics va() events. Section funnel (IntersectionObserver, fires once per section at 30% visibility threshold): hero -> what-you-get -> why-it-costs-less -> privacy-problem -> privacy-architecture -> developer-experience -> pricing -> earn -> footer CTA click tracking: - Hero buttons (Start building, Estimate earnings, Read the Paper) - Card buttons (Open Console, Start Earning) - Paper download links (eigen-block CTAs) - Nav anchor clicks (Why, Privacy, API, Pricing, Earn) - Footer link clicks - Install tab toggle (CLI vs Mac App) All events use the va() queue shim already present in <head>. The existing scroll-reveal animation is preserved and runs alongside. * improve stats model catalog display (#222) * Improve stats model catalog display * Enable analytics by default co-authored with codex * feat: streamline provider onboarding to one post-install command (#223) * Improve stats model catalog display * feat: streamline provider onboarding to one post-install command Reduce the provider onboarding flow from 5+ manual steps to a single command after the curl installer. install.sh: - Remove [5/5] model catalog step (redundant with start's picker) - Make MDM enrollment non-blocking (no more read -p wait) - Replace 5-line 'next steps' with: source ~/.zshrc && darkbloom start - Renumber steps from [1/5]...[5/5] to [1/4]...[4/4] LoginCommand.swift: - Fix stale 'darkbloom serve' -> 'darkbloom start' in success message StartCommand.swift: - Add preflight doctor checks (SIP, debugger, min RAM) before model picker so problems surface before downloading GBs of weights - Add inline login prompt ('Link account? [Y/n]') before model picker so users don't need a separate darkbloom login step - Both are skipped in non-interactive/foreground/--model modes * fix: default 'darkbloom models' to catalog instead of local list A new user running 'darkbloom models' with nothing downloaded saw 'No local MLX models found.' -- unhelpful. Now it shows the full coordinator catalog with download status markers (✓ for downloaded), so they can immediately see what's available. 'darkbloom models list' still works for the local-only view. * feat: show supported vs local-only models in 'darkbloom models' Split the catalog view into two sections: Supported models ✓ Qwen 3.5 [qwen3.5-4b] ~2.5 GB Llama 4 [llama-4-8b] ~4.8 GB Local only (not in current catalog) old-model-v1 3.2 GB These models are no longer served by the network. Remove with: darkbloom models remove <id> Users immediately see what's active vs what's just taking up disk space from old downloads. Nudges cleanup without being aggressive. * feat(console-ui): public models catalog proxy and earn page resilience (#224) Models API route: - Unauthenticated requests now proxy to /v1/models/catalog + /v1/models/capacity instead of the auth-gated /v1/models, so the earn page and other public surfaces can display the full model catalog without an API key. - toModelEntry() normalizes catalog fields (size_gb, min_ram_gb, architecture, capacity stats) into the standard model shape the UI expects. Client (api.ts): - fetchModels() handles three response shapes: data.data (OpenAI list), data.models (catalog), or a raw array. Earn page: - Models without explicit pricing fall back to a default output price instead of being filtered out entirely. Tests: - Add catalog response unwrapping test for fetchModels. - Update earn page tests to mock fetchModels/fetchPricing from @/lib/api. * feat: multi-model swap — download multiple models, serve one at a time (#225) * feat: multi-model swap — download multiple models, serve one at a time Providers can now select and download multiple models even when their combined size exceeds available RAM. Only one model is warm (loaded in GPU memory) at a time; the coordinator manages demand-driven model swaps via the existing load_model protocol. Provider (Swift): - TUI picker: removed simultaneous memory budget constraint; each model only needs to individually fit. Shows 'one model active at a time (swap on demand)' when total exceeds RAM. - Fixed pre-existing download resume bug: range-resumption (HTTP 206) now appends to the partial file instead of replacing it. Coordinator (Go): - Cold-start routing: freeMemoryAdmits now admits idle providers that have the model on disk but not loaded, accounting for LRU eviction. - Raised cold-start penalty from 2.5s to 30s (realistic for model swap times of 15–60s) so warm providers are strongly preferred. - Proactive model swap: TriggerModelSwaps sends load_model to idle cold providers when queued requests have no warm provider. Includes deduplication (2-min cooldown per provider+model pair), one-provider- per-pass selection, and full routing safety gates (trust, runtime, privacy, challenge freshness, catalog). - SendLoadModel, ClearPendingModelLoad, QueuedModels helpers. * chore: gofmt billing_handlers.go and pricing_test.go * fix: address review — routing gates on warm check, stale WarmModels, idle-only swaps, Content-Range validation - hasWarmProviderLocked now applies full routing gates (trust, runtime, privacy, challenge freshness) so stale-attested providers don't suppress model swaps - Heartbeat always overwrites WarmModels (including empty) to clear stale entries after model unload - bestModelLoadProviderLocked only selects idle providers (pendingCount == 0) to avoid failed load_model on busy single-slot providers - Download resume validates Content-Range start offset before appending; falls back to full re-download on mismatch * fix: address second review round — idle slot penalty, Content-Range strictness, load oscillation, catalog gate - slotStatePenalty: handle 'idle' state as running (0ms) — provider reports 'idle' for warm-but-no-active-requests models - Content-Range: discard partial on missing/unparseable header instead of appending optimistically; test mock now sends Content-Range - bestModelLoadProviderLocked: skip providers with ANY pending load_model (providerHasPendingLoad) to prevent swap oscillation - providerHasWarmModelLocked: add catalog gate so retired/hash-changed models don't suppress swap planning * fix: per-provider reservation race + drain queue on load success - reservePendingModelLoads: check providerHasPendingLoad (not just per-key) to prevent concurrent heartbeat goroutines from reserving the same idle provider for different models - load_model_status handler: drain queued requests immediately on success instead of waiting for next heartbeat (up to 5s) * fix: adversarial review — BackendCapacity authority, load failure backoff, disconnect cleanup, TUI preselect - providerHasWarmModelLocked: BackendCapacity is authoritative when present; only 'running'/'idle' slots count as warm. Prevents crashed slots from suppressing needed model swaps via stale WarmModels. - load_model_status: only clear pendingModelLoads on success. Failures retain the 2-min cooldown to prevent retry storms against providers that consistently fail (deleted files, OOM). - Disconnect: clear pendingModelLoads entries for the disconnected provider to prevent stale entries from blocking future swaps. - TUI preselect: check canFitIndividually before preselecting a downloaded model. * feat: reject queued requests immediately when model is unservable When load_model fails and no other provider can serve the model, queued requests are now rejected immediately with a fast error instead of waiting 120 seconds for the queue timeout. - FailQueuedRequestsForModel: sends nil to all ResponseChs, causing waiters to receive ErrQueueTimeout - RejectUnservableQueuedRequests: checks QuickCapacityCheck after a load failure; if no eligible provider exists, flushes the queue - Wired into load_model_status handler alongside the existing success/drain path * fix: clear stale CurrentModel on nil heartbeat, mark provider warm before queue drain - Heartbeat: clear CurrentModel when active_model is nil/omitted, preventing attestation challenges from comparing against unloaded models - load_model_status:succeeded: call MarkModelWarm before draining so the scheduler sees the provider as warm immediately, not after the next heartbeat (up to 5s delay) * fix: RejectUnservableQueuedRequests must check capacityRejections Only reject queued requests when NO provider serves the model at all. If providers exist but are temporarily at capacity, requests should wait — those providers may finish current work and become available. * fix: MarkModelWarm injects synthetic BackendCapacity slot The scheduler uses BackendCapacity.Slots (not WarmModels) for Swift providers. When load_model_status:succeeded arrives before the next heartbeat, the model had no slot so the scheduler still saw it as cold/unknown. Now injects an 'idle' slot so DrainQueuedRequestsForModel immediately routes to the just-warmed provider. * fix: MarkModelWarm clears stale evicted slots from BackendCapacity When a swap evicts model A and loads model B, stale 'running'/'idle' slots for A remained in BackendCapacity until the next heartbeat, causing the scheduler to treat A as still warm. Now drops all warm slots except the newly loaded model. * fix: MarkModelWarm preserves existing warm slots Provider may have multiple model slots loaded simultaneously (maxModelSlots=3). Only add/update the new model's slot; leave existing slots untouched. Next heartbeat provides authoritative state. * docs: add coordinator state model and mutation checklist to AGENTS.md Documents the overlapping state views (BackendCapacity vs WarmModels vs CurrentModel vs pendingModelLoads), their precedence rules, and a 5-point checklist for mutating provider state. Learned from 10 fix iterations on the multi-model swap feature. * docs: fix WarmModels reader list — include legacy ScoreProvider and /v1/me/providers * ci: require approval before running e2e benchmarks (#227) * chore: remove dead coordinator code (#211) Remove unused functions, methods, constants, and a duplicate directory: - coordinator/internal/e2e/e2e/: accidental byte-identical copy of parent directory, never imported by any code - api/provider.go: SendInferenceRequest() -- consumer path writes directly to provider.Conn, this was a leftover from a refactor - registry/queue.go: WaitForProvider() -- superseded by WaitForProviderContext(), the only method actually called - registry/queue.go: TryAssign() -- stale queue method from older design, never called from production code - registry/queue.go: CleanStale() -- stale queue method, never called (inline cleanStaleLocked is still used by Enqueue) - registry/registry.go: BackendInprocessMLX const -- dead enum value, the in-process MLX path was removed. String literal kept where needed for backward compat with old providers. - registry/registry.go: ForceTrustProvider() -- bypasses attestation with no legitimate production use. Tests updated to use testMakeTextRoutable(). - registry/registry.go: ProviderCountByChip() -- analytics method never wired to any endpoint - registry/registry.go: ModelProviderCounts() -- analytics method never wired to any endpoint Tests updated: removed 3 tests for deleted methods, migrated 2 tests from ForceTrustProvider to testMakeTextRoutable, replaced WaitForProvider calls with WaitForProviderContext. All tests pass. go vet clean. * [codex] Add stats leaderboard tab (#226) * Add stats leaderboard tab * Add earn now CTA to stats leaderboard * fix(coordinator): resolve DB connection starvation, deprecate Python providers (#228) Production outage root cause: Postgres connection pool (20 max) exhausted by concurrent stats scans, heartbeat upserts, and billing settlement. When SyncRuntimeManifest happened to overlap with pool exhaustion, ListReleases timed out, the manifest was nuked, and revalidateConnectedProvidersAgainstRuntimePolicy set RuntimeVerified=false for ALL providers — instantly derouting the fleet. Critical fixes: - Increase pool MaxConns from 20 to 80, MinConns from 5 to 10 - SyncRuntimeManifest: return early on ListReleases nil (DB timeout) instead of nuking a working manifest - revalidateConnectedProvidersAgainstRuntimePolicy: only deroute on intentional manifest withdrawal, not transient DB failures - Add 5s timeout to telemetry batch INSERT (was unbounded) Python/legacy provider deprecation: - privateTextBackendSupported only accepts mlx-swift - verifyRuntimeHashesForBackend immediately rejects non-Swift backends - providerSupportsPrivateTextLocked: remove dead Python caps branch - Remove dead code: r2SitePackagesCDNURL, verifyRuntimeHashes(), EIGENINFERENCE_KNOWN_PYTHON_HASHES, EIGENINFERENCE_KNOWN_RUNTIME_HASHES - All test fixtures updated from inprocess-mlx to mlx-swift DB performance optimizations: - CreditProviderAccount: 6 sequential round-trips → single CTE - Usage recording made async (saferun.Go) - Provider credit + platform fee run concurrently (WaitGroup) - Auth middleware: 3 DB queries → 1 (ValidateKeyFull) + LRU cache (60s TTL) - PersistProviderThrottled: heartbeat writes rate-limited to 1x/30s per provider - Add indexes: idx_usage_created, idx_usage_consumer, idx_usage_provider - Add earnings_summary materialized table: eliminates full-table SUM scans on /v1/provider/account-earnings (PK lookup instead) - Backfill migration populates earnings_summary from existing data - Add detailed mismatch logging (component+hash, not just count) All migrations are idempotent (CREATE IF NOT EXISTS / ON CONFLICT DO NOTHING). No manual SQL required — indexes and tables auto-create on restart. All tests pass. go vet clean. * fix(coordinator): unblock WebSocket read loop from billing settlement Root cause of challenge timeouts: handleComplete runs billing DB calls (GetModelPrice, Credit, Charge) synchronously on the WebSocket read loop. Under DB pressure (cross-cloud RDS latency), these block for 5+ seconds, preventing the read loop from receiving attestation challenge responses. The 30s challenge timeout expires, RecordChallengeFailure clears LastChallengeVerified, and the provider becomes unroutable. Fixes: - Move handleComplete to a saferun.Go goroutine so billing settlement never blocks the read loop - RecordChallengeFailure: only clear LastChallengeVerified on security failures (SIP disabled, signature mismatch, etc.), NOT on transient timeouts. Transient timeouts only deroute at MaxFailedChallenges (3). - Move MaxFailedChallenges constant to registry package (was hardcoded) All tests pass. go vet clean. * refactor(coordinator): replace MaxMind with ip-api.com for provider geolocation Remove the geoip2-golang dependency and MaxMind .mmdb file requirement. Provider geolocation now uses ip-api.com (free, no API key, 45 req/min). Called once per provider WebSocket connection so rate limit is never hit. The resolver always initializes now — no env vars needed for basic geo. EIGENINFERENCE_TRUST_GEO_HEADERS=1 still works as a fast-path when behind Cloudflare/Vercel. EIGENINFERENCE_GEOIP_DB is removed. * style: gofmt provider.go, postgres.go * perf(coordinator): stop writing telemetry to Postgres — Datadog is sole sink Removes the synchronous InsertTelemetryEvents call from the telemetry handler. With 60 providers sending batches every 10s, this was 6 INSERTs per second, each writing up to 50 rows into a table with 5 indexes. That alone consumed ~30-40% of the DB connection pool. Datadog already receives all telemetry asynchronously via the Logs API. The Postgres copy was documented as best-effort secondary storage and adds no value that Datadog doesn't already provide. The telemetry_events table and its schema are left intact (no migration needed). New events simply stop being written. * fix(provider-swift): migrate SE key to AfterFirstUnlock for background signing The SE key was created with kSecAttrAccessibleWhenUnlockedThisDeviceOnly, which blocks signing when the screen is locked. This caused all attestation challenges to fail with OSStatus -25308 (errSecInteractionNotAllowed) on provider machines with locked screens, making them unroutable. Changes: - New keys use kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly — accessible after first unlock even when screen subsequently locks - loadOrCreate performs a test sign on existing keys; if it gets -25308, deletes the old key and recreates with the new policy - Migration is automatic on provider restart — no manual intervention Providers need to update to this version and restart. The old key is deleted and a new one is created, which means the provider will re-attest with a new public key on next coordinator connection. * chore: bump provider version to 0.5.11 * fix: add missing r2SitePackagesCDNURL field and setter from PR branch * fix: DB perf optimizations, error classification, and provider diagnostics (#232) * fix: DB perf optimizations, error classification, and provider diagnostics Coordinator DB performance: - Add usage_totals counter table (O(1) vs full-table scan) - Add partial index on usage.request_location IS NOT NULL - Replace UsageRecordsSince + ListProviderRecords with SQL JOIN - Add 60s cache to /v1/models/catalog endpoint - Fix N+1 query in ListActiveModelRegistryWithError (batch file load) - Add 20s cache to /v1/provider/account-earnings - Merge GetBalance + GetWithdrawableBalance into single query Billing error classification: - Add ErrInsufficientBalance sentinel to store package - Debit() distinguishes pgx.ErrNoRows from DB timeouts - Consumer handler returns 503 (not 402) for DB errors - Provider handler logs warn vs error for balance vs DB failures Provider diagnostics: - darkbloom logs now streams macOS unified logging by default - darkbloom logs --last 1h shows historical unified logs - darkbloom logs --file falls back to provider.log - New darkbloom report command uploads 24h unified logs - New POST /v1/provider/log-report endpoint (API key auth) - New GET /v1/admin/log-reports admin endpoints - New provider_log_reports DB table Closes #230 * fix: address Codex review findings - Accept provider tokens (eigeninference-pt-...) in requireAuth so darkbloom report works with device-login tokens - Include limit param in earnings cache key to prevent stale responses - Invalidate catalog cache in SyncModelCatalog after admin changes - Fix log show to use --info flag instead of --level info (macOS log(1)) * fix: restore in-memory telemetry buffer, no-op Postgres telemetry writes The telemetry Postgres removal (e0a63cc) removed both the Postgres INSERT and the in-memory buffer write. The in-memory buffer is free (no DB, bounded at 10K entries) and is needed by the admin metrics endpoint and test assertions. - Restore InsertTelemetryEvents call in the handler (writes to in-memory MemoryStore buffer only) - Make PostgresStore.InsertTelemetryEvents a no-op (was still doing the expensive batch INSERT that the removal intended to eliminate) - All 9 telemetry tests now pass (were failing on master) * fix: remove telemetry Postgres writes, fix tests to assert on Datadog path Telemetry is forwarded to Datadog only — no store writes. The previous fix incorrectly re-added InsertTelemetryEvents to the HTTP handler. - Remove InsertTelemetryEvents call from ingestion handler - Make PostgresStore.InsertTelemetryEvents a no-op (was still doing the expensive batch INSERT the removal intended to eliminate) - Update 3 tests to assert on HTTP response counts and metrics counters instead of TelemetryEventsSnapshot (which is empty since the handler no longer writes to the store) - Recover middleware test unchanged (uses Emitter path, not HTTP handler) All 12 packages pass with zero failures. * style: gofmt server.go, stats.go, memory.go * feat: trust_status message, auto-report, and MDM re-verification (#233) Coordinator → Provider trust status notification: - Add TypeTrustStatus protocol message (Go + Swift) - Send trust_status after SE attestation (self_signed), MDM upgrade (hardware), ACME upgrade (hardware), and MarkUntrusted - Provider receives trust level and status over WebSocket Provider auto-report on degraded trust: - When provider learns it is self_signed or untrusted, schedules a one-time auto-report of 24h unified logs after 10 minutes - Report is uploaded to POST /v1/provider/log-report - Cancelled if trust is upgraded before the 10-min window - Once-per-session flag prevents spamming MDM re-verification for self_signed providers: - Challenge loop now re-attempts MDM verification after a successful challenge if the provider is still at self_signed trust - Providers that install MDM enrollment after registration will get upgraded to hardware trust on the next challenge cycle (5 minutes) instead of being stuck at self_signed forever * chore: bump provider version to 0.5.12 * fix: MDM channel saturation, timeout-marks-untrusted, and model load memory gate MDM channel architecture (coordinator/mdm/mdm.go): - Replace shared buffered channels (size 16) with per-UDID waiter maps - Eliminates channel saturation: late/unsolicited webhooks no longer fill the buffer and block all future MDM verifications - Eliminates CPU busy-spin: no more read-put-back loops when waiting for a specific UDID while other UDIDs are in the buffer - Same fix applied to attestation (MDA) response path MDM timeout handling (coordinator/api/provider.go): - SecurityInfo timeout no longer marks provider untrusted - Timeout is APN latency, not evidence of compromise - Provider stays at self_signed trust, MDM re-check retries on next challenge cycle (every 5 minutes) Model load memory gate (coordinator/registry/registry.go): - TriggerModelSwaps now checks provider memory before sending load_model - Uses catalog SizeGB * 2.5 as the coordinator-side memory threshold - Prevents sending load_model to machines that will always reject (e.g., 32GB Mac for gpt-oss-20b needing 40.5GB) - Stops the infinite retry loop of failed load_model commands * fix: APN reliability for MDM — network assertions, 90s timeout, late-arrival path Provider (Swift): - Add NetworkPowerAssertion: IOKit assertions for NetworkClientActive and BackgroundTask, acquired for the entire provider session - Keeps the macOS network stack alive during sleep so APN pushes (courier.push.apple.com:5223) can be delivered for MDM commands - No root required — uses IOPMAssertionCreateWithName API Coordinator: - Increase SecurityInfo timeout from 30s to 90s to cover Power Nap cycles (every ~15 minutes on AC power) - Add OnLateSecurityInfoCallback: when a SecurityInfo webhook arrives after the 90s timeout, retroactively upgrade the self_signed provider to hardware trust instead of silently dropping the response - Wire up the callback in main.go alongside the existing SetOnMDA callback, using the same ForEachProvider + serial match pattern * chore: bump provider version to 0.5.13 * chore: remove telemetry_events Postgres table and writes (#234) * chore: remove telemetry_events Postgres table and writes The telemetry_events table + 5 indexes was the single largest source of DB write pressure (60 providers × batch/10s × 50 rows × 5 indexes consumed ~30-40% of the connection pool). The /v1/telemetry/events ingestion handler already skips Postgres entirely — Datadog is the sole durable sink. No read endpoints consumed this table. - Remove CREATE TABLE telemetry_events + 5 CREATE INDEX from migration - Delete telemetry_postgres.go, telemetry_memory.go, telemetry_test.go - Remove InsertTelemetryEvents from Store interface - Remove store field/param from telemetry.Emitter - Remove telemetryEvents ring buffer from MemoryStore - Update all callers (main.go, server.go, tests) * ci: trigger re-run --------- Co-authored-by: ethenotethan <42627790+ethenotethan@users.noreply.github.com> Co-authored-by: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com>
Summary
Providers can now select and download multiple models even when their combined size exceeds available RAM. Only one model is warm (loaded in GPU memory) at a time; the coordinator manages demand-driven model swaps via the existing
load_modelprotocol.Example
A machine with 36 GB RAM can now select both a 12 GB and a 26 GB model. Whichever model is warm is the one being served. When the warm model goes idle and demand arrives for the cold model, the coordinator triggers a swap.
Before / After Flow
Before: Request for cold model (no swap support)
sequenceDiagram participant C as Consumer participant Co as Coordinator participant P as Provider (12GB warm) C->>Co: POST /v1/chat/completions (model: 26GB) Co->>Co: QuickCapacityCheck Note over Co: freeMemoryAdmits: GPU memory<br/>occupied by 12GB model<br/>→ REJECT (no room for 26GB) Co-->>C: 429 Too Many Requests Note over C: Consumer retries forever<br/>or gives up. 26GB model<br/>is never served.After: Request for cold model (demand-driven swap)
sequenceDiagram participant C as Consumer participant Co as Coordinator participant P as Provider (12GB warm, 26GB on disk) C->>Co: POST /v1/chat/completions (model: 26GB) Co->>Co: QuickCapacityCheck Note over Co: availableOnDisk=true<br/>provider idle (pending=0)<br/>26GB + KV + 4GB ≤ 36GB → ADMIT<br/>penalty: +30s (cold) Co->>Co: ReserveProviderEx (30s cost penalty) Co->>P: inference_request (26GB model) P->>P: ensureModelLoaded(26GB) P->>P: evict 12GB (LRU, idle) P->>P: load 26GB from disk P-->>Co: inference_accepted P-->>Co: inference_response_chunk (streaming) Co-->>C: 200 OK (streaming SSE)Before: No warm provider, request queues
sequenceDiagram participant C as Consumer participant Co as Coordinator participant P as Provider (model A warm) C->>Co: POST /v1/chat/completions (model: B) Co->>Co: No warm provider for B Co->>Co: Queue request (120s timeout) Note over Co: No proactive action.<br/>Request waits until timeout. Co-->>C: 429 queue timeout (after 120s)After: No warm provider, proactive swap + fast reject
sequenceDiagram participant C as Consumer participant Co as Coordinator participant P as Provider (model A warm, B on disk) C->>Co: POST /v1/chat/completions (model: B) Co->>Co: No warm provider for B → queue request Co->>Co: Heartbeat arrives Co->>Co: TriggerModelSwaps: B queued, no warm provider Co->>P: load_model(B) P->>P: evict A, load B P-->>Co: load_model_status: succeeded Co->>Co: MarkModelWarm(P, B) Co->>Co: DrainQueuedRequestsForModel(B) Co->>P: inference_request (model B) P-->>Co: inference_response_chunk Co-->>C: 200 OK (streaming SSE) Note over Co: If load fails instead: Note over Co: RejectUnservableQueuedRequests<br/>→ immediate 429 (not 120s wait)Before: TUI model picker
flowchart TD A[User selects 12GB model ✓] --> B{Select 26GB model?} B -->|12 + 26 = 38 > 32 budget| C[❌ Blocked - won't fit] C --> D[User can only serve 1 model]After: TUI model picker
flowchart TD A[User selects 12GB model ✓] --> B{Select 26GB model?} B -->|26 ≤ 32 individually| C[✓ Selected] C --> D[Status: one model active at a time - swap on demand] D --> E[Both models registered with coordinator] E --> F[Coordinator manages warm/cold swaps]Before / After Table
Model Selection (TUI Picker)
12 + 26 = 38 > 32budget"X GB used · Y GB remaining""X GB on disk · one model active at a time"or"all models can be served simultaneously"Coordinator Routing
freeMemoryAdmitssaw GPU memory occupied by warm model"idle"fell through to"unknown"→ 30s"idle"treated as"running"→ 0msTriggerModelSwapssendsload_modelto idle cold providers when requests queue(provider, model), one provider per pass, per-provider pending checkMarkModelWarm+DrainQueuedRequestsForModelimmediatelyRejectUnservableQueuedRequests— immediate 429 if no provider can serveProvider State Tracking
WarmModelson empty heartbeatCurrentModelon nil heartbeatpendingModelLoadsleakedModel Download Resume
appendDownloadedRangeContent-Range: bytes start-end/totalFiles changed (9)
provider-swift/.../StartCommand.swiftprovider-swift/.../ModelCatalog.swiftappendDownloadedRangeprovider-swift/.../ModelCatalogTests.swiftcoordinator/registry/registry.goSendLoadModel,TriggerModelSwaps,MarkModelWarm,RejectUnservableQueuedRequests,ClearPendingModelLoad,providerHasPendingLoad,pendingModelLoads, heartbeat state fixescoordinator/registry/scheduler.goavailableOnDisk,freeMemoryAdmitscold path,slotStatePenaltyidle/unknown,DrainQueuedRequestsForModelcoordinator/registry/queue.goQueuedModels,FailQueuedRequestsForModelcoordinator/api/provider.goload_model_statushandler: success/failure pathscoordinator/api/billing_handlers.gocoordinator/payments/pricing_test.goTesting
Deploy Order
load_model)