diff --git a/coordinator/api/admin_reject_models.go b/coordinator/api/admin_reject_models.go new file mode 100644 index 0000000000..9045041c94 --- /dev/null +++ b/coordinator/api/admin_reject_models.go @@ -0,0 +1,149 @@ +package api + +import ( + "fmt" + "net/http" + "strings" + "unicode" + "unicode/utf8" +) + +// Runtime shed-list ops. +// +// EIGENINFERENCE_REJECT_MODELS seeds the per-model reject set at startup +// (cmd/coordinator/main.go); before these endpoints existed, every shed flip +// (for example taking Gemma out of — or back into — rotation) required a +// coordinator restart, and each restart wipes the in-memory TTFT calibrator, +// TPS registries, breakers, and warm-pool state mid-recovery (1,589 provider +// sessions died to coordinator restarts in one 48h window). These endpoints +// mutate the set live: +// +// GET /v1/admin/reject-models -> {"models": ["..."]} (current set, sorted) +// PUT /v1/admin/reject-models <- {"models": ["..."]} (FULL replacement; +// "models":[] = clear; a MISSING or null +// "models" key is a 400, not a clear) +// +// Auth mirrors POST /v1/admin/drain (the other runtime-ops toggle): the routes +// are wrapped in requireAuth (which parses a Privy JWT into context and accepts +// the admin key as a pseudo-account — no credentials at all is a 401), and the +// handlers authorize via isAdminAuthorized (admin key OR Privy admin; anything +// else is a 403). + +// rejectModelsResponse is the wire shape of GET /v1/admin/reject-models. +type rejectModelsResponse struct { + Models []string `json:"models"` +} + +// rejectModelsReplaceResponse is the wire shape of PUT /v1/admin/reject-models: +// the installed set plus the set it replaced, both sorted. +type rejectModelsReplaceResponse struct { + Models []string `json:"models"` + Previous []string `json:"previous"` +} + +// Bounds on a PUT /v1/admin/reject-models payload. The reject set only ever +// holds model IDs from a catalog of a few dozen entries, and real IDs (e.g. +// "mlx-community/Qwen3.5-0.8B-MLX-4bit") are well under 100 bytes, so these +// are generous. They exist so a fat-fingered or hostile admin-key holder +// can't install megabyte-long or control-character-laden strings that would +// then be echoed into logs and JSON responses. +const ( + maxRejectModelsCount = 128 + maxRejectModelNameLen = 256 +) + +// validateRejectModelName rejects entries that could garble logs or responses: +// over-long names, invalid UTF-8, and control characters. '/' stays legal — +// real model IDs contain it. The strings are only ever used as map keys, +// slog values, and JSON array elements (never filesystem paths or commands), +// so this is defense-in-depth for the admin surface, not an injection fix. +func validateRejectModelName(model string) error { + if len(model) > maxRejectModelNameLen { + return fmt.Errorf("model name exceeds %d bytes", maxRejectModelNameLen) + } + if !utf8.ValidString(model) { + return fmt.Errorf("model name is not valid UTF-8") + } + for _, r := range model { + if unicode.IsControl(r) { + return fmt.Errorf("model name contains a control character") + } + } + return nil +} + +// handleAdminGetRejectModels serves GET /v1/admin/reject-models: the current +// reject set, sorted. Admin-gated and read-only. +func (s *Server) handleAdminGetRejectModels(w http.ResponseWriter, r *http.Request) { + if !s.isAdminAuthorized(w, r) { + return + } + writeJSON(w, http.StatusOK, rejectModelsResponse{Models: s.RejectModels()}) +} + +// handleAdminPutRejectModels serves PUT /v1/admin/reject-models: full +// replacement of the reject set. An explicit empty list ({"models":[]}) clears +// the set; a MISSING or null "models" key is a 400 (see below). Every change is +// logged loudly (old set -> new set) — this is the same class of operator +// action as flipping EIGENINFERENCE_REJECT_MODELS, minus the restart. +func (s *Server) handleAdminPutRejectModels(w http.ResponseWriter, r *http.Request) { + if !s.isAdminAuthorized(w, r) { + return + } + // A pointer so a MISSING or null "models" key (nil) is distinguishable from + // an explicit empty list (non-nil, len 0). Clearing the shed list is a + // deliberate operation — {"models":[]} — because clearing it mid-incident + // re-enables a model that was intentionally pulled from rotation. A body that + // forgot the key ({}), typoed it ({"model":[...]} — decodeCappedJSON does not + // disallow unknown fields), or sent JSON null ({"models":null}) all yield nil + // here and MUST NOT silently clear the live set; they are rejected before + // ReplaceRejectModels is called. + var req struct { + Models *[]string `json:"models"` + } + if !decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) { + return + } + if req.Models == nil { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", + `missing required field "models" (send {"models":[]} to clear the shed list)`)) + return + } + models := *req.Models + if len(models) > maxRejectModelsCount { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", + fmt.Sprintf("too many models: %d (max %d)", len(models), maxRejectModelsCount))) + return + } + // Validate everything before touching the live set: a bad entry must not + // leave a half-applied replacement. + set := make(map[string]bool, len(models)) + for i, model := range models { + model = strings.TrimSpace(model) + if model == "" { + continue // blank/whitespace-only entries are dropped, not errors + } + if err := validateRejectModelName(model); err != nil { + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", + fmt.Sprintf("models[%d]: %v", i, err))) + return + } + set[model] = true + } + previous, current, failedQueued := s.replaceRejectModels(set) + // A runtime shed must take effect on requests ALREADY in the queue, not just + // future admission: fail the queued waiters for every model the new set sheds + // so an operator pulling a model mid-incident isn't undercut by up to a full + // queue window of requests still dispatching to it. Exclusive self-route + // waiters are preserved (they bypass the shed at admission). + s.logger.Warn("model shed set REPLACED via /v1/admin/reject-models (runtime, no restart)", + "old", previous, + "new", current, + "failed_queued", failedQueued, + "remote_addr", r.RemoteAddr, + ) + writeJSON(w, http.StatusOK, rejectModelsReplaceResponse{ + Models: current, + Previous: previous, + }) +} diff --git a/coordinator/api/admin_reject_models_queue_test.go b/coordinator/api/admin_reject_models_queue_test.go new file mode 100644 index 0000000000..c8f2a500b5 --- /dev/null +++ b/coordinator/api/admin_reject_models_queue_test.go @@ -0,0 +1,121 @@ +package api + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "nhooyr.io/websocket" +) + +// TestAdminRejectModelsQueuedHTTPRequestsReturnModelShed exercises both HTTP +// queue consumers end to end. A request already waiting when the operator PUT +// lands must return promptly as model_shed, never masquerade as queue_full or a +// 120-second queue_timeout. +func TestAdminRejectModelsQueuedHTTPRequestsReturnModelShed(t *testing.T) { + for _, tc := range []struct { + name string + path string + body func(string) string + }{ + { + name: "chat_completions", + path: "/v1/chat/completions", + body: func(model string) string { + return `{"model":"` + model + `","messages":[{"role":"user","content":"hello"}],"stream":true,"max_tokens":64}` + }, + }, + { + name: "legacy_completions", + path: "/v1/completions", + body: func(model string) string { + return `{"model":"` + model + `","prompt":"hello","stream":false,"max_tokens":64}` + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + ts, srv := setupAdminRejectModels(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + model := "queued-http-shed-" + tc.name + conn := connectProvider(t, ctx, ts.URL, []protocol.ModelInfo{ + {ID: model, ModelType: "chat", Quantization: "4bit"}, + }, testPublicKeyB64()) + defer conn.Close(websocket.StatusNormalClosure, "done") + p := markOnlyProviderRoutable(t, srv.registry) + p.Mu().Lock() + p.BackendCapacity = &protocol.BackendCapacity{ + TotalMemoryGB: 64, + MaxModelSlots: 3, + Slots: []protocol.BackendSlotCapacity{{ + Model: model, + State: "running", + NumRunning: 1, + MaxConcurrency: 1, + }}, + } + p.Mu().Unlock() + + type result struct { + status int + body string + retryAfter string + err error + } + resultCh := make(chan result, 1) + go func() { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, ts.URL+tc.path, strings.NewReader(tc.body(model))) + if err != nil { + resultCh <- result{err: err} + return + } + req.Header.Set("Authorization", "Bearer test-key") + req.Header.Set("Content-Type", "application/json") + resp, err := http.DefaultClient.Do(req) + if err != nil { + resultCh <- result{err: err} + return + } + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + resultCh <- result{status: resp.StatusCode, body: string(data), retryAfter: resp.Header.Get("Retry-After")} + }() + + deadline := time.Now().Add(3 * time.Second) + for srv.registry.Queue().QueueSize(model) != 1 && time.Now().Before(deadline) { + time.Sleep(10 * time.Millisecond) + } + if got := srv.registry.Queue().QueueSize(model); got != 1 { + t.Fatalf("request never reached queue; depth = %d", got) + } + + status, body := rejectModelsCall(t, ts, http.MethodPut, "admin-secret", `{"models":["`+model+`"]}`) + if status != http.StatusOK { + t.Fatalf("PUT status = %d, want 200; body = %s", status, body) + } + + select { + case got := <-resultCh: + if got.err != nil { + t.Fatalf("inference request: %v", got.err) + } + if got.status != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429; body = %s", got.status, got.body) + } + if !strings.Contains(got.body, "temporarily rate-limited") || strings.Contains(got.body, "queue timeout") { + t.Fatalf("body = %s, want model_shed response and no queue_timeout", got.body) + } + if got.retryAfter == "" { + t.Fatal("model_shed 429 missing Retry-After") + } + case <-time.After(2 * time.Second): + t.Fatal("queued request did not fail promptly after reject-models PUT") + } + }) + } +} diff --git a/coordinator/api/admin_reject_models_test.go b/coordinator/api/admin_reject_models_test.go new file mode 100644 index 0000000000..196025ecf6 --- /dev/null +++ b/coordinator/api/admin_reject_models_test.go @@ -0,0 +1,463 @@ +package api + +import ( + "context" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// Tests for the runtime shed-list admin endpoints (GET/PUT +// /v1/admin/reject-models), through the real HTTP mux per repo policy. + +func setupAdminRejectModels(t *testing.T) (*httptest.Server, *Server) { + t.Helper() + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + // The store admin key doubles as a VALID (non-admin) consumer API key, so + // the 403 leg exercises an authenticated-but-unauthorized caller. + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + reg := registry.New(logger) + srv := NewServer(reg, st, ServerConfig{AdminKey: "admin-secret"}, logger) + ts := httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + return ts, srv +} + +// rejectModelsCall performs a GET/PUT against /v1/admin/reject-models. +func rejectModelsCall(t *testing.T, ts *httptest.Server, method, bearer, body string) (int, string) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + var rdr io.Reader + if body != "" { + rdr = strings.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, ts.URL+"/v1/admin/reject-models", rdr) + if err != nil { + t.Fatalf("build request: %v", err) + } + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("do request: %v", err) + } + defer resp.Body.Close() + data, _ := io.ReadAll(resp.Body) + return resp.StatusCode, string(data) +} + +// TestAdminRejectModelsAuth pins the auth ladder (same pattern as +// /v1/admin/drain): no credentials => 401 from requireAuth; a valid consumer +// key that is not the admin key => 403 from isAdminAuthorized; the admin key +// => 200. +func TestAdminRejectModelsAuth(t *testing.T) { + ts, _ := setupAdminRejectModels(t) + + if status, body := rejectModelsCall(t, ts, http.MethodGet, "", ""); status != http.StatusUnauthorized { + t.Fatalf("no-auth GET status = %d, want 401; body = %s", status, body) + } + if status, body := rejectModelsCall(t, ts, http.MethodPut, "", `{"models":["x"]}`); status != http.StatusUnauthorized { + t.Fatalf("no-auth PUT status = %d, want 401; body = %s", status, body) + } + if status, body := rejectModelsCall(t, ts, http.MethodGet, "test-key", ""); status != http.StatusForbidden { + t.Fatalf("non-admin GET status = %d, want 403; body = %s", status, body) + } + if status, body := rejectModelsCall(t, ts, http.MethodPut, "test-key", `{"models":["x"]}`); status != http.StatusForbidden { + t.Fatalf("non-admin PUT status = %d, want 403; body = %s", status, body) + } + status, body := rejectModelsCall(t, ts, http.MethodGet, "admin-secret", "") + if status != http.StatusOK { + t.Fatalf("admin GET status = %d, want 200; body = %s", status, body) + } + var got struct { + Models []string `json:"models"` + } + if err := json.Unmarshal([]byte(body), &got); err != nil || got.Models == nil || len(got.Models) != 0 { + t.Fatalf("admin GET body = %s, want {\"models\":[]} (never-nil array); err = %v", body, err) + } +} + +// TestAdminRejectModelsReplaceAndLiveFlip covers the full runtime flow: the +// startup-seeded set sheds requests on the real inference path, PUT replaces +// it live (no restart), GET reflects it, the previously shed model flows +// again, the newly shed one 429s, and an empty PUT sheds nothing. +func TestAdminRejectModelsReplaceAndLiveFlip(t *testing.T) { + ts, srv := setupAdminRejectModels(t) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + seeded := "seeded-shed-model" + runtime := "runtime-shed-model" + // Startup env seeding path (cmd/coordinator/main.go calls SetRejectModels). + srv.SetRejectModels(map[string]bool{seeded: true}) + + // The seeded model is shed on the REAL inference path (429, model_shed). + status, body, retryAfter, err := chatRequestWithHeaders(ctx, ts.URL, seeded) + if err != nil { + t.Fatalf("seeded request: %v", err) + } + if status != http.StatusTooManyRequests || !strings.Contains(body, "temporarily rate-limited") { + t.Fatalf("seeded model status/body = %d %s, want shed 429", status, body) + } + if retryAfter == "" { + t.Fatal("shed 429 missing Retry-After") + } + + // PUT replaces the whole set at runtime. + status, body = rejectModelsCall(t, ts, http.MethodPut, "admin-secret", `{"models":["`+runtime+`"," ",""]}`) + if status != http.StatusOK { + t.Fatalf("PUT status = %d, want 200; body = %s", status, body) + } + var put struct { + Models []string `json:"models"` + Previous []string `json:"previous"` + } + if err := json.Unmarshal([]byte(body), &put); err != nil { + t.Fatalf("PUT body = %s: %v", body, err) + } + if len(put.Models) != 1 || put.Models[0] != runtime || len(put.Previous) != 1 || put.Previous[0] != seeded { + t.Fatalf("PUT response = %+v, want models=[%s] previous=[%s]", put, runtime, seeded) + } + + // GET reflects the new set. + if _, body = rejectModelsCall(t, ts, http.MethodGet, "admin-secret", ""); !strings.Contains(body, runtime) || strings.Contains(body, seeded) { + t.Fatalf("GET after PUT = %s, want only %s", body, runtime) + } + + // The flip is LIVE on the inference path: the seeded model is no longer + // shed (it now falls through to the no-provider 503), the runtime one is. + status, body, _, err = chatRequestWithHeaders(ctx, ts.URL, seeded) + if err != nil { + t.Fatalf("unshed request: %v", err) + } + if status != http.StatusServiceUnavailable || !strings.Contains(body, "model_unavailable") { + t.Fatalf("unshed model status/body = %d %s, want no-provider 503 (shed lifted live)", status, body) + } + status, body, _, err = chatRequestWithHeaders(ctx, ts.URL, runtime) + if err != nil { + t.Fatalf("runtime-shed request: %v", err) + } + if status != http.StatusTooManyRequests || !strings.Contains(body, "temporarily rate-limited") { + t.Fatalf("runtime-shed model status/body = %d %s, want shed 429", status, body) + } + + // Empty list = shed nothing. + if status, body = rejectModelsCall(t, ts, http.MethodPut, "admin-secret", `{"models":[]}`); status != http.StatusOK { + t.Fatalf("clearing PUT status = %d, want 200; body = %s", status, body) + } + status, body, _, err = chatRequestWithHeaders(ctx, ts.URL, runtime) + if err != nil { + t.Fatalf("cleared request: %v", err) + } + if status != http.StatusServiceUnavailable { + t.Fatalf("cleared model status = %d, want 503 (shed nothing); body = %s", status, body) + } +} + +// TestAdminRejectModelsWireShape pins the exact JSON keys of both responses so +// the typed response structs can never silently drift from the documented wire +// shape ({"models":[...]} for GET, {"models":[...],"previous":[...]} for PUT). +func TestAdminRejectModelsWireShape(t *testing.T) { + ts, _ := setupAdminRejectModels(t) + + assertKeys := func(body string, want ...string) { + t.Helper() + var raw map[string]json.RawMessage + if err := json.Unmarshal([]byte(body), &raw); err != nil { + t.Fatalf("body %s: %v", body, err) + } + if len(raw) != len(want) { + t.Fatalf("body %s has %d keys, want %v", body, len(raw), want) + } + for _, k := range want { + if _, ok := raw[k]; !ok { + t.Fatalf("body %s missing key %q, want keys %v", body, k, want) + } + } + } + + status, body := rejectModelsCall(t, ts, http.MethodPut, "admin-secret", `{"models":["mlx-community/Qwen3.5-0.8B-MLX-4bit"]}`) + if status != http.StatusOK { + t.Fatalf("PUT status = %d, want 200; body = %s", status, body) + } + assertKeys(body, "models", "previous") + + status, body = rejectModelsCall(t, ts, http.MethodGet, "admin-secret", "") + if status != http.StatusOK { + t.Fatalf("GET status = %d, want 200; body = %s", status, body) + } + assertKeys(body, "models") +} + +// TestAdminRejectModelsValidation drives the PUT input hardening through the +// real HTTP path: bounded count, bounded name length, no control characters, +// '/' explicitly legal (real model IDs contain it), and a rejected payload +// leaves the live set untouched. +func TestAdminRejectModelsValidation(t *testing.T) { + longName := strings.Repeat("a", maxRejectModelNameLen+1) + tooMany := make([]string, maxRejectModelsCount+1) + for i := range tooMany { + tooMany[i] = "m" + } + tooManyBody, _ := json.Marshal(map[string][]string{"models": tooMany}) + + tests := []struct { + name string + body string + wantStatus int + wantSubstr string + }{ + {"slash in model ID is legal", `{"models":["mlx-community/Qwen3.5-0.8B-MLX-4bit"]}`, http.StatusOK, "mlx-community/Qwen3.5-0.8B-MLX-4bit"}, + {"max-length name accepted", `{"models":["` + strings.Repeat("a", maxRejectModelNameLen) + `"]}`, http.StatusOK, ""}, + {"blank entries dropped, not errors", `{"models":[" ",""]}`, http.StatusOK, `"models":[]`}, + {"over-long name rejected", `{"models":["` + longName + `"]}`, http.StatusBadRequest, "exceeds"}, + {"NUL control character rejected", `{"models":["bad\u0000name"]}`, http.StatusBadRequest, "control character"}, + {"newline control character rejected", `{"models":["bad\nname"]}`, http.StatusBadRequest, "control character"}, + {"index reported for bad entry", `{"models":["ok","bad\tname"]}`, http.StatusBadRequest, "models[1]"}, + {"too many entries rejected", string(tooManyBody), http.StatusBadRequest, "too many models"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ts, srv := setupAdminRejectModels(t) + sentinel := "pre-existing-model" + srv.SetRejectModels(map[string]bool{sentinel: true}) + + status, body := rejectModelsCall(t, ts, http.MethodPut, "admin-secret", tc.body) + if status != tc.wantStatus { + t.Fatalf("status = %d, want %d; body = %s", status, tc.wantStatus, body) + } + if tc.wantSubstr != "" && !strings.Contains(body, tc.wantSubstr) { + t.Fatalf("body = %s, want substring %q", body, tc.wantSubstr) + } + got := srv.RejectModels() + if tc.wantStatus == http.StatusBadRequest { + // A rejected payload must not half-apply: the live set is untouched. + if len(got) != 1 || got[0] != sentinel { + t.Fatalf("reject set after failed PUT = %v, want [%s] untouched", got, sentinel) + } + } else if len(got) != 0 && got[0] == sentinel { + t.Fatalf("reject set after successful PUT still holds sentinel: %v", got) + } + }) + } +} + +// TestAdminRejectModelsRequiresModelsKey is the finding-3 regression: clearing +// the shed list is an EXPLICIT operation ({"models":[]}), so a body with a +// missing, null, or typoed "models" key must be a 400 that leaves the live set +// untouched — never a silent clear that re-enables a model pulled from rotation +// during an incident. +func TestAdminRejectModelsRequiresModelsKey(t *testing.T) { + tests := []struct { + name string + body string + wantStatus int + }{ + {"empty object clears nothing (400)", `{}`, http.StatusBadRequest}, + {"null models clears nothing (400)", `{"models":null}`, http.StatusBadRequest}, + {"typoed key clears nothing (400)", `{"model":["x"]}`, http.StatusBadRequest}, + {"explicit empty list clears (200)", `{"models":[]}`, http.StatusOK}, + {"explicit list replaces (200)", `{"models":["replacement"]}`, http.StatusOK}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ts, srv := setupAdminRejectModels(t) + sentinel := "incident-shed-model" + srv.SetRejectModels(map[string]bool{sentinel: true}) + + status, body := rejectModelsCall(t, ts, http.MethodPut, "admin-secret", tc.body) + if status != tc.wantStatus { + t.Fatalf("status = %d, want %d; body = %s", status, tc.wantStatus, body) + } + got := srv.RejectModels() + if tc.wantStatus == http.StatusBadRequest { + if !strings.Contains(body, "models") { + t.Fatalf("400 body = %s, want it to name the missing field", body) + } + // The set the operator installed during the incident must survive + // the malformed request — a silent clear here is the footgun. + if len(got) != 1 || got[0] != sentinel { + t.Fatalf("reject set after 400 = %v, want [%s] untouched", got, sentinel) + } + } else if len(got) != 0 && got[0] == sentinel { + t.Fatalf("reject set after successful PUT still holds sentinel: %v", got) + } + }) + } +} + +// TestAdminRejectModelsFailsQueuedWaiters is the finding-4 regression: adding a +// model to the shed at runtime must fail its ALREADY-queued public waiters, not +// just future admission — otherwise up to a full queue window of requests keeps +// dispatching to a model the operator just pulled from rotation. Exclusive +// self-route waiters are preserved (they bypass the shed). +func TestAdminRejectModelsFailsQueuedWaiters(t *testing.T) { + ts, srv := setupAdminRejectModels(t) + queue := srv.registry.Queue() + + shedModel := "queued-shed-model" + keepModel := "queued-keep-model" + + // A public waiter and a self-route waiter for the model about to be shed, plus + // a public waiter for an unrelated model that must NOT be touched. + publicShed := ®istry.QueuedRequest{RequestID: "pub-shed", Model: shedModel, Pending: ®istry.PendingRequest{RequestID: "pub-shed", Model: shedModel}} + selfRouteShed := ®istry.QueuedRequest{RequestID: "self-shed", Model: shedModel, Pending: ®istry.PendingRequest{RequestID: "self-shed", Model: shedModel, SelfRouteOnly: true}} + publicKeep := ®istry.QueuedRequest{RequestID: "pub-keep", Model: keepModel, Pending: ®istry.PendingRequest{RequestID: "pub-keep", Model: keepModel}} + for _, q := range []*registry.QueuedRequest{publicShed, selfRouteShed, publicKeep} { + if err := queue.Enqueue(q); err != nil { + t.Fatalf("enqueue %s: %v", q.RequestID, err) + } + } + + // Shed only shedModel via the real admin HTTP path. + status, body := rejectModelsCall(t, ts, http.MethodPut, "admin-secret", `{"models":["`+shedModel+`"]}`) + if status != http.StatusOK { + t.Fatalf("PUT status = %d, want 200; body = %s", status, body) + } + + // The public waiter receives a typed shed failure, not a false queue timeout. + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if _, err := queue.WaitForProviderContext(ctx, publicShed); !errors.Is(err, registry.ErrModelShed) { + t.Fatalf("public shed waiter error = %v, want ErrModelShed", err) + } + + // The self-route waiter for the shed model is preserved (bypasses the shed). + select { + case <-selfRouteShed.ResponseCh: + t.Fatal("self-route waiter was failed on shed, want preserved") + default: + } + + // The waiter for an unrelated model is untouched. + select { + case <-publicKeep.ResponseCh: + t.Fatal("unrelated-model waiter was failed on shed") + default: + } +} + +// TestAdminRejectModelsFailsOnlyMatchingAliasWaiters pins queue identity across +// alias resolution. Requests queue under the concrete build id, but an operator +// may shed the caller-facing alias. Only requests made through that alias should +// fail; raw-build, other-alias, and exclusive self-route waiters sharing the +// concrete queue must survive. +func TestAdminRejectModelsFailsOnlyMatchingAliasWaiters(t *testing.T) { + ts, srv := setupAdminRejectModels(t) + queue := srv.registry.Queue() + + build := "mlx-community/model-build" + alias := "public-model" + otherAlias := "other-public-model" + requests := []*registry.QueuedRequest{ + {RequestID: "alias", Model: build, Pending: ®istry.PendingRequest{RequestID: "alias", Model: build, PublicModel: alias}}, + {RequestID: "raw", Model: build, Pending: ®istry.PendingRequest{RequestID: "raw", Model: build, PublicModel: build}}, + {RequestID: "other-alias", Model: build, Pending: ®istry.PendingRequest{RequestID: "other-alias", Model: build, PublicModel: otherAlias}}, + {RequestID: "self-alias", Model: build, Pending: ®istry.PendingRequest{RequestID: "self-alias", Model: build, PublicModel: alias, SelfRouteOnly: true}}, + } + for _, req := range requests { + if err := queue.Enqueue(req); err != nil { + t.Fatalf("enqueue %s: %v", req.RequestID, err) + } + } + + status, body := rejectModelsCall(t, ts, http.MethodPut, "admin-secret", `{"models":["`+alias+`"]}`) + if status != http.StatusOK { + t.Fatalf("PUT status = %d, want 200; body = %s", status, body) + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if _, err := queue.WaitForProviderContext(ctx, requests[0]); !errors.Is(err, registry.ErrModelShed) { + t.Fatalf("matching alias waiter error = %v, want ErrModelShed", err) + } + for _, req := range requests[1:] { + select { + case <-req.ResponseCh: + t.Fatalf("nonmatching or self-route waiter %q was failed", req.RequestID) + default: + } + } + if got := queue.QueueSize(build); got != 3 { + t.Fatalf("concrete build queue depth = %d, want 3 surviving waiters", got) + } +} + +// TestValidateRejectModelName covers the invalid-UTF-8 leg directly: it is +// unreachable through the HTTP path (encoding/json coerces invalid bytes to +// U+FFFD during decode) but guards non-JSON callers such as the +// EIGENINFERENCE_REJECT_MODELS startup seeding. +func TestValidateRejectModelName(t *testing.T) { + if err := validateRejectModelName("mlx-community/Qwen3.5-0.8B-MLX-4bit"); err != nil { + t.Fatalf("real model ID rejected: %v", err) + } + if err := validateRejectModelName("bad\xff\xfename"); err == nil { + t.Fatal("invalid UTF-8 accepted, want error") + } + if err := validateRejectModelName("bad\x1bname"); err == nil { + t.Fatal("ESC control character accepted, want error") + } +} + +// TestAdminRejectModelsConcurrentAccess exercises replace/read/shed-check under +// the race detector: the set is read on every inference admission while the +// admin endpoint replaces it. +func TestAdminRejectModelsConcurrentAccess(t *testing.T) { + _, srv := setupAdminRejectModels(t) + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + for j := 0; j < 200; j++ { + switch i % 3 { + case 0: + srv.ReplaceRejectModels(map[string]bool{"m-a": true, "m-b": j%2 == 0}) + case 1: + _ = srv.RejectModels() + default: + _ = srv.modelShed("m-a", "m-b") + } + } + }(i) + } + wg.Wait() + + // The queue guard and the public admission set must finish on the same + // snapshot even when replacements race; otherwise a stale post-replace sweep + // can reject the wrong model or admit a newly shed one. + current := make(map[string]bool) + for _, model := range srv.RejectModels() { + current[model] = true + } + for _, model := range []string{"m-a", "m-b", "m-c"} { + req := ®istry.QueuedRequest{ + RequestID: "snapshot-" + model, + Model: model, + Pending: ®istry.PendingRequest{RequestID: "snapshot-" + model, Model: model, PublicModel: model}, + } + err := srv.registry.Queue().Enqueue(req) + if gotShed := errors.Is(err, registry.ErrModelShed); gotShed != current[model] { + t.Fatalf("queue shed snapshot for %q = %v (err %v), admission set = %v", model, gotShed, err, current) + } + if err == nil { + srv.registry.Queue().Remove(req.RequestID, model) + } + } +} diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index 1d9083050e..41ea62dde9 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -146,11 +146,7 @@ func (s *Server) shedIfModelRejected(w http.ResponseWriter, r *http.Request, par if policy.enabled || !s.modelShed(model, publicModel) { return false } - retryAfter := s.estimateRetryAfter(model) - if retryAfter <= 0 { - retryAfter = 30 - } - s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:model_shed"}) + retryAfter := s.modelShedRetryAfter(model) s.recordRejection(rejectionInfo{ r: r, stage: "model_shed", @@ -170,11 +166,24 @@ func (s *Server) shedIfModelRejected(w http.ResponseWriter, r *http.Request, par retryAfterMs: retryAfter * 1000, params: rejectionSamplingParams(parsed), }) + s.writeModelShedResponse(w, publicModel, model, retryAfter) + return true +} + +func (s *Server) modelShedRetryAfter(model string) int { + retryAfter := s.estimateRetryAfter(model) + if retryAfter <= 0 { + return 30 + } + return retryAfter +} + +func (s *Server) writeModelShedResponse(w http.ResponseWriter, publicModel, model string, retryAfter int) { + s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:model_shed"}) w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) writeJSON(w, http.StatusTooManyRequests, errorResponse("rate_limit_exceeded", fmt.Sprintf("model %q is temporarily rate-limited — retry after %ds", publicModel, retryAfter), withCode("rate_limit_exceeded"))) - return true } // sendProviderCancel sends a Cancel message for the given request to the @@ -3507,6 +3516,13 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request, } timing.QueuedAt = time.Now() if err := s.registry.Queue().Enqueue(queuedReq); err != nil { + if errors.Is(err, registry.ErrModelShed) { + retryAfter := s.modelShedRetryAfter(model) + refundReservation() + s.recordRejection(rejectionForGenericWithDecision("queue", "model_shed", http.StatusTooManyRequests, retryAfter*1000, decision)) + s.writeModelShedResponse(w, publicModel, model, retryAfter) + return + } retryAfter := s.estimateRetryAfter(model) w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) refundReservation() @@ -3555,6 +3571,15 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request, refundReservation() return } + if errors.Is(err, registry.ErrModelShed) { + s.recordWarmPoolQueueState(model) + s.updateInferenceRouteOutcomeForPending(pr, pendingRouteOutcome(pr, "error", "model_shed", http.StatusTooManyRequests)) + retryAfter := s.modelShedRetryAfter(model) + refundReservation() + s.recordRejection(rejectionForGenericWithDecision("queue", "model_shed", http.StatusTooManyRequests, retryAfter*1000, decision)) + s.writeModelShedResponse(w, publicModel, model, retryAfter) + return + } if errors.Is(err, registry.ErrQueueTTFTTooSlow) { // Deterministic drain-time TTFT rejection: every eligible // provider fails only the TTFT ceiling, so answer with the diff --git a/coordinator/api/dispatch.go b/coordinator/api/dispatch.go index 88acafc406..8c37c252d8 100644 --- a/coordinator/api/dispatch.go +++ b/coordinator/api/dispatch.go @@ -792,6 +792,13 @@ func (d *dispatchState) dispatchPrimary() dispatchOutcome { } queuePR.Timing.QueuedAt = time.Now() if err := s.registry.Queue().Enqueue(queuedReq); err != nil { + if errors.Is(err, registry.ErrModelShed) { + retryAfter := s.modelShedRetryAfter(d.model) + d.refundReservation() + s.recordRejection(d.rejectionInfoWithDecision("queue", "model_shed", http.StatusTooManyRequests, retryAfter*1000, decision)) + s.writeModelShedResponse(w, d.publicModel, d.model, retryAfter) + return outcomeResponseWritten + } s.ddIncr("routing.decisions", []string{"model:" + d.model, "model_type:" + s.registry.ModelType(d.model), "outcome:over_capacity"}) retryAfter := s.estimateRetryAfter(d.model) w.Header().Set("Retry-After", strconv.Itoa(retryAfter)) @@ -830,6 +837,15 @@ func (d *dispatchState) dispatchPrimary() dispatchOutcome { d.refundReservation() return outcomeClientGone } + if errors.Is(err, registry.ErrModelShed) { + s.recordWarmPoolQueueState(d.model) + d.updateRoutingOutcome(d.errorRoutingOutcome("error", "model_shed", http.StatusTooManyRequests)) + d.refundReservation() + retryAfter := s.modelShedRetryAfter(d.model) + s.recordRejection(d.rejectionInfoWithDecision("queue", "model_shed", http.StatusTooManyRequests, retryAfter*1000, decision)) + s.writeModelShedResponse(w, d.publicModel, d.model, retryAfter) + return outcomeResponseWritten + } if errors.Is(err, registry.ErrQueueTTFTTooSlow) { // The drain proved every eligible provider fails ONLY the TTFT // ceiling — deterministic, so answer with the standard diff --git a/coordinator/api/inference_admission.go b/coordinator/api/inference_admission.go index 2b9227e885..dc007353ab 100644 --- a/coordinator/api/inference_admission.go +++ b/coordinator/api/inference_admission.go @@ -305,18 +305,40 @@ func (s *Server) runInferenceAdmission(w http.ResponseWriter, r *http.Request, p if s.coldDispatchEnabled() && s.coldSpillAvailable(model, registry.RequestTraits{HasTools: p.hasTools}, p.requiresVision, p.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, p.allowedProviderSerials...) { - // 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. + } else if s.registry.HasCapableProviderForModel(model, registry.RequestTraits{HasTools: p.hasTools}, p.requiresVision, p.allowedProviderSerials...) { + // The fleet DOES serve this model on a provider that is STRUCTURALLY + // capable of taking this public request (passes trust/privacy + + // render/trait gates), but none can take it right now (all are + // transiently excluded — cooling, breaker-open, thermal, or — for a + // dedicated family — non-dedicated). 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. + // + // The predicate is HasCapableProviderForModel, NOT the bare + // HasProviderForModel: a model advertised only by private-only, + // runtime-unverified, below-trust, or render-broken providers is + // STRUCTURALLY unservable (no freeing slot ever makes it routable) and + // must stay on the 503 path below — a 429 there would have the client + // retry a permanently-dead model forever. The split is still keyed + // ONLY on provider capability, never on IsDedicatedModel: shed + // classification must not change when EIGENINFERENCE_DEDICATED_MODELS + // is cleared, so that env is a pure routing-policy flip with instant + // rollback (HasCapableProviderForModel ignores the dedicated rule, so a + // dedicated-family model on a non-dedicated box still reads as + // transient). The outcome tag keeps its historical name (dashboards key + // on it); the reason tag splits the old dedicated trigger from the + // re-keyed provider-exists one — IsDedicatedModel is consulted for + // that TAG only, not for the status code. 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"}) + reason := "provider_exists" + if s.registry.IsDedicatedModel(model) { + reason = "dedicated" + } + s.ddIncr("routing.decisions", []string{"model:" + model, "model_type:" + s.registry.ModelType(model), "outcome:dedicated_capacity_429", "reason:" + reason}) s.recordRejection(rejectionInfo{ r: r, stage: "preflight_capacity", @@ -340,7 +362,7 @@ func (s *Server) runInferenceAdmission(w http.ResponseWriter, r *http.Request, p 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), + fmt.Sprintf("no provider for model %q can take the request right now — retry after %ds", publicModel, retryAfter), withCode("rate_limit_exceeded"))) return model, true } else { diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 17c7b5503a..04f863a1fc 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -235,7 +235,14 @@ type Server struct { // keep Gemma shed while allowing gpt-oss traffic with TTFT_HARD_REJECT=false). // Exclusive self-route bypasses this because it never falls back to the public // fleet and is useful for owner debugging. nil/empty = none. - rejectModels map[string]bool + // + // Seeded from EIGENINFERENCE_REJECT_MODELS at startup and mutable at RUNTIME + // via GET/PUT /v1/admin/reject-models (admin_reject_models.go) so a shed flip + // no longer costs a coordinator restart (each restart wipes in-memory + // calibrator/TPS/breaker state). Guarded by rejectModelsMu: the set is read on + // the per-request admission path and replaced wholesale by the admin endpoint. + rejectModelsMu sync.RWMutex + rejectModels map[string]bool // minDecodeTPS is the per-request sustained-decode floor (tokens/sec) passed // to the scheduler as PendingRequest.MinDecodeTPS. When > 0 the router prefers @@ -1034,13 +1041,29 @@ func (s *Server) SetTTFTHardReject(enabled bool) { } // SetRejectModels sets the requested/resolved model IDs to 429 at public -// admission. Call before serving starts. +// admission. Safe for concurrent use: startup seeds it from +// EIGENINFERENCE_REJECT_MODELS and the admin endpoint (PUT +// /v1/admin/reject-models) replaces it at runtime. func (s *Server) SetRejectModels(models map[string]bool) { - if len(models) == 0 { - s.rejectModels = nil - return - } - copy := make(map[string]bool, len(models)) + s.ReplaceRejectModels(models) +} + +// ReplaceRejectModels atomically replaces the reject set (full replacement — +// an empty/nil set sheds nothing) and returns the previous and installed sets +// as sorted lists, so callers can log the exact old -> new transition even +// under concurrent replacements. Entries mapped to false, blank, or +// whitespace-only are dropped. +func (s *Server) ReplaceRejectModels(models map[string]bool) (previous, current []string) { + previous, current, _ = s.replaceRejectModels(models) + return previous, current +} + +// replaceRejectModels serializes the public admission set with the queue's +// matching snapshot. Holding rejectModelsMu across both updates means +// concurrent PUTs cannot apply stale queue sweeps, and readers observe the new +// admission set only after enqueue/requeue/drain guards are installed. +func (s *Server) replaceRejectModels(models map[string]bool) (previous, current []string, failedQueued int) { + normalized := make(map[string]bool, len(models)) for model, reject := range models { if !reject { continue @@ -1049,16 +1072,42 @@ func (s *Server) SetRejectModels(models map[string]bool) { if model == "" { continue } - copy[model] = true + normalized[model] = true } - if len(copy) == 0 { - s.rejectModels = nil - return + if len(normalized) == 0 { + normalized = nil } - s.rejectModels = copy + s.rejectModelsMu.Lock() + prev := s.rejectModels + s.rejectModels = normalized + previous = sortedModelSet(prev) + current = sortedModelSet(normalized) + failedQueued = s.registry.RejectQueuedRequestsForShedModels(current) + s.rejectModelsMu.Unlock() + return previous, current, failedQueued +} + +// RejectModels returns the current reject set as a sorted list. Never nil (an +// empty set yields an empty slice) so JSON consumers always see an array. +func (s *Server) RejectModels() []string { + s.rejectModelsMu.RLock() + defer s.rejectModelsMu.RUnlock() + return sortedModelSet(s.rejectModels) +} + +// sortedModelSet flattens a model set to a sorted, never-nil slice. +func sortedModelSet(models map[string]bool) []string { + out := make([]string, 0, len(models)) + for model := range models { + out = append(out, model) + } + sort.Strings(out) + return out } func (s *Server) modelShed(resolved, requested string) bool { + s.rejectModelsMu.RLock() + defer s.rejectModelsMu.RUnlock() if len(s.rejectModels) == 0 { return false } @@ -1883,6 +1932,14 @@ func (s *Server) routes() { // /readyz stays unauthenticated. See drain.go (DAR-327 Phase 1). s.mux.HandleFunc("POST /v1/admin/drain", s.requireAuth(s.handleAdminDrain)) + // Runtime shed list (admin only) — read/replace the per-model reject set + // (seeded from EIGENINFERENCE_REJECT_MODELS at startup) without a coordinator + // restart. Same auth pattern as /v1/admin/drain: requireAuth parses a Privy + // admin JWT / accepts the admin key as a pseudo-account, and the handlers + // authorize via isAdminAuthorized. See admin_reject_models.go. + s.mux.HandleFunc("GET /v1/admin/reject-models", s.requireAuth(s.handleAdminGetRejectModels)) + s.mux.HandleFunc("PUT /v1/admin/reject-models", s.requireAuth(s.handleAdminPutRejectModels)) + // Routing telemetry (admin-gated; metadata only — no prompt/response content). // Browse as JSON or stream a CSV/NDJSON download for offline analysis. // See docs/architecture/routing-telemetry-and-calibration.md §6. Handlers @@ -1927,52 +1984,76 @@ func (s *Server) StartDDGaugeLoop(ctx context.Context) { case <-ctx.Done(): return case <-ticker.C: - s.ddGauge("providers.online", float64(s.registry.OnlineCount()), nil) - // APNs code-identity coverage — watch this climb during the grace - // window before letting APNS_ENFORCE_AFTER pass. - codeAttested, _ := s.registry.CodeAttestationCoverage() - s.ddGauge("attestation.code_attested", float64(codeAttested), nil) - enforced := 0.0 - if s.registry.CodeAttestationEnforced() { - enforced = 1.0 - } - s.ddGauge("attestation.code_enforced", enforced, nil) - for model, count := range s.registry.ModelProviderSnapshot() { - s.ddGauge("providers.per_model", float64(count), []string{"model:" + model}) - } - for ver, count := range s.registry.ProviderCountByVersion() { - s.ddGauge("providers.per_version", float64(count), []string{"version:" + ver}) - } - // Trust-state cohort gauges — alert when self_signed/untrusted grows. - for _, b := range s.registry.ProviderCountByTrustStatus() { - s.ddGauge("providers.by_trust_status", float64(b.Count), - []string{"trust_level:" + b.TrustLevel, "status:" + b.Status}) - } - // Stuck-cohort breakdown — distinguishes never-enrolled from - // enrolled-but-SecurityInfo-timing-out so we know if the problem is - // provider-side enrollment or APNs/MDM delivery. - for reason, count := range s.registry.ProviderCountByMDMFailure() { - s.ddGauge("providers.by_mdm_failure", float64(count), []string{"reason:" + reason}) - } - if s.minProviderVersion != "" { - s.ddGauge("coordinator.min_provider_version_set", 1, []string{"min_version:" + s.minProviderVersion}) - } - if q := s.registry.Queue(); q != nil { - s.ddGauge("request_queue.depth", float64(q.TotalSize()), nil) - } - // Network utilization — demand/capacity across the warm-serving and - // token-budget axes, plus a per-model breakdown. - util := s.registry.NetworkUtilizationSnapshot() - s.ddGauge("utilization.network", util.Utilization, nil) - s.ddGauge("utilization.warm", util.WarmUtilization, nil) - s.ddGauge("utilization.token_budget", util.TokenBudgetUtilization, nil) - s.ddGauge("utilization.bottleneck", util.BottleneckUtilization, nil) - s.ddGauge("capacity.tps", util.CapacityTPS, nil) - s.ddGauge("capacity.demand_concurrency", util.DemandConcurrency, nil) - s.ddGauge("capacity.serving_capacity", util.ServingCapacity, nil) - s.ddGauge("capacity.spill_arrival_rate", util.SpillArrivalRate, nil) - for _, m := range util.Models { - s.ddGauge("utilization.model", m.Utilization, []string{"model:" + m.Model}) + s.pushDDGauges() + } + } +} + +// pushDDGauges pushes one round of point-in-time gauge values to DogStatsD. +// Split from StartDDGaugeLoop's ticker so tests can exercise the emission +// directly against a live UDP collector. +func (s *Server) pushDDGauges() { + s.ddGauge("providers.online", float64(s.registry.OnlineCount()), nil) + // APNs code-identity coverage — watch this climb during the grace + // window before letting APNS_ENFORCE_AFTER pass. + codeAttested, _ := s.registry.CodeAttestationCoverage() + s.ddGauge("attestation.code_attested", float64(codeAttested), nil) + enforced := 0.0 + if s.registry.CodeAttestationEnforced() { + enforced = 1.0 + } + s.ddGauge("attestation.code_enforced", enforced, nil) + for model, count := range s.registry.ModelProviderSnapshot() { + s.ddGauge("providers.per_model", float64(count), []string{"model:" + model}) + } + for ver, count := range s.registry.ProviderCountByVersion() { + s.ddGauge("providers.per_version", float64(count), []string{"version:" + ver}) + } + // Trust-state cohort gauges — alert when self_signed/untrusted grows. + for _, b := range s.registry.ProviderCountByTrustStatus() { + s.ddGauge("providers.by_trust_status", float64(b.Count), + []string{"trust_level:" + b.TrustLevel, "status:" + b.Status}) + } + // Stuck-cohort breakdown — distinguishes never-enrolled from + // enrolled-but-SecurityInfo-timing-out so we know if the problem is + // provider-side enrollment or APNs/MDM delivery. + for reason, count := range s.registry.ProviderCountByMDMFailure() { + s.ddGauge("providers.by_mdm_failure", float64(count), []string{"reason:" + reason}) + } + if s.minProviderVersion != "" { + s.ddGauge("coordinator.min_provider_version_set", 1, []string{"min_version:" + s.minProviderVersion}) + } + if q := s.registry.Queue(); q != nil { + s.ddGauge("request_queue.depth", float64(q.TotalSize()), nil) + } + // Network utilization — demand/capacity across the warm-serving and + // token-budget axes, plus a per-model breakdown. + util := s.registry.NetworkUtilizationSnapshot() + s.ddGauge("utilization.network", util.Utilization, nil) + s.ddGauge("utilization.warm", util.WarmUtilization, nil) + s.ddGauge("utilization.token_budget", util.TokenBudgetUtilization, nil) + s.ddGauge("utilization.bottleneck", util.BottleneckUtilization, nil) + s.ddGauge("capacity.tps", util.CapacityTPS, nil) + s.ddGauge("capacity.demand_concurrency", util.DemandConcurrency, nil) + s.ddGauge("capacity.serving_capacity", util.ServingCapacity, nil) + s.ddGauge("capacity.spill_arrival_rate", util.SpillArrivalRate, nil) + for _, m := range util.Models { + s.ddGauge("utilization.model", m.Utilization, []string{"model:" + m.Model}) + } + // Warm-pool cold-eligibility diagnostics: why the controller can (or cannot) + // act. eligible_cold hitting 0 silently clamps every warm target — including + // MIN_WARM floors — so the per-(model, reason) disqualifier tallies make "why + // is eligible_cold 0" a dashboard instead of a restart-and-grep (postmortem + // 2026-07-06 §3.3). Reason values are the warmColdReason strings + // (registry/warm_pool_controller.go) — keep them stable, dashboards key on them. + if snaps, _ := s.registry.LatestWarmPoolSnapshots(); len(snaps) > 0 { + for _, snap := range snaps { + modelTag := []string{"model:" + snap.Model} + s.ddGauge("warm_pool.eligible_cold", float64(snap.EligibleCold), modelTag) + s.ddGauge("warm_pool.cold_ineligible", float64(snap.ColdIneligible), modelTag) + for reason, n := range snap.ColdDisqualifiers { + s.ddGauge("warm_pool.cold_disqualified", float64(n), + []string{"model:" + snap.Model, "reason:" + reason}) } } } diff --git a/coordinator/api/shed_classification_test.go b/coordinator/api/shed_classification_test.go new file mode 100644 index 0000000000..62896c8164 --- /dev/null +++ b/coordinator/api/shed_classification_test.go @@ -0,0 +1,251 @@ +package api + +import ( + "context" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" + "nhooyr.io/websocket" +) + +// Tests for the shed re-key: the uptime-neutral 429-vs-503 classification on +// the no-eligible-provider preflight branch keys ONLY on provider existence +// (HasProviderForModel), never on IsDedicatedModel — so clearing +// EIGENINFERENCE_DEDICATED_MODELS is a pure routing-policy flip that cannot +// change shed classification. + +// setupShedClassification boots a coordinator with a live DogStatsD UDP +// collector so the routing.decisions tags can be asserted alongside the HTTP +// classification. drainMetrics flushes the buffered statsd client and returns +// the collected packets. +func setupShedClassification(t *testing.T) (ts *httptest.Server, reg *registry.Registry, drainMetrics func() []string) { + t.Helper() + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + reg = registry.New(logger) + srv := NewServer(reg, st, ServerConfig{}, logger) + srv.challengeInterval = time.Hour + collector := newUDPCollector(t) + t.Cleanup(collector.Close) + dd := newTestDD(t, collector) + t.Cleanup(func() { dd.Close() }) + srv.SetDatadog(dd) + ts = httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + return ts, reg, func() []string { + _ = dd.Statsd.Flush() + return collector.drain() + } +} + +// TestShedReKey429WhenProviderExistsWithoutDedicated is the re-key regression +// (fails with the old IsDedicatedModel trigger): DEDICATED is UNSET, a +// NON-dedicated model's only provider is structurally ineligible right now +// (thermal-critical — zero candidates, zero capacity rejections), but the +// provider EXISTS, so the shed must be an uptime-neutral 429 + Retry-After. +// Before the re-key this exact state returned a 503. A model with no provider +// at all keeps the 503. The routing.decisions emission keeps the historical +// outcome tag and adds reason:provider_exists for the re-keyed trigger. +func TestShedReKey429WhenProviderExistsWithoutDedicated(t *testing.T) { + ts, reg, drainMetrics := setupShedClassification(t) + // Pin the preflight shed path: no queue spill via cold dispatch. + t.Setenv(envColdDispatch, "false") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + model := "shed-rekey-test" + conn := connectProvider(t, ctx, ts.URL, []protocol.ModelInfo{ + {ID: model, ModelType: "chat", Quantization: "4bit"}, + }, testPublicKeyB64()) + defer conn.Close(websocket.StatusNormalClosure, "done") + p := markOnlyProviderRoutable(t, reg) + + // Thermal-critical: passes the structural routing gates (still online, + // trusted, serving the catalog model — HasProviderForModel is true) but is + // excluded from candidacy without counting as a capacity rejection, which is + // exactly the zero-candidates/zero-rejections branch under re-key. + p.Mu().Lock() + p.SystemMetrics.ThermalState = "critical" + p.Mu().Unlock() + + status, body, retryAfter, err := chatRequestWithHeaders(ctx, ts.URL, model) + if err != nil { + t.Fatalf("request: %v", err) + } + if status != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429 (provider exists => uptime-neutral shed); body = %s", status, body) + } + if !strings.Contains(body, "rate_limit_exceeded") { + t.Fatalf("body = %s, want rate_limit_exceeded", body) + } + if retryAfter == "" { + t.Fatal("429 missing Retry-After header") + } + + // The emission keeps the historical outcome tag (dashboards key on it) and + // tags the re-keyed trigger reason. + decisions := findMetrics(drainMetrics(), "outcome:dedicated_capacity_429") + if len(decisions) == 0 { + t.Fatal("no routing.decisions packet with outcome:dedicated_capacity_429") + } + if !strings.Contains(decisions[0], "reason:provider_exists") { + t.Fatalf("decision packet = %s, want reason:provider_exists tag", decisions[0]) + } + + // A model truly absent from the fleet is still a 503 — the re-key must not + // turn structural absence into an endless-retry 429. + 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("absent-model status = %d, want 503; body = %s", statusC, bodyC) + } + if !strings.Contains(bodyC, "model_unavailable") { + t.Fatalf("absent-model body = %s, want model_unavailable", bodyC) + } +} + +// TestShedStructurallyUnservableStays503 is the finding-1 regression: a +// NON-dedicated model whose only provider is STRUCTURALLY unroutable for a +// public request (private-only, or runtime-unverified) must stay on the 503 +// model_unavailable path, NOT flip to a 429 the client would retry forever. The +// provider is online, trusted, and advertises the model — so the bare +// HasProviderForModel is true and the pre-fix code 429'd — but no freeing slot +// can ever make a private-only / unverified box serve a public request, so the +// re-key must key on structural CAPABILITY (HasCapableProviderForModel), not +// mere existence. +func TestShedStructurallyUnservableStays503(t *testing.T) { + cases := []struct { + name string + breakIt func(p *registry.Provider) + }{ + {"private_only", func(p *registry.Provider) { p.PrivateOnly = true }}, + {"runtime_unverified", func(p *registry.Provider) { p.RuntimeVerified = false }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ts, reg, _ := setupShedClassification(t) + t.Setenv(envColdDispatch, "false") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + model := "structurally-unservable" + conn := connectProvider(t, ctx, ts.URL, []protocol.ModelInfo{ + {ID: model, ModelType: "chat", Quantization: "4bit"}, + }, testPublicKeyB64()) + defer conn.Close(websocket.StatusNormalClosure, "done") + p := markOnlyProviderRoutable(t, reg) + + // Apply the structural break AFTER marking routable so the ONLY + // disqualifier is the one under test. + p.Mu().Lock() + tc.breakIt(p) + p.Mu().Unlock() + + status, body, _, err := chatRequestWithHeaders(ctx, ts.URL, model) + if err != nil { + t.Fatalf("request: %v", err) + } + if status != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503 (structurally unservable, not a retryable 429); body = %s", status, body) + } + if !strings.Contains(body, "model_unavailable") { + t.Fatalf("body = %s, want model_unavailable", body) + } + }) + } +} + +// TestShedColdModelTooLargeStays503 covers permanent hardware incapability that +// QuickCapacityCheck cannot classify after a transient gate wins first. A +// thermal-critical provider advertising a cold model is not a retryable source +// of capacity when the catalog says the model can never fit that machine. +func TestShedColdModelTooLargeStays503(t *testing.T) { + ts, reg, _ := setupShedClassification(t) + t.Setenv(envColdDispatch, "false") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + model := "cold-too-large" + conn := connectProvider(t, ctx, ts.URL, []protocol.ModelInfo{ + {ID: model, ModelType: "chat", Quantization: "4bit"}, + }, testPublicKeyB64()) + defer conn.Close(websocket.StatusNormalClosure, "done") + p := markOnlyProviderRoutable(t, reg) + reg.SetModelCatalog([]registry.CatalogEntry{{ID: model, MinRAMGB: 64}}) + + p.Mu().Lock() + p.Hardware.MemoryGB = 16 + p.BackendCapacity = nil // cold: no resident slot proving the model has fit + p.SystemMetrics.ThermalState = "critical" + p.Mu().Unlock() + + status, body, _, err := chatRequestWithHeaders(ctx, ts.URL, model) + if err != nil { + t.Fatalf("request: %v", err) + } + if status != http.StatusServiceUnavailable { + t.Fatalf("status = %d, want 503 for permanently undersized cold pool; body = %s", status, body) + } + if !strings.Contains(body, "model_unavailable") { + t.Fatalf("body = %s, want model_unavailable", body) + } +} + +// TestShedReKeyDedicatedTaggedButNotClassifying verifies the DEDICATED-set +// behavior is preserved under re-key: a dedicated-family model whose only +// provider is a mixed (non-dedicated) box still sheds 429 + Retry-After +// (HasProviderForModel is true — same outcome as the old dedicated trigger), +// and the emission tags reason:dedicated so the old and re-keyed triggers can +// be told apart on the dashboard. +func TestShedReKeyDedicatedTaggedButNotClassifying(t *testing.T) { + ts, reg, drainMetrics := setupShedClassification(t) + reg.SetDedicatedModels([]string{"gemma-4"}) + t.Setenv(envColdDispatch, "false") + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + gemma := "gemma-4-26b-test" + qwen := "qwen-3-test" + // One MIXED provider (gemma + qwen): excluded by the dedicated-box rule, so + // gemma has zero candidates and zero capacity rejections while the fleet + // still serves it. + 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") + markOnlyProviderRoutable(t, reg) + + status, body, retryAfter, err := chatRequestWithHeaders(ctx, ts.URL, gemma) + if err != nil { + t.Fatalf("request: %v", err) + } + if status != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429; body = %s", status, body) + } + if retryAfter == "" { + t.Fatal("429 missing Retry-After header") + } + + decisions := findMetrics(drainMetrics(), "outcome:dedicated_capacity_429") + if len(decisions) == 0 { + t.Fatal("no routing.decisions packet with outcome:dedicated_capacity_429") + } + if !strings.Contains(decisions[0], "reason:dedicated") { + t.Fatalf("decision packet = %s, want reason:dedicated tag", decisions[0]) + } +} diff --git a/coordinator/api/warm_pool_gauges_test.go b/coordinator/api/warm_pool_gauges_test.go new file mode 100644 index 0000000000..e91a3a22e6 --- /dev/null +++ b/coordinator/api/warm_pool_gauges_test.go @@ -0,0 +1,94 @@ +package api + +import ( + "log/slog" + "os" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +// TestWarmPoolColdDisqualifierGauges verifies the warm-pool eligibility +// diagnostics reach Datadog: per-model eligible_cold / cold_ineligible gauges +// and the per-(model, reason) cold_disqualified tally, emitted from the +// controller's latest snapshots by the same gauge loop that pushes the fleet +// and utilization gauges. This is the "why is eligible_cold 0" dashboard +// (postmortem 2026-07-06 §3.3) — asserted against a live UDP DogStatsD +// collector. +func TestWarmPoolColdDisqualifierGauges(t *testing.T) { + logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) + st := store.NewMemory(store.Config{AdminKey: "test-key"}) + reg := registry.New(logger) + + model := "gauge-cold-model" + // A cold provider for `model` (no backend slot for it) that is BUSY serving a + // co-resident model: disqualified from warming with reason not_idle. + p := makeRoutableProvider(t, reg, "busy-cold-box", model) + p.Mu().Lock() + p.BackendCapacity.Slots = []protocol.BackendSlotCapacity{ + {Model: "co-resident-model", State: "running", NumRunning: 1}, + } + p.Mu().Unlock() + + reg.ConfigureWarmPool(registry.WarmPoolConfig{ + Enabled: true, + Interval: time.Second, + CapacityRejectThreshold: 1, + TTFTMissThreshold: 1, + SpeculativeStartThreshold: 1, + SpeculativeWinThreshold: 1, + ColdDispatchThreshold: 1, + FallbackQualityConcurrency: 4, + MaxLoadsPerTick: 1, + MaxLoadsPerTickCeiling: 4, + MaxGlobalPendingLoads: 4, + }) + snaps := reg.TriggerWarmPool() + found := false + for _, s := range snaps { + if s.Model == model && s.ColdIneligible == 1 && s.ColdDisqualifiers["not_idle"] == 1 { + found = true + } + } + if !found { + t.Fatalf("warm-pool snapshots missing the not_idle disqualifier for %s: %+v", model, snaps) + } + + collector := newUDPCollector(t) + defer collector.Close() + dd := newTestDD(t, collector) + defer dd.Close() + srv := NewServer(reg, st, ServerConfig{}, logger) + srv.SetDatadog(dd) + + srv.pushDDGauges() + _ = dd.Statsd.Flush() + packets := collector.drain() + + disq := findMetrics(packets, "warm_pool.cold_disqualified") + if len(disq) == 0 { + t.Fatalf("no warm_pool.cold_disqualified gauge; packets: %v", packets) + } + tagged := false + for _, pkt := range disq { + if strings.Contains(pkt, "model:"+model) && strings.Contains(pkt, "reason:not_idle") { + tagged = true + } + } + if !tagged { + t.Fatalf("warm_pool.cold_disqualified missing (model, reason) tags; packets: %v", disq) + } + + eligible := findMetrics(packets, "warm_pool.eligible_cold") + if len(eligible) == 0 || !strings.Contains(strings.Join(eligible, "\n"), "model:"+model) { + t.Fatalf("no per-model warm_pool.eligible_cold gauge; packets: %v", packets) + } + ineligible := findMetrics(packets, "warm_pool.cold_ineligible") + if len(ineligible) == 0 || !strings.Contains(strings.Join(ineligible, "\n"), "model:"+model) { + t.Fatalf("no per-model warm_pool.cold_ineligible gauge; packets: %v", packets) + } +} diff --git a/coordinator/cmd/coordinator/main.go b/coordinator/cmd/coordinator/main.go index 42f6d9322c..bffe1c3e60 100644 --- a/coordinator/cmd/coordinator/main.go +++ b/coordinator/cmd/coordinator/main.go @@ -201,6 +201,16 @@ func main() { "decode_floor_tps", cfg.RegistryCfg.WarmPool.DecodeFloorTPS, ) + // Combined (box-wide) admission cap: per-model quality caps are checked + // independently, so a box saturated on model A still admits model B. This + // adds Σ_slots(load/qc) + 1/qc_model <= overcommit on top of the per-model + // caps. Dormant by default — turned on together with the open-pool + // (DEDICATED_MODELS="") flip. + if os.Getenv("EIGENINFERENCE_COMBINED_ADMISSION_CAP") == "true" { + reg.SetCombinedAdmissionCap(true) + logger.Warn("combined admission cap ENABLED via EIGENINFERENCE_COMBINED_ADMISSION_CAP (box-wide Σ load/qc budget on top of per-model caps)") + } + 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) diff --git a/coordinator/protocol/messages.go b/coordinator/protocol/messages.go index 1024d4c155..58d712f78a 100644 --- a/coordinator/protocol/messages.go +++ b/coordinator/protocol/messages.go @@ -252,6 +252,14 @@ type BackendCapacity struct { GPUMemoryPeakGB float64 `json:"gpu_memory_peak_gb"` // Metal peak memory GPUMemoryCacheGB float64 `json:"gpu_memory_cache_gb"` // Metal cache memory (reclaimable) TotalMemoryGB float64 `json:"total_memory_gb"` // total system/GPU memory + // MaxModelSlots is the provider's current effective resident-model slot cap. + // Zero means a legacy/unknown provider. The warm-pool bounded-busy path uses + // it to avoid issuing a load_model that cannot allocate another slot. + MaxModelSlots int `json:"max_model_slots,omitempty"` + // OccupiedModelSlots is the provider's authoritative resident or committed-load + // slot count, including models hidden from routable capacity while loading, + // queued, or unloading. Zero means legacy/unknown. + OccupiedModelSlots int `json:"occupied_model_slots,omitempty"` // FreeForLoadGB is the max additional model-WEIGHT footprint (GB) the // provider can load right now: net of the 90% unified-memory cap, OS/operator // reserve, and activation+min-KV load headroom, clamped to real OS-available diff --git a/coordinator/protocol/messages_backend_capacity_test.go b/coordinator/protocol/messages_backend_capacity_test.go index 6be6fcf6e2..036e25db4b 100644 --- a/coordinator/protocol/messages_backend_capacity_test.go +++ b/coordinator/protocol/messages_backend_capacity_test.go @@ -103,10 +103,12 @@ func TestBackendCapacityMarshalRoundtrip(t *testing.T) { MaxTokensPotential: 0, }, }, - GPUMemoryActiveGB: 45.2, - GPUMemoryPeakGB: 52.1, - GPUMemoryCacheGB: 8.3, - TotalMemoryGB: 128, + GPUMemoryActiveGB: 45.2, + GPUMemoryPeakGB: 52.1, + GPUMemoryCacheGB: 8.3, + TotalMemoryGB: 128, + MaxModelSlots: 3, + OccupiedModelSlots: 2, } data, err := json.Marshal(cap) @@ -137,6 +139,12 @@ func TestBackendCapacityMarshalRoundtrip(t *testing.T) { if decoded.TotalMemoryGB != 128 { t.Errorf("total_memory_gb = %f, want 128", decoded.TotalMemoryGB) } + if decoded.MaxModelSlots != 3 { + t.Errorf("max_model_slots = %d, want 3", decoded.MaxModelSlots) + } + if decoded.OccupiedModelSlots != 2 { + t.Errorf("occupied_model_slots = %d, want 2", decoded.OccupiedModelSlots) + } } func TestHeartbeatWithBackendCapacityMarshal(t *testing.T) { diff --git a/coordinator/registry/concurrency_cap.go b/coordinator/registry/concurrency_cap.go index 3b6f2b3aeb..ac8d0db5ad 100644 --- a/coordinator/registry/concurrency_cap.go +++ b/coordinator/registry/concurrency_cap.go @@ -304,15 +304,160 @@ func (r *Registry) effectiveMaxConcurrencyForModelRateLocked(p *Provider, model // hasConcurrencyHeadroomForModelCapResolvedLocked mirrors // Provider.hasConcurrencyHeadroomForModelLocked but applies the registry's // quality-concurrency cap to the per-model limit, with the static single-stream -// decode rate resolved internally — per-model (solo median / seed) when -// available, else the provider-level rate. It is the single production entry -// point: the routing snapshot, the queue-drain preflight, the final admit -// re-check, the warm-pool saturation gate, and the public capacity feeds -// (ModelCapacitySnapshot) all consume it, so /v1/models[/capacity] report the -// SAME headroom the routing path enforces — otherwise a capped box is -// advertised as routable and upstream routers keep sending requests it 429s. +// decode rate resolved internally. It is the single production entry point for +// routing, queue preflight, final admission, warm-pool saturation, and public +// capacity. The candidate rate is resolved once and shared with the box-wide +// combined cap so the two gates cannot disagree on rate provenance. // Caller holds r.mu and p.mu. func (r *Registry) hasConcurrencyHeadroomForModelCapResolvedLocked(p *Provider, model string) bool { - return p.pendingLoadForModelLocked(model) < r.effectiveMaxConcurrencyForModelResolvedLocked(p, model) && - p.pendingCount() < p.maxConcurrency() + rate := r.resolvedSoloModelTPSLocked(p, model) + return p.pendingLoadForModelLocked(model) < r.effectiveMaxConcurrencyForModelRateLocked(p, model, rate) && + p.pendingCount() < p.maxConcurrency() && + r.combinedAdmissionHeadroomLocked(p, model, rate) +} + +// SetCombinedAdmissionCap toggles the box-wide combined admission budget (see +// combinedAdmissionHeadroomLocked). Called once at startup, from +// EIGENINFERENCE_COMBINED_ADMISSION_CAP; default false leaves per-model +// admission byte-identical to the independent per-model caps. +func (r *Registry) SetCombinedAdmissionCap(enabled bool) { + r.mu.Lock() + defer r.mu.Unlock() + r.combinedAdmissionCap = enabled +} + +// combinedAdmissionEpsilon absorbs float rounding in the Σ(load/qc) budget so a +// box exactly AT its overcommit budget (e.g. 1.0 + 1/5 vs overcommit 1.2) is not +// rejected on the last binary digit. +const combinedAdmissionEpsilon = 1e-9 + +// combinedSlotLoad is one backend slot's contribution to the combined admission +// budget: its current load and the quality concurrency of its model on this +// provider. qc <= 0 marks the slot's quality concurrency unresolvable — the slot +// is skipped (fails open per-slot) rather than guessed. +type combinedSlotLoad struct { + load int + qc int +} + +// combinedAdmissionAdmits is the pure core of the combined (box-wide) admission +// cap: +// +// Σ_slots(load_s / qc_s) + 1/qc_candidate <= overcommit +// +// Each slot's in-flight load is normalized by that model's quality concurrency, +// so the sum is the fraction of the box's quality-bounded capacity already +// committed, on a scale where 1.0 = "every resident model at its own quality +// batch". Admitting one more request of the candidate model costs 1/qc_candidate. +// The bound is the candidate model's resolved overcommit — the same allowance the +// per-model cap grants. An unresolvable candidate qc (<= 0) fails open, matching +// the per-model cap's trust rules, and a box with ZERO combined load always +// admits — the same at-least-one floor the per-model cap applies (capped < 1 → +// 1), so a sub-1/qc overcommit can never starve an idle box. +func combinedAdmissionAdmits(slots []combinedSlotLoad, candidateQC int, overcommit float64) bool { + if candidateQC <= 0 { + return true + } + used := 0.0 + for _, s := range slots { + if s.qc <= 0 || s.load <= 0 { + continue + } + used += float64(s.load) / float64(s.qc) + } + if used == 0 { + return true + } + return used+1.0/float64(candidateQC) <= overcommit+combinedAdmissionEpsilon +} + +// combinedAdmissionHeadroomLocked applies the box-wide combined admission cap +// (combinedAdmissionAdmits) to a candidate (provider, model) pair. Per-model +// caps are checked independently, so a box saturated on model A still admits +// model B — each model sees only its own slot. This gate sums every resident +// slot's normalized load plus coordinator-pending cold models that are absent +// from the latest heartbeat, so cross-model saturation is visible at admission +// (the hard edge that lets the pool open before contention-aware scoring lands). +// +// Dormant unless BOTH EIGENINFERENCE_COMBINED_ADMISSION_CAP and the quality cap +// are enabled. Candidate and co-resident quality concurrency both use +// resolvedSoloModelTPSLocked, the same per-model solo median / seed / provider +// fallback chain as the independent cap. The trust rule also matches the +// independent cap: an unbenchmarked non-dedicated model with only the coarse +// provider fallback is unresolvable and fails open rather than being hard-capped. +// +// Per-slot load is the model-scoped max(coordinator-pending, backend +// running+waiting) — pendingLoadForModelLocked's semantics — computed inline +// because that helper's legacy fallback (no reported MaxConcurrency → TOTAL +// pending count) is per-model-safe but would double-count when summed across +// slots. Caller holds r.mu and p.mu. +func (r *Registry) combinedAdmissionHeadroomLocked(p *Provider, model string, candidate soloModelTPS) bool { + if !r.combinedAdmissionCap || !r.qualityCapEnabled { + return true + } + candidateQC := r.combinedQualityConcurrencyLocked(p, model, candidate) + var slots []combinedSlotLoad + if p.BackendCapacity != nil { + pendingByModel := make(map[string]int) + for _, pending := range p.pendingReqs { + if pending != nil && pending.Model != "" { + pendingByModel[pending.Model]++ + } + } + slots = make([]combinedSlotLoad, 0, len(p.BackendCapacity.Slots)+len(pendingByModel)) + for _, slot := range p.BackendCapacity.Slots { + if slot.Model == "" { + continue + } + load := pendingByModel[slot.Model] + delete(pendingByModel, slot.Model) + if backendLoad := clampNonNegative(slot.NumRunning) + clampNonNegative(slot.NumWaiting); backendLoad > load { + load = backendLoad + } + slotRate := r.resolvedSoloModelTPSLocked(p, slot.Model) + if slot.Model == model { + slotRate = candidate + } + qc := r.combinedQualityConcurrencyLocked(p, slot.Model, slotRate) + slots = append(slots, combinedSlotLoad{load: load, qc: qc}) + } + // Coordinator reservations can precede the heartbeat slot for a cold + // model. Charge those pending-only models once so heartbeat lag cannot + // make already-committed box load disappear. + for pendingModel, load := range pendingByModel { + rate := r.resolvedSoloModelTPSLocked(p, pendingModel) + if pendingModel == model { + rate = candidate + } + qc := r.combinedQualityConcurrencyLocked(p, pendingModel, rate) + slots = append(slots, combinedSlotLoad{load: load, qc: qc}) + } + } + return combinedAdmissionAdmits(slots, candidateQC, r.qualityCapOvercommitForModelLocked(model)) +} + +// combinedQualityConcurrencyLocked resolves the strict quality concurrency used +// by the combined budget while applying the same provenance trust rule as the +// independent per-model cap. Zero means unresolvable and is handled fail-open by +// combinedAdmissionAdmits. Caller holds r.mu and p.mu. +func (r *Registry) combinedQualityConcurrencyLocked(p *Provider, model string, rate soloModelTPS) int { + if rate.tps <= 0 { + return 0 + } + if p.DecodeTPS <= 0 && !rate.perModel { + if _, dedicated := r.dedicatedPatternForLocked(model); !dedicated { + return 0 + } + } + return qualityConcurrency(rate.tps, r.qualityCapFloorTPS, effectiveTPSLoadFactor, + p.maxConcurrencyForModelLocked(model), r.qualityCapFallback) +} + +// clampNonNegative floors a heartbeat-reported count at 0 so a malformed slot +// cannot subtract from the combined load sum. +func clampNonNegative(v int) int { + if v < 0 { + return 0 + } + return v } diff --git a/coordinator/registry/concurrency_cap_combined_test.go b/coordinator/registry/concurrency_cap_combined_test.go new file mode 100644 index 0000000000..b45e215dfc --- /dev/null +++ b/coordinator/registry/concurrency_cap_combined_test.go @@ -0,0 +1,208 @@ +package registry + +import ( + "fmt" + "testing" + + "github.com/eigeninference/d-inference/coordinator/protocol" +) + +// Tests for the combined (box-wide) admission cap: per-model quality caps are +// checked independently, so a box saturated on model A still admits model B. +// Behind EIGENINFERENCE_COMBINED_ADMISSION_CAP the admission check also +// requires Σ_slots(load/qc) + 1/qc_candidate <= overcommit. + +// TestCombinedAdmissionAdmitsTable pins the pure budget math, including the +// fail-open rules (unresolvable candidate or slot qc) and the epsilon at exact +// budget equality. +func TestCombinedAdmissionAdmitsTable(t *testing.T) { + cases := []struct { + name string + slots []combinedSlotLoad + candidateQC int + overcommit float64 + want bool + }{ + {name: "empty_box_admits", slots: nil, candidateQC: 10, overcommit: 1.2, want: true}, + {name: "a_at_qc_blocks_b", slots: []combinedSlotLoad{{load: 2, qc: 2}}, candidateQC: 10, overcommit: 1.0, want: false}, + {name: "a_drained_admits_b", slots: []combinedSlotLoad{{load: 0, qc: 2}}, candidateQC: 10, overcommit: 1.0, want: true}, + {name: "overcommit_grants_headroom", slots: []combinedSlotLoad{{load: 2, qc: 2}}, candidateQC: 10, overcommit: 1.2, want: true}, + {name: "slow_candidate_blocked_within_overcommit", slots: []combinedSlotLoad{{load: 2, qc: 2}}, candidateQC: 2, overcommit: 1.2, want: false}, + {name: "exact_budget_equality_admits", slots: []combinedSlotLoad{{load: 2, qc: 2}}, candidateQC: 5, overcommit: 1.2, want: true}, + {name: "unresolvable_slot_skipped", slots: []combinedSlotLoad{{load: 50, qc: 0}}, candidateQC: 4, overcommit: 1.0, want: true}, + {name: "unresolvable_candidate_fails_open", slots: []combinedSlotLoad{{load: 50, qc: 1}}, candidateQC: 0, overcommit: 1.0, want: true}, + {name: "negative_load_ignored", slots: []combinedSlotLoad{{load: -3, qc: 1}}, candidateQC: 4, overcommit: 1.0, want: true}, + {name: "multi_slot_sum", slots: []combinedSlotLoad{{load: 1, qc: 2}, {load: 5, qc: 10}}, candidateQC: 10, overcommit: 1.0, want: false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := combinedAdmissionAdmits(tc.slots, tc.candidateQC, tc.overcommit); got != tc.want { + t.Fatalf("combinedAdmissionAdmits(%+v, qc %d, oc %.2f) = %v, want %v", + tc.slots, tc.candidateQC, tc.overcommit, got, tc.want) + } + }) + } +} + +// combinedHeadroom evaluates the full admission headroom check (per-model caps +// + combined cap) under the routing path's lock discipline. The production +// entry point resolves the candidate's per-model static rate internally. +func combinedHeadroom(reg *Registry, p *Provider, model string) bool { + reg.mu.RLock() + defer reg.mu.RUnlock() + p.mu.Lock() + defer p.mu.Unlock() + return reg.hasConcurrencyHeadroomForModelCapResolvedLocked(p, model) +} + +// makeCombinedCapBox builds one provider serving two models: slot A +// (MaxConcurrency 2 — its quality cap) carrying loadA in-flight requests, and +// slot B (MaxConcurrency 24) idle. DecodeTPS 57 -> quality batch +// floor((57/15-1)/0.27) = 10, so qc_A = min(10, 2) = 2 and qc_B = min(10, 24) +// = 10 (per-slot MaxConcurrency clamps qualityConcurrency). +func makeCombinedCapBox(t *testing.T, reg *Registry, modelA, modelB string, loadA int) *Provider { + t.Helper() + p := makeSchedulerProvider(t, reg, "combined-box", modelA, 57) + p.mu.Lock() + p.BackendCapacity.Slots = []protocol.BackendSlotCapacity{ + {Model: modelA, State: "running", MaxConcurrency: 2, NumRunning: loadA}, + {Model: modelB, State: "running", MaxConcurrency: 24}, + } + p.mu.Unlock() + return p +} + +// TestCombinedAdmissionCapCrossModel is the cross-model hard edge end to end +// through hasConcurrencyHeadroomForModelCapResolvedLocked: with the flag OFF a box +// saturated on model A still admits model B (today's behavior, byte-identical); +// with the flag ON the A-saturated box refuses B (Σ 2/2 + 1/10 = 1.1 > 1.0); +// once A drains, B admits again (0 + 1/10 <= 1.0). +func TestCombinedAdmissionCapCrossModel(t *testing.T) { + modelA := "combined-model-a" + modelB := "combined-model-b" + + // Flag OFF (default): A-saturated box still admits B — the pre-existing + // independent per-model behavior this flag must not change while dormant. + reg := New(testLogger()) + enableQualityCap(t, reg, "1.0") + p := makeCombinedCapBox(t, reg, modelA, modelB, 2) + if !combinedHeadroom(reg, p, modelB) { + t.Fatal("flag off: A-saturated box must still admit B (independent per-model caps)") + } + + // Flag ON: the same box refuses B while A sits at its quality cap. + reg = New(testLogger()) + enableQualityCap(t, reg, "1.0") + reg.SetCombinedAdmissionCap(true) + p = makeCombinedCapBox(t, reg, modelA, modelB, 2) + if combinedHeadroom(reg, p, modelB) { + t.Fatal("flag on: A at its quality cap must make B inadmissible (box-wide budget)") + } + // A's own per-model cap still binds first for A itself (load 2 >= cap 2). + if combinedHeadroom(reg, p, modelA) { + t.Fatal("flag on: A at its quality cap must stay inadmissible for A") + } + + // A drains -> B admits (same registry/flag state). + p.mu.Lock() + p.BackendCapacity.Slots[0].NumRunning = 0 + p.mu.Unlock() + if !combinedHeadroom(reg, p, modelB) { + t.Fatal("flag on: B must admit once A drains") + } +} + +// TestCombinedAdmissionUsesPerModelRateForResidentSlots pins the #524 merge +// boundary: co-resident slot load must be normalized by THAT model's resolved +// solo rate, not the provider-wide registration benchmark. A slow model at one +// request already consumes its whole quality budget even when the box happened +// to benchmark fast on another model. Trusted per-model seeds must also bind on +// providers that did not report a registration benchmark. +func TestCombinedAdmissionUsesPerModelRateForResidentSlots(t *testing.T) { + modelA := "combined-slow-resident" + modelB := "combined-slow-candidate" + + for _, providerTPS := range []float64{93, 0} { + t.Run(fmt.Sprintf("provider_tps_%.0f", providerTPS), func(t *testing.T) { + reg := New(testLogger()) + enablePerModelQualityCap(t, reg, modelA+"=14,"+modelB+"=14", "", "") + reg.SetCombinedAdmissionCap(true) + p := makeCombinedCapBox(t, reg, modelA, modelB, 1) + p.mu.Lock() + p.DecodeTPS = providerTPS + p.BackendCapacity.Slots[0].MaxConcurrency = 24 + p.BackendCapacity.Slots[1].MaxConcurrency = 24 + p.mu.Unlock() + + if combinedHeadroom(reg, p, modelB) { + t.Fatal("slow resident at quality concurrency 1 must exhaust the combined box budget") + } + }) + } +} + +// TestCombinedAdmissionCountsPendingColdModelWithoutHeartbeatSlot covers the +// gap between coordinator reservation and the next provider heartbeat. A cold +// model with a pending request may not have a BackendCapacity slot yet, but its +// load still consumes box-wide quality capacity. The independent per-model cap +// permits the second request (ceil(1 * 1.2) = 2); the combined cap must reject it. +func TestCombinedAdmissionCountsPendingColdModelWithoutHeartbeatSlot(t *testing.T) { + resident := "combined-resident" + cold := "combined-pending-cold" + reg := New(testLogger()) + enablePerModelQualityCap(t, reg, cold+"=14", "", "") + reg.SetCombinedAdmissionCap(true) + p := makeSchedulerProvider(t, reg, "pending-cold-box", resident, 93) + p.mu.Lock() + p.pendingReqs["cold-1"] = &PendingRequest{RequestID: "cold-1", Model: cold} + p.mu.Unlock() + + if combinedHeadroom(reg, p, cold) { + t.Fatal("pending cold model absent from heartbeat slots must consume the combined box budget") + } +} + +// TestCombinedAdmissionCapFailOpenRules pins the wrapper's fail-open guards: +// no benchmark on a non-dedicated candidate (the per-model cap's trust rule), +// quality cap disabled, and a slotless provider all admit. +func TestCombinedAdmissionCapFailOpenRules(t *testing.T) { + modelA := "combined-failopen-a" + modelB := "combined-failopen-b" + + // No registration benchmark (DecodeTPS 0) and not dedicated: fail open even + // with the flag on — mirrors effectiveMaxConcurrencyForModelLocked's rule of + // never hard-capping a non-dedicated model from the bandwidth fallback. + reg := New(testLogger()) + enableQualityCap(t, reg, "1.0") + reg.SetCombinedAdmissionCap(true) + p := makeCombinedCapBox(t, reg, modelA, modelB, 2) + p.mu.Lock() + p.DecodeTPS = 0 + p.Hardware.MemoryBandwidthGBs = 800 + p.mu.Unlock() + if !combinedHeadroom(reg, p, modelB) { + t.Fatal("no-benchmark non-dedicated candidate must fail open under the combined cap") + } + + // Quality cap disabled: the combined budget has no meaningful qc inputs and + // must stay dormant even with the flag on. + reg = New(testLogger()) + reg.SetQualityConcurrencyCap(false, 1.0, 15, 4) + reg.SetCombinedAdmissionCap(true) + p = makeCombinedCapBox(t, reg, modelA, modelB, 2) + if !combinedHeadroom(reg, p, modelB) { + t.Fatal("combined cap must be dormant while the quality cap is disabled") + } + + // No backend capacity: nothing box-wide to combine. + reg = New(testLogger()) + enableQualityCap(t, reg, "1.0") + reg.SetCombinedAdmissionCap(true) + p = makeSchedulerProvider(t, reg, "slotless", modelB, 57) + p.mu.Lock() + p.BackendCapacity = nil + p.mu.Unlock() + if !combinedHeadroom(reg, p, modelB) { + t.Fatal("provider without backend capacity must fail open under the combined cap") + } +} diff --git a/coordinator/registry/config.go b/coordinator/registry/config.go index 01c6da0ac3..257609b7a1 100644 --- a/coordinator/registry/config.go +++ b/coordinator/registry/config.go @@ -82,6 +82,17 @@ type WarmPoolConfig struct { // Floors are capped by warm+eligibleCold and still obey load throttles. MinWarmByModel map[string]int + // AllowBusyLoadMax bounds the busy-load a COLD provider may carry and still be + // an eligible warm-pool target: eligible when max(pendingCount, Σ slots + // (NumRunning+NumWaiting)) <= AllowBusyLoadMax. The default 0 preserves the + // historical fully-idle requirement (any activity disqualifies — + // warmColdNotIdle). Raising it (runbook: 2) lets the controller warm a + // lightly-busy box instead of stalling at eligible_cold=0 during recovery + // (postmortem 2026-07-06 §3.3); a non-idle candidate is additionally required + // to fit the weights WITHOUT evicting co-resident models (warmColdBusyNoEvict), + // mirroring the dispatch-path no-eviction rule in freeMemoryAdmits. + AllowBusyLoadMax int + // Ramp shaping. MaxLoadsPerTick is the baseline per-tick load burst; // RampGapFraction scales the burst up with the remaining target gap, bounded // by MaxLoadsPerTickCeiling (a sane hard maximum). MaxGlobalPendingLoads caps @@ -130,6 +141,7 @@ func ReadConfig() Config { AssumedPromptTokens: env.EnvInt(env.EnvPrefix+"_WARM_POOL_ASSUMED_PROMPT_TOKENS", 512), AssumedCompletionTokens: env.EnvInt(env.EnvPrefix+"_WARM_POOL_ASSUMED_COMPLETION_TOKENS", 256), MinWarmByModel: envModelIntMap(env.EnvPrefix + "_WARM_POOL_MIN_WARM"), + AllowBusyLoadMax: env.EnvInt(env.EnvPrefix+"_WARM_POOL_ALLOW_BUSY_LOAD_MAX", 0), MaxLoadsPerTick: env.EnvInt(env.EnvPrefix+"_WARM_POOL_MAX_LOADS_PER_TICK", 4), MaxLoadsPerTickCeiling: env.EnvInt(env.EnvPrefix+"_WARM_POOL_MAX_LOADS_PER_TICK_CEILING", 16), @@ -251,6 +263,9 @@ func (c WarmPoolConfig) Check() error { if c.AssumedPromptTokens < 0 || c.AssumedCompletionTokens < 0 { return fmt.Errorf("registry: warm pool assumed token counts must be >= 0") } + if c.AllowBusyLoadMax < 0 { + return fmt.Errorf("registry: warm pool allow-busy load max must be >= 0") + } if c.FallbackQualityConcurrency < 1 { return fmt.Errorf("registry: warm pool fallback quality concurrency must be >= 1") } diff --git a/coordinator/registry/dedicated_models.go b/coordinator/registry/dedicated_models.go index 045e79485f..9a9574d8a9 100644 --- a/coordinator/registry/dedicated_models.go +++ b/coordinator/registry/dedicated_models.go @@ -1,6 +1,9 @@ package registry -import "strings" +import ( + "strings" + "time" +) // Dedicated-model routing isolates a model family (e.g. Gemma 4) to providers // that run ONLY that family. A "dedicated" provider is one whose entire @@ -140,3 +143,72 @@ func (r *Registry) HasProviderForModel(model string, allowedSerials ...string) b } return false } + +// HasCapableProviderForModel is the capability-aware sibling of +// HasProviderForModel: it reports whether any provider advertises a +// catalog-allowed build of the resolved model id AND passes the STRUCTURAL +// public-routing gates — the liveness/trust/privacy core (online, trust floor, +// runtime-verified, private-text support, challenge freshness, not private-only) +// and trait eligibility (render-ok + capability version floors; vision when +// requiresVision), plus absolute hardware fit for non-resident models — while +// IGNORING the transient exclusions a freeing slot or a lapsing timer clears +// (the dedicated-box isolation rule, capacity / +// dispatch-load / inference-error cooldowns, the node-health breaker, and +// thermal state). +// +// It answers the question HasProviderForModel cannot: is a zero-candidate state +// TRANSIENT (a slot/cooldown will clear, or a dedicated box will free — shed as +// an uptime-neutral 429) or STRUCTURAL (the model is advertised only by +// private-only, runtime-unverified, below-trust, or render-broken providers that +// can NEVER serve this public request as configured — a 503 the client should +// not retry forever)? The consumer preflight uses it to keep genuinely +// unservable models on the 503 path while a dedicated-family model whose only +// providers are non-dedicated (dedicated-rule-excluded but otherwise capable) +// still reads as a transient 429. Like HasProviderForModel it never consults +// IsDedicatedModel, so the 429-vs-503 classification stays independent of +// EIGENINFERENCE_DEDICATED_MODELS (a pure routing-policy flip with instant +// rollback). When allowedSerials is non-empty the check is restricted to +// providers whose attested serial is in the set. +func (r *Registry) HasCapableProviderForModel(model string, traits RequestTraits, requiresVision bool, allowedSerials ...string) bool { + allowedSet := make(map[string]struct{}, len(allowedSerials)) + for _, s := range allowedSerials { + allowedSet[s] = struct{}{} + } + now := time.Now() + r.mu.RLock() + defer r.mu.RUnlock() + for _, p := range r.providers { + if len(allowedSet) > 0 && !providerMatchesAllowedSerial(p, allowedSet) { + continue + } + p.mu.Lock() + capable := r.providerServesCatalogModelLocked(p, model) && + r.providerLivenessGateLocked(p, r.MinTrustLevel, false, now) && + r.providerEligibleForTraitsLocked(p, model, traits) && + (!requiresVision || r.providerServesVisionModelLocked(p, model, false)) + if capable { + slotState := "unknown" + totalMemoryGB := float64(p.Hardware.MemoryGB) + if p.BackendCapacity != nil { + if p.BackendCapacity.TotalMemoryGB > 0 { + totalMemoryGB = p.BackendCapacity.TotalMemoryGB + } + for _, slot := range p.BackendCapacity.Slots { + if slot.Model == model { + slotState = slot.State + break + } + } + } + if !slotStateModelLoaded(slotState) && + !modelFitsHardware(r.catalogMinRAMGbLocked(model), r.modelSizeGBForFitLocked(p, model), totalMemoryGB) { + capable = false + } + } + p.mu.Unlock() + if capable { + return true + } + } + return false +} diff --git a/coordinator/registry/queue.go b/coordinator/registry/queue.go index e5443def79..f8c66b7f2a 100644 --- a/coordinator/registry/queue.go +++ b/coordinator/registry/queue.go @@ -42,6 +42,11 @@ var ErrQueueTimeout = errors.New("request queue timeout") // ttft_too_slow 429 instead of a queue timeout. var ErrQueueTTFTTooSlow = errors.New("all providers for queued request exceed the TTFT target") +// ErrModelShed is returned when an operator reject-set replacement removes a +// queued public request, or when a request that passed the API admission check +// races with that replacement and attempts to enqueue or drain afterward. +var ErrModelShed = errors.New("request model is temporarily shed") + // QueuedRequest represents a request waiting for a provider. type QueuedRequest struct { RequestID string @@ -52,6 +57,9 @@ type QueuedRequest struct { EnqueuedAt time.Time DoneCh chan struct{} // closed when the waiter is no longer interested doneOnce sync.Once + // queueState is guarded by RequestQueue.mu. It linearizes provider + // assignment and terminal failure against timeout/cancellation. + queueState queuedRequestState // Decision captures the cost breakdown of the routing decision that // dispatched (or terminally failed) this queued request. Populated by @@ -70,6 +78,15 @@ type QueuedRequest struct { FailureReason error } +type queuedRequestState uint8 + +const ( + queuedRequestWaiting queuedRequestState = iota + queuedRequestAssigned + queuedRequestFailed + queuedRequestAbandoned +) + func (r *QueuedRequest) init() { if r.ResponseCh == nil { r.ResponseCh = make(chan *Provider, 1) @@ -130,10 +147,11 @@ func drainRejectionTTFTTerminal(pr *PendingRequest, decision RoutingDecision) bo // RequestQueue manages per-model queues for requests awaiting providers. type RequestQueue struct { - mu sync.Mutex - queues map[string][]*QueuedRequest // model -> queue - maxSize int // max queue size per model - maxWait time.Duration // max time a request waits + mu sync.Mutex + queues map[string][]*QueuedRequest // model -> queue + shedModels map[string]struct{} // current public reject-set snapshot + maxSize int // max queue size per model + maxWait time.Duration // max time a request waits } // Default queue limits (see NewRequestQueueFromEnv for the sizing rationale). @@ -182,6 +200,9 @@ func (q *RequestQueue) Enqueue(req *QueuedRequest) error { q.mu.Lock() defer q.mu.Unlock() + if queuedRequestMatchesModels(req, q.shedModels) { + return ErrModelShed + } // Clean stale entries first q.cleanStaleLocked(req.Model) @@ -205,31 +226,54 @@ func (q *RequestQueue) WaitForProviderContext(ctx context.Context, req *QueuedRe select { case p := <-req.ResponseCh: - req.markDone() - if p == nil { - if req.FailureReason != nil { - return nil, req.FailureReason - } + return queuedRequestResult(req, p) + case <-timer.C: + if q.abandonIfWaiting(req) { return nil, ErrQueueTimeout } - return p, nil - case <-timer.C: - // Remove the request from the queue - req.markDone() - q.Remove(req.RequestID, req.Model) - return nil, ErrQueueTimeout + return queuedRequestResult(req, <-req.ResponseCh) case <-ctx.Done(): - req.markDone() - q.Remove(req.RequestID, req.Model) - return nil, ctx.Err() + if q.abandonIfWaiting(req) { + return nil, ctx.Err() + } + return queuedRequestResult(req, <-req.ResponseCh) + } +} + +func queuedRequestResult(req *QueuedRequest, provider *Provider) (*Provider, error) { + req.markDone() + if provider != nil { + return provider, nil + } + if req.FailureReason != nil { + return nil, req.FailureReason + } + return nil, ErrQueueTimeout +} + +// abandonIfWaiting atomically commits timeout/cancellation against provider +// assignment and queue failures. False means another terminal outcome already +// committed and its buffered response must be consumed by the waiter. +func (q *RequestQueue) abandonIfWaiting(req *QueuedRequest) bool { + q.mu.Lock() + defer q.mu.Unlock() + if req == nil || req.queueState != queuedRequestWaiting { + return false } + req.queueState = queuedRequestAbandoned + req.markDone() + q.removeLocked(req.RequestID, req.Model) + return true } // Remove removes a specific request from the queue by request ID. func (q *RequestQueue) Remove(requestID, model string) { q.mu.Lock() defer q.mu.Unlock() + q.removeLocked(requestID, model) +} +func (q *RequestQueue) removeLocked(requestID, model string) { queue := q.queues[model] for i, req := range queue { if req.RequestID == requestID { @@ -258,11 +302,7 @@ func (q *RequestQueue) PopNextFresh(model string) *QueuedRequest { delete(q.queues, model) } if now.Sub(req.EnqueuedAt) > q.maxWait { - req.markDone() - select { - case req.ResponseCh <- nil: - default: - } + q.failRequestLocked(req, nil) continue } return req @@ -277,6 +317,13 @@ func (q *RequestQueue) RequeueFront(req *QueuedRequest) { q.mu.Lock() defer q.mu.Unlock() + if req.queueState != queuedRequestWaiting { + return + } + if queuedRequestMatchesModels(req, q.shedModels) { + q.failRequestLocked(req, ErrModelShed) + return + } queue := q.queues[req.Model] queue = append([]*QueuedRequest{req}, queue...) q.queues[req.Model] = queue @@ -384,11 +431,8 @@ func (q *RequestQueue) FailQueuedRequestsForModel(model string, preferOwnerEligi continue } } - req.markDone() - select { - case req.ResponseCh <- nil: + if q.failRequestLocked(req, nil) { failed++ - default: } } if len(survivors) == 0 { @@ -399,6 +443,110 @@ func (q *RequestQueue) FailQueuedRequestsForModel(model string, preferOwnerEligi return failed } +// ReplaceShedModels atomically installs the queue's public reject-set snapshot +// and rejects matching waiters already present. Enqueue, requeue, and drain +// assignment consult the same snapshot under q.mu, closing races where a +// request passed API admission just before an operator PUT. Requests queue under +// the resolved build, so matching checks both that id and Pending.PublicModel. +// Exclusive self-route bypasses the public shed policy. Returns the number of +// queued waiters removed. +func (q *RequestQueue) ReplaceShedModels(models []string) int { + shed := make(map[string]struct{}, len(models)) + for _, model := range models { + if model != "" { + shed[model] = struct{}{} + } + } + q.mu.Lock() + defer q.mu.Unlock() + q.shedModels = shed + + failed := 0 + for queueModel := range q.queues { + q.cleanStaleLocked(queueModel) + queue := q.queues[queueModel] + if len(queue) == 0 { + continue + } + survivors := make([]*QueuedRequest, 0, len(queue)) + for _, req := range queue { + if !queuedRequestMatchesModels(req, shed) { + survivors = append(survivors, req) + continue + } + if q.failRequestLocked(req, ErrModelShed) { + failed++ + } + } + if len(survivors) == 0 { + delete(q.queues, queueModel) + } else { + q.queues[queueModel] = survivors + } + } + return failed +} + +// AssignProviderIfAllowed is the queue-drain commit point. It serializes the +// final shed check with ReplaceShedModels and the provider send, so either the +// assignment commits before an operator replacement or the waiter receives +// ErrModelShed after it; a popped request cannot slip through between them. +func (q *RequestQueue) AssignProviderIfAllowed(req *QueuedRequest, provider *Provider) bool { + if req == nil || provider == nil { + return false + } + q.mu.Lock() + defer q.mu.Unlock() + if req.queueState != queuedRequestWaiting { + return false + } + if queuedRequestMatchesModels(req, q.shedModels) { + q.failRequestLocked(req, ErrModelShed) + return false + } + select { + case req.ResponseCh <- provider: + req.queueState = queuedRequestAssigned + return true + default: + return false + } +} + +// FailRequest commits a typed terminal queue failure unless assignment, +// timeout, or cancellation already won the request-state transition. +func (q *RequestQueue) FailRequest(req *QueuedRequest, reason error) bool { + q.mu.Lock() + defer q.mu.Unlock() + return q.failRequestLocked(req, reason) +} + +func (q *RequestQueue) failRequestLocked(req *QueuedRequest, reason error) bool { + if req == nil || req.queueState != queuedRequestWaiting { + return false + } + req.queueState = queuedRequestFailed + req.failWithReason(reason) + return true +} + +func queuedRequestMatchesModels(req *QueuedRequest, models map[string]struct{}) bool { + if req == nil || len(models) == 0 { + return false + } + if req.Pending != nil && req.Pending.SelfRouteOnly { + return false + } + if _, ok := models[req.Model]; ok { + return true + } + if req.Pending != nil { + _, ok := models[req.Pending.PublicModel] + return ok + } + return false +} + // QueuedModels returns the set of model IDs that currently have at least // one request waiting in the queue. func (q *RequestQueue) QueuedModels() []string { @@ -427,12 +575,7 @@ func (q *RequestQueue) cleanStaleLocked(model string) { var fresh []*QueuedRequest for _, req := range queue { if now.Sub(req.EnqueuedAt) > q.maxWait { - // Close the response channel to signal timeout - req.markDone() - select { - case req.ResponseCh <- nil: - default: - } + q.failRequestLocked(req, nil) } else { fresh = append(fresh, req) } diff --git a/coordinator/registry/queue_test.go b/coordinator/registry/queue_test.go index 9ad8c9640b..37f78d8397 100644 --- a/coordinator/registry/queue_test.go +++ b/coordinator/registry/queue_test.go @@ -367,3 +367,145 @@ func TestFailQueuedRequestsForModelFailsOwnerlessPreferWaiter(t *testing.T) { t.Fatal("owner-less prefer waiter was not failed") } } + +func TestRequestQueueShedSnapshotGuardsLateEnqueue(t *testing.T) { + q := NewRequestQueue(10, 30*time.Second) + build := "queue-shed-build" + alias := "queue-shed-alias" + q.ReplaceShedModels([]string{alias}) + + matching := &QueuedRequest{ + RequestID: "matching", + Model: build, + Pending: &PendingRequest{RequestID: "matching", Model: build, PublicModel: alias}, + } + if err := q.Enqueue(matching); !errors.Is(err, ErrModelShed) { + t.Fatalf("matching alias enqueue error = %v, want ErrModelShed", err) + } + + raw := &QueuedRequest{ + RequestID: "raw", + Model: build, + Pending: &PendingRequest{RequestID: "raw", Model: build, PublicModel: build}, + } + if err := q.Enqueue(raw); err != nil { + t.Fatalf("raw-build waiter sharing the concrete queue was rejected: %v", err) + } + + selfRoute := &QueuedRequest{ + RequestID: "self", + Model: build, + Pending: &PendingRequest{RequestID: "self", Model: build, PublicModel: alias, SelfRouteOnly: true}, + } + if err := q.Enqueue(selfRoute); err != nil { + t.Fatalf("exclusive self-route waiter was rejected: %v", err) + } + if got := q.QueueSize(build); got != 2 { + t.Fatalf("queue size = %d, want raw-build plus self-route waiters", got) + } +} + +func TestRequestQueueShedSnapshotGuardsRequeueAndDrainAssignment(t *testing.T) { + q := NewRequestQueue(10, 30*time.Second) + model := "queue-shed-model" + + requeued := &QueuedRequest{ + RequestID: "requeued", + Model: model, + Pending: &PendingRequest{RequestID: "requeued", Model: model, PublicModel: model}, + } + draining := &QueuedRequest{ + RequestID: "draining", + Model: model, + Pending: &PendingRequest{RequestID: "draining", Model: model, PublicModel: model}, + } + if err := q.Enqueue(requeued); err != nil { + t.Fatalf("enqueue requeue candidate: %v", err) + } + if err := q.Enqueue(draining); err != nil { + t.Fatalf("enqueue drain candidate: %v", err) + } + requeued = q.PopNextFresh(model) + draining = q.PopNextFresh(model) + q.ReplaceShedModels([]string{model}) + q.RequeueFront(requeued) + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if _, err := q.WaitForProviderContext(ctx, requeued); !errors.Is(err, ErrModelShed) { + t.Fatalf("requeued shed waiter error = %v, want ErrModelShed", err) + } + + if q.AssignProviderIfAllowed(draining, &Provider{ID: "p1"}) { + t.Fatal("drain assigned a provider after the model was shed") + } + if _, err := q.WaitForProviderContext(ctx, draining); !errors.Is(err, ErrModelShed) { + t.Fatalf("draining shed waiter error = %v, want ErrModelShed", err) + } + + // Exclusive self-route bypasses the public shed even if it was popped before + // the replacement and reaches the final assignment afterward. + q.ReplaceShedModels(nil) + selfRoute := &QueuedRequest{ + RequestID: "self", + Model: model, + Pending: &PendingRequest{RequestID: "self", Model: model, PublicModel: model, SelfRouteOnly: true}, + } + if err := q.Enqueue(selfRoute); err != nil { + t.Fatalf("enqueue self-route: %v", err) + } + selfRoute = q.PopNextFresh(model) + q.ReplaceShedModels([]string{model}) + provider := &Provider{ID: "self-provider"} + if !q.AssignProviderIfAllowed(selfRoute, provider) { + t.Fatal("self-route drain was blocked by the public shed") + } + if got, err := q.WaitForProviderContext(ctx, selfRoute); err != nil || got != provider { + t.Fatalf("self-route assignment = (%v, %v), want provider", got, err) + } +} + +func TestRequestQueueAssignmentAndAbandonAreAtomic(t *testing.T) { + q := NewRequestQueue(10, 30*time.Second) + for i := 0; i < 1000; i++ { + req := &QueuedRequest{ + RequestID: "atomic", + Model: "atomic-model", + Pending: &PendingRequest{RequestID: "atomic", Model: "atomic-model"}, + } + req.init() + provider := &Provider{ID: "p1"} + start := make(chan struct{}) + assignedCh := make(chan bool, 1) + abandonedCh := make(chan bool, 1) + go func() { + <-start + assignedCh <- q.AssignProviderIfAllowed(req, provider) + }() + go func() { + <-start + abandonedCh <- q.abandonIfWaiting(req) + }() + close(start) + assigned := <-assignedCh + abandoned := <-abandonedCh + if assigned == abandoned { + t.Fatalf("iteration %d: assigned=%v abandoned=%v, want exactly one terminal transition", i, assigned, abandoned) + } + if assigned { + select { + case got := <-req.ResponseCh: + if got != provider { + t.Fatalf("iteration %d: assigned provider = %v, want %v", i, got, provider) + } + default: + t.Fatalf("iteration %d: assignment won without provider response", i) + } + } else { + select { + case <-req.Done(): + default: + t.Fatalf("iteration %d: abandon won without closing Done", i) + } + } + } +} diff --git a/coordinator/registry/registry.go b/coordinator/registry/registry.go index f8c32f81ce..464f9a88cf 100644 --- a/coordinator/registry/registry.go +++ b/coordinator/registry/registry.go @@ -1206,6 +1206,10 @@ type Registry struct { providers map[string]*Provider queue *RequestQueue + // queueShedModels mirrors the Server's current public reject set into any + // test-swapped queue. Production installs the queue once at startup, but + // keeping the snapshot here makes SetQueue linearizable too. + queueShedModels []string MinTrustLevel TrustLevel @@ -1233,6 +1237,14 @@ type Registry struct { qualityCapFloorTPS float64 qualityCapFallback int + // combinedAdmissionCap extends the quality-concurrency cap with a box-wide + // budget (see combinedAdmissionHeadroomLocked in concurrency_cap.go): per-model + // caps are otherwise checked independently, so a box saturated on model A + // still admits model B. Default off (dormant until the open-pool flip); set + // once at startup via SetCombinedAdmissionCap from + // EIGENINFERENCE_COMBINED_ADMISSION_CAP. Guarded by r.mu. + combinedAdmissionCap bool + // APNs code-identity rollout policy (v0.6.0), guarded by r.mu and evaluated // LIVE at every routing decision so a deadline can flip enforcement on/off // without forcing providers to reconnect. @@ -2338,6 +2350,9 @@ func (r *Registry) SetQueue(q *RequestQueue) { r.mu.Lock() defer r.mu.Unlock() r.queue = q + if q != nil { + q.ReplaceShedModels(r.queueShedModels) + } } // Sanity caps on provider-reported stats. A malicious (or broken) provider @@ -3302,6 +3317,24 @@ func (r *Registry) MarkModelWarm(providerID, modelID string) { } } if !found { + // Preserve slot-cap safety until the next heartbeat replaces this + // synthetic snapshot. OccupiedModelSlots may include non-routable + // unloading/loading models that are absent from Slots, so advance its + // count conservatively when a newly successful load is injected. + visibleBefore := make(map[string]struct{}, len(p.BackendCapacity.Slots)) + for _, slot := range p.BackendCapacity.Slots { + if slot.Model != "" { + visibleBefore[slot.Model] = struct{}{} + } + } + occupied := p.BackendCapacity.OccupiedModelSlots + if len(visibleBefore) > occupied { + occupied = len(visibleBefore) + } + if p.BackendCapacity.MaxModelSlots <= 0 || occupied < p.BackendCapacity.MaxModelSlots { + occupied++ + } + p.BackendCapacity.OccupiedModelSlots = occupied p.BackendCapacity.Slots = append(p.BackendCapacity.Slots, protocol.BackendSlotCapacity{ Model: modelID, State: "idle", @@ -3433,6 +3466,38 @@ func (r *Registry) RejectUnservableQueuedRequests(modelID string) { } } +// RejectQueuedRequestsForShedModels fails the queued waiters for models the +// operator just added to the reject set (PUT /v1/admin/reject-models), so a +// runtime shed takes effect on requests ALREADY waiting in the queue rather than +// only future admission — otherwise up to a full queue window of requests +// (queued by queue-before-shed / cold-dispatch before the flip) would still +// dispatch to a model pulled out of rotation mid-incident. Unlike +// RejectUnservableQueuedRequests this makes NO capacity check: the operator's +// shed is authoritative, so a served-model verdict must not preserve the +// waiters. Exclusive self-route waiters (SelfRouteOnly) are preserved by the +// queue filter because they bypass the shed at admission (an +// owner's own machine is never shed); prefer-owner and public waiters are failed. +// Matching is per request against both the resolved queue model and PublicModel, +// so shedding an alias does not fail raw-build or other-alias waiters that share +// the same concrete queue. Returns the total number of queued requests failed. +func (r *Registry) RejectQueuedRequestsForShedModels(models []string) int { + r.mu.Lock() + defer r.mu.Unlock() + r.queueShedModels = append(r.queueShedModels[:0], models...) + queue := r.queue + if queue == nil { + return 0 + } + failed := queue.ReplaceShedModels(models) + if failed > 0 { + r.logger.Warn("failed queued requests for shed models", + "models", models, + "rejected", failed, + ) + } + return failed +} + func cumulativeDelta(previous, current int64) int64 { if current <= 0 { return 0 diff --git a/coordinator/registry/scheduler.go b/coordinator/registry/scheduler.go index 477a873aca..a8b6e32dde 100644 --- a/coordinator/registry/scheduler.go +++ b/coordinator/registry/scheduler.go @@ -2410,7 +2410,7 @@ func (r *Registry) drainQueuedRequestsForModels(models []string) { // the decision's BestTTFTMs for Retry-After. if drainRejectionTTFTTerminal(req.Pending, decision) { req.Decision = decision - req.failWithReason(ErrQueueTTFTTooSlow) + queue.FailRequest(req, ErrQueueTTFTTooSlow) continue } skipped = append(skipped, req) @@ -2419,22 +2419,7 @@ func (r *Registry) drainQueuedRequestsForModels(models []string) { req.Decision = decision requeueSkipped() - select { - case <-req.Done(): - provider.RemovePending(req.Pending.RequestID) - r.SetProviderIdle(provider.ID) - continue - default: - } - - select { - case req.ResponseCh <- provider: - // Successfully assigned. - case <-req.Done(): - provider.RemovePending(req.Pending.RequestID) - r.SetProviderIdle(provider.ID) - continue - default: + if !queue.AssignProviderIfAllowed(req, provider) { provider.RemovePending(req.Pending.RequestID) r.SetProviderIdle(provider.ID) continue diff --git a/coordinator/registry/scheduler_helpers_test.go b/coordinator/registry/scheduler_helpers_test.go index 9db6395c6b..0ed2efb0a4 100644 --- a/coordinator/registry/scheduler_helpers_test.go +++ b/coordinator/registry/scheduler_helpers_test.go @@ -27,6 +27,7 @@ func makeSchedulerProvider(t *testing.T, reg *Registry, id, model string, decode } p.BackendCapacity = &protocol.BackendCapacity{ TotalMemoryGB: 64, + MaxModelSlots: 3, Slots: []protocol.BackendSlotCapacity{ { Model: model, diff --git a/coordinator/registry/warm_pool_busy_gate_test.go b/coordinator/registry/warm_pool_busy_gate_test.go new file mode 100644 index 0000000000..5c81c7d2b9 --- /dev/null +++ b/coordinator/registry/warm_pool_busy_gate_test.go @@ -0,0 +1,350 @@ +package registry + +import ( + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" +) + +// Tests for the bounded-busy warm-pool candidate gate (postmortem 2026-07-06 +// layer 7): eligibility is max(pendingCount, Σ slots(NumRunning+NumWaiting)) <= +// WarmPoolConfig.AllowBusyLoadMax, with the default 0 preserving the historical +// fully-idle requirement exactly, and non-idle candidates additionally required +// to fit the model weights WITHOUT evicting co-resident models. + +// warmCandidateReason evaluates the warm-pool candidate gate under the lock +// discipline the fleet snapshot uses and returns the disqualification reason +// ("" = eligible). +func warmCandidateReason(reg *Registry, p *Provider, model string) warmColdReason { + reg.mu.RLock() + defer reg.mu.RUnlock() + p.mu.Lock() + defer p.mu.Unlock() + _, reason := reg.warmPoolCandidateReasonLocked(p, model, time.Now()) + return reason +} + +// configureBusyGate installs a warm-pool config with the given bounded-busy +// threshold (the only knob under test here). +func configureBusyGate(reg *Registry, allowBusyLoadMax int) { + cfg := testWarmPoolConfig() + cfg.AllowBusyLoadMax = allowBusyLoadMax + reg.ConfigureWarmPool(cfg) +} + +// TestWarmPoolBusyGateDefaultZeroPreservesFullIdle pins the AllowBusyLoadMax=0 +// default to the exact historical behavior: ANY activity — one coordinator- +// pending request or one backend-busy slot — disqualifies the cold candidate +// with warmColdNotIdle, and a truly idle box is eligible. Covers both the +// unconfigured-controller default and an explicit 0. +func TestWarmPoolBusyGateDefaultZeroPreservesFullIdle(t *testing.T) { + model := "busy-gate-default" + + for _, configured := range []bool{false, true} { + reg := New(testLogger()) + if configured { + configureBusyGate(reg, 0) + } + + idle := makeWarmPoolColdProvider(t, reg, "idle", model, 80, 64, 8) + if got := warmCandidateReason(reg, idle, model); got != warmColdEligible { + t.Fatalf("configured=%v idle box reason = %q, want eligible", configured, got) + } + + backendBusy := makeWarmPoolColdProvider(t, reg, "backend-busy", model, 80, 64, 8) + backendBusy.mu.Lock() + backendBusy.BackendCapacity.Slots[0].NumRunning = 1 + backendBusy.mu.Unlock() + if got := warmCandidateReason(reg, backendBusy, model); got != warmColdNotIdle { + t.Fatalf("configured=%v backend-busy box reason = %q, want %q", configured, got, warmColdNotIdle) + } + + pending := makeWarmPoolColdProvider(t, reg, "pending", model, 80, 64, 8) + pending.mu.Lock() + pending.pendingReqs["r1"] = &PendingRequest{RequestID: "r1", Model: "other-model"} + pending.mu.Unlock() + if got := warmCandidateReason(reg, pending, model); got != warmColdNotIdle { + t.Fatalf("configured=%v 1-pending box reason = %q, want %q", configured, got, warmColdNotIdle) + } + } +} + +// TestWarmPoolBusyGateBoundedThreshold exercises the AllowBusyLoadMax=2 +// boundary: coordinator and backend counts are overlapping views of the same +// work, so their maximum (not their sum) of 1 or 2 is eligible and 3 is not. +func TestWarmPoolBusyGateBoundedThreshold(t *testing.T) { + model := "busy-gate-bounded" + + cases := []struct { + name string + pending int + numRunning int + numWaiting int + want warmColdReason + }{ + {name: "busy_1_running", numRunning: 1, want: warmColdEligible}, + {name: "busy_2_running_waiting", numRunning: 1, numWaiting: 1, want: warmColdEligible}, + {name: "mirrored_busy_2_not_double_counted", pending: 2, numRunning: 2, want: warmColdEligible}, + {name: "busy_3_over_threshold", numRunning: 2, numWaiting: 1, want: warmColdNotIdle}, + {name: "pending_3_over_threshold", pending: 3, numRunning: 2, want: warmColdNotIdle}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + reg := New(testLogger()) + configureBusyGate(reg, 2) + p := makeWarmPoolColdProvider(t, reg, "box-"+tc.name, model, 80, 64, 8) + p.mu.Lock() + p.BackendCapacity.Slots[0].NumRunning = tc.numRunning + p.BackendCapacity.Slots[0].NumWaiting = tc.numWaiting + for i := 0; i < tc.pending; i++ { + id := "r" + string(rune('0'+i)) + p.pendingReqs[id] = &PendingRequest{RequestID: id, Model: "other-model"} + } + p.mu.Unlock() + + if got := warmCandidateReason(reg, p, model); got != tc.want { + t.Fatalf("reason = %q, want %q", got, tc.want) + } + }) + } +} + +// TestWarmPoolBusyGateRequiresModelSlotHeadroom prevents bounded-busy recovery +// from issuing a load the provider must reject. A busy provider cannot evict an +// active slot, so its heartbeat must prove the target can consume another model +// slot. Legacy providers that omit max_model_slots fail closed only on the +// bounded-busy path; fully idle warming remains backward compatible. +func TestWarmPoolBusyGateRequiresModelSlotHeadroom(t *testing.T) { + model := "busy-gate-slot-headroom" + + for _, tc := range []struct { + name string + maxModelSlots int + want warmColdReason + }{ + {name: "one_of_two_slots_used", maxModelSlots: 2, want: warmColdEligible}, + {name: "only_slot_is_active", maxModelSlots: 1, want: warmColdBusyNoEvict}, + {name: "legacy_slot_cap_unknown", maxModelSlots: 0, want: warmColdBusyNoEvict}, + } { + t.Run(tc.name, func(t *testing.T) { + reg := New(testLogger()) + configureBusyGate(reg, 2) + p := makeWarmPoolColdProvider(t, reg, "box-"+tc.name, model, 80, 64, 8) + p.mu.Lock() + p.BackendCapacity.MaxModelSlots = tc.maxModelSlots + p.BackendCapacity.Slots[0].State = "running" + p.BackendCapacity.Slots[0].NumRunning = 1 + p.mu.Unlock() + + if got := warmCandidateReason(reg, p, model); got != tc.want { + t.Fatalf("reason = %q, want %q", got, tc.want) + } + }) + } +} + +func TestWarmPoolBusyGateRejectsUnusableTargetSlot(t *testing.T) { + model := "busy-gate-unusable-target-slot" + for _, state := range []string{"crashed", "reloading", "idle_shutdown"} { + t.Run(state, func(t *testing.T) { + reg := New(testLogger()) + configureBusyGate(reg, 2) + p := makeWarmPoolColdProvider(t, reg, "box-"+state, model, 80, 64, 8) + p.mu.Lock() + p.BackendCapacity.MaxModelSlots = 2 + p.BackendCapacity.Slots[0] = protocol.BackendSlotCapacity{ + Model: model, State: state, NumRunning: 1, + } + p.mu.Unlock() + + if got := warmCandidateReason(reg, p, model); got != warmColdBusyNoEvict { + t.Fatalf("target slot state %q reason = %q, want %q", state, got, warmColdBusyNoEvict) + } + }) + } +} + +func TestWarmPoolBusyGateCountsPendingColdModelsAgainstSlotCap(t *testing.T) { + model := "busy-gate-pending-slot" + reg := New(testLogger()) + configureBusyGate(reg, 2) + p := makeWarmPoolColdProvider(t, reg, "pending-slot-box", model, 80, 64, 8) + p.mu.Lock() + p.BackendCapacity.MaxModelSlots = 2 + p.BackendCapacity.Slots[0].State = "running" + p.BackendCapacity.Slots[0].NumRunning = 1 + p.pendingReqs["pending-cold"] = &PendingRequest{ + RequestID: "pending-cold", + Model: "another-cold-model", + } + p.mu.Unlock() + + if got := warmCandidateReason(reg, p, model); got != warmColdBusyNoEvict { + t.Fatalf("reason = %q, want %q when pending cold model reserves final slot", got, warmColdBusyNoEvict) + } +} + +func TestWarmPoolBusyGateCountsHiddenOccupiedSlots(t *testing.T) { + model := "busy-gate-hidden-occupied-slot" + reg := New(testLogger()) + configureBusyGate(reg, 2) + p := makeWarmPoolColdProvider(t, reg, "hidden-slot-box", model, 80, 64, 8) + p.mu.Lock() + p.BackendCapacity.MaxModelSlots = 2 + p.BackendCapacity.OccupiedModelSlots = 2 + p.BackendCapacity.Slots[0].State = "running" + p.BackendCapacity.Slots[0].NumRunning = 1 + p.mu.Unlock() + + if got := warmCandidateReason(reg, p, model); got != warmColdBusyNoEvict { + t.Fatalf("reason = %q, want %q when an unloading slot is hidden from routable slots", got, warmColdBusyNoEvict) + } +} + +func TestMarkModelWarmConservativelyAdvancesOccupiedSlots(t *testing.T) { + model := "synthetic-warm-occupancy" + reg := New(testLogger()) + p := makeWarmPoolColdProvider(t, reg, "synthetic-warm-box", model, 80, 64, 8) + p.mu.Lock() + p.BackendCapacity.MaxModelSlots = 3 + p.BackendCapacity.OccupiedModelSlots = 2 + p.mu.Unlock() + + reg.MarkModelWarm(p.ID, model) + + p.mu.Lock() + defer p.mu.Unlock() + if got := p.BackendCapacity.OccupiedModelSlots; got != 3 { + t.Fatalf("occupied model slots after synthetic warm = %d, want 3", got) + } + found := false + for _, slot := range p.BackendCapacity.Slots { + if slot.Model == model && slot.State == "idle" { + found = true + break + } + } + if !found { + t.Fatal("synthetic warm slot was not installed") + } +} + +// TestWarmPoolBusyGateNoEvictionFit pins the no-eviction rule for non-idle +// candidates (mirror of the dispatch path's freeMemoryAdmits, which only +// consults the eviction-aware headroom when totalPending == 0): a busy box must +// fit the weights in its CURRENT free memory (total - gpuActive), because it +// cannot evict idle co-resident models. The same box, idle, stays eligible — +// eviction is available again. +func TestWarmPoolBusyGateNoEvictionFit(t *testing.T) { + model := "busy-gate-no-evict" + catalog := []CatalogEntry{{ID: model, SizeGB: 30, MinRAMGB: 36}} + + build := func(t *testing.T, activeGB float64, busy int, freeForLoadGB *float64) (*Registry, *Provider) { + reg := New(testLogger()) + configureBusyGate(reg, 2) + reg.SetModelCatalog(catalog) + p := makeWarmPoolColdProvider(t, reg, "box", model, 80, 36, activeGB) + p.mu.Lock() + p.BackendCapacity.Slots[0].NumRunning = busy + p.BackendCapacity.FreeForLoadGB = freeForLoadGB + p.mu.Unlock() + return reg, p + } + + // Busy box, weights (30 GB) exceed current free memory (36-20=16 GB): the + // bounded-busy gate admits it but the no-eviction fit vetoes. + reg, p := build(t, 20, 1, nil) + if got := warmCandidateReason(reg, p, model); got != warmColdBusyNoEvict { + t.Fatalf("busy tight-memory box reason = %q, want %q", got, warmColdBusyNoEvict) + } + + // The SAME memory shape, idle: eligible — an idle box may evict, and the + // eviction-aware reported gate (absent here) is the only fit authority. + reg, p = build(t, 20, 0, nil) + if got := warmCandidateReason(reg, p, model); got != warmColdEligible { + t.Fatalf("idle tight-memory box reason = %q, want eligible (idle boxes may evict)", got) + } + + // Busy box with real headroom (36-2=34 GB >= 30 GB): eligible. + reg, p = build(t, 2, 1, nil) + if got := warmCandidateReason(reg, p, model); got != warmColdEligible { + t.Fatalf("busy roomy box reason = %q, want eligible", got) + } + + // The provider-reported free-for-load gate still runs FIRST: a busy box whose + // reported loadable headroom is too small is no_free_for_load, not the + // no-eviction reason. + tooSmall := 10.0 + reg, p = build(t, 2, 1, &tooSmall) + if got := warmCandidateReason(reg, p, model); got != warmColdNoFreeForLoad { + t.Fatalf("busy reported-too-small box reason = %q, want %q", got, warmColdNoFreeForLoad) + } +} + +// TestWarmPoolBusyGateNoEvictUsesPaddedGiB is the finding-2 regression: the +// busy no-evict fit must compare the model's PADDED-GiB load footprint +// (catalog decimal GB × coldLoadCatalogGBToMemGiB, the provider's own +// ModelLoadAdmission basis) against freeGB (reported in GiB), NOT the raw +// decimal-GB catalog size. A 30 GB model needs ~33.5 GiB loaded, so a busy box +// with 32 GiB free must be vetoed (a raw 30>32 check wrongly admits it, and the +// provider then rejects load_model → failed warm + pending-load cooldown). A box +// with 34 GiB free clears the padded 33.5 GiB and stays eligible. +func TestWarmPoolBusyGateNoEvictUsesPaddedGiB(t *testing.T) { + model := "busy-gate-padded" + catalog := []CatalogEntry{{ID: model, SizeGB: 30, MinRAMGB: 36}} + + // freeForLoadGB is nil so the reported free-for-load gate (which already uses + // the padded basis) is skipped and the no-evict fit is what decides. + build := func(t *testing.T, totalGB, activeGB float64) (*Registry, *Provider) { + reg := New(testLogger()) + configureBusyGate(reg, 2) + reg.SetModelCatalog(catalog) + p := makeWarmPoolColdProvider(t, reg, "box", model, 80, totalGB, activeGB) + p.mu.Lock() + p.BackendCapacity.Slots[0].NumRunning = 1 // busy => no-evict fit applies + p.BackendCapacity.FreeForLoadGB = nil + p.mu.Unlock() + return reg, p + } + + // freeGB = 40 - 8 = 32 GiB: sits BETWEEN the raw size (30) and the padded + // footprint (30 × ~1.1176 ≈ 33.5). The raw check admitted this; the padded + // check correctly vetoes it. + reg, p := build(t, 40, 8) + if got := warmCandidateReason(reg, p, model); got != warmColdBusyNoEvict { + t.Fatalf("busy box with 32 GiB free (< 33.5 GiB padded) reason = %q, want %q", got, warmColdBusyNoEvict) + } + + // freeGB = 40 - 6 = 34 GiB: clears the padded 33.5 GiB footprint => eligible. + reg, p = build(t, 40, 6) + if got := warmCandidateReason(reg, p, model); got != warmColdEligible { + t.Fatalf("busy box with 34 GiB free (> 33.5 GiB padded) reason = %q, want eligible", got) + } +} + +// TestWarmColdReasonStringsStable pins every warmColdReason string: they are +// exported as Datadog gauge tags (warm_pool.cold_disqualified reason:<...>) and +// appear in warm_pool_tick logs — dashboards key on them, so a rename is a +// breaking change, not a refactor. +func TestWarmColdReasonStringsStable(t *testing.T) { + want := map[warmColdReason]string{ + warmColdEligible: "", + warmColdOfflineUntrust: "offline_untrusted_private", + warmColdPendingLoad: "pending_load_or_cooldown", + warmColdNotIdle: "not_idle", + warmColdThermal: "thermal_critical", + warmColdTrust: "trust_or_runtime", + warmColdStaleChallenge: "stale_challenge", + warmColdNotServing: "not_serving_catalog", + warmColdDedicated: "dedicated_excluded", + warmColdTooLarge: "model_too_large", + warmColdNoFreeForLoad: "no_free_for_load", + warmColdBusyNoEvict: "busy_no_evict_headroom", + } + for reason, s := range want { + if string(reason) != s { + t.Fatalf("warmColdReason %q changed, want %q — gauge tags/dashboards key on these strings", string(reason), s) + } + } +} diff --git a/coordinator/registry/warm_pool_controller.go b/coordinator/registry/warm_pool_controller.go index 861f8a2e82..5fd642d734 100644 --- a/coordinator/registry/warm_pool_controller.go +++ b/coordinator/registry/warm_pool_controller.go @@ -650,6 +650,7 @@ const ( warmColdDedicated warmColdReason = "dedicated_excluded" warmColdTooLarge warmColdReason = "model_too_large" warmColdNoFreeForLoad warmColdReason = "no_free_for_load" + warmColdBusyNoEvict warmColdReason = "busy_no_evict_headroom" ) // warmColdReasonStrings converts a reason tally to a string-keyed map for @@ -691,7 +692,20 @@ func (r *Registry) warmPoolCandidateReasonLocked(p *Provider, model string, now if r.providerHasPendingLoad(p.ID) || r.dispatchLoadCooldownActiveLocked(p.ID, model, now) { return warmPoolCandidate{}, warmColdPendingLoad } - if p.pendingCount() != 0 || warmPoolBackendSlotBusyLocked(p) { + // Bounded-busy eligibility (postmortem 2026-07-06 layer 7): the historical + // gate disqualified a cold candidate on ANY activity, so during a recovery + // every box carrying a single request read as ineligible, eligible_cold hit 0, + // and the MIN_WARM floor was clamped into a no-op. Coordinator pending and + // backend running+waiting are overlapping views of the same work, so use + // their maximum instead of double-counting mirrored requests. Eligible when + // that busy load is within AllowBusyLoadMax + // (EIGENINFERENCE_WARM_POOL_ALLOW_BUSY_LOAD_MAX). The default 0 preserves the + // exact historical fully-idle behavior. + busyLoad := p.pendingCount() + if backendLoad := warmPoolBackendSlotLoadLocked(p); backendLoad > busyLoad { + busyLoad = backendLoad + } + if busyLoad > r.warmPoolAllowBusyLoadMaxLocked() { return warmPoolCandidate{}, warmColdNotIdle } if p.SystemMetrics.ThermalState == "critical" { @@ -735,6 +749,32 @@ func (r *Registry) warmPoolCandidateReasonLocked(p *Provider, model string, now if freeGB < 0 { freeGB = 0 } + // No-eviction fit for non-idle candidates: a busy box cannot evict idle + // co-resident models to make room (the provider only swaps when it has no + // in-flight requests), and its reported free_for_load_gb may assume exactly + // that eviction. Mirror the dispatch-path rule (freeMemoryAdmits falls through + // to the eviction-free `free >= required` check whenever totalPending > 0): + // when the bounded-busy gate admitted a non-idle box, the weights must + // additionally fit in the CURRENT free memory. Unknown catalog size fails + // open, like the gates above. Unreachable at AllowBusyLoadMax=0 (busyLoad is + // always 0 there), so the default behavior is unchanged. + // + // The catalog size is decimal GB (on-disk, TotalSizeBytes/1e9) while freeGB is + // GiB (the provider reports total/active memory as bytes/2^30). Compare on the + // provider's padded-GiB load basis (coldLoadCatalogGBToMemGiB: ×1.2 memory + // overhead, then decimal-GB→GiB) so this mirrors the provider's own + // ModelLoadAdmission gate exactly — otherwise a near-threshold model whose RAW + // size fits freeGB but whose PADDED footprint does not is admitted here and + // then rejected at load_model (failed warm + pending-load cooldown, Codex + // #390), instead of selecting a truly loadable box. + if busyLoad > 0 { + if !warmPoolModelSlotHeadroomLocked(p, model) { + return warmPoolCandidate{}, warmColdBusyNoEvict + } + if size := r.catalogSizeGBLocked(model); size > 0 && size*coldLoadCatalogGBToMemGiB > freeGB { + return warmPoolCandidate{}, warmColdBusyNoEvict + } + } thermalPenalty := 0.0 switch p.SystemMetrics.ThermalState { case "serious": @@ -746,6 +786,51 @@ func (r *Registry) warmPoolCandidateReasonLocked(p *Provider, model string, now return warmPoolCandidate{providerID: p.ID, score: score}, warmColdEligible } +// warmPoolModelSlotHeadroomLocked reports whether a busy provider can load the +// target without evicting a co-resident model. Caller holds p.mu. Legacy +// providers omit MaxModelSlots; fail closed only for bounded-busy warming +// because their active slot cap cannot be proven. +func warmPoolModelSlotHeadroomLocked(p *Provider, model string) bool { + if p.BackendCapacity == nil || p.BackendCapacity.MaxModelSlots <= 0 { + return false + } + + occupiedModels := make(map[string]struct{}, len(p.BackendCapacity.Slots)+len(p.pendingReqs)) + for _, slot := range p.BackendCapacity.Slots { + if slot.Model == model { + // The caller only evaluates cold targets. A target-labelled slot here + // is therefore crashed, reloading, or shutting down; load_model would + // short-circuit on that existing slot instead of creating a warm one. + return false + } + if slot.Model != "" { + occupiedModels[slot.Model] = struct{}{} + } + } + occupied := len(occupiedModels) + if p.BackendCapacity.OccupiedModelSlots > occupied { + // The provider keeps unloading models resident until teardown completes, + // but omits them from routable Slots. Preserve that authoritative count. + occupied = p.BackendCapacity.OccupiedModelSlots + } + // A newly assigned cold model may not appear in the next heartbeat yet, but + // it has already reserved a model slot. Count distinct pending models that + // are absent from the heartbeat. The target itself is the prospective slot + // this admission check is deciding, so do not count it twice. + pendingOnlyModels := make(map[string]struct{}) + for _, pending := range p.pendingReqs { + if pending == nil || pending.Model == "" || pending.Model == model { + continue + } + if _, reported := occupiedModels[pending.Model]; reported { + continue + } + pendingOnlyModels[pending.Model] = struct{}{} + } + occupied += len(pendingOnlyModels) + return occupied < p.BackendCapacity.MaxModelSlots +} + func warmPoolBackendSlotBusyLocked(p *Provider) bool { if p.BackendCapacity == nil { return false @@ -758,6 +843,37 @@ func warmPoolBackendSlotBusyLocked(p *Provider) bool { return false } +// warmPoolBackendSlotLoadLocked sums the backend-reported in-flight load +// (NumRunning + NumWaiting) across ALL slots — the Σ term of the bounded-busy +// candidate gate. Negative heartbeat values are clamped to 0 so a malformed slot +// cannot mask another slot's real load. Caller must hold p.mu. +func warmPoolBackendSlotLoadLocked(p *Provider) int { + if p.BackendCapacity == nil { + return 0 + } + load := 0 + for _, slot := range p.BackendCapacity.Slots { + if slot.NumRunning > 0 { + load += slot.NumRunning + } + if slot.NumWaiting > 0 { + load += slot.NumWaiting + } + } + return load +} + +// warmPoolAllowBusyLoadMaxLocked returns the bounded-busy eligibility threshold +// (WarmPoolConfig.AllowBusyLoadMax), or 0 — the historical fully-idle +// requirement — when the controller is not configured or the value is invalid. +// Caller must hold r.mu (the controller pointer and its config are guarded by it). +func (r *Registry) warmPoolAllowBusyLoadMaxLocked() int { + if r.warmPool == nil || r.warmPool.config.AllowBusyLoadMax < 0 { + return 0 + } + return r.warmPool.config.AllowBusyLoadMax +} + func (r *Registry) pendingModelLoadCount(now time.Time) int { r.mu.Lock() defer r.mu.Unlock() diff --git a/coordinator/registry/warm_pool_controller_test.go b/coordinator/registry/warm_pool_controller_test.go index 731f99ce0b..2849abf041 100644 --- a/coordinator/registry/warm_pool_controller_test.go +++ b/coordinator/registry/warm_pool_controller_test.go @@ -35,6 +35,7 @@ func makeWarmPoolColdProvider(t *testing.T, reg *Registry, id, model string, dec p.BackendCapacity = &protocol.BackendCapacity{ TotalMemoryGB: totalMemory, GPUMemoryActiveGB: activeMemory, + MaxModelSlots: 3, Slots: []protocol.BackendSlotCapacity{ {Model: "other-model", State: "idle"}, }, diff --git a/coordinator/registry/warm_pool_rewarm_test.go b/coordinator/registry/warm_pool_rewarm_test.go new file mode 100644 index 0000000000..bb271dd596 --- /dev/null +++ b/coordinator/registry/warm_pool_rewarm_test.go @@ -0,0 +1,118 @@ +package registry + +import ( + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/protocol" +) + +// Tests for the MIN_WARM floor's ability to actually re-warm a box after the +// provider's 1h idle-unload (postmortem 2026-07-06 §3.3: floors were impotent +// because the controller clamps its target to warm + eligible_cold, and +// eligibility blocked every cold box — "eligible_cold: 0"). + +// warmSnapshotFor returns the snapshot row for model (tick emits one row per +// observed model). +func warmSnapshotFor(t *testing.T, snaps []WarmPoolSnapshot, model string) WarmPoolSnapshot { + t.Helper() + for _, s := range snaps { + if s.Model == model { + return s + } + } + t.Fatalf("no warm-pool snapshot for model %q in %+v", model, snaps) + return WarmPoolSnapshot{} +} + +// TestWarmPoolMinWarmFloorRewarmsIdleUnloadedBox covers the floor path with the +// busy gate at its default 0 and a truly idle cold candidate: a warm box whose +// provider idle-unloads the model (its backend slot disappears) is re-warmed on +// the next tick because warm < MinWarmByModel — with ZERO demand pressure. The +// floor must act on eligibility alone. +func TestWarmPoolMinWarmFloorRewarmsIdleUnloadedBox(t *testing.T) { + reg := New(testLogger()) + model := "warm-pool-floor-rewarm" + cfg := testWarmPoolConfig() + cfg.MinWarmByModel = map[string]int{model: 1} + p := makeSchedulerProvider(t, reg, "floor-box", model, 80) + reg.ConfigureWarmPool(cfg) + sent := captureWarmPoolLoads(reg) + + // Warm and floor-satisfied: no loads issued. + snaps := reg.warmPool.tick(time.Now()) + if len(*sent) != 0 { + t.Fatalf("warm phase sent %d loads, want 0", len(*sent)) + } + snap := warmSnapshotFor(t, snaps, model) + if snap.WarmProviders != 1 || snap.TargetWarm != 1 { + t.Fatalf("warm phase snapshot = warm %d target %d, want 1/1", snap.WarmProviders, snap.TargetWarm) + } + + // Simulate the provider's idle-unload: the model's backend slot disappears + // (the provider reports one slot per resident model), box now cold and idle. + p.mu.Lock() + p.BackendCapacity.Slots = nil + p.mu.Unlock() + + snaps = reg.warmPool.tick(time.Now()) + snap = warmSnapshotFor(t, snaps, model) + if snap.WarmProviders != 0 || snap.EligibleCold != 1 { + t.Fatalf("cold phase snapshot = warm %d eligible_cold %d (disq %v), want 0/1 — eligibility wrongly blocks the re-warm", + snap.WarmProviders, snap.EligibleCold, snap.ColdDisqualifiers) + } + if snap.TargetWarm != 1 { + t.Fatalf("cold phase target = %d, want 1 (MIN_WARM floor with zero demand pressure)", snap.TargetWarm) + } + if len(*sent) != 1 || (*sent)[0].providerID != "floor-box" || (*sent)[0].modelID != model { + t.Fatalf("cold phase loads = %+v, want exactly one re-warm of floor-box/%s", *sent, model) + } +} + +// TestWarmPoolMinWarmFloorRewarmsLightlyBusyBox is the busy-gate regression on +// the same floor path: the idle-unloaded box is still serving ONE request of +// another model. With the historical fully-idle gate (AllowBusyLoadMax=0) the +// floor is clamped to eligible_cold=0 and cannot act; with the bounded-busy +// gate at 2 the box is eligible and the floor re-warms it. +func TestWarmPoolMinWarmFloorRewarmsLightlyBusyBox(t *testing.T) { + model := "warm-pool-floor-busy-rewarm" + + build := func(t *testing.T, allowBusyLoadMax int) (*Registry, *[]modelLoadAction) { + reg := New(testLogger()) + cfg := testWarmPoolConfig() + cfg.MinWarmByModel = map[string]int{model: 1} + cfg.AllowBusyLoadMax = allowBusyLoadMax + p := makeSchedulerProvider(t, reg, "busy-box", model, 80) + p.mu.Lock() + // Idle-unloaded `model`, still decoding one request of a co-resident model. + p.BackendCapacity.Slots = []protocol.BackendSlotCapacity{ + {Model: "co-resident-model", State: "running", NumRunning: 1}, + } + p.mu.Unlock() + reg.ConfigureWarmPool(cfg) + return reg, captureWarmPoolLoads(reg) + } + + // Historical gate: the single in-flight request blocks eligibility, the + // floor is clamped, no load is issued (this is the postmortem trap). + reg, sent := build(t, 0) + snaps := reg.warmPool.tick(time.Now()) + snap := warmSnapshotFor(t, snaps, model) + if len(*sent) != 0 || snap.EligibleCold != 0 { + t.Fatalf("allow_busy=0: loads %d eligible_cold %d, want 0/0 (historical behavior preserved)", len(*sent), snap.EligibleCold) + } + if snap.ColdDisqualifiers["not_idle"] != 1 { + t.Fatalf("allow_busy=0: disqualifiers = %v, want not_idle:1 surfaced for the dashboard", snap.ColdDisqualifiers) + } + + // Bounded-busy gate: the same box is eligible and the floor re-warms it. + reg, sent = build(t, 2) + snaps = reg.warmPool.tick(time.Now()) + snap = warmSnapshotFor(t, snaps, model) + if snap.EligibleCold != 1 { + t.Fatalf("allow_busy=2: eligible_cold = %d (disq %v), want 1", snap.EligibleCold, snap.ColdDisqualifiers) + } + if len(*sent) != 1 || (*sent)[0].providerID != "busy-box" || (*sent)[0].modelID != model { + t.Fatalf("allow_busy=2: loads = %+v, want exactly one re-warm of busy-box/%s", *sent, model) + } +} diff --git a/docs/operations/coordinator-deploy.md b/docs/operations/coordinator-deploy.md index 6027e2b20d..18371ba331 100644 --- a/docs/operations/coordinator-deploy.md +++ b/docs/operations/coordinator-deploy.md @@ -186,8 +186,9 @@ The fallback version advertised when no release is registered is `LatestProvider exists** — fixed by registering the release, not by bumping code. ```bash -git tag -a v0.7.4 -m "Release v0.7.4" -git push origin master --tags +VERSION=0.7.5 +git tag -a "v${VERSION}" -m "Release v${VERSION}" +git push origin master "v${VERSION}" ``` ### Required GitHub secrets @@ -234,13 +235,36 @@ semantics is the code (`coordinator/registry/`, `coordinator/api/`); the highlig | `EIGENINFERENCE_QUEUE_BEFORE_SHED`, `_QUEUE_MAX_DEPTH`, `_QUEUE_MAX_WAIT` | Capacity queueing (dedicated pools included) | | `EIGENINFERENCE_HEALTH_EJECTION` | Stable-identity ejection kill switch — **`on` in prod**; `off` disables black-hole ejection entirely | | `EIGENINFERENCE_QUALITY_CONCURRENCY_OVERCOMMIT`, `_BY_MODEL` | Per-box admission density (default 1.2) | +| `EIGENINFERENCE_COMBINED_ADMISSION_CAP` | Box-wide Σ(load/qc) admission budget on top of the per-model quality caps (default `false` — dormant; turned on with the open-pool flip) | | `EIGENINFERENCE_QUALITY_CAP_PER_MODEL_TPS` | Quality cap reads each model's own solo decode rate (default `true`; `false` restores the provider-level benchmark) | | `EIGENINFERENCE_QUALITY_CAP_SOLO_MIN_SAMPLES` | Solo samples required before a per-(model, chip) median is trusted (default 5) | | `EIGENINFERENCE_MODEL_SOLO_TPS_SEED` | Cold-start solo rates, `build-id=tok/s` CSV (e.g. `gemma-4-26b-qat-4bit=14,gpt-oss-20b=30`); the in-memory TPS registry is restart-wiped | -| `EIGENINFERENCE_WARM_POOL_*` | Warm-pool controller (active; `OBSERVE_ONLY=false`) | +| `EIGENINFERENCE_WARM_POOL_*` | Warm-pool controller (active; `OBSERVE_ONLY=false`). `_ALLOW_BUSY_LOAD_MAX` bounds `max(coordinator pending, backend running+waiting)` for a cold box (default `0` = fully idle required; runbook raises to `2` for recovery). Busy warming also requires no-eviction memory headroom and v0.7.5+ `max_model_slots` plus `occupied_model_slots` heartbeats proving a free resident slot, including models still unloading; legacy/unknown busy boxes remain ineligible | +| `EIGENINFERENCE_REJECT_MODELS` | Startup seed for the per-model shed list (429 at admission). Mutable at RUNTIME via `GET/PUT /v1/admin/reject-models` (`scripts/admin.sh reject-models get\|set\|clear`) — shed flips no longer need a restart | | `EIGENINFERENCE_DEDICATED_MODELS` | Static dedicated-box partition (`gemma-4`) | | `EIGENINFERENCE_IPAPI_KEY` | ip-api.com PRO key; unset falls back to the free 45 req/min tier | +### v0.7.5 release-train gate + +Do not deploy an intermediate coordinator while the one-engine v0.7.5 release +is incomplete. Legacy-engine removal and the coordinator routing changes ship +as one validated release train: + +1. Merge PR #525, then PR #526. Do not deploy either intermediate coordinator. +2. Run the combined coordinator merge-train gates on the resulting `master`. +3. Bring PR #522 onto that final `master`, close its release blockers, and run + the complete provider release gates. +4. Use a dev tag or `workflow_dispatch` with `environment=dev` to validate the + signed and notarized v0.7.5 bundle, installer, update path, and owned-provider + canary in pre-production. Complete that signoff before creating a production + tag or manually dispatching the workflow with `environment=prod`; either + production path registers an active release. +5. Create the production tag only after pre-production signoff. The production + workflow uploads and registers an active release, so fleet rollout begins + immediately; monitor the rollout and stop or roll back if its gates fail. +6. Only after the complete one-engine provider release is healthy, deploy the + coordinator once with the full merged train. + ## Troubleshooting | Symptom | Likely cause | Fix | diff --git a/docs/reference/protocol-messages.md b/docs/reference/protocol-messages.md index 7a0e64253c..3d030ca7a2 100644 --- a/docs/reference/protocol-messages.md +++ b/docs/reference/protocol-messages.md @@ -294,6 +294,9 @@ Go: [`BackendCapacity`](../../coordinator/protocol/messages.go); Swift: `Backend | `gpu_memory_peak_gb` | number | | `gpu_memory_cache_gb` | number | | `total_memory_gb` | number | +| `free_for_load_gb` | number / omitted | Additional model-weight footprint currently loadable | +| `max_model_slots` | integer / omitted | Effective resident-model slot cap; omitted by legacy providers | +| `occupied_model_slots` | integer / omitted | Resident or committed load slots, including queued/loading/unloading models hidden from `slots` | ### `BackendSlotCapacity` diff --git a/provider-swift/Sources/ProviderCore/Protocol/Types.swift b/provider-swift/Sources/ProviderCore/Protocol/Types.swift index 3e3151a515..be5139cf1a 100644 --- a/provider-swift/Sources/ProviderCore/Protocol/Types.swift +++ b/provider-swift/Sources/ProviderCore/Protocol/Types.swift @@ -556,6 +556,12 @@ public struct BackendCapacity: Codable, Sendable, Equatable { public var gpuMemoryPeakGb: Double public var gpuMemoryCacheGb: Double public var totalMemoryGb: Double + /// Current effective resident-model slot cap. Zero means unknown when + /// decoding a legacy payload that predates `max_model_slots`. + public var maxModelSlots: Int + /// Authoritative resident or committed-load slot count, including models + /// hidden from routable `slots` while loading, queued, or unloading. + public var occupiedModelSlots: Int /// Max additional model-WEIGHT footprint (GB) the provider can load right /// now, accounting for the 90% unified cap, OS/operator reserve, load /// headroom, real OS-available memory, and eviction of idle resident models @@ -572,6 +578,8 @@ public struct BackendCapacity: Codable, Sendable, Equatable { case gpuMemoryCacheGb = "gpu_memory_cache_gb" case totalMemoryGb = "total_memory_gb" case freeForLoadGb = "free_for_load_gb" + case maxModelSlots = "max_model_slots" + case occupiedModelSlots = "occupied_model_slots" } public init( @@ -580,7 +588,9 @@ public struct BackendCapacity: Codable, Sendable, Equatable { gpuMemoryPeakGb: Double, gpuMemoryCacheGb: Double, totalMemoryGb: Double, - freeForLoadGb: Double = 0 + freeForLoadGb: Double = 0, + maxModelSlots: Int = 0, + occupiedModelSlots: Int = 0 ) { self.slots = slots self.gpuMemoryActiveGb = gpuMemoryActiveGb @@ -588,10 +598,12 @@ public struct BackendCapacity: Codable, Sendable, Equatable { self.gpuMemoryCacheGb = gpuMemoryCacheGb self.totalMemoryGb = totalMemoryGb self.freeForLoadGb = freeForLoadGb + self.maxModelSlots = maxModelSlots + self.occupiedModelSlots = occupiedModelSlots } - // Explicit decode so older payloads without `free_for_load_gb` still decode - // (defaults to 0). Encoding stays synthesized and always emits the field. + // Explicit decode keeps older payloads compatible. Zero means the optional + // field was absent; new provider heartbeats always report a positive cap. public init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) self.slots = try c.decode([BackendSlotCapacity].self, forKey: .slots) @@ -600,6 +612,24 @@ public struct BackendCapacity: Codable, Sendable, Equatable { self.gpuMemoryCacheGb = try c.decode(Double.self, forKey: .gpuMemoryCacheGb) self.totalMemoryGb = try c.decode(Double.self, forKey: .totalMemoryGb) self.freeForLoadGb = try c.decodeIfPresent(Double.self, forKey: .freeForLoadGb) ?? 0 + self.maxModelSlots = try c.decodeIfPresent(Int.self, forKey: .maxModelSlots) ?? 0 + self.occupiedModelSlots = try c.decodeIfPresent(Int.self, forKey: .occupiedModelSlots) ?? 0 + } + + public func encode(to encoder: Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(slots, forKey: .slots) + try c.encode(gpuMemoryActiveGb, forKey: .gpuMemoryActiveGb) + try c.encode(gpuMemoryPeakGb, forKey: .gpuMemoryPeakGb) + try c.encode(gpuMemoryCacheGb, forKey: .gpuMemoryCacheGb) + try c.encode(totalMemoryGb, forKey: .totalMemoryGb) + try c.encode(freeForLoadGb, forKey: .freeForLoadGb) + if maxModelSlots > 0 { + try c.encode(maxModelSlots, forKey: .maxModelSlots) + } + if occupiedModelSlots > 0 { + try c.encode(occupiedModelSlots, forKey: .occupiedModelSlots) + } } } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Capacity.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Capacity.swift index fb20b82865..f4300e3117 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Capacity.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Capacity.swift @@ -117,13 +117,25 @@ extension ProviderLoop { reserveBytes: loadReserve, outstandingReservationBytes: outstandingKV) + // The real slot-cap guard counts resident slots, while in-progress and + // globally queued loads have committed future slots. Use a union because + // the success path installs modelSlots[model] before clearing modelsLoading. + var occupiedModelIDs = Set(modelSlots.keys) + occupiedModelIDs.formUnion(modelsLoading) + occupiedModelIDs.formUnion(loadGateWaitingModels.keys) + state.backendCapacity = BackendCapacity( slots: allSlots, gpuMemoryActiveGb: Double(MLX.GPU.activeMemory) / gbDivisor, gpuMemoryPeakGb: Double(MLX.GPU.peakMemory) / gbDivisor, gpuMemoryCacheGb: Double(MLX.GPU.cacheMemory) / gbDivisor, totalMemoryGb: Double(totalMem) / gbDivisor, - freeForLoadGb: freeForLoadGb + freeForLoadGb: freeForLoadGb, + maxModelSlots: maxModelSlots, + // `allSlots` intentionally omits models being unloaded so the + // coordinator cannot route to them. Resident entries plus loads + // already in progress are the slot commitments the next load sees. + occupiedModelSlots: occupiedModelIDs.count ) state.inferenceActive = totalActive > 0 } diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift index 120f5f7dba..a48009bef1 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+ModelLoading.swift @@ -141,8 +141,21 @@ extension ProviderLoop { ) } - // Serialize loads so concurrent eviction decisions don't interleave + // Serialize loads so concurrent eviction decisions don't interleave. + // Keep each distinct queued model visible to capacity reporting: local + // endpoint loads have no coordinator-side pending request to account for + // their future slot. + var registeredLoadGateWaiter = false + defer { + if registeredLoadGateWaiter { + removeLoadGateWaitingModel(modelId) + } + } while isLoadingAny { + if !registeredLoadGateWaiter { + loadGateWaitingModels[modelId, default: 0] += 1 + registeredLoadGateWaiter = true + } await withCheckedContinuation { (cont: CheckedContinuation) in loadGateWaiters.append(cont) } @@ -157,6 +170,11 @@ extension ProviderLoop { if modelSlots[modelId] != nil { return } } isLoadingAny = true + modelsLoading.insert(modelId) + if registeredLoadGateWaiter { + removeLoadGateWaitingModel(modelId) + registeredLoadGateWaiter = false + } // Re-check slot cap after gate (another load may have consumed a slot) if modelSlots.count >= maxModelSlots { @@ -165,15 +183,20 @@ extension ProviderLoop { !modelsWithInflight.contains($0.key) && !hasLocalReservation($0.key) && !modelsUnloading.contains($0.key) } if evictable.isEmpty || !allowEviction { - isLoadingAny = false - releaseLoadGateWaiters() - // Both messages contain "slot" so loadErrorStatusCode maps - // them to 503 (transient capacity, coordinator reroutes). - throw InferenceError.invalidModelDirectory( + let error = InferenceError.invalidModelDirectory( allowEviction ? "All \(maxModelSlots) model slot(s) are active; cannot load '\(modelId)'" : "All \(maxModelSlots) model slot(s) are occupied and eviction is disabled for this load; cannot load '\(modelId)'" ) + modelsLoading.remove(modelId) + isLoadingAny = false + releaseLoadGateWaiters() + for waiter in loadingWaiters.removeValue(forKey: modelId) ?? [] { + waiter.resume(throwing: error) + } + // Both messages contain "slot" so loadErrorStatusCode maps + // them to 503 (transient capacity, coordinator reroutes). + throw error } if let lru = evictable.min(by: { $0.value.lastInferenceAt < $1.value.lastInferenceAt }) { await unloadModel(lru.key) @@ -184,7 +207,6 @@ extension ProviderLoop { // kvBudget once the gate passes and released once the weights are // resident. Declared out here so the catch can release it on any path. let pendingLoadID = "pending-load:\(modelId)" - modelsLoading.insert(modelId) do { try Task.checkCancellation() if isShuttingDown { throw CancellationError() } @@ -417,6 +439,15 @@ extension ProviderLoop { } } + internal func removeLoadGateWaitingModel(_ modelId: String) { + guard let count = loadGateWaitingModels[modelId] else { return } + if count <= 1 { + loadGateWaitingModels.removeValue(forKey: modelId) + } else { + loadGateWaitingModels[modelId] = count - 1 + } + } + internal func waitForModelUnload(_ modelId: String) async { await withCheckedContinuation { (cont: CheckedContinuation) in unloadingWaiters[modelId, default: []].append(cont) diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop+Testing.swift b/provider-swift/Sources/ProviderCore/ProviderLoop+Testing.swift index d9e9111551..cad119e44d 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop+Testing.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop+Testing.swift @@ -41,6 +41,36 @@ extension ProviderLoop { /// advertised set, clamped to `[1, backend.maxModelSlots]`). func maxModelSlotsForTesting() -> Int { maxModelSlots } + /// Test seam: hide or reveal a resident model as unload-in-progress without + /// running the real scheduler teardown. + func setModelUnloadingForTesting(_ id: String, _ unloading: Bool) { + if unloading { + modelsUnloading.insert(id) + } else { + modelsUnloading.remove(id) + } + } + + /// Test seam: reserve or release a future resident slot without loading + /// model weights. + func setModelLoadingForTesting(_ id: String, _ loading: Bool) { + if loading { + modelsLoading.insert(id) + } else { + modelsLoading.remove(id) + } + } + + /// Test seam: reserve or release a distinct model commitment queued behind + /// the global load gate. + func setModelWaitingForLoadGateForTesting(_ id: String, _ waiting: Bool) { + if waiting { + loadGateWaitingModels[id] = 1 + } else { + loadGateWaitingModels.removeValue(forKey: id) + } + } + /// Test seam: override the desired-build prefetch retry backoff schedule /// (the production default waits tens of seconds between attempts). func setDesiredPrefetchRetryDelaysForTesting(_ delays: [Duration]) { diff --git a/provider-swift/Sources/ProviderCore/ProviderLoop.swift b/provider-swift/Sources/ProviderCore/ProviderLoop.swift index 1bd3dcd075..6efbb1754e 100644 --- a/provider-swift/Sources/ProviderCore/ProviderLoop.swift +++ b/provider-swift/Sources/ProviderCore/ProviderLoop.swift @@ -225,6 +225,9 @@ public actor ProviderLoop { internal var loadingWaiters: [String: [CheckedContinuation]] = [:] internal var modelsLoading: Set = [] internal var loadGateWaiters: [CheckedContinuation] = [] + /// Distinct model commitments queued behind the global load gate. Counts + /// preserve duplicate callers while capacity reports the dictionary keys. + internal var loadGateWaitingModels: [String: Int] = [:] internal var isLoadingAny: Bool = false internal var isShuttingDown: Bool = false @@ -610,4 +613,3 @@ import MLX import MLXLLM import MLXLMCommon import MLXVLM - diff --git a/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift b/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift index 3c3f9cd415..f6d8fdca4d 100644 --- a/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/EngineV2ProductionWiringTests.swift @@ -1276,6 +1276,46 @@ struct EngineV2RuntimeGuardTests { #expect(await runtime.consultCount == 0) } + @Test("capacity counts a resident slot hidden while unloading") + func capacityCountsUnloadingSlot() async throws { + let loop = try makeWiringLoop() + await loop.installModelSlotForTesting( + modelId: "qwen3-8b", + scheduler: BatchScheduler(), + container: makeStubContainer(), + tokenizer: TokenizerHandle(WiringStubTokenizer()) + ) + await loop.setModelUnloadingForTesting("qwen3-8b", true) + + await loop.updateAggregateCapacity() + let capacity = try #require(await loop.backendCapacityForTesting()) + #expect(capacity.slots.isEmpty) + #expect(capacity.occupiedModelSlots == 1) + } + + @Test("capacity counts a model load before its resident slot is installed") + func capacityCountsLoadingModel() async throws { + let loop = try makeWiringLoop() + await loop.setModelLoadingForTesting("qwen3-8b", true) + + await loop.updateAggregateCapacity() + let capacity = try #require(await loop.backendCapacityForTesting()) + #expect(capacity.slots.isEmpty) + #expect(capacity.occupiedModelSlots == 1) + } + + @Test("capacity counts distinct models queued behind the global load gate") + func capacityCountsQueuedLoadModels() async throws { + let loop = try makeWiringLoop() + await loop.setModelLoadingForTesting("qwen3-8b", true) + await loop.setModelWaitingForLoadGateForTesting("gemma-4-27b-it", true) + + await loop.updateAggregateCapacity() + let capacity = try #require(await loop.backendCapacityForTesting()) + #expect(capacity.slots.isEmpty) + #expect(capacity.occupiedModelSlots == 2) + } + @Test("capacity folds the v2 bridge slot into the heartbeat when a v2 slot exists") func capacityIncludesV2Slot() async throws { let loop = try makeWiringLoop() diff --git a/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift b/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift index 589604b45c..10f0ce2086 100644 --- a/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ModelLoadAdmissionTests.swift @@ -215,5 +215,7 @@ private let gib: UInt64 = 1024 * 1024 * 1024 let legacy = #"{"slots":[],"gpu_memory_active_gb":1,"gpu_memory_peak_gb":2,"gpu_memory_cache_gb":0.5,"total_memory_gb":64}"# let decoded = try JSONDecoder().decode(BackendCapacity.self, from: Data(legacy.utf8)) #expect(decoded.freeForLoadGb == 0, "legacy payload defaults to 0, no throw") + #expect(decoded.maxModelSlots == 0, "legacy payload defaults unknown slot cap to 0") + #expect(decoded.occupiedModelSlots == 0, "legacy payload defaults unknown slot occupancy to 0") #expect(abs(decoded.totalMemoryGb - 64) < 0.001) } diff --git a/provider-swift/Tests/ProviderCoreTests/ProtocolTests.swift b/provider-swift/Tests/ProviderCoreTests/ProtocolTests.swift index 0d9b15c10d..e11c021765 100644 --- a/provider-swift/Tests/ProviderCoreTests/ProtocolTests.swift +++ b/provider-swift/Tests/ProviderCoreTests/ProtocolTests.swift @@ -814,7 +814,9 @@ import Testing gpuMemoryActiveGb: 5.5, gpuMemoryPeakGb: 6.5, gpuMemoryCacheGb: 1.5, - totalMemoryGb: 36 + totalMemoryGb: 36, + maxModelSlots: 3, + occupiedModelSlots: 2 ) )) @@ -827,6 +829,8 @@ import Testing #expect(capacity?["gpu_memory_peak_gb"] as? Double == 6.5) #expect(capacity?["gpu_memory_cache_gb"] as? Double == 1.5) #expect(capacity?["total_memory_gb"] as? Double == 36) + #expect(capacity?["max_model_slots"] as? Int == 3) + #expect(capacity?["occupied_model_slots"] as? Int == 2) #expect(slot?["num_running"] as? Int == 1) #expect(slot?["num_waiting"] as? Int == 2) #expect(slot?["active_tokens"] as? Int == 3000) diff --git a/scripts/admin.sh b/scripts/admin.sh index d6eaac7a27..e9424e95ed 100755 --- a/scripts/admin.sh +++ b/scripts/admin.sh @@ -110,6 +110,21 @@ cmd_models_list() { curl -fsSL "$COORDINATOR_URL/v1/models/catalog" | python3 -m json.tool } +cmd_reject_models_get() { + authed_curl "$COORDINATOR_URL/v1/admin/reject-models" | python3 -m json.tool +} + +cmd_reject_models_set() { + # FULL replacement of the runtime shed list (no restart). No args = shed + # nothing. Startup still seeds the initial set from + # EIGENINFERENCE_REJECT_MODELS. + local body + body=$(python3 -c 'import json, sys; print(json.dumps({"models": sys.argv[1:]}))' "$@") + authed_curl -X PUT "$COORDINATOR_URL/v1/admin/reject-models" \ + -H "Content-Type: application/json" \ + -d "$body" | python3 -m json.tool +} + cmd_raw() { local method="${1:?Usage: $0 raw [body]}" local path="${2:?Usage: $0 raw [body]}" @@ -148,6 +163,14 @@ case "${1:-help}" in *) echo "Usage: $0 models [list]" ;; esac ;; + reject-models) + case "${2:-get}" in + get) cmd_reject_models_get ;; + set) shift 2; cmd_reject_models_set "$@" ;; + clear) cmd_reject_models_set ;; + *) echo "Usage: $0 reject-models [get|set ...|clear]" ;; + esac + ;; raw) cmd_raw "${2:-}" "${3:-}" "${4:-}" ;; @@ -161,6 +184,9 @@ case "${1:-help}" in echo " releases latest [platform] Show latest active release" echo " releases deactivate Deactivate a release" echo " models list List model catalog" + echo " reject-models get Show the runtime shed list" + echo " reject-models set ... REPLACE the shed list (no restart)" + echo " reject-models clear Shed nothing (empty list)" echo " raw [body] Raw API call with auth" echo "" echo "Environment:"