From a88867b169b315c4e3751588a651ac75b0be915e Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Wed, 17 Jun 2026 16:41:01 -0700 Subject: [PATCH 1/6] feat(coordinator): graceful HTTP drain for zero-downtime upgrades DAR-327 Phase 1. Lets the coordinator drain in-flight inference before a restart/swap so no request is cancelled mid-flight. - Server: atomic httpInflight counter + coordinatorDraining flag with SetDraining/IsDraining/Inflight + inc/dec helpers (new coordinator/api/drain.go). - POST /v1/admin/drain (admin-gated via isAdminAuthorized, registered raw like /v1/admin/metrics): sets draining=true; optional {"draining": false} body un-drains for rollback. - drainGate middleware (outermost) on the 4 inference routes: rejects new requests with 429+Retry-After while draining, else counts the request as in-flight for the handler's lifetime. - GET /readyz (unauthenticated): {draining,inflight,ready}; 200 when ready, 503 while draining so LBs/deploy treat draining as not-ready. - main.go: SetDraining(true) before http.Server.Shutdown on SIGINT/SIGTERM so /readyz flips immediately and in-flight requests finish within the 15s deadline. Coordinator-only; no protocol/Swift changes. Names avoid collision with the provider-side drain concepts. Tests in coordinator/api/drain_test.go (real HTTP path via srv.Handler(), no mocks) cover admin gating, 429-while-draining + Retry-After, /readyz 200/503 states, inflight inc/dec back to 0, and the non-draining pass-through regression. --- coordinator/api/drain.go | 148 +++++++++++++++++++++ coordinator/api/drain_test.go | 198 ++++++++++++++++++++++++++++ coordinator/api/server.go | 35 ++++- coordinator/cmd/coordinator/main.go | 5 + 4 files changed, 382 insertions(+), 4 deletions(-) create mode 100644 coordinator/api/drain.go create mode 100644 coordinator/api/drain_test.go diff --git a/coordinator/api/drain.go b/coordinator/api/drain.go new file mode 100644 index 0000000000..89cf42b4c7 --- /dev/null +++ b/coordinator/api/drain.go @@ -0,0 +1,148 @@ +package api + +import ( + "net/http" + "time" +) + +// Graceful coordinator drain (DAR-327 Phase 1, zero-downtime upgrades). +// +// Before a restart or binary swap the coordinator is put into drain mode via +// POST /v1/admin/drain. While draining: +// - the drain gate rejects NEW inference requests with 429 + Retry-After so +// clients (and OpenRouter-style routers) retry against a ready coordinator; +// - already-admitted in-flight requests run to completion; +// - GET /readyz reports not-ready (503) so load balancers stop sending traffic +// and the deploy script can poll until inflight reaches 0 before shutting the +// process down. +// +// This is purely the coordinator's own HTTP-ingress drain and is intentionally +// distinct from the provider-side drain concepts (protocol.ProviderDrainingForUpdate, +// registry.drainQueuedRequestsForModels). The state lives on the Server struct +// (httpInflight atomic.Int64, coordinatorDraining atomic.Bool — see server.go). + +// coordinatorDrainRetryAfter is the Retry-After advertised to inference requests +// rejected by the drain gate. Kept small so well-behaved clients retry quickly +// against the next ready coordinator instead of failing hard. +const coordinatorDrainRetryAfter = 3 * time.Second + +// SetDraining toggles the coordinator's graceful-drain state. When true the +// drain gate rejects new inference requests (429 + Retry-After) while in-flight +// requests finish, and /readyz reports not-ready. Pass false to un-drain (e.g. +// to roll back an aborted upgrade). Safe for concurrent use. +func (s *Server) SetDraining(draining bool) { + s.coordinatorDraining.Store(draining) +} + +// IsDraining reports whether the coordinator is currently draining for a +// restart/upgrade. Safe for concurrent use. +func (s *Server) IsDraining() bool { + return s.coordinatorDraining.Load() +} + +// Inflight returns the number of inference requests currently being served +// through the drain gate. Safe for concurrent use. +func (s *Server) Inflight() int64 { + return s.httpInflight.Load() +} + +// incInflight records the entry of an inference request into the drain gate and +// returns the new in-flight count. +func (s *Server) incInflight() int64 { + return s.httpInflight.Add(1) +} + +// decInflight records the exit of an inference request from the drain gate and +// returns the new in-flight count. +func (s *Server) decInflight() int64 { + return s.httpInflight.Add(-1) +} + +// drainGate wraps an inference handler with the coordinator's graceful-drain +// gate. Mirrors the sealedTransport wrapper shape (func(http.HandlerFunc) +// http.HandlerFunc) and is applied as the OUTERMOST wrapper on the inference +// routes so it short-circuits before any auth/decrypt work. +// +// While draining it rejects the request with 429 + Retry-After (reusing +// writeTokenRateLimited so the body/headers match the coordinator's other 429s). +// Otherwise it counts the request as in-flight for the lifetime of the handler +// so /readyz and the deploy script can wait for inflight==0 before shutdown. +// +// Once draining is set, every new request observes it and is rejected, so the +// in-flight count only decreases and, combined with http.Server.Shutdown's own +// connection draining, reaches a stable 0. +func (s *Server) drainGate(next http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if s.IsDraining() { + s.writeTokenRateLimited(w, "coordinator", "draining", coordinatorDrainRetryAfter) + return + } + s.incInflight() + defer s.decInflight() + next(w, r) + } +} + +// handleReadyz handles GET /readyz (unauthenticated). It reports the +// coordinator's drain/readiness state so load balancers and the deploy script +// treat a draining coordinator as not-ready and can wait for inflight==0 before +// restarting. Returns 200 while ready and 503 while draining. Modeled on +// handleHealth, but health is liveness ("process is up") while this is readiness +// ("safe to route new traffic here"). +func (s *Server) handleReadyz(w http.ResponseWriter, r *http.Request) { + draining := s.IsDraining() + status := http.StatusOK + if draining { + status = http.StatusServiceUnavailable + } + writeJSON(w, status, readinessResponse{ + Draining: draining, + Inflight: s.Inflight(), + Ready: !draining, + }) +} + +// readinessResponse is the JSON body returned by GET /readyz. +type readinessResponse struct { + Draining bool `json:"draining"` + Inflight int64 `json:"inflight"` + Ready bool `json:"ready"` +} + +// handleAdminDrain handles POST /v1/admin/drain (admin-gated, registered raw +// like /v1/admin/metrics). It sets the coordinator into graceful-drain mode so +// new inference requests are rejected with 429 while in-flight ones finish. +// +// The body is optional: an empty body (the common case) sets draining=true. An +// explicit JSON body {"draining": false} un-drains, for rolling back an aborted +// upgrade. Returns the resulting drain state and current in-flight count. +func (s *Server) handleAdminDrain(w http.ResponseWriter, r *http.Request) { + if !s.isAdminAuthorized(w, r) { + return + } + + // Default to draining=true; only parse a body when one is actually present + // (decodeCappedJSON treats an empty body as invalid JSON). + draining := true + if r.ContentLength > 0 { + var req struct { + Draining *bool `json:"draining"` + } + if !decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) { + return + } + if req.Draining != nil { + draining = *req.Draining + } + } + + s.SetDraining(draining) + s.logger.Info("coordinator drain state changed", + "draining", draining, + "inflight", s.Inflight(), + ) + writeJSON(w, http.StatusOK, map[string]any{ + "draining": draining, + "inflight": s.Inflight(), + }) +} diff --git a/coordinator/api/drain_test.go b/coordinator/api/drain_test.go new file mode 100644 index 0000000000..5b20a3490e --- /dev/null +++ b/coordinator/api/drain_test.go @@ -0,0 +1,198 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strconv" + "strings" + "testing" +) + +// minimalChatBody is a small, well-formed chat-completions body. The drain gate +// is the outermost wrapper and short-circuits before the body is read, so its +// exact contents don't matter — it only needs to look like a real request. +const minimalChatBody = `{"model":"test","messages":[{"role":"user","content":"hi"}]}` + +// doReq drives a request through the full server handler (CORS → recover → +// logging → mux → middleware chain) — the real HTTP path, no mocks. +func doReq(srv *Server, method, path, auth, body string) *httptest.ResponseRecorder { + var r *http.Request + if body == "" { + r = httptest.NewRequest(method, path, nil) + } else { + r = httptest.NewRequest(method, path, strings.NewReader(body)) + } + if auth != "" { + r.Header.Set("Authorization", auth) + } + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, r) + return w +} + +// (a) POST /v1/admin/drain is admin-gated: 403 without an admin bearer. +func TestAdminDrain_RequiresAdminAuth(t *testing.T) { + srv, _ := testServer(t) + srv.SetAdminKey("test-key") + + // No bearer at all. + if w := doReq(srv, http.MethodPost, "/v1/admin/drain", "", ""); w.Code != http.StatusForbidden { + t.Fatalf("no-bearer status = %d, want %d", w.Code, http.StatusForbidden) + } + // Wrong bearer (constant-time compare must reject). + if w := doReq(srv, http.MethodPost, "/v1/admin/drain", "Bearer wrong-key", ""); w.Code != http.StatusForbidden { + t.Fatalf("wrong-bearer status = %d, want %d", w.Code, http.StatusForbidden) + } + // A rejected admin call must not have changed drain state. + if srv.IsDraining() { + t.Fatal("IsDraining() = true after a rejected admin call, want false") + } +} + +// (a) POST /v1/admin/drain with Bearer test-key returns 200 and flips +// IsDraining()→true; an explicit {"draining": false} body un-drains. +func TestAdminDrain_SetAndUndrain(t *testing.T) { + srv, _ := testServer(t) + srv.SetAdminKey("test-key") + + // Empty body defaults to draining=true. + w := doReq(srv, http.MethodPost, "/v1/admin/drain", "Bearer test-key", "") + if w.Code != http.StatusOK { + t.Fatalf("drain status = %d, want %d (body=%s)", w.Code, http.StatusOK, w.Body.String()) + } + if !srv.IsDraining() { + t.Fatal("IsDraining() = false after drain, want true") + } + var got struct { + Draining bool `json:"draining"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("unmarshal drain response: %v", err) + } + if !got.Draining { + t.Fatalf("response draining = false, want true (body=%s)", w.Body.String()) + } + + // Explicit {"draining": false} un-drains (rollback path). + w = doReq(srv, http.MethodPost, "/v1/admin/drain", "Bearer test-key", `{"draining": false}`) + if w.Code != http.StatusOK { + t.Fatalf("undrain status = %d, want %d", w.Code, http.StatusOK) + } + if srv.IsDraining() { + t.Fatal("IsDraining() = true after undrain, want false") + } +} + +// (b) While draining, a NEW POST /v1/chat/completions is rejected at the gate +// with 429 + Retry-After, before dispatch, and does not leak the in-flight count. +func TestDrainGate_RejectsNewInferenceWhileDraining(t *testing.T) { + srv, _ := testServer(t) + srv.SetDraining(true) + + w := doReq(srv, http.MethodPost, "/v1/chat/completions", "", minimalChatBody) + if w.Code != http.StatusTooManyRequests { + t.Fatalf("status = %d, want %d (body=%s)", w.Code, http.StatusTooManyRequests, w.Body.String()) + } + ra := w.Header().Get("Retry-After") + if ra == "" { + t.Fatal("Retry-After header missing on drain 429") + } + if secs, err := strconv.Atoi(ra); err != nil || secs < 1 { + t.Fatalf("Retry-After = %q, want a positive integer seconds value", ra) + } + // The gate rejected before incrementing — nothing is in flight. + if n := srv.Inflight(); n != 0 { + t.Fatalf("Inflight() = %d after a rejected request, want 0", n) + } +} + +// (c) GET /readyz reports 200/{ready:true} normally and 503/{draining:true} +// after drain — unauthenticated either way. +func TestReadyz_ReflectsDrainState(t *testing.T) { + srv, _ := testServer(t) + + w := doReq(srv, http.MethodGet, "/readyz", "", "") + if w.Code != http.StatusOK { + t.Fatalf("ready status = %d, want %d", w.Code, http.StatusOK) + } + var ready readinessResponse + if err := json.Unmarshal(w.Body.Bytes(), &ready); err != nil { + t.Fatalf("unmarshal readyz: %v", err) + } + if ready.Draining || !ready.Ready { + t.Fatalf("readyz = %+v, want {draining:false, ready:true}", ready) + } + + srv.SetDraining(true) + w = doReq(srv, http.MethodGet, "/readyz", "", "") + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("draining status = %d, want %d", w.Code, http.StatusServiceUnavailable) + } + var draining readinessResponse + if err := json.Unmarshal(w.Body.Bytes(), &draining); err != nil { + t.Fatalf("unmarshal readyz (draining): %v", err) + } + if !draining.Draining || draining.Ready { + t.Fatalf("readyz = %+v, want {draining:true, ready:false}", draining) + } +} + +// (d) The in-flight counter increments/decrements back to 0, and SetDraining is +// deterministic. Exercises the real Server methods directly (same package). +func TestInflight_AndSetDrainingAreDeterministic(t *testing.T) { + srv, _ := testServer(t) + + if n := srv.Inflight(); n != 0 { + t.Fatalf("initial Inflight() = %d, want 0", n) + } + if n := srv.incInflight(); n != 1 { + t.Fatalf("after inc Inflight() = %d, want 1", n) + } + if n := srv.Inflight(); n != 1 { + t.Fatalf("Inflight() = %d, want 1", n) + } + if n := srv.decInflight(); n != 0 { + t.Fatalf("after dec Inflight() = %d, want 0", n) + } + + if srv.IsDraining() { + t.Fatal("IsDraining() = true by default, want false") + } + srv.SetDraining(true) + if !srv.IsDraining() { + t.Fatal("IsDraining() = false after SetDraining(true)") + } + srv.SetDraining(false) + if srv.IsDraining() { + t.Fatal("IsDraining() = true after SetDraining(false)") + } + + // A full request through the gate must leave the counter back at 0 even when + // the request is rejected downstream (here: 401 from requireAuth). + _ = doReq(srv, http.MethodPost, "/v1/chat/completions", "", minimalChatBody) + if n := srv.Inflight(); n != 0 { + t.Fatalf("Inflight() = %d after a completed request, want 0", n) + } +} + +// (e) Regression: when NOT draining, an inference request passes the gate (it is +// not 429'd by the gate) and proceeds into the normal chain — here it reaches +// requireAuth and gets 401, proving the gate let it through. +func TestDrainGate_PassesThroughWhenNotDraining(t *testing.T) { + srv, _ := testServer(t) + + if srv.IsDraining() { + t.Fatal("precondition: server should not be draining") + } + w := doReq(srv, http.MethodPost, "/v1/chat/completions", "", minimalChatBody) + if w.Code == http.StatusTooManyRequests { + t.Fatalf("gate returned 429 while not draining (body=%s)", w.Body.String()) + } + if w.Code != http.StatusUnauthorized { + t.Fatalf("status = %d, want %d (passed gate, rejected by auth)", w.Code, http.StatusUnauthorized) + } + if n := srv.Inflight(); n != 0 { + t.Fatalf("Inflight() = %d after request, want 0", n) + } +} diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 9c944016ae..7026d1a4ac 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -32,6 +32,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "time" "github.com/eigeninference/d-inference/coordinator/apns" @@ -186,6 +187,17 @@ type Server struct { codeAttestThrottle *codeAttestThrottle // per-device APNs push budget + reuse cache (v0.6.0) trustReuseCache *trustReuseCache // per-device trust-reuse cache: skip a fleet-wide live MDM herd on restart (DAR-326) + // Graceful-drain state (DAR-327 Phase 1, zero-downtime upgrades). Set + // coordinatorDraining=true before a restart/swap so the drain gate rejects + // NEW inference requests with 429+Retry-After while already-admitted ones run + // to completion; httpInflight counts requests currently inside the gate so + // /readyz (and the deploy script) can wait for it to reach 0 before shutdown. + // Deliberately named to avoid collision with the provider-side drain concepts + // (protocol.ProviderDrainingForUpdate, registry.drainQueuedRequestsForModels): + // this is purely the coordinator's own HTTP-ingress drain. See drain.go. + httpInflight atomic.Int64 + coordinatorDraining atomic.Bool + // knownBinaryHashes is the set of accepted provider binary SHA-256 hashes. // When binaryHashPolicyConfigured is true, providers whose binary hash is // missing or doesn't match are rejected. @@ -1644,6 +1656,11 @@ func (s *Server) routes() { // Health check — no auth required. s.mux.HandleFunc("GET /health", s.handleHealth) + // Readiness probe — no auth required. Reports graceful-drain state so load + // balancers and the deploy script treat a draining coordinator as not-ready + // (503) and can wait for inflight==0 before restart. See drain.go (DAR-327). + s.mux.HandleFunc("GET /readyz", s.handleReadyz) + // Provider WebSocket — no API key auth (providers authenticate differently). s.mux.HandleFunc("GET /ws/provider", s.handleProviderWS) @@ -1671,10 +1688,14 @@ func (s *Server) routes() { // rateLimitConsumer is chained inside requireAuth so the accountID is in // context. Read-only endpoints (GET /v1/models) skip rate limiting since // they're cheap and clients poll them. - s.mux.HandleFunc("POST /v1/chat/completions", s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleChatCompletions)))) - s.mux.HandleFunc("POST /v1/responses", s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleChatCompletions)))) // Responses API — same handler, auto-detects input vs messages - s.mux.HandleFunc("POST /v1/completions", s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleCompletions)))) - s.mux.HandleFunc("POST /v1/messages", s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleAnthropicMessages)))) + // drainGate is the OUTERMOST wrapper: while the coordinator is draining for a + // restart/upgrade it rejects NEW inference requests with 429+Retry-After + // before any auth/decrypt work, and otherwise counts the request as in-flight + // so /readyz can report when it's safe to shut down (DAR-327 Phase 1). + s.mux.HandleFunc("POST /v1/chat/completions", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleChatCompletions))))) + s.mux.HandleFunc("POST /v1/responses", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleChatCompletions))))) // Responses API — same handler, auto-detects input vs messages + s.mux.HandleFunc("POST /v1/completions", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleCompletions))))) + s.mux.HandleFunc("POST /v1/messages", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleAnthropicMessages))))) s.mux.HandleFunc("GET /v1/models", s.requireAuth(s.handleListModels)) // Dedicated OpenRouter provider feed — pure OpenRouter schema, no Darkbloom metadata. s.mux.HandleFunc("GET /v1/models/openrouter", s.requireAuth(s.handleListModelsOpenRouter)) @@ -1844,6 +1865,12 @@ func (s *Server) routes() { // internally via requireAdminKey. s.mux.HandleFunc("GET /v1/admin/utilization", s.handleAdminUtilization) + // Graceful drain toggle (admin only) — sets the coordinator into drain mode + // before a restart/upgrade so new inference requests get 429 while in-flight + // ones finish. Registered RAW (auth gated inside via isAdminAuthorized) like + // /v1/admin/metrics, and before the /v1/ catch-all. See drain.go (DAR-327). + s.mux.HandleFunc("POST /v1/admin/drain", s.handleAdminDrain) + // 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 diff --git a/coordinator/cmd/coordinator/main.go b/coordinator/cmd/coordinator/main.go index 08bf8c4f8b..3f8da25555 100644 --- a/coordinator/cmd/coordinator/main.go +++ b/coordinator/cmd/coordinator/main.go @@ -698,6 +698,11 @@ func main() { shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) defer shutdownCancel() + // Enter drain mode first so /readyz immediately reports not-ready and new + // inference requests get 429+Retry-After while http.Server.Shutdown waits for + // in-flight requests to finish within the deadline (DAR-327 Phase 1). + srv.SetDraining(true) + cancel() // Stop the eviction loop. if err := httpServer.Shutdown(shutdownCtx); err != nil { From 64ca99ba8f5ec28ad499327655e44096ba8e70d7 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Wed, 17 Jun 2026 17:04:46 -0700 Subject: [PATCH 2/6] fix(coordinator): un-drain honors chunked/unknown-length body (Phase 1 review) The admin-drain handler only parsed the JSON body when ContentLength > 0, so a {"draining":false} rollback sent with chunked transfer-encoding / unknown length (ContentLength == -1) was silently skipped and defaulted to draining=true, failing to un-drain. Decode whenever a body may be present (r.Body != nil && r.ContentLength != 0), tolerating an empty body (io.EOF) as the draining=true default while still capping the body for safety. Adds a regression test posting a chunked {"draining":false} with no Content-Length and asserting IsDraining() flips to false. --- coordinator/api/drain.go | 32 +++++++++++++++++++------ coordinator/api/drain_test.go | 45 +++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 7 deletions(-) diff --git a/coordinator/api/drain.go b/coordinator/api/drain.go index 89cf42b4c7..45cffad44a 100644 --- a/coordinator/api/drain.go +++ b/coordinator/api/drain.go @@ -1,6 +1,9 @@ package api import ( + "encoding/json" + "errors" + "io" "net/http" "time" ) @@ -121,18 +124,33 @@ func (s *Server) handleAdminDrain(w http.ResponseWriter, r *http.Request) { return } - // Default to draining=true; only parse a body when one is actually present - // (decodeCappedJSON treats an empty body as invalid JSON). + // Default to draining=true. Attempt to decode a body whenever one MAY be + // present — including chunked / unknown-length requests (ContentLength == -1). + // The previous ContentLength>0 guard silently skipped those and defaulted to + // draining=true, which broke the {"draining":false} rollback path when sent + // without a Content-Length (e.g. chunked transfer-encoding). We can't reuse + // decodeCappedJSON here because it treats an empty body as invalid JSON; an + // empty body surfaces as io.EOF, which we tolerate as "no override" and keep + // the draining=true default. The body is still capped for safety. draining := true - if r.ContentLength > 0 { - var req struct { + if r.Body != nil && r.ContentLength != 0 { + var payload struct { Draining *bool `json:"draining"` } - if !decodeCappedJSON(w, r, maxControlPlaneBodyBytes, &req) { + r.Body = http.MaxBytesReader(w, r.Body, maxControlPlaneBodyBytes) + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil && !errors.Is(err, io.EOF) { + var maxErr *http.MaxBytesError + if errors.As(err, &maxErr) { + writeJSON(w, http.StatusRequestEntityTooLarge, + errorResponse("invalid_request_error", "request body too large")) + return + } + writeJSON(w, http.StatusBadRequest, + errorResponse("invalid_request_error", "invalid JSON")) return } - if req.Draining != nil { - draining = *req.Draining + if payload.Draining != nil { + draining = *payload.Draining } } diff --git a/coordinator/api/drain_test.go b/coordinator/api/drain_test.go index 5b20a3490e..dd99281591 100644 --- a/coordinator/api/drain_test.go +++ b/coordinator/api/drain_test.go @@ -2,6 +2,7 @@ package api import ( "encoding/json" + "io" "net/http" "net/http/httptest" "strconv" @@ -84,6 +85,50 @@ func TestAdminDrain_SetAndUndrain(t *testing.T) { } } +// (a) Regression (DAR-327 Phase 1 review): the un-drain rollback must work even +// when {"draining":false} arrives with chunked transfer-encoding / unknown +// Content-Length (ContentLength == -1). The old `ContentLength > 0` guard skipped +// the body for such requests and silently defaulted to draining=true, so a +// rollback sent without a Content-Length would fail to un-drain. +func TestAdminDrain_UndrainChunkedBodyNoContentLength(t *testing.T) { + srv, _ := testServer(t) + srv.SetAdminKey("test-key") + + // Start from the state a rollback must clear. + srv.SetDraining(true) + if !srv.IsDraining() { + t.Fatal("precondition: IsDraining() should be true before rollback") + } + + // Build a chunked POST with no Content-Length. An io.NopCloser body is not + // one of httptest's length-known types, so ContentLength is unset; we also + // force ContentLength = -1 and chunked transfer-encoding to make the + // unknown-length path explicit and exercise the exact regression. + body := io.NopCloser(strings.NewReader(`{"draining":false}`)) + r := httptest.NewRequest(http.MethodPost, "/v1/admin/drain", body) + r.ContentLength = -1 + r.TransferEncoding = []string{"chunked"} + r.Header.Set("Authorization", "Bearer test-key") + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, r) + + if w.Code != http.StatusOK { + t.Fatalf("chunked undrain status = %d, want %d (body=%s)", w.Code, http.StatusOK, w.Body.String()) + } + if srv.IsDraining() { + t.Fatal(`IsDraining() = true after chunked {"draining":false}, want false`) + } + var got struct { + Draining bool `json:"draining"` + } + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { + t.Fatalf("unmarshal undrain response: %v", err) + } + if got.Draining { + t.Fatalf("response draining = true, want false (body=%s)", w.Body.String()) + } +} + // (b) While draining, a NEW POST /v1/chat/completions is rejected at the gate // with 429 + Retry-After, before dispatch, and does not leak the in-flight count. func TestDrainGate_RejectsNewInferenceWhileDraining(t *testing.T) { From ffc1470cb1b48167a1f732a14eb22f255ec0381f Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Thu, 18 Jun 2026 14:59:50 -0700 Subject: [PATCH 3/6] fix(coordinator): address Phase 1 Codex review for graceful drain MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 1 Codex review (DAR-327, PR #393): A) /v1/admin/drain Privy-admin auth was dead — the route was registered raw with no middleware, so auth.UserFromContext was never populated and only EIGENINFERENCE_ADMIN_KEY worked (scripts/admin.sh uses a Privy token, got 403). Wrap with requireAuth (the canonical pattern shared by the other isAdminAuthorized/requireAdminKey endpoints) so a Privy admin JWT is parsed into context and the admin key is accepted as a pseudo-account; isAdminAuthorized then authorizes either. B) drainGate count-before-check race — increment in-flight BEFORE reading the drain flag (decrement + reject if draining) so /readyz inflight is a strict upper bound on requests past the gate and can never report 0 while a request is still running. C) /health is now drain-aware — returns 503 + draining:true while draining so EigenCloud Caddy marks the instance not-ready instead of keeping it in rotation (where clients hit drain 429s). D) /v1/models/capacity reports empty + draining:true while draining (not cached) so OpenRouter-style routers stop selecting a draining instance. E) SIGTERM shutdown waits for Inflight()==0 up to EIGENINFERENCE_DRAIN_GRACE (default 60s) before http.Server.Shutdown, instead of cutting streams at the 15s deadline; the 15s Shutdown remains the hard backstop. Drain logic stays in drain.go (DrainGraceFromEnv, WaitForInflightZero). Tests added/updated for A-E incl. a -race concurrency test for the gate. --- coordinator/api/capacity.go | 25 ++- coordinator/api/consumer.go | 20 ++- coordinator/api/drain.go | 86 ++++++++- coordinator/api/drain_test.go | 270 +++++++++++++++++++++++++++- coordinator/api/server.go | 10 +- coordinator/api/types/types.go | 6 +- coordinator/cmd/coordinator/main.go | 36 +++- 7 files changed, 424 insertions(+), 29 deletions(-) diff --git a/coordinator/api/capacity.go b/coordinator/api/capacity.go index dfade619b0..d046314e57 100644 --- a/coordinator/api/capacity.go +++ b/coordinator/api/capacity.go @@ -8,12 +8,33 @@ import ( "github.com/eigeninference/d-inference/coordinator/registry" ) +// modelsCapacityResponse is the GET /v1/models/capacity response body. Draining +// is omitted during normal operation so the healthy response is byte-identical to +// before; it is set true only while the coordinator is draining (empty Models). +type modelsCapacityResponse struct { + Models []registry.ModelCapacity `json:"models"` + Draining bool `json:"draining,omitempty"` +} + // handleModelsCapacity handles GET /v1/models/capacity. // // Returns a live capacity snapshot for every model served by at least one // routable provider. Designed for upstream routers (e.g. OpenRouter) to poll // before dispatching requests. No authentication required. func (s *Server) handleModelsCapacity(w http.ResponseWriter, r *http.Request) { + // While draining for a restart/upgrade, advertise zero capacity / not-ready so + // OpenRouter-style routers stop selecting this instance instead of dispatching + // here and then getting drain-gate 429s. Checked BEFORE the cache so a pre-drain + // snapshot can't keep advertising capacity, and intentionally NOT cached so an + // un-drain (rollback) is reflected on the very next poll. + if s.IsDraining() { + writeJSON(w, http.StatusOK, modelsCapacityResponse{ + Models: []registry.ModelCapacity{}, + Draining: true, + }) + return + } + const cacheKey = "models_capacity:v1" if cached, ok := s.readCache.Get(cacheKey); ok { writeCachedJSON(w, cached) @@ -22,9 +43,7 @@ func (s *Server) handleModelsCapacity(w http.ResponseWriter, r *http.Request) { capacities := s.registry.ModelCapacitySnapshot() - resp := struct { - Models []registry.ModelCapacity `json:"models"` - }{ + resp := modelsCapacityResponse{ Models: capacities, } diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index 40b3d285a0..37061cb545 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -4353,9 +4353,25 @@ func (s *Server) handleRotateAPIKey(w http.ResponseWriter, r *http.Request) { // handleHealth handles GET /health. // Returns the coordinator's status and the number of connected providers. // This endpoint does not require authentication. +// +// Drain-aware: while the coordinator is draining for a restart/upgrade it returns +// 503 with draining=true. EigenCloud's Caddy health-checks /health, so a 200 while +// draining would keep this instance marked ready and the load balancer would keep +// routing here — clients would then hit the drain gate's 429s. Returning 503 marks +// the instance not-ready so traffic shifts to the next (non-draining) color, which +// returns 200 normally. This mirrors /readyz (handleReadyz), which load balancers +// and the deploy script also consult. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { - writeJSON(w, http.StatusOK, types.HealthResponse{ - Status: "ok", + draining := s.IsDraining() + status := http.StatusOK + statusText := "ok" + if draining { + status = http.StatusServiceUnavailable + statusText = "draining" + } + writeJSON(w, status, types.HealthResponse{ + Status: statusText, + Draining: draining, Providers: s.registry.ProviderCount(), Version: BuildVersion, BuildCommit: BuildCommit, diff --git a/coordinator/api/drain.go b/coordinator/api/drain.go index 45cffad44a..6c6d9d5e12 100644 --- a/coordinator/api/drain.go +++ b/coordinator/api/drain.go @@ -1,10 +1,13 @@ package api import ( + "context" "encoding/json" "errors" "io" "net/http" + "os" + "strings" "time" ) @@ -76,11 +79,22 @@ func (s *Server) decInflight() int64 { // connection draining, reaches a stable 0. func (s *Server) drainGate(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { + // Count this request as in-flight BEFORE reading the drain flag. If we + // checked draining first and incremented second, a request entering in the + // window between a concurrent SetDraining(true) and its own increment could + // slip past the gate while /readyz still reported inflight:0 — telling the + // deploy script it was safe to kill the process mid-request. Incrementing + // first makes Inflight() (and thus /readyz) a strict upper bound on requests + // past the gate: any request that observes draining==false was already + // counted, so it can never be running while /readyz reports 0. + s.incInflight() if s.IsDraining() { + // Lost the race (or drain was already set): back the count out and + // reject. A rejected request nets zero change to Inflight(). + s.decInflight() s.writeTokenRateLimited(w, "coordinator", "draining", coordinatorDrainRetryAfter) return } - s.incInflight() defer s.decInflight() next(w, r) } @@ -112,9 +126,18 @@ type readinessResponse struct { Ready bool `json:"ready"` } -// handleAdminDrain handles POST /v1/admin/drain (admin-gated, registered raw -// like /v1/admin/metrics). It sets the coordinator into graceful-drain mode so -// new inference requests are rejected with 429 while in-flight ones finish. +// handleAdminDrain handles POST /v1/admin/drain. It sets the coordinator into +// graceful-drain mode so new inference requests are rejected with 429 while +// in-flight ones finish. +// +// Authorization: the route is wrapped with requireAuth (see routes() in +// server.go) — the SAME pattern used by the other isAdminAuthorized/requireAdminKey +// endpoints (invite codes, credit, reward). requireAuth parses a Privy admin JWT +// into the request context AND accepts EIGENINFERENCE_ADMIN_KEY as a pseudo-account, +// so the isAdminAuthorized check below authorizes EITHER the admin key OR a Privy +// admin. Previously this route was registered raw with no middleware, so +// auth.UserFromContext was never populated and the Privy-admin branch was dead — +// only the admin key worked (the bug this fixes; scripts/admin.sh uses a Privy token). // // The body is optional: an empty body (the common case) sets draining=true. An // explicit JSON body {"draining": false} un-drains, for rolling back an aborted @@ -164,3 +187,58 @@ func (s *Server) handleAdminDrain(w http.ResponseWriter, r *http.Request) { "inflight": s.Inflight(), }) } + +// DefaultDrainGrace is how long SIGTERM shutdown waits for in-flight inference +// requests to finish (after entering drain mode) before forcing the HTTP server +// to shut down. Streaming responses can run well past the old 15s Shutdown +// deadline, so the default is generous. Overridable via EIGENINFERENCE_DRAIN_GRACE. +const DefaultDrainGrace = 60 * time.Second + +// drainGracePollInterval is how often WaitForInflightZero re-checks the in-flight +// count while waiting for requests to finish. +const drainGracePollInterval = 100 * time.Millisecond + +// DrainGraceFromEnv returns the configured SIGTERM drain grace. It reads +// EIGENINFERENCE_DRAIN_GRACE (a Go duration string, e.g. "90s"); an unset, empty, +// or invalid value falls back to DefaultDrainGrace. An explicit "0" disables the +// wait so shutdown calls http.Server.Shutdown immediately. +func DrainGraceFromEnv() time.Duration { + raw := strings.TrimSpace(os.Getenv("EIGENINFERENCE_DRAIN_GRACE")) + if raw == "" { + return DefaultDrainGrace + } + d, err := time.ParseDuration(raw) + if err != nil || d < 0 { + return DefaultDrainGrace + } + return d +} + +// WaitForInflightZero blocks until the in-flight inference count reaches 0 or ctx +// is done (its deadline elapses or it is cancelled), polling periodically. It +// returns true if inflight reached 0 (clean drain) and false if it gave up with +// requests still in flight. +// +// Used by SIGTERM shutdown to let already-admitted (possibly long-streaming) +// requests finish before calling http.Server.Shutdown. It never blocks forever: +// the caller bounds the wait with a context deadline (EIGENINFERENCE_DRAIN_GRACE) +// and then proceeds to Shutdown regardless — Shutdown's own deadline is the hard +// backstop. Pair with SetDraining(true) first so no NEW requests are admitted +// while we wait, otherwise the count may never settle. +func (s *Server) WaitForInflightZero(ctx context.Context) bool { + if s.Inflight() == 0 { + return true + } + ticker := time.NewTicker(drainGracePollInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return s.Inflight() == 0 + case <-ticker.C: + if s.Inflight() == 0 { + return true + } + } + } +} diff --git a/coordinator/api/drain_test.go b/coordinator/api/drain_test.go index dd99281591..14b230b3fd 100644 --- a/coordinator/api/drain_test.go +++ b/coordinator/api/drain_test.go @@ -1,13 +1,19 @@ package api import ( + "context" "encoding/json" "io" "net/http" "net/http/httptest" "strconv" "strings" + "sync" + "sync/atomic" "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/store" ) // minimalChatBody is a small, well-formed chat-completions body. The drain gate @@ -32,18 +38,22 @@ func doReq(srv *Server, method, path, auth, body string) *httptest.ResponseRecor return w } -// (a) POST /v1/admin/drain is admin-gated: 403 without an admin bearer. +// (a) POST /v1/admin/drain is admin-gated. The route is wrapped with requireAuth +// (the canonical admin-endpoint pattern), so unauthenticated callers get 401 +// (missing/invalid credentials) and authenticated-but-non-admin callers get 403. +// Either way a rejected call must not flip drain state. func TestAdminDrain_RequiresAdminAuth(t *testing.T) { srv, _ := testServer(t) srv.SetAdminKey("test-key") - // No bearer at all. - if w := doReq(srv, http.MethodPost, "/v1/admin/drain", "", ""); w.Code != http.StatusForbidden { - t.Fatalf("no-bearer status = %d, want %d", w.Code, http.StatusForbidden) + // No bearer at all → requireAuth rejects with 401 (missing credentials). + if w := doReq(srv, http.MethodPost, "/v1/admin/drain", "", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("no-bearer status = %d, want %d", w.Code, http.StatusUnauthorized) } - // Wrong bearer (constant-time compare must reject). - if w := doReq(srv, http.MethodPost, "/v1/admin/drain", "Bearer wrong-key", ""); w.Code != http.StatusForbidden { - t.Fatalf("wrong-bearer status = %d, want %d", w.Code, http.StatusForbidden) + // Wrong bearer (not the admin key, not a valid API key) → 401 from requireAuth; + // the constant-time admin-key compare must not match. + if w := doReq(srv, http.MethodPost, "/v1/admin/drain", "Bearer wrong-key", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("wrong-bearer status = %d, want %d", w.Code, http.StatusUnauthorized) } // A rejected admin call must not have changed drain state. if srv.IsDraining() { @@ -51,6 +61,50 @@ func TestAdminDrain_RequiresAdminAuth(t *testing.T) { } } +// (a) A Privy admin (email in the admin list) is authorized via the Privy branch +// of isAdminAuthorized — the path that was dead while the route was registered +// raw with no middleware to populate auth.UserFromContext. We exercise the +// handler with the user already in context (what requireAuth does after verifying +// the JWT), so the test is deterministic and needs no Privy verifier. +func TestAdminDrain_PrivyAdminAuthorized(t *testing.T) { + srv, _ := testServer(t) + srv.SetAdminKey("test-key") + srv.SetAdminEmails([]string{"admin@darkbloom.ai"}) + + admin := &store.User{AccountID: "acct-admin", Email: "admin@darkbloom.ai"} + r := withPrivyUser(httptest.NewRequest(http.MethodPost, "/v1/admin/drain", nil), admin) + w := httptest.NewRecorder() + srv.handleAdminDrain(w, r) + + if w.Code != http.StatusOK { + t.Fatalf("privy-admin status = %d, want %d (body=%s)", w.Code, http.StatusOK, w.Body.String()) + } + if !srv.IsDraining() { + t.Fatal("IsDraining() = false after privy-admin drain, want true") + } +} + +// (a) A valid but non-admin identity (Privy user whose email is NOT in the admin +// list) is rejected with 403 by isAdminAuthorized, proving authentication alone +// (passing requireAuth) is not sufficient — admin authorization still applies. +func TestAdminDrain_NonAdminForbidden(t *testing.T) { + srv, _ := testServer(t) + srv.SetAdminKey("test-key") + srv.SetAdminEmails([]string{"admin@darkbloom.ai"}) + + user := &store.User{AccountID: "acct-user", Email: "nobody@example.com"} + r := withPrivyUser(httptest.NewRequest(http.MethodPost, "/v1/admin/drain", nil), user) + w := httptest.NewRecorder() + srv.handleAdminDrain(w, r) + + if w.Code != http.StatusForbidden { + t.Fatalf("non-admin status = %d, want %d (body=%s)", w.Code, http.StatusForbidden, w.Body.String()) + } + if srv.IsDraining() { + t.Fatal("IsDraining() = true after a non-admin call, want false") + } +} + // (a) POST /v1/admin/drain with Bearer test-key returns 200 and flips // IsDraining()→true; an explicit {"draining": false} body un-drains. func TestAdminDrain_SetAndUndrain(t *testing.T) { @@ -183,6 +237,85 @@ func TestReadyz_ReflectsDrainState(t *testing.T) { } } +// (c) GET /health is drain-aware: 200/"ok" normally, 503/draining:true while +// draining. EigenCloud's Caddy health-checks /health, so it must flip to +// not-ready during drain or the load balancer keeps routing to this instance. +func TestHealth_ReflectsDrainState(t *testing.T) { + srv, _ := testServer(t) + + // Healthy: 200 + status ok, no draining flag. + w := doReq(srv, http.MethodGet, "/health", "", "") + if w.Code != http.StatusOK { + t.Fatalf("health status = %d, want %d", w.Code, http.StatusOK) + } + var h struct { + Status string `json:"status"` + Draining bool `json:"draining"` + } + if err := json.Unmarshal(w.Body.Bytes(), &h); err != nil { + t.Fatalf("unmarshal health: %v", err) + } + if h.Status != "ok" || h.Draining { + t.Fatalf("health = %+v, want {status:ok, draining:false}", h) + } + + // Draining: 503 + draining:true. + srv.SetDraining(true) + w = doReq(srv, http.MethodGet, "/health", "", "") + if w.Code != http.StatusServiceUnavailable { + t.Fatalf("draining health status = %d, want %d", w.Code, http.StatusServiceUnavailable) + } + if err := json.Unmarshal(w.Body.Bytes(), &h); err != nil { + t.Fatalf("unmarshal health (draining): %v", err) + } + if !h.Draining { + t.Fatalf("health = %+v, want draining:true", h) + } +} + +// (d) GET /v1/models/capacity is drain-aware: while draining it advertises zero +// models + draining:true (and is not cached) so OpenRouter-style routers stop +// selecting this instance instead of dispatching and then getting drain 429s. +func TestModelsCapacity_EmptyWhileDraining(t *testing.T) { + srv, _ := testServer(t) + + srv.SetDraining(true) + w := doReq(srv, http.MethodGet, "/v1/models/capacity", "", "") + if w.Code != http.StatusOK { + t.Fatalf("capacity status = %d, want %d", w.Code, http.StatusOK) + } + var resp struct { + Models []json.RawMessage `json:"models"` + Draining bool `json:"draining"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("unmarshal capacity: %v", err) + } + if !resp.Draining { + t.Fatalf("capacity draining = false, want true (body=%s)", w.Body.String()) + } + if len(resp.Models) != 0 { + t.Fatalf("capacity models = %d, want 0 while draining", len(resp.Models)) + } + + // Un-drain must be reflected immediately — the draining response is not cached. + // Use a fresh struct: the non-draining body omits the draining field (omitempty), + // and json.Unmarshal leaves absent fields untouched, so reusing resp would keep + // the previous true. + srv.SetDraining(false) + w = doReq(srv, http.MethodGet, "/v1/models/capacity", "", "") + var resp2 struct { + Models []json.RawMessage `json:"models"` + Draining bool `json:"draining"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp2); err != nil { + t.Fatalf("unmarshal capacity (undrained): %v", err) + } + if resp2.Draining { + t.Fatal("capacity draining = true after un-drain, want false (stale cache?)") + } +} + // (d) The in-flight counter increments/decrements back to 0, and SetDraining is // deterministic. Exercises the real Server methods directly (same package). func TestInflight_AndSetDrainingAreDeterministic(t *testing.T) { @@ -241,3 +374,126 @@ func TestDrainGate_PassesThroughWhenNotDraining(t *testing.T) { t.Fatalf("Inflight() = %d after request, want 0", n) } } + +// (b) Concurrency/-race: hammering the gate while SetDraining flips on and off +// must never leak the in-flight counter and it must settle back to 0 once traffic +// stops. Run with -race. Also asserts the gate's count-before-check invariant: +// every request that reaches next() was already counted in-flight, so an external +// reader (e.g. /readyz) can never observe a running request as inflight:0. +func TestDrainGate_ConcurrentNoInflightLeak(t *testing.T) { + srv, _ := testServer(t) + + var ranUncounted atomic.Int64 + gate := srv.drainGate(func(w http.ResponseWriter, r *http.Request) { + // We are past the gate; it must have counted us before calling next. + if srv.Inflight() < 1 { + ranUncounted.Add(1) + } + w.WriteHeader(http.StatusOK) + }) + + const workers = 64 + const iters = 50 + + // Flip draining on/off concurrently with the traffic until told to stop. + stop := make(chan struct{}) + var flipper sync.WaitGroup + flipper.Add(1) + go func() { + defer flipper.Done() + for { + select { + case <-stop: + return + default: + srv.SetDraining(true) + srv.SetDraining(false) + } + } + }() + + var work sync.WaitGroup + for i := 0; i < workers; i++ { + work.Add(1) + go func() { + defer work.Done() + for j := 0; j < iters; j++ { + w := httptest.NewRecorder() + r := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", nil) + gate(w, r) + } + }() + } + work.Wait() + close(stop) + flipper.Wait() + + // No request is running, so inflight must be 0 regardless of the final flag. + srv.SetDraining(false) + if n := srv.Inflight(); n != 0 { + t.Fatalf("Inflight() = %d after all requests, want 0 (counter leak)", n) + } + if n := ranUncounted.Load(); n != 0 { + t.Fatalf("%d requests reached next() while Inflight()<1 (count-before-check violated)", n) + } +} + +// (e) DrainGraceFromEnv parses EIGENINFERENCE_DRAIN_GRACE, falling back to the +// default for unset/empty/invalid/negative values and honoring an explicit "0" +// (no wait — Shutdown is called immediately). +func TestDrainGraceFromEnv(t *testing.T) { + cases := []struct { + name string + val string + want time.Duration + }{ + {"unset", "", DefaultDrainGrace}, + {"valid_seconds", "90s", 90 * time.Second}, + {"valid_minutes", "2m", 2 * time.Minute}, + {"zero_disables_wait", "0", 0}, + {"invalid_falls_back", "not-a-duration", DefaultDrainGrace}, + {"negative_falls_back", "-5s", DefaultDrainGrace}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Setenv("EIGENINFERENCE_DRAIN_GRACE", tc.val) + if got := DrainGraceFromEnv(); got != tc.want { + t.Fatalf("DrainGraceFromEnv() = %v, want %v", got, tc.want) + } + }) + } +} + +// (e) WaitForInflightZero returns immediately when nothing is in flight, times +// out (false) while a request is still in flight, and returns true once the count +// drops to 0 before the deadline. +func TestWaitForInflightZero(t *testing.T) { + srv, _ := testServer(t) + + // Already zero → true immediately. + if !srv.WaitForInflightZero(context.Background()) { + t.Fatal("WaitForInflightZero() = false with inflight 0, want true") + } + + // One in flight, short deadline → times out false. + srv.incInflight() + ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) + defer cancel() + if srv.WaitForInflightZero(ctx) { + t.Fatal("WaitForInflightZero() = true while a request is in flight, want false") + } + + // Drop to 0 from another goroutine → returns true before the deadline. + go func() { + time.Sleep(20 * time.Millisecond) + srv.decInflight() + }() + ctx2, cancel2 := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel2() + if !srv.WaitForInflightZero(ctx2) { + t.Fatal("WaitForInflightZero() = false after inflight dropped to 0, want true") + } + if n := srv.Inflight(); n != 0 { + t.Fatalf("Inflight() = %d at end, want 0", n) + } +} diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 7026d1a4ac..6fb14e4d3d 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -1867,9 +1867,13 @@ func (s *Server) routes() { // Graceful drain toggle (admin only) — sets the coordinator into drain mode // before a restart/upgrade so new inference requests get 429 while in-flight - // ones finish. Registered RAW (auth gated inside via isAdminAuthorized) like - // /v1/admin/metrics, and before the /v1/ catch-all. See drain.go (DAR-327). - s.mux.HandleFunc("POST /v1/admin/drain", s.handleAdminDrain) + // ones finish. Wrapped with requireAuth (the SAME pattern as the other + // isAdminAuthorized/requireAdminKey endpoints, e.g. invite codes) so a Privy + // admin JWT is parsed into the request context AND the admin key is accepted + // as a pseudo-account; handleAdminDrain then authorizes via isAdminAuthorized + // (admin key OR Privy admin). Registered before the /v1/ catch-all. Note: + // /readyz stays unauthenticated. See drain.go (DAR-327 Phase 1). + s.mux.HandleFunc("POST /v1/admin/drain", s.requireAuth(s.handleAdminDrain)) // Routing telemetry (admin-gated; metadata only — no prompt/response content). // Browse as JSON or stream a CSV/NDJSON download for offline analysis. diff --git a/coordinator/api/types/types.go b/coordinator/api/types/types.go index 31cf19c288..f7af92f1f0 100644 --- a/coordinator/api/types/types.go +++ b/coordinator/api/types/types.go @@ -264,7 +264,11 @@ type CreateAPIKeyResponse struct { // HealthResponse is the GET /health response. type HealthResponse struct { - Status string `json:"status"` + Status string `json:"status"` + // Draining is true while the coordinator is gracefully draining for a + // restart/upgrade; in that state /health also returns HTTP 503 (not-ready). + // Omitted (false) during normal operation so the healthy response is unchanged. + Draining bool `json:"draining,omitempty"` Providers int `json:"providers"` Version string `json:"version"` BuildCommit string `json:"build_commit"` diff --git a/coordinator/cmd/coordinator/main.go b/coordinator/cmd/coordinator/main.go index 3f8da25555..b5210f6673 100644 --- a/coordinator/cmd/coordinator/main.go +++ b/coordinator/cmd/coordinator/main.go @@ -13,8 +13,10 @@ // Configuration is defined per-package and composed into config.AppConfig. // See coordinator/config/ for the full schema. // -// Graceful shutdown: The coordinator handles SIGINT/SIGTERM, stops the -// eviction loop, and drains active connections with a 15-second deadline. +// Graceful shutdown: The coordinator handles SIGINT/SIGTERM, enters drain mode, +// stops the eviction loop, waits for in-flight requests to finish (up to +// EIGENINFERENCE_DRAIN_GRACE, default 60s), then drains connections with a hard +// 15-second http.Server.Shutdown deadline as the final backstop. package main import ( @@ -694,17 +696,33 @@ func main() { sig := <-sigCh logger.Info("shutting down", "signal", sig.String()) - // Graceful shutdown with a deadline. - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) - defer shutdownCancel() - - // Enter drain mode first so /readyz immediately reports not-ready and new - // inference requests get 429+Retry-After while http.Server.Shutdown waits for - // in-flight requests to finish within the deadline (DAR-327 Phase 1). + // Enter drain mode first so /readyz and /health immediately report not-ready, + // the capacity feed stops advertising, and new inference requests get + // 429+Retry-After (DAR-327 Phase 1). srv.SetDraining(true) cancel() // Stop the eviction loop. + // Wait for already-admitted in-flight requests to finish before shutting the + // HTTP server down. Streaming responses can run well past the 15s Shutdown + // deadline, so we poll Inflight() until it reaches 0 or EIGENINFERENCE_DRAIN_GRACE + // (default 60s) elapses — whichever comes first — instead of cutting them off. + // We never block forever: the grace context bounds the wait, and the hard + // Shutdown deadline below is the final backstop. + grace := api.DrainGraceFromEnv() + graceCtx, graceCancel := context.WithTimeout(context.Background(), grace) + if srv.WaitForInflightZero(graceCtx) { + logger.Info("drain complete; in-flight requests finished", "grace", grace.String()) + } else { + logger.Warn("drain grace elapsed; forcing shutdown with requests still in flight", + "grace", grace.String(), "inflight", srv.Inflight()) + } + graceCancel() + + // Hard backstop: even after the grace wait, give Shutdown a bounded deadline so + // a stuck connection can't block process exit forever. + shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) + defer shutdownCancel() if err := httpServer.Shutdown(shutdownCtx); err != nil { logger.Error("shutdown error", "error", err) } From 01b74e6031811b7912975b0c00b9642cdabbd9ed Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Thu, 18 Jun 2026 15:10:22 -0700 Subject: [PATCH 4/6] fix(coordinator): keep /health as liveness (200 while draining); readiness lives on /readyz EigenCloud Caddy health-checks the single coordinator upstream on /health with health_status 200, so a 503-while-draining marked the only backend down and made the admin rollback (POST /v1/admin/drain {"draining":false}) and /readyz unreachable. /health is now a pure liveness probe (always 200, reports draining in the body); /readyz remains the readiness signal the deploy script + LBs consult. Addresses Codex re-review of #393. --- coordinator/api/consumer.go | 29 ++++++++++++----------------- coordinator/api/drain_test.go | 14 ++++++++------ 2 files changed, 20 insertions(+), 23 deletions(-) diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index 37061cb545..80fcb5f2fc 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -4354,24 +4354,19 @@ func (s *Server) handleRotateAPIKey(w http.ResponseWriter, r *http.Request) { // Returns the coordinator's status and the number of connected providers. // This endpoint does not require authentication. // -// Drain-aware: while the coordinator is draining for a restart/upgrade it returns -// 503 with draining=true. EigenCloud's Caddy health-checks /health, so a 200 while -// draining would keep this instance marked ready and the load balancer would keep -// routing here — clients would then hit the drain gate's 429s. Returning 503 marks -// the instance not-ready so traffic shifts to the next (non-draining) color, which -// returns 200 normally. This mirrors /readyz (handleReadyz), which load balancers -// and the deploy script also consult. +// /health is a LIVENESS probe: it returns 200 whenever the process is up, INCLUDING +// while draining. This is deliberate. EigenCloud's Caddy health-checks its single +// coordinator upstream on /health with health_status 200, so returning 503 here +// would mark the only backend down and make the admin/rollback endpoints +// (POST /v1/admin/drain {"draining":false}) and /readyz unreachable through the +// public URL — you could not undo a drain remotely. Drain/readiness lives on +// /readyz (handleReadyz, 503 while draining), which the deploy script and +// multi-backend load balancers consult to shift traffic. The body still reports +// draining=true for observability, but the status code stays 200. func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) { - draining := s.IsDraining() - status := http.StatusOK - statusText := "ok" - if draining { - status = http.StatusServiceUnavailable - statusText = "draining" - } - writeJSON(w, status, types.HealthResponse{ - Status: statusText, - Draining: draining, + writeJSON(w, http.StatusOK, types.HealthResponse{ + Status: "ok", + Draining: s.IsDraining(), Providers: s.registry.ProviderCount(), Version: BuildVersion, BuildCommit: BuildCommit, diff --git a/coordinator/api/drain_test.go b/coordinator/api/drain_test.go index 14b230b3fd..dbcb37933a 100644 --- a/coordinator/api/drain_test.go +++ b/coordinator/api/drain_test.go @@ -237,9 +237,11 @@ func TestReadyz_ReflectsDrainState(t *testing.T) { } } -// (c) GET /health is drain-aware: 200/"ok" normally, 503/draining:true while -// draining. EigenCloud's Caddy health-checks /health, so it must flip to -// not-ready during drain or the load balancer keeps routing to this instance. +// (c) GET /health is a LIVENESS probe: it stays 200 even while draining (it just +// reports draining:true in the body). It must NOT flip to 503, because EigenCloud's +// Caddy health-checks its single coordinator upstream on /health — a 503 would mark +// the only backend down and make the admin/rollback endpoints and /readyz +// unreachable. Drain/readiness is exposed on /readyz (see above), not /health. func TestHealth_ReflectsDrainState(t *testing.T) { srv, _ := testServer(t) @@ -259,11 +261,11 @@ func TestHealth_ReflectsDrainState(t *testing.T) { t.Fatalf("health = %+v, want {status:ok, draining:false}", h) } - // Draining: 503 + draining:true. + // Draining: stays 200 (liveness) but reports draining:true for observability. srv.SetDraining(true) w = doReq(srv, http.MethodGet, "/health", "", "") - if w.Code != http.StatusServiceUnavailable { - t.Fatalf("draining health status = %d, want %d", w.Code, http.StatusServiceUnavailable) + if w.Code != http.StatusOK { + t.Fatalf("draining health status = %d, want %d (liveness must stay up)", w.Code, http.StatusOK) } if err := json.Unmarshal(w.Body.Bytes(), &h); err != nil { t.Fatalf("unmarshal health (draining): %v", err) From 51cfc0f95b7f862cc7fb384955743c5ea323ab11 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Fri, 19 Jun 2026 22:47:56 -0700 Subject: [PATCH 5/6] =?UTF-8?q?fix(coordinator):=20DAR-327=20Phase=201=20r?= =?UTF-8?q?eview=20=E2=80=94=20align=20drain=20grace=20to=20120s,=20correc?= =?UTF-8?q?t=20/health=20liveness=20doc,=20gate-future-routes=20note,=20me?= =?UTF-8?q?rge-order=20note?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- coordinator/api/drain.go | 11 +++++++++-- coordinator/api/server.go | 7 +++++++ coordinator/api/types/types.go | 4 +++- coordinator/cmd/coordinator/main.go | 9 +++++++-- 4 files changed, 26 insertions(+), 5 deletions(-) diff --git a/coordinator/api/drain.go b/coordinator/api/drain.go index 6c6d9d5e12..bd09e66cc3 100644 --- a/coordinator/api/drain.go +++ b/coordinator/api/drain.go @@ -191,8 +191,15 @@ func (s *Server) handleAdminDrain(w http.ResponseWriter, r *http.Request) { // DefaultDrainGrace is how long SIGTERM shutdown waits for in-flight inference // requests to finish (after entering drain mode) before forcing the HTTP server // to shut down. Streaming responses can run well past the old 15s Shutdown -// deadline, so the default is generous. Overridable via EIGENINFERENCE_DRAIN_GRACE. -const DefaultDrainGrace = 60 * time.Second +// deadline, so the default is generous. +// +// It is set to 120s to match the two upstream budgets that bound how long a +// single in-flight request can legitimately take: the provider-side going_away +// drain budget and the coordinator's request-queue timeout are BOTH 120s. A +// shorter coordinator grace (the original 60s) would cut long in-flight requests +// here before the provider had finished draining them, defeating the point of a +// graceful drain. Overridable via EIGENINFERENCE_DRAIN_GRACE. +const DefaultDrainGrace = 120 * time.Second // drainGracePollInterval is how often WaitForInflightZero re-checks the in-flight // count while waiting for requests to finish. diff --git a/coordinator/api/server.go b/coordinator/api/server.go index 6fb14e4d3d..1d3da0e81b 100644 --- a/coordinator/api/server.go +++ b/coordinator/api/server.go @@ -1692,6 +1692,13 @@ func (s *Server) routes() { // restart/upgrade it rejects NEW inference requests with 429+Retry-After // before any auth/decrypt work, and otherwise counts the request as in-flight // so /readyz can report when it's safe to shut down (DAR-327 Phase 1). + // + // IMPORTANT: ANY future provider-routed inference endpoint (e.g. + // /v1/audio/transcriptions, /v1/images/generations, /v1/embeddings) MUST also + // be wrapped in s.drainGate(...). An ungated route won't 429 during drain and, + // because it isn't counted in httpInflight, won't be seen by WaitForInflightZero + // — so a graceful shutdown could cut it off mid-flight. Add new dispatch routes + // here, gated, alongside the four below. s.mux.HandleFunc("POST /v1/chat/completions", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleChatCompletions))))) s.mux.HandleFunc("POST /v1/responses", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleChatCompletions))))) // Responses API — same handler, auto-detects input vs messages s.mux.HandleFunc("POST /v1/completions", s.drainGate(s.requireAuth(s.rateLimitConsumer(s.sealedTransport(s.handleCompletions))))) diff --git a/coordinator/api/types/types.go b/coordinator/api/types/types.go index f7af92f1f0..efc1f79c1f 100644 --- a/coordinator/api/types/types.go +++ b/coordinator/api/types/types.go @@ -266,7 +266,9 @@ type CreateAPIKeyResponse struct { type HealthResponse struct { Status string `json:"status"` // Draining is true while the coordinator is gracefully draining for a - // restart/upgrade; in that state /health also returns HTTP 503 (not-ready). + // restart/upgrade. Note /health STAYS HTTP 200 while draining (it is a + // liveness probe); readiness/draining is exposed on /readyz, which returns + // 503 while draining. The body still reports draining=true for observability. // Omitted (false) during normal operation so the healthy response is unchanged. Draining bool `json:"draining,omitempty"` Providers int `json:"providers"` diff --git a/coordinator/cmd/coordinator/main.go b/coordinator/cmd/coordinator/main.go index b5210f6673..4849938271 100644 --- a/coordinator/cmd/coordinator/main.go +++ b/coordinator/cmd/coordinator/main.go @@ -15,7 +15,7 @@ // // Graceful shutdown: The coordinator handles SIGINT/SIGTERM, enters drain mode, // stops the eviction loop, waits for in-flight requests to finish (up to -// EIGENINFERENCE_DRAIN_GRACE, default 60s), then drains connections with a hard +// EIGENINFERENCE_DRAIN_GRACE, default 120s), then drains connections with a hard // 15-second http.Server.Shutdown deadline as the final backstop. package main @@ -701,12 +701,17 @@ func main() { // 429+Retry-After (DAR-327 Phase 1). srv.SetDraining(true) + // DAR-327 merge note: when Phase 3 (#396) lands, srv.BroadcastGoingAway() + // belongs HERE — right after SetDraining(true) and BEFORE cancel() / + // WaitForInflightZero — so providers begin draining+reconnecting while we wait + // for in-flight HTTP to finish. The canonical combined shutdown order is: + // SetDraining → BroadcastGoingAway → cancel → WaitForInflightZero → Shutdown. cancel() // Stop the eviction loop. // Wait for already-admitted in-flight requests to finish before shutting the // HTTP server down. Streaming responses can run well past the 15s Shutdown // deadline, so we poll Inflight() until it reaches 0 or EIGENINFERENCE_DRAIN_GRACE - // (default 60s) elapses — whichever comes first — instead of cutting them off. + // (default 120s) elapses — whichever comes first — instead of cutting them off. // We never block forever: the grace context bounds the wait, and the hard // Shutdown deadline below is the final backstop. grace := api.DrainGraceFromEnv() From 3900ed4db9eb9c2f60cde36538134301b2efa9c7 Mon Sep 17 00:00:00 2001 From: Gajesh Naik <26431906+Gajesh2007@users.noreply.github.com> Date: Sat, 20 Jun 2026 14:32:22 -0700 Subject: [PATCH 6/6] fix(coordinator): align drain grace with inference timeout --- coordinator/api/drain.go | 12 +++++------- coordinator/cmd/coordinator/main.go | 4 ++-- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/coordinator/api/drain.go b/coordinator/api/drain.go index bd09e66cc3..cb3f9bf114 100644 --- a/coordinator/api/drain.go +++ b/coordinator/api/drain.go @@ -193,13 +193,11 @@ func (s *Server) handleAdminDrain(w http.ResponseWriter, r *http.Request) { // to shut down. Streaming responses can run well past the old 15s Shutdown // deadline, so the default is generous. // -// It is set to 120s to match the two upstream budgets that bound how long a -// single in-flight request can legitimately take: the provider-side going_away -// drain budget and the coordinator's request-queue timeout are BOTH 120s. A -// shorter coordinator grace (the original 60s) would cut long in-flight requests -// here before the provider had finished draining them, defeating the point of a -// graceful drain. Overridable via EIGENINFERENCE_DRAIN_GRACE. -const DefaultDrainGrace = 120 * time.Second +// It matches the coordinator's inferenceTimeout (10 minutes): streaming requests +// reset that timeout on each chunk and non-streaming requests may validly take +// the full budget, so a shorter default would still cut healthy generations +// during an otherwise graceful restart. Overridable via EIGENINFERENCE_DRAIN_GRACE. +const DefaultDrainGrace = 600 * time.Second // drainGracePollInterval is how often WaitForInflightZero re-checks the in-flight // count while waiting for requests to finish. diff --git a/coordinator/cmd/coordinator/main.go b/coordinator/cmd/coordinator/main.go index 4849938271..3a13fd0a33 100644 --- a/coordinator/cmd/coordinator/main.go +++ b/coordinator/cmd/coordinator/main.go @@ -15,7 +15,7 @@ // // Graceful shutdown: The coordinator handles SIGINT/SIGTERM, enters drain mode, // stops the eviction loop, waits for in-flight requests to finish (up to -// EIGENINFERENCE_DRAIN_GRACE, default 120s), then drains connections with a hard +// EIGENINFERENCE_DRAIN_GRACE, default 10m), then drains connections with a hard // 15-second http.Server.Shutdown deadline as the final backstop. package main @@ -711,7 +711,7 @@ func main() { // Wait for already-admitted in-flight requests to finish before shutting the // HTTP server down. Streaming responses can run well past the 15s Shutdown // deadline, so we poll Inflight() until it reaches 0 or EIGENINFERENCE_DRAIN_GRACE - // (default 120s) elapses — whichever comes first — instead of cutting them off. + // (default 10m) elapses — whichever comes first — instead of cutting them off. // We never block forever: the grace context bounds the wait, and the hard // Shutdown deadline below is the final backstop. grace := api.DrainGraceFromEnv()