Skip to content

fix(provider): load models for one-request fit, not full-concurrency headroom - #273

Merged
Gajesh2007 merged 3 commits into
masterfrom
worktree-dynamic-memory-admission
Jun 4, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
worktree-dynamic-memory-admission

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

The foundational flaw

~Half the fleet sits idle. Live /v1/stats shows 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.

requiredGb        = estimatedMemoryGb × 2.0   // full-concurrency KV headroom
availableMemoryGb = free × 0.7                // runtime KV safety — double-counted here
⇒ effectively demands  free ≥ weights × 2.86

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 / effectiveMaxConcurrentRequests scale concurrency to live memory with a floor of one request.

So the 2.0× (concurrency headroom) and the 0.7 (runtime KV safety) belong at request time, not at load time.

The fix

New pure, unit-tested ModelLoadAdmission:

  • Load gate requires only weights + one-request headroom (estimatedMemoryGb + loadHeadroomGb, default 2 GB).
  • availableMemoryGb drops the 0.7 discount — weights are a known one-time allocation; the 0.7 stays where it belongs (per-request KV).
  • Concurrency beyond one request grows dynamically via the existing budget. A 24 GB box serves 1–2; a 128 GB box serves many.
  • Cannot OOM: a load is admitted only if one request fits; everything past that is gated per-request by GlobalKVCacheBudget. Worst case a tight box serves one request at a time.

Impact (measured against the live fleet)

Model Before After
gpt-oss-20b (~13.5 GB weights) needed 40.5 GB → only 64 GB+ served loads on 24/32/36/48 GB ✓
gemma-4-26b (~31 GB weights) needed 93.7 GB → only 96 GB+ served loads on 48/64 GB (incl. the 18× 64 GB tier) ✓
gemma-8bit on 32 GB — correctly still rejected (weights + OS ≈ whole box) — no OOM

This is also the provider half of the coordinator min_ram_gb gate (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 + filtered swift test green (MLX-runtime tests need a metallib, skipped locally).

Follow-ups

  • Expose gpu_memory_active_gb per provider in /v1/stats to verify post-deploy that small boxes now serve and to measure real footprints (the coordinator already receives it).
  • Make loadHeadroomGb provider-config-tunable.

🤖 Generated with Claude Code


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

…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.
@vercel

vercel Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 4, 2026 1:17am
d-inference-console-ui-dev Ready Ready Preview Jun 4, 2026 1:17am
d-inference-landing Ready Ready Preview Jun 4, 2026 1:17am

Request Review

@github-actions

github-actions Bot commented Jun 3, 2026 •

Copy link
Copy Markdown
Contributor

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

  • TB-002 (Coordinator → Provider WebSocket) — load-gate changes affect how provider capacity is reported and whether requests are accepted or rejected
  • TB-003 (Provider operator vs. process) — memory accounting paths affect inference isolation guarantees
  • TB-007 (Provider inference engine) — core change: model admission, KV budget accounting, and eviction logic

Threat-by-threat assessment

T-007 — Provider serves manipulated model outputs (GlobalKVCacheBudget.swift, ModelLoadAdmission.swift, SystemMemory.swift)
ℹ️ Neutral. Weight-hash enforcement is unchanged (still fail-open, SEC-007 remains open). The memory arithmetic changes don't affect whether a model's hash is verified.

T-008 — Provider sends plaintext SSE chunks on encryption failure (ProviderLoop.swift)
ℹ️ Neutral. The plaintext fallback at ProviderLoop.swift:436–451 (SEC-016) is not modified by this PR. The fail-open behaviour persists.

T-009 — Elevated trust / routing gate (ProviderLoop.swift)
ℹ️ Neutral. The fastAdmissionReject and evictUntilAvailable changes don't touch the privacy-capability flags checked by the routing gate.

T-010 — Cancellation not propagated (ProviderLoop.swift)
ℹ️ Neutral. Cancellation wiring is unchanged; the known limitation (cannot interrupt an active GPU forward pass) remains.

T-028 — Residual inference data in GPU memory (indirectly, ModelLoadAdmission.swift)
ℹ️ Neutral. GPU buffer zeroing between requests is still absent. The new load gate does not add or remove Metal memset calls.


New attack surface not covered by an existing threat

1. Mach host statistics as a denial-of-service / spoofing oracle (SystemMemory.swift)

host_statistics64(mach_host_self(), HOST_VM_INFO64, ...) is a privileged Mach call that any process on the machine can invoke. A sufficiently adversarial operator process that continuously allocates and pins memory can manipulate free_count + inactive_count to fool the load gate into thinking the machine is full, preventing any model from loading without triggering the coordinator's untrust path. This is a local resource-exhaustion primitive against the load decision. Not covered by any T-0xx. Low severity in context (operator already has physical access), but worth noting given TB-003 aims to limit what the operator can influence.

2. TOCTOU window in fastAdmissionReject after await availableMemoryGb()

The comment in the diff (line ~1648, truncated) starts: // Re-check residency after the suspension: the model may have been loaded by a concurrent request while we were awaiting memory. The code then re-reads modelSlots[m… — the diff is truncated, so the full post-await residency check is not visible. If modelSlots mutation between the await and the residency re-check is possible (e.g. a concurrent Task on this actor completing a load), the conservative admission comment may not hold. Please ensure the full post-await state read is reviewed for completeness before merge. The comment itself flags this concern correctly, but the truncation in the diff makes verification impossible from the PR alone.

3. UInt64.max sentinel propagation (SystemMemory.swift line 35, GlobalKVCacheBudget.swift line 56)

Both files saturate to UInt64.max on overflow. ModelLoadAdmission.freeForLoadGb receives systemAvailableBytes: SystemMemory.availableBytes() ?? .max (ProviderLoop.swift around line 1562). If availableBytes() returns nil (failed Mach call), .max is passed, which means the OS-availability clamp is silently disabled and the gate falls back to the pure MLX view — the same over-reporting behaviour the PR is trying to fix. A failed host_statistics64 (e.g. resource limit on Mach port allocation) would silently degrade back to the pre-fix logic without any log warning. Consider logging a warning when availableBytes() returns nil so operators can detect the degradation.


Open findings status

No 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

File Security delta
GlobalKVCacheBudget.swift Overflow-safe sum exposed; no regression
ModelLoadAdmission.swift New pure-function gate; arithmetic is correct; no crypto/auth change
SystemMemory.swift New Mach call; nil-fallback silently degrades; needs a log warning
ProviderLoop.swift async propagation correct; post-await re-check is truncated in diff — needs full review

🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

// Mirrors evictUntilAvailable's terminal failure: not enough free
// memory and nothing idle to free.
if availableMemoryGb() < requiredGb && !hasEvictable {

P2 Badge Account for in-progress cold loads

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

Comment on lines +1557 to +1561
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

Comment on lines +1557 to +1561
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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.
@Gajesh2007

Copy link
Copy Markdown
Member Author

Companion PR / coordinator side: the coordinator's admission + pre-warm gate is fixed in #268, which switches modelFitsHardware to the catalog's authoritative min_ram_gb (gpt-oss-20b=24, gemma-4-26b=36). Together the two PRs are coherent:

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 SizeGB × 2.5 pre-warm gate still blocks proactive load_model to these boxes — that's resolved by #268, not by changes here.

…+ 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.
@Gajesh2007
Gajesh2007 merged commit 5bb5296 into master Jun 4, 2026
15 of 17 checks passed
Gajesh2007 added a commit that referenced this pull request Jun 4, 2026
…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.
Gajesh2007 added a commit that referenced this pull request Jun 4, 2026
…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.
Gajesh2007 added a commit that referenced this pull request Jun 5, 2026
…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.
Gajesh2007 added a commit that referenced this pull request Jun 5, 2026
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.

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 13a4719a Deployed Jun 4, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 13a4719a Deployed Jun 4, 2026 by vercel[bot]
Preview – d-inference-landing — 13a4719a Deployed Jun 4, 2026 by vercel[bot]
benchmarks — 13a4719a Deployed Jun 4, 2026 by Gajesh2007 via E2E Benchmarks #552
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant