Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 85 additions & 3 deletions coordinator/api/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -2036,10 +2036,16 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
// it. The dispatch/queue path still returns a 429 when the queue is
// full or the wait times out (true saturation). The reservation is
// kept for dispatch.
if s.queueBeforeShedEnabled() {
// Dedicated-family models (e.g. Gemma 4) bypass queue-before-shed when
// their dedicated boxes are saturated: holding an OpenRouter request in
// the 120s queue would blow its TTFT SLA, so shed immediately with a
// 429 + Retry-After for a clean failover rather than waiting on a
// dedicated slot that may not free in time.
if s.queueBeforeShedEnabled() && !s.registry.IsDedicatedModel(model) {
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:capacity_queue_spill"})
} else {
// Legacy fast-shed: immediate 429.
// Fast-shed: immediate 429 (always for dedicated models; for every
// model when queue-before-shed is disabled).
retryAfter := s.estimateRetryAfter(model)
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
refundReservation()
Expand Down Expand Up @@ -2096,6 +2102,44 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
if s.coldDispatchEnabled() && s.coldSpillAvailable(model, registry.RequestTraits{HasTools: hasTools}, requiresVision, allowedProviderSerials) {
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:cold_dispatch_spill"})
// Fall through to dispatch+queue; reservation kept.
} else if s.registry.IsDedicatedModel(model) && s.registry.HasProviderForModel(model, allowedProviderSerials...) {
Comment thread
Gajesh2007 marked this conversation as resolved.
Resolved
// Dedicated-box model (e.g. Gemma 4): the fleet DOES serve this
// model, but no provider DEDICATED to it can take the request right
// now — either none are dedicated, or the dedicated ones are busy/
// cooling. That is transient capacity pressure, not an absent model,
// so shed to OpenRouter as a 429 + Retry-After (clean failover)
// rather than a 503 (which can get the endpoint marked unhealthy /
// deranked). Mirrors the capacity_429 path above.
retryAfter := s.estimateRetryAfter(model)
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
refundReservation()
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:dedicated_capacity_429"})
s.recordRejection(rejectionInfo{
r: r,
stage: "preflight_capacity",
reasonCode: "machine_busy",
httpStatus: http.StatusTooManyRequests,
keyID: keyIDFromContext(r.Context()),
consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())),
requestedModel: publicModel,
resolvedModel: model,
stream: stream,
estimatedPromptTokens: estimatedPromptTokens,
requestedMaxTokens: requestedMaxTokens,
requiresVision: requiresVision,
hasTools: hasTools,
retryAfterMs: retryAfter * 1000,
params: rejectionSamplingParams(parsed),
servabilityComputed: true,
candidateCount: candidateCount,
capacityRejections: capacityRejections,
modelTooLargeRejections: modelTooLarge,
bestTTFTMs: ttftMsForRejection(bestTTFT, hasTTFT),
})
writeJSON(w, http.StatusTooManyRequests, errorResponse("rate_limit_exceeded",
fmt.Sprintf("no provider dedicated to model %q is available right now — retry after %ds", publicModel, retryAfter),
withCode("rate_limit_exceeded")))
Comment on lines +2105 to +2141

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.

🔵 [INFO] ⚡ Duplicate rejection recording and response writing logic

💡 Suggestion: Extract common rejection handling into a shared function to avoid code duplication between handleChatCompletions and handleGenericInference

📊 Score: 2×3 = 6 · Category: repeated_work

Comment on lines +2105 to +2141

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.

🟡 [MEDIUM] 🧩 Identical 37-line rejection handling block duplicated between chat completions and generic inference

💡 Suggestion: Extract the dedicated model rejection logic into a shared helper method like handleDedicatedModelRejection(w, r, model, publicModel, retryAfter, refundReservation)

📊 Score: 3×4 = 12 · Category: duplicate logic

return
} else {
// None of these clear by a slot freeing up, so queueing for up to
// 120s only adds misleading latency before the same error. Fail
Expand Down Expand Up @@ -4832,7 +4876,10 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request,
// capacity right now. Fall through to the dispatch+queue path so a slot
// freeing — or a cold load completing — within the queue window serves
// it; the queue path still 429s on a full queue or wait timeout.
if s.queueBeforeShedEnabled() {
// Dedicated-family models (e.g. Gemma 4) bypass queue-before-shed when
// saturated — fast-429 for a clean OpenRouter failover instead of a
// 120s queue that would blow the TTFT SLA. Mirrors handleChatCompletions.
if s.queueBeforeShedEnabled() && !s.registry.IsDedicatedModel(model) {
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:capacity_queue_spill"})
} else {
retryAfter := s.estimateRetryAfter(model)
Expand Down Expand Up @@ -4882,6 +4929,41 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request,
if s.coldDispatchEnabled() && s.coldSpillAvailable(model, registry.RequestTraits{HasTools: hasTools}, requiresVision, allowedProviderSerials) {
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:cold_dispatch_spill"})
// Fall through to dispatch+queue; reservation kept.
} else if s.registry.IsDedicatedModel(model) && s.registry.HasProviderForModel(model, allowedProviderSerials...) {
// Dedicated-box model served by the fleet but no dedicated box is
// available right now: transient capacity, so shed with 429 +
// Retry-After (not 503). Mirrors the chat-completions preflight so
// /v1/completions and /v1/messages classify the shed identically.
retryAfter := s.estimateRetryAfter(model)
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
refundReservation()
s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:dedicated_capacity_429"})
s.recordRejection(rejectionInfo{
r: r,
stage: "preflight_capacity",
reasonCode: "machine_busy",
httpStatus: http.StatusTooManyRequests,
keyID: keyIDFromContext(r.Context()),
consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())),
requestedModel: publicModel,
resolvedModel: model,
stream: stream,
estimatedPromptTokens: estimatedPromptTokens,
requestedMaxTokens: requestedMaxTokens,
requiresVision: requiresVision,
hasTools: hasTools,
retryAfterMs: retryAfter * 1000,
params: rejectionSamplingParams(parsed),
servabilityComputed: true,
candidateCount: candidateCount,
capacityRejections: capacityRejections,
modelTooLargeRejections: modelTooLarge,
bestTTFTMs: ttftMsForRejection(bestTTFT, hasTTFT),
})
writeJSON(w, http.StatusTooManyRequests, errorResponse("rate_limit_exceeded",
fmt.Sprintf("no provider dedicated to model %q is available right now — retry after %ds", publicModel, retryAfter),
withCode("rate_limit_exceeded")))
return
} else {
// Queueing cannot help — fail fast with a retryable 503 instead of
Comment on lines +4932 to 4968

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.

🔵 [INFO] ⚡ Duplicate rejection recording and response writing logic

💡 Suggestion: Extract common rejection handling into a shared function to avoid code duplication between handleChatCompletions and handleGenericInference

📊 Score: 2×3 = 6 · Category: repeated_work

Comment on lines +4932 to 4968

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.

🟡 [MEDIUM] 🧩 Second instance of identical 37-line rejection handling block

💡 Suggestion: Use the same extracted helper method as suggested for the first instance

📊 Score: 3×4 = 12 · Category: duplicate logic

// a 120s queue. Mirrors the chat-completions preflight.
Expand Down
168 changes: 168 additions & 0 deletions coordinator/api/dedicated_models_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
package api

import (
"context"
"io"
"net/http"
"strings"
"testing"
"time"

"github.com/eigeninference/d-inference/coordinator/protocol"
"nhooyr.io/websocket"
)

// chatRequestWithHeaders posts a chat completion and returns status, body, and
// the Retry-After header (adaptiveChatRequest drops headers).
func chatRequestWithHeaders(ctx context.Context, baseURL, model string) (int, string, string, error) {
body := `{"model":"` + model + `","messages":[{"role":"user","content":"hello"}],"stream":true,"max_tokens":64}`
req, err := http.NewRequestWithContext(ctx, http.MethodPost, baseURL+"/v1/chat/completions", strings.NewReader(body))
if err != nil {
return 0, "", "", err
}
req.Header.Set("Authorization", "Bearer test-key")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return 0, "", "", err
}
defer resp.Body.Close()
data, _ := io.ReadAll(resp.Body)
return resp.StatusCode, string(data), resp.Header.Get("Retry-After"), nil
}

// TestDedicatedModelShed429NotServiceUnavailable verifies that when a dedicated
// model (gemma-4) is served by the fleet but no DEDICATED box can take the
// request (only a mixed gemma-4+qwen box exists), the coordinator sheds to
// OpenRouter with a transient 429 + Retry-After — NOT a 503. A truly-absent,
// non-dedicated model still returns 503.
func TestDedicatedModelShed429NotServiceUnavailable(t *testing.T) {
ts, reg := setupAdaptiveCapacityIntegration(t)
defer ts.Close()
reg.SetDedicatedModels([]string{"gemma-4"})
// Keep cold-dispatch from spilling to the queue; pin the preflight shed path.
t.Setenv(envColdDispatch, "false")

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

gemma := "gemma-4-26b-test"
qwen := "qwen-3-test"
// A single MIXED provider: advertises gemma-4 AND qwen -> not dedicated.
conn := connectProvider(t, ctx, ts.URL, []protocol.ModelInfo{
{ID: gemma, ModelType: "chat", Quantization: "4bit"},
{ID: qwen, ModelType: "chat", Quantization: "4bit"},
}, testPublicKeyB64())
defer conn.Close(websocket.StatusNormalClosure, "done")
p := markOnlyProviderRoutable(t, reg)

writeAdaptiveHeartbeat(t, ctx, conn, gemma, &protocol.BackendCapacity{
TotalMemoryGB: 64,
Slots: []protocol.BackendSlotCapacity{
{Model: gemma, State: "running", MaxConcurrency: 8, ActiveTokenBudgetMax: 32_768},
},
})
waitForAdaptiveCondition(t, time.Second, func() bool {
p.Mu().Lock()
defer p.Mu().Unlock()
return p.BackendCapacity != nil
})

// Gemma-4 to a mixed-only fleet -> transient 429 + Retry-After (not 503).
status, body, retryAfter, err := chatRequestWithHeaders(ctx, ts.URL, gemma)
if err != nil {
t.Fatalf("gemma request: %v", err)
}
if status != http.StatusTooManyRequests {
t.Fatalf("gemma status = %d, want 429; body = %s", status, body)
}
if !strings.Contains(body, "rate_limit_exceeded") {
t.Fatalf("gemma body = %s, want rate_limit_exceeded", body)
}
if retryAfter == "" {
t.Fatalf("gemma 429 missing Retry-After header")
}

// Control: a non-dedicated model absent from the fleet still 503s.
statusC, bodyC, _, err := chatRequestWithHeaders(ctx, ts.URL, "totally-absent-model")
if err != nil {
t.Fatalf("control request: %v", err)
}
if statusC != http.StatusServiceUnavailable {
t.Fatalf("control status = %d, want 503; body = %s", statusC, bodyC)
}
if !strings.Contains(bodyC, "model_unavailable") {
t.Fatalf("control body = %s, want model_unavailable", bodyC)
}

// The legacy /v1/completions endpoint (handleGenericInference) must classify
// the dedicated shed identically — 429, not 503.
cbody := `{"model":"` + gemma + `","prompt":"hello","stream":true,"max_tokens":64}`
req, err := http.NewRequestWithContext(ctx, http.MethodPost, ts.URL+"/v1/completions", strings.NewReader(cbody))
if err != nil {
t.Fatalf("completions request build: %v", err)
}
req.Header.Set("Authorization", "Bearer test-key")
req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("completions request: %v", err)
}
defer resp.Body.Close()
cdata, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("/v1/completions status = %d, want 429; body = %s", resp.StatusCode, string(cdata))
}
if resp.Header.Get("Retry-After") == "" {
t.Fatalf("/v1/completions 429 missing Retry-After header")
}
}

// TestDedicatedSaturatedBoxFast429 verifies that when the dedicated box for a
// Gemma 4 request EXISTS but is at capacity, the request is fast-429'd
// immediately instead of sitting in the 120s queue-before-shed window (which is
// left at its default ON) — so OpenRouter fails over within its TTFT SLA.
func TestDedicatedSaturatedBoxFast429(t *testing.T) {
ts, reg := setupAdaptiveCapacityIntegration(t)
defer ts.Close()
reg.SetDedicatedModels([]string{"gemma-4"})
// queue-before-shed left at default (ON): dedicated models must still fast-429.

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

gemma := "gemma-4-26b-test"
// A single DEDICATED gemma-4 box with its token budget nearly exhausted.
conn := connectProvider(t, ctx, ts.URL, []protocol.ModelInfo{
{ID: gemma, ModelType: "chat", Quantization: "4bit"},
}, testPublicKeyB64())
defer conn.Close(websocket.StatusNormalClosure, "done")
p := markOnlyProviderRoutable(t, reg)

writeAdaptiveHeartbeat(t, ctx, conn, gemma, &protocol.BackendCapacity{
TotalMemoryGB: 64,
Slots: []protocol.BackendSlotCapacity{{
Model: gemma,
State: "running",
MaxConcurrency: 8,
ActiveTokenBudgetUsed: 950,
ActiveTokenBudgetMax: 1_000,
}},
})
waitForAdaptiveCondition(t, time.Second, func() bool {
p.Mu().Lock()
defer p.Mu().Unlock()
return p.BackendCapacity != nil && p.BackendCapacity.Slots[0].ActiveTokenBudgetMax == 1_000
})

status, body, retryAfter, err := chatRequestWithHeaders(ctx, ts.URL, gemma)
if err != nil {
t.Fatalf("request: %v (a hang here means the dedicated request was queued instead of fast-429'd)", err)
}
if status != http.StatusTooManyRequests {
t.Fatalf("status = %d, want 429 (dedicated boxes bypass queue-before-shed when saturated); body = %s", status, body)
}
if retryAfter == "" {
t.Fatalf("saturated dedicated 429 missing Retry-After header")
}
}
24 changes: 24 additions & 0 deletions coordinator/cmd/coordinator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,30 @@ func main() {
reg.MinTrustLevel = registry.TrustLevel(cfg.RegistryCfg.MinTrustLevel)
logger.Info("minimum trust level override", "level", cfg.RegistryCfg.MinTrustLevel)
}

// Dedicated-box routing: model families (matched as case-insensitive
// substrings of the resolved build id) that may ONLY route to providers
// whose entire advertised catalog is that family — isolating an unstable
// model (e.g. Gemma 4) onto dedicated machines so it never contends with
// other models. Default: "gemma-4". Override with a comma-separated list, or
// set the value to empty / "none" to disable. With no dedicated box
// available, a request for such a model sheds to OpenRouter as a transient
// 429 (not 503).
dedicatedModels := []string{"gemma-4"}
if v, ok := os.LookupEnv("EIGENINFERENCE_DEDICATED_MODELS"); ok {
if strings.EqualFold(strings.TrimSpace(v), "none") {
dedicatedModels = nil
} else {
dedicatedModels = registry.ParseDedicatedModels(v)
}
}
reg.SetDedicatedModels(dedicatedModels)
if len(dedicatedModels) > 0 {
logger.Info("dedicated-model routing ENABLED", "patterns", strings.Join(dedicatedModels, ","))
} else {
logger.Info("dedicated-model routing disabled")
}

reg.ConfigureCacheAffinity(cfg.RegistryCfg.CacheAffinity)
cacheAffinityCfg := reg.CacheAffinityConfigSnapshot()
logger.Info("cache affinity configured", "ttl", cacheAffinityCfg.TTL.String(), "bonus_ms", cacheAffinityCfg.BonusMs, "enabled", cacheAffinityCfg.BonusMs > 0)
Expand Down
Loading
Loading