Skip to content

fix(coordinator): cap per-box concurrency at quality_concurrency; keep dedicated pool warm - #439

Merged
Gajesh2007 merged 3 commits into
masterfrom
feat/gemma-loadbalance-quality-cap
Jun 21, 2026
Merged

Gajesh2007 merged 3 commits into
masterfrom
feat/gemma-loadbalance-quality-cap

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 21, 2026 •

Copy link
Copy Markdown
Member

Problem

The Gemma dedicated pool (PR #434 isolated Gemma-4 onto dedicated boxes — isolation works) is collapsing under load. Live routing telemetry (/v1/admin/routes, 4,923 Gemma reqs / 30 min):

  • ~80% of requests fail: 53% cancelled, 27% error, ~15% success.

  • Success rate vs the box's in-flight load at dispatch:

    box load when dispatched requests success
    0 (idle) 968 47%
    10–19 2,046 4%
    20+ 1,222 3%
  • 66% of traffic lands on boxes already running ≥10 concurrent; median served decode 5 tok/s. Meanwhile ~48 cold dedicated boxes sit idle.

Root cause (universal latent flaw)

The per-provider concurrency cap is a flat 24 (maxConcurrencyForModelLocked fallback for token-budget providers). It's a hard-coded guess at "how many concurrent decodes before per-request TPS collapses" — but a 26B model at ~23 tok/s solo only sustains ~2 concurrent at the 15 tok/s quality floor. quality_concurrency IS computed (warm-pool planning) but never enforced at admission. The 15 tok/s guard that should stop this is non-binding: the decode-floor preference is soft ("never fails closed"), and TTFT_HARD_REJECT gates first-token latency, not sustained decode.

  • gpt-oss doesn't trigger it: fast (~57 tok/s → real qc 7, far below 24) AND 4% utilized. The bug is universal; Gemma just exposes it.
  • Cold dedicated boxes are unreachable on demand: a cold box's ~30s model-load TTFT exceeds the ~5s ceiling, so it's always TTFT-rejected — and nothing was warming the pool.
  • The "~2.6 tok/s solo" the warm-pool used is the degraded under-load rate (a feedback loop: overload → observed EWMA collapses → qc computed as 1 → pool looks 350% over capacity). True single-stream is ~23 tok/s (registration benchmark; 16–28 range).

Before → After

flowchart TD
  subgraph Before
    A1[Gemma request] --> A2{box has headroom?<br/>cap = flat 24}
    A2 -->|yes, always<br/>token budget 0.4%| A3[pile onto warm box<br/>→ 10-23 concurrent]
    A3 --> A4[decode collapses ~5 tok/s<br/>→ cancel / error]
    A5[48 cold boxes] -.30s TTFT > 5s ceiling.-> A6[never selected,<br/>never warmed → idle]
  end
Loading
flowchart TD
  subgraph After
    B1[Gemma request] --> B2{box at quality cap?<br/>cap = quality_concurrency x overcommit<br/>from STATIC tps → Gemma 2}
    B2 -->|under cap| B3[admit → spread across boxes]
    B2 -->|all warm boxes at cap| B4[fast-429 to OpenRouter]
    B5[warm-pool: keep WHOLE dedicated<br/>pool warm] --> B6[48 idle boxes enter service]
  end
Loading

The fix (coordinator-only; default-on; env-tunable)

  1. Universal per-box cap = min(reported_cap, quality_concurrency × overcommit), computed from each provider's static single-stream decode rate (resolvedDecodeTPS), not the observed-under-load EWMA (which would inherit the feedback loop and force cap=1). Slow models capped tight (Gemma→2); fast/over-provisioned models effectively unchanged (gpt-oss→20, ≤ the old 24, far above its load). A provider-reported per-slot MaxConcurrency still binds when it's tighter. Hooked into the single shared admission gate (snap.hasHeadroom + the preflight), so routing and the 429-shed decision stay consistent.
  2. Keep the whole dedicated pool warm: for dedicated models the warm-pool target = warm + eligibleCold (the entire eligible pool), so idle dedicated boxes are proactively warmed into service. Adds per-reason EligibleCold disqualifier instrumentation to surface why cold boxes aren't warmable.
  3. Disable cache-affinity pinning for dedicated models (concurrency-bound, not prompt-cache-bound) so it can't reintroduce concentration.

Knobs (live env, no rebuild): EIGENINFERENCE_QUALITY_CONCURRENCY_CAP (default on), EIGENINFERENCE_QUALITY_CONCURRENCY_OVERCOMMIT (default 2.0 → Gemma 2/box; set 1.0 for the strict 15-tok/s batch, higher for throughput). Reuses the warm-pool DECODE_FLOOR_TPS (15) and FALLBACK_QUALITY_CONCURRENCY.

Default off in registry.New, so existing unit tests and the e2e testbed are unaffected; only the coordinator entrypoint turns it on.

Tests

  • concurrency_cap_test.go: cap reads STATIC (not observed) TPS — the regression that matters; scales with model speed (slow→2, fast→20); min(reported, quality) both directions; disabled→flat-24; spread + shed through the real ReserveProvider path; dedicated warm-target = whole pool.
  • Full go test ./registry/... ./api/... green; go build, gofmt, go vet, -race, and the Linux/amd64 (EigenCloud) cross-build all pass.

Verify after deploy (read-only)

/v1/admin/routes: expect backend_running-at-dispatch ≤ cap, cancel rate to fall from 53%, running_providers to climb toward the pool size, success rate up from ~15%.

Coordinator-only. Deploy is human-only (EigenCloud prod / GCP dev) — this PR prepares the code; it does not deploy.

🤖 Generated with Claude Code


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

…p dedicated pool warm

Gemma's dedicated pool was collapsing under load: ~80% of requests failed
(53% cancelled, 27% error, telemetry over 30m) because the per-provider
concurrency cap is a flat 24 while a 26B model only sustains ~2 concurrent
at the 15 tok/s quality bar. Routing piled 10-23 concurrent onto a few warm
boxes (decode collapsed to ~5 tok/s) while ~48 cold dedicated boxes sat idle:
a cold box's ~30s model-load TTFT exceeds the 5s ceiling, so it is never
routable on demand, and nothing was warming it.

- Universal per-box cap = quality_concurrency x overcommit, computed from the
  STATIC single-stream decode rate (not the observed-under-load EWMA, which
  collapses under the very overload the cap prevents and would force cap=1).
  Slow models capped tight (Gemma->2); fast/over-provisioned models effectively
  unchanged (gpt-oss->20). Default on; EIGENINFERENCE_QUALITY_CONCURRENCY_CAP /
  _OVERCOMMIT (default 2.0). A provider-reported per-slot MaxConcurrency is
  honored over the computed cap.
- Dedicated pools (e.g. Gemma) keep the WHOLE eligible pool warm so idle boxes
  enter service, with per-reason EligibleCold disqualifier instrumentation.
- Disable cache-affinity pinning for dedicated models (concurrency-bound, not
  prompt-cache-bound) so it cannot reintroduce concentration.

Coordinator-only. Cap defaults off in registry.New, so existing unit tests and
the e2e testbed are unaffected.
@vercel

vercel Bot commented Jun 21, 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 21, 2026 4:15am
d-inference-console-ui-dev Ready Ready Preview Jun 21, 2026 4:15am
d-inference-landing Ready Ready Preview Jun 21, 2026 4:15am

Request Review

@github-actions

github-actions Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces a quality-concurrency admission cap that is a scheduling/capacity change with no direct security impact; all threat model postures are neutral.


Trust Boundaries Touched

  • TB-002 — Coordinator → Provider WebSocket (registry routing/preflight paths)
  • TB-001 — Consumer → Coordinator API (indirectly: ModelCapacitySnapshot feeds upstream routing decisions that affect 429 behaviour)

Threat Assessment

Threat File(s) Status Notes
T-034 (APNs code-identity gate) registry/registry.go:4628 ℹ️ Neutral hasConcurrencyHeadroomForModelCapResolvedLocked replaces hasConcurrencyHeadroomForModelLocked on the capacity snapshot path only. The CodeAttested gate and providerSupportsPrivateTextLocked chokepoint are untouched by this diff.
T-038 (slow-header / HTTP server config) cmd/coordinator/main.go ℹ️ Neutral The new SetQualityConcurrencyCap block is inserted well before server startup; no http.Server fields are modified. ReadHeaderTimeout and MaxHeaderBytes are unaffected.
T-032 (Solana mnemonic) cmd/coordinator/main.go ℹ️ Neutral New logging statement at line ~200 logs only enabled, overcommit, decode_floor_tps — all numeric config values. No secrets or env vars are logged.
T-041 (profile-signing identity) cmd/coordinator/main.go ℹ️ Neutral Insertion point is in the registry-configuration block, not the profilesign or KMS loading path. No change to P12 handling.

New Attack Surface

None introduced. The cap values (QualityCap.Enabled, QualityCap.Overcommit, WarmPool.DecodeFloorTPS, WarmPool.FallbackQualityConcurrency) originate from the coordinator's own config struct, not from any provider- or consumer-supplied input. They are set once at startup and read under r.mu on hot paths — no new external-input trust boundary is opened.

One minor observation worth a quick code-review glance (not a new threat, existing limitation):

registry.go:4628 — ModelCapacitySnapshot now calls hasConcurrencyHeadroomForModelCapResolvedLocked which presumably reads qualityCapEnabled/Overcommit fields set by SetQualityConcurrencyCap. Confirm those fields are initialised before ModelCapacitySnapshot can be called (i.e., SetQualityConcurrencyCap is always invoked before the HTTP server starts accepting requests). The insertion order in main.go (cap set → ConfigureCacheAffinity → server start) appears correct, but if the five uncovered files (concurrency_cap.go, config.go, scheduler.go, warm_pool_controller.go, concurrency_cap_test.go) expose a reset or re-init path at runtime, a TOCTOU on those fields under concurrent routing decisions should be verified. This is a correctness concern rather than a security boundary crossing, since all values are coordinator-internal.


Open Findings Resolved

None — this PR does not address any SEC-* finding.


🔐 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

Here are some automated review suggestions for this pull request.

Reviewed commit: 0665ff955c

ℹ️ 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 thread coordinator/registry/scheduler.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
…pacity feed, demand-gated dedicated warming

Codex review on #439 (1 P1, 2 P2), all valid:

- P1: Swift providers don't report decode_tps, so resolvedDecodeTPS falls back to
  sqrt(memory_bandwidth) — a model-agnostic hardware proxy that under-estimates fast
  models (~57 tok/s gpt-oss reads as ~28). Hard-capping a fast model from it could
  shed healthy traffic. Now the bandwidth fallback only caps DEDICATED models
  (known-slow, urgently need it); a non-dedicated model without a real benchmark
  keeps the flat cap until its provider reports decode_tps.
- P2: ModelCapacitySnapshot (/v1/models[/capacity]) used the flat-24 headroom, so a
  capped Gemma box was advertised routable up to 24 and upstream routers kept sending
  requests this path 429s. Now uses the same quality-capped headroom as routing.
- P2: the dedicated whole-pool warm target is now gated on per-build demand, so a box
  advertising multiple matching builds (e.g. desired+previous during an alias
  migration) doesn't force-warm every matching build across the pool — only the one
  receiving traffic.

Tests: added the fallback-rate-only-caps-dedicated regression; warm-target test now
covers demand-gated vs idle. Full go test ./registry/... ./api/... green.
@blacksmith-sh

blacksmith-sh Bot commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

Test View Logs
github.com/eigeninference/d-inference/e2e/TestProfile_SingleProviderNonStreaming View Logs

Fix with Codesmith
Need help on this PR? Tag /codesmith with what you need.

@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

Here are some automated review suggestions for this pull request.

Reviewed commit: e34357a1c9

ℹ️ 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 thread coordinator/registry/scheduler.go Resolved
Codex follow-up review (P2): the cap was applied when building the selection
snapshot and in the preflight, but ReserveProviderEx's final admit re-check
(providerCanAdmitLockedEx) still used the legacy flat-cap headroom. If a heartbeat
bumped NumRunning between snapshot and reservation, a box that just reached its
quality cap could be over-admitted via the re-check. Now the re-check uses the same
quality-capped headroom. Added TestQualityCapAppliedAtAdmitRecheck.

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 4 finding(s) (3 blocking)

  • 🟡 [MEDIUM] coordinator/registry/concurrency_cap.go:89-92 — Nested mutex locks in hasConcurrencyHeadroomForModelCapLocked could cause deadlock
    • Suggestion: Document lock ordering requirements or refactor to avoid nested locking patterns
  • 🔵 [INFO] coordinator/registry/scheduler.go:908 — resolvedDecodeTPS called multiple times in hot path
    • Suggestion: Cache the result of resolvedDecodeTPS(p) in a local variable to avoid recomputation
  • 🟡 [MEDIUM] coordinator/registry/warm_pool_controller.go:556-577 — Map allocations in loop without pre-sizing
    • Suggestion: Pre-allocate maps with estimated capacity based on provider count to reduce allocations
  • 🟡 [MEDIUM] coordinator/registry/scheduler.go:1658 — resolvedDecodeTPS called again in quickCapacityCheck
    • Suggestion: Cache resolvedDecodeTPS result to avoid redundant computation in tight loop

Type_diligence — 3 finding(s) (3 blocking)

  • 🟡 [MEDIUM] coordinator/registry/concurrency_cap.go:55 — Missing type assertion check for dedicated model pattern lookup
    • Suggestion: Add ok check: if _, dedicated := r.dedicatedPatternForLocked(model); !dedicated { ... } should verify the second return value is used safely
  • 🟡 [MEDIUM] coordinator/registry/concurrency_cap_test.go:74 — Missing type assertion check for dedicated model pattern lookup in test
    • Suggestion: Add ok check: if _, dedicated := r.dedicatedPatternForLocked(model); !dedicated { ... } should verify the second return value is used safely
  • 🟡 [MEDIUM] coordinator/registry/scheduler.go:433 — Missing type assertion check for dedicated model pattern lookup
    • Suggestion: Add ok check: if _, dedicated := r.dedicatedPatternForLocked(model); !dedicated { ... } should verify the second return value is used safely

Additive_complexity — 6 finding(s) (3 blocking)

  • 🟡 [MEDIUM] coordinator/registry/concurrency_cap.go:1-103 — New file adds complex quality-concurrency cap system when simpler per-model configuration could suffice
    • Suggestion: Consider if this could be simplified to a per-model concurrency map in config rather than dynamic calculation based on decode rates and quality floors
  • 🟡 [MEDIUM] coordinator/registry/concurrency_cap.go:55-82 — effectiveMaxConcurrencyForModelLocked duplicates quality concurrency calculation from warm_pool_target.go
    • Suggestion: Extract shared qualityConcurrency calculation to a common helper function to avoid maintaining the same math in multiple places
  • 🔵 [INFO] coordinator/registry/concurrency_cap_test.go:1-265 — Test file creates many test helpers that could be simplified
    • Suggestion: Consolidate budgetSlot, effCap, and mkFallback helpers into fewer, more focused test utilities
  • 🔵 [INFO] coordinator/registry/config.go:25-41 — QualityCapConfig adds new configuration layer when existing WarmPoolConfig already has similar parameters
    • Suggestion: Consider merging quality cap settings into existing WarmPoolConfig to reduce configuration surface area
  • 🟡 [MEDIUM] coordinator/registry/warm_pool_controller.go:555-635 — warmColdReason enum and conversion logic adds significant complexity for diagnostic logging
    • Suggestion: Consider if simple error strings would suffice instead of typed reasons and conversion maps, or if this diagnostic detail is truly necessary
  • 🔵 [INFO] coordinator/registry/scheduler.go:427-435 — Cache affinity logic embedded in selection scan adds model-specific routing logic
    • Suggestion: Move dedicated model cache affinity exclusion to a separate method or configuration to keep selection logic cleaner

13 finding(s) total, 9 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — ec22ec63 Deployed Jun 21, 2026 by vercel[bot]
Preview – d-inference — ec22ec63 Deployed Jun 21, 2026 by vercel[bot]
Preview – d-inference-landing — ec22ec63 Deployed Jun 21, 2026 by vercel[bot]
benchmarks — ec22ec63 Deployed Jun 21, 2026 by Gajesh2007 via E2E Benchmarks #1332
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.

2 participants