Repository navigation
fix(provider): load models for one-request fit, not full-concurrency headroom - #273
Conversation
…headroom This is the foundational fix for ~half the fleet sitting idle. A small/mid machine could not LOAD a model it was perfectly capable of serving, because the load gate was doubly conservative: requiredGb = estimatedMemoryGb * 2.0 (full-concurrency KV headroom) availableMemoryGb = free * 0.7 (runtime KV safety, double-counted) => effectively demanded free >= weights * 2.86 Measured effect: gpt-oss-20b "needed" 40.5 GB and gemma-4-26b 93.7 GB to load — ~3.35x the weights — so every 24/32/36/48 GB box (and most 64 GB boxes) served ZERO requests despite advertising the models. The runtime is ALREADY safe and dynamic: GlobalKVCacheBudget.reserve() strictly rejects any request whose KV won't fit real free memory, and the live token budget scales concurrency with a floor of one request. So the 2x/0.7 belonged nowhere near the LOAD decision. Fix (ModelLoadAdmission, pure + unit-tested): - Load gate now requires only WEIGHTS + one-request headroom (estimatedMemoryGb + loadHeadroomGb, default 2 GB). - availableMemoryGb drops the 0.7 discount — loading weights is a known one-time allocation; the 0.7 runtime safety stays where it belongs (per-request KV). - Concurrency beyond one request is grown dynamically by the existing budget, so a 24 GB box serves 1-2 and a 128 GB box serves many. Cannot OOM: a load that fits one request is admitted; everything past that is gated per request. Impact (measured against the live fleet): gpt-oss-20b now loads on 24/32/36/48 GB boxes; gemma-4-26b now loads on the 48/64 GB tiers (18x 64 GB machines that served nothing before). gemma-8bit correctly still rejected on 32 GB (weights + OS ≈ whole box). Tests: ModelLoadAdmissionTests (gpt-oss-on-24GB admit, gemma-on-64GB admit, gemma-on-32GB reject, resident-model no-room, free-memory math, regression guard proving the old gate rejected gpt-oss-on-24GB). swift build + swift test green.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This PR refactors the model-load memory gate to use real OS-available memory and per-request KV reservations; it is net security-neutral but introduces one new attack surface and one subtle race that deserve eyes before merge. Trust boundaries touched
Threat-by-threat assessmentT-007 — Provider serves manipulated model outputs ( T-008 — Provider sends plaintext SSE chunks on encryption failure ( T-009 — Elevated trust / routing gate ( T-010 — Cancellation not propagated ( T-028 — Residual inference data in GPU memory (indirectly, New attack surface not covered by an existing threat1. Mach host statistics as a denial-of-service / spoofing oracle (
2. TOCTOU window in The comment in the diff (line ~1648, truncated) starts: 3. Both files saturate to Open findings statusNo SEC-* findings are resolved by this PR. SEC-007 (weight-hash fail-open), SEC-016 (plaintext SSE fallback), and SEC-017 (Swift provider excluded from private routing) all remain open and are untouched. Summary for reviewers
🔐 Threat model: |
There was a problem hiding this comment.
💡 Codex Review
d-inference/provider-swift/Sources/ProviderCore/ProviderLoop.swift
Lines 1633 to 1635 in e54fbf7
When another model is already cold-loading, this pre-accept check still only looks at currently resident slots and current MLX memory. On the newly admitted one-model machines, a second request for a different cold model can arrive while the first load is suspended, see enough free memory, get inferenceAccepted, and then fail after the first load becomes resident and cannot be evicted because its request is in requestToModel; that is exactly the accepted-then-failed path this fast check is meant to avoid. Treat modelsLoading/isLoadingAny as pending non-evictable memory or reject until the load settles.
ℹ️ 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".
| ModelLoadAdmission.freeForLoadGb( | ||
| totalBytes: ProcessInfo.processInfo.physicalMemory, | ||
| gpuActiveBytes: UInt64(max(0, MLX.GPU.activeMemory)), | ||
| gpuCacheBytes: UInt64(max(0, MLX.GPU.cacheMemory)), | ||
| reserveBytes: Self.memoryReserveBytes(forGiB: loopConfig.config.provider.memoryReserveGB)) |
There was a problem hiding this comment.
Include outstanding KV reservations in load headroom
When a request is already running on another loaded model, GlobalKVCacheBudget.reserve() may have reserved prompt+max-token KV bytes before those bytes show up in MLX.GPU.activeMemory/cacheMemory. This new load gate treats that reserved-but-not-yet-materialized headroom as free memory, so a concurrent preload/load can place another model's weights into memory already promised to an in-flight request; the KV budget cannot protect that request because model loads never consult or reserve against it. This is especially risky on the tight 24/32/64 GB machines this change newly admits, where a second model load during decoding can still drive the provider into the OOM path instead of merely reducing concurrency.
Useful? React with 👍 / 👎.
| ModelLoadAdmission.freeForLoadGb( | ||
| totalBytes: ProcessInfo.processInfo.physicalMemory, | ||
| gpuActiveBytes: UInt64(max(0, MLX.GPU.activeMemory)), | ||
| gpuCacheBytes: UInt64(max(0, MLX.GPU.cacheMemory)), | ||
| reserveBytes: Self.memoryReserveBytes(forGiB: loopConfig.config.provider.memoryReserveGB)) |
There was a problem hiding this comment.
Clamp load checks to system free memory
With the 0.7 cushion removed, this now treats all physical RAM except MLX active/cache and the fixed reserve as loadable, even when macOS or other user processes have already consumed the remaining memory. For example, a 24 GB provider with ~8 GB used outside MLX can still report 20 GB free here and admit a 15.5 GB cold load even though the OS only has roughly 12 GB available, so the load can hit memory pressure/OOM before the per-request KV budget ever runs. The standalone server avoids this by clamping against systemAvailableMemoryBytes(), and the provider loop needs the same real-system-free cap when using the looser gate.
Useful? React with 👍 / 👎.
| /// cache + activations at load time. Small on purpose: it only needs to | ||
| /// cover a single in-flight request; the runtime budget grows concurrency | ||
| /// from whatever is left. Tunable via provider config. | ||
| public static let defaultLoadHeadroomGb: Double = 2.0 |
There was a problem hiding this comment.
Size load headroom from the actual request
This fixed 2 GB headroom does not prove that even the first accepted request fits: long prompts or models whose scheduler raises the default output budget toward 8192 tokens can require more than 2 GB of KV. On a tight cold load that now passes with only this margin, the model is loaded and inferenceAccepted has already been sent, but BatchScheduler/GlobalKVCacheBudget.reserve() can still reject the real prompt+max-token budget with token_budget_exhausted; use the decoded request budget or a conservative model-specific KV estimate for the load gate instead of a constant.
Useful? React with 👍 / 👎.
…er (--local) Review parity follow-up: the --local standalone path still sized loads at estimatedMemoryGb × 2.0. Route it through the shared ModelLoadAdmission helper so the dev/local path matches the production ProviderLoop gate (weights + one-request headroom). Removes the now-unused modelLoadMemoryMultiplier.
|
Companion PR / coordinator side: the coordinator's admission + pre-warm gate is fixed in #268, which switches
For the headline cases they agree (gpt-oss on 24–48 GB; gemma on 48–64 GB), with the coordinator slightly tighter so it won't route to a box the provider then rejects. They should land together. On master alone, the coordinator's old |
…+ in-flight KV) The one-request load gate let small/mid machines finally load models they can serve, but two holes could still drive a box into OOM: 1. System-free clamp. Free memory was computed as total − MLX.active − MLX.cache, which over-reports whenever the OS or other processes hold RAM. availableMemoryGb now also reads real OS-available memory (SystemMemory.availableBytes, via vm_statistics64) and takes the smaller of the two views, so the gate can never count memory that is already gone. 2. In-flight KV reservations. A concurrent preload/cold-load could place a new model's weights into memory already promised to a mid-decode request (those bytes may not yet appear in MLX.active/cache). The gate now subtracts GlobalKVCacheBudget.outstandingReservedBytes() before admitting a load. ModelLoadAdmission.freeForLoadGb/canLoad gain systemAvailableBytes (default .max) and outstandingReservationBytes (default 0), so the pure arithmetic stays unit-testable. ProviderLoop.availableMemoryGb / fastAdmissionReject and StandaloneServer.availableMemoryGb become async to query the KV actor; StandaloneServer drops its duplicated vm_statistics helper for the shared SystemMemory. The headline win is preserved: an idle box with low OS usage and no reservations still loads gpt-oss on 24 GB. Adds tests for the system clamp, reservation subtraction, and a guard that the idle-box gpt-oss-on-24GB case still passes under both clamps.
…eview gaps Addresses the doctor review findings, now that #273 replaced the runtime load gate with ModelLoadAdmission (weights + one-request headroom; free clamped to real OS-available memory, no 0.7 discount): - Model-fit accounting (P2): ModelFitDiagnostic now delegates to the SAME ModelLoadAdmission arithmetic the daemon uses, so doctor's verdict can't drift from runtime. required = weights + 2 GB headroom (not weights x 2.0); usable = freeForLoadGb clamped to live OS-available memory (SystemMemory), not (total-reserve) x 0.7. doctor now reads real OS-available RAM on the same box. - Stale daemon state (P2): the fit target prefers state.currentModel only when the daemon is up AND its snapshot is fresh; otherwise it diagnoses the CONFIGURED model. Prevents checking last session's model after the operator stops the daemon and switches provider.toml to a larger model. - Configured model filtered out (P2): added ModelScanner.scanAllModels (unfiltered). doctor uses it so a configured model too large to pass the memory filter is still found and flagged, instead of silently diagnosing a different fitting model. - ACME false MDM warning (P2): the 'enroll in MDM' hint is suppressed when the daemon's live trust level is already hardware (e.g. ACME device attestation), which needs no MDM profile — it previously contradicted the trust line above. - Coordinator minimum version (P2): deferred with a code note. VersionDiagnostic supports a below-min FAIL, but min_provider_version is only on Privy-authed /v1/me endpoints the device-token CLI can't call; surfacing it needs a device-authed source (follow-up). Below-min providers are still reflected via the trust section (coordinator sets RuntimeVerified=false). Tests updated for the new gate; added OS-available clamp + runtime-parity cases.
…eview gaps Addresses the doctor review findings, now that #273 replaced the runtime load gate with ModelLoadAdmission (weights + one-request headroom; free clamped to real OS-available memory, no 0.7 discount): - Model-fit accounting (P2): ModelFitDiagnostic now delegates to the SAME ModelLoadAdmission arithmetic the daemon uses, so doctor's verdict can't drift from runtime. required = weights + 2 GB headroom (not weights x 2.0); usable = freeForLoadGb clamped to live OS-available memory (SystemMemory), not (total-reserve) x 0.7. doctor now reads real OS-available RAM on the same box. - Stale daemon state (P2): the fit target prefers state.currentModel only when the daemon is up AND its snapshot is fresh; otherwise it diagnoses the CONFIGURED model. Prevents checking last session's model after the operator stops the daemon and switches provider.toml to a larger model. - Configured model filtered out (P2): added ModelScanner.scanAllModels (unfiltered). doctor uses it so a configured model too large to pass the memory filter is still found and flagged, instead of silently diagnosing a different fitting model. - ACME false MDM warning (P2): the 'enroll in MDM' hint is suppressed when the daemon's live trust level is already hardware (e.g. ACME device attestation), which needs no MDM profile — it previously contradicted the trust line above. - Coordinator minimum version (P2): deferred with a code note. VersionDiagnostic supports a below-min FAIL, but min_provider_version is only on Privy-authed /v1/me endpoints the device-token CLI can't call; surfacing it needs a device-authed source (follow-up). Below-min providers are still reflected via the trust section (coordinator sets RuntimeVerified=false). Tests updated for the new gate; added OS-available clamp + runtime-parity cases.
…tus (#271) Adds an operator-facing "why am I / aren't I earning?" diagnosis to darkbloom doctor and status, sourced from local probes + a small daemon state file (no new IPC) + a coordinator version check. - SE key self-test, hardware/RAM probes, MDM enrollment hint, live trust reason (from the daemon's last trust_status), runtime/billing stats, version check. - DaemonStateFile: the daemon writes a small atomic JSON snapshot each heartbeat so the CLI can show live trust/model/usage state with zero IPC, surviving the daemon being asleep or wedged. - Model-fit check delegates to the SAME ModelLoadAdmission arithmetic the daemon enforces (post-#273), so doctor's verdict can't drift from runtime: clamps to real OS-available memory, subtracts reserve + resident MLX (active+cache), required = weights + one-request headroom. Uses an unfiltered model scan so a configured model too large to pass the memory filter is still flagged. - Prefers the live loaded model only when the daemon is up and fresh; otherwise diagnoses the configured model. Suppresses the MDM-enroll hint when the box is already hardware-trusted (e.g. ACME). - Surfaces billing usage-gaps (missing/zero usage chunks) and the last model load failure with the exact 'Insufficient memory' reason. Note: surfacing the coordinator minimum version in doctor is deferred (code note) — it's only on Privy-authed /v1/me endpoints the device CLI can't reach. Analyze (swift) CodeQL is a pre-existing infra config error; all functional gates (Provider/Coordinator/E2E tests, lints, threat model) pass.
Honors the OpenAI reasoning_effort request field end to end and reports an accurate reasoning_tokens count. - Protocol (symmetric): reasoning_effort plumbed through coordinator/protocol/ messages.go + provider-swift Protocol/Types.swift; the provider applies it to the MLX generation and accumulates reasoning_content deltas (gpt-oss analysis channel, Qwen3/DeepSeek <think>, Gemma4 channels). - Accurate accounting: reasoning text is re-tokenized at completion to populate completion_tokens_details.reasoning_tokens, since upstream's usage block only carries the total completion count. Composes with the billing-floor content-frame counter (reasoning frames count toward visible output). - Tests: consumer + inbound-decode + protocol + stream-chunk + a (gated) live gpt-oss E2E for reasoning_tokens. Rebased onto current master (resolved against #271/#273's ProviderLoop changes). Analyze (swift) CodeQL is the pre-existing infra config error; all functional gates pass.
The foundational flaw
~Half the fleet sits idle. Live
/v1/statsshows every 16/24/32/36/48 GB box and most 64 GB boxes serve zero requests — they connect, get trusted, advertise the models, and never serve anything. The work piles onto 96 GB+ machines.Root cause: the provider's load gate is doubly conservative.
Measured from 5,966 production log lines: gpt-oss-20b "needs" 40.5 GB and gemma-4-26b 93.7 GB to load — ~3.35× the weights. So a 24 GB box that can comfortably serve a gpt-oss request is refused at load and serves nothing.
Why it's safe to loosen this
The runtime is already dynamic and OOM-safe — it just never gets the chance because the model won't load:
GlobalKVCacheBudget.reserve()strictly rejects any request whose KV won't fit real free memory ((total − active − cache − reserve) × 0.7).tokenBudgetMax/effectiveMaxConcurrentRequestsscale concurrency to live memory with a floor of one request.So the
2.0×(concurrency headroom) and the0.7(runtime KV safety) belong at request time, not at load time.The fix
New pure, unit-tested
ModelLoadAdmission:weights + one-request headroom(estimatedMemoryGb + loadHeadroomGb, default 2 GB).availableMemoryGbdrops the 0.7 discount — weights are a known one-time allocation; the 0.7 stays where it belongs (per-request KV).GlobalKVCacheBudget. Worst case a tight box serves one request at a time.Impact (measured against the live fleet)
This is also the provider half of the coordinator
min_ram_gbgate (PR #268): the coordinator admits the right boxes, and now the provider actually loads on them.Testing
ModelLoadAdmissionTests: gpt-oss-on-24GB admit, gemma-on-64GB admit, gemma-on-32GB reject, resident-model no-room, free-memory math, and a regression guard proving the old gate rejected gpt-oss-on-24GB.swift build+ filteredswift testgreen (MLX-runtime tests need a metallib, skipped locally).Follow-ups
gpu_memory_active_gbper provider in/v1/statsto verify post-deploy that small boxes now serve and to measure real footprints (the coordinator already receives it).loadHeadroomGbprovider-config-tunable.🤖 Generated with Claude Code
Need help on this PR? Tag
/codesmithwith what you need. Autofix is disabled.