Skip to content
25 changes: 22 additions & 3 deletions coordinator/api/capacity.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
}
Comment on lines +11 to +17

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 New modelsCapacityResponse struct when existing anonymous struct worked fine

💡 Suggestion: Keep the existing anonymous struct and add draining field inline, or reuse existing response types

📊 Score: 2×2 = 4 · Category: duplicate logic


Comment on lines +11 to +18

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 New struct duplicates existing response pattern

💡 Suggestion: Consider reusing existing response struct with omitempty tag instead of creating modelsCapacityResponse. The draining field could be added to the existing anonymous struct.

📊 Score: 2×2 = 4 · Category: duplicate logic

Comment on lines +11 to +18

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 New struct duplicates existing anonymous struct pattern

💡 Suggestion: The existing anonymous struct pattern was working fine. Adding a named type for one field (draining) adds complexity without clear benefit.

📊 Score: 2×2 = 4 · Category: duplicate logic

// 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.
Comment on lines 22 to +29

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Draining check bypasses cache on every request, potentially increasing load

💡 Suggestion: Consider caching the draining response for a short TTL (e.g. 1-2 seconds) to reduce repeated work while still allowing quick drain state changes

📊 Score: 2×4 = 8 · Category: cache_bypass

Comment on lines 22 to +29

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Draining check bypasses cache on every request, potentially increasing load

💡 Suggestion: Consider caching the draining response for a short TTL (e.g. 1-2 seconds) to reduce repeated work while still allowing quick drain state changes.

📊 Score: 2×4 = 8 · Category: cache_bypass

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)
Expand All @@ -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,
}

Expand Down
11 changes: 11 additions & 0 deletions coordinator/api/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -4397,9 +4397,20 @@ 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.
//
// /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) {
writeJSON(w, http.StatusOK, types.HealthResponse{
Status: "ok",
Draining: s.IsDraining(),
Providers: s.registry.ProviderCount(),
Version: BuildVersion,
BuildCommit: BuildCommit,
Expand Down
249 changes: 249 additions & 0 deletions coordinator/api/drain.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
package api

import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"os"
"strings"
"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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Hard-coded retry-after constant when existing writeTokenRateLimited already handles this

💡 Suggestion: Remove coordinatorDrainRetryAfter constant and let writeTokenRateLimited use its existing retry logic

📊 Score: 2×3 = 6 · Category: over-configuration

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) {
// 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
}
defer s.decInflight()
next(w, r)
Comment on lines +79 to +99

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Multiple atomic operations in drainGate create potential race window

💡 Suggestion: Consider using a single atomic operation or restructure to minimize the race window between increment and drain check

📊 Score: 3×4 = 12 · Category: atomic_operations

Comment on lines +78 to +99

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Race condition in drainGate: increment-check-decrement pattern allows requests to slip through during drain

💡 Suggestion: Check draining state first, then increment only if not draining. Use atomic compare-and-swap or mutex to make the check-and-increment atomic.

📊 Score: 3×4 = 12 · Category: race_condition

Comment on lines +78 to +99

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] ⚡ Race condition in drainGate between increment and drain check allows requests to slip through

💡 Suggestion: Move the drain check before incrementing the counter, or use atomic compare-and-swap to ensure atomicity of the check-and-increment operation

📊 Score: 3×4 = 12 · Category: race_condition

}
}

// 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. 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
// 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. 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.Body != nil && r.ContentLength != 0 {
var payload struct {
Draining *bool `json:"draining"`
}
Comment on lines +160 to +162

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🔒 MaxBytesReader limit uses shared constant that may be too large for drain endpoint

💡 Suggestion: Consider using a smaller, dedicated limit for the drain endpoint body since it only needs to parse a simple JSON boolean

📊 Score: 3×2 = 6 · Category: missing-input-validation

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 payload.Draining != nil {
draining = *payload.Draining
}
Comment on lines +155 to +177

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ JSON decoder reads entire request body into memory without size validation

💡 Suggestion: The MaxBytesReader is correctly applied, but consider using a streaming decoder or explicit size check before decoding for better memory control

📊 Score: 2×2 = 4 · Category: unbounded_allocation

}
Comment on lines +158 to +178

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🔒 JSON body parsing lacks size limit validation

💡 Suggestion: The maxControlPlaneBodyBytes constant is used but not defined in this file. Ensure it's properly imported and has a reasonable value (e.g., 1MB) to prevent memory exhaustion attacks.

📊 Score: 3×2 = 6 · Category: missing-input-validation


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(),
})
Comment thread
ethenotethan marked this conversation as resolved.
Resolved
Comment thread
ethenotethan marked this conversation as resolved.
Resolved
Comment on lines +186 to +188

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🏷️ map[string]any used for JSON response instead of typed struct

💡 Suggestion: Define a typed struct for the drain response: type drainResponse struct { Draining bool json:"draining" Inflight int64 json:"inflight" }

📊 Score: 2×3 = 6 · Category: map[string]any

}

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 DefaultDrainGrace duplicates inferenceTimeout concept

💡 Suggestion: Reference existing timeout constants rather than defining a new 600s default

📊 Score: 2×3 = 6 · Category: over-configuration

// 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.
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
Comment on lines +223 to +245

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ WaitForInflightZero uses 100ms polling interval which may be inefficient under high load

💡 Suggestion: Consider using a condition variable or channel-based notification instead of polling, or make the interval configurable for different deployment scenarios

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

}
}
Comment on lines +1 to +247

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 249-line file for what could be 50 lines of drain state management

💡 Suggestion: Consider consolidating drain logic into server.go or splitting into smaller focused files. The drain gate, admin handler, and readiness probe could be separate concerns.

📊 Score: 3×4 = 12 · Category: over-abstraction

}
Comment on lines +235 to +248

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ WaitForInflightZero uses 100ms polling interval which may be inefficient under high load

💡 Suggestion: Consider using a condition variable or channel-based notification when inflight count changes, or make the polling interval configurable for different deployment scenarios.

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

Comment on lines +235 to +248

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] ⚡ WaitForInflightZero uses 100ms polling interval which may be inefficient under high load

💡 Suggestion: Consider using a condition variable or channel-based notification when inflight count changes to zero instead of polling

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

}
Comment on lines +1 to +249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 249-line file for what could be simpler atomic state + middleware

💡 Suggestion: Consider if this could be 50-80 lines: atomic bool + int64, simple middleware func, basic admin handler. The extensive documentation and helper functions may be over-engineering a straightforward drain pattern.

📊 Score: 3×4 = 12 · Category: over-abstraction

Comment on lines +195 to +249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Environment parsing and polling logic adds complexity for marginal benefit

💡 Suggestion: Consider hardcoding reasonable defaults (e.g. 10m grace, 100ms poll) instead of making them configurable. The env parsing and context polling could be simplified to just time.Sleep in a loop.

📊 Score: 2×3 = 6 · Category: over-configuration

Comment on lines +1 to +249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 [MEDIUM] 🧩 249-line file for what could be simpler atomic state + middleware

💡 Suggestion: Consider if this could be 50-80 lines: atomic bool/int64 fields, simple middleware func, basic admin handler. The extensive comments and helper functions may be over-engineering a straightforward feature.

📊 Score: 3×4 = 12 · Category: over-abstraction

Comment on lines +200 to +249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 [INFO] 🧩 Complex environment parsing and polling logic for drain grace period

💡 Suggestion: Consider if a simple fixed timeout (e.g. 30s) would suffice instead of configurable duration parsing, polling intervals, and context management. Most deployments likely use the default anyway.

📊 Score: 2×3 = 6 · Category: over-configuration

Loading
Loading