Skip to content

DAR-327 Phase 1: graceful coordinator drain for zero-downtime upgrades - #393

Merged
Gajesh2007 merged 7 commits into
masterfrom
dar-327-phase1-graceful-drain
Jun 21, 2026
Merged

Gajesh2007 merged 7 commits into
masterfrom
dar-327-phase1-graceful-drain

Conversation

@Gajesh2007

@Gajesh2007 Gajesh2007 commented Jun 17, 2026 •

Copy link
Copy Markdown
Member

What & why

Phase 1 of DAR-327 (zero-downtime coordinator upgrades). Independent change, on top of Phase 0 (DAR-326 provider trust-reuse cache).

Today a coordinator restart/swap cancels any inference request that is mid-flight. This adds a graceful HTTP drain: before shutdown the coordinator stops admitting new inference requests (429 + Retry-After) while in-flight requests run to completion, and exposes a readiness signal so a deploy script / load balancer can wait until inflight == 0 before pulling the process.

Coordinator-only — no protocol or Swift changes. Naming deliberately avoids collision with the existing provider-side drain concepts (protocol.ProviderDrainingForUpdate, registry.drainQueuedRequestsForModels); this is purely the coordinator's own HTTP-ingress drain.

Endpoints / behavior

  • POST /v1/admin/drain — admin-gated (via isAdminAuthorized, registered raw like /v1/admin/metrics, before the /v1/ catch-all). Empty body sets draining=true; optional body {"draining": false} un-drains (rollback). Returns {draining, inflight}.
  • drain gate — outermost middleware on the 4 inference routes (POST /v1/chat/completions, /v1/responses, /v1/completions, /v1/messages). While draining: reject with 429 + Retry-After (reuses writeTokenRateLimited, ~3s) before any auth/decrypt work. Otherwise: count the request as in-flight for the handler's lifetime.
  • GET /readyz — unauthenticated, beside /health. Returns {"draining":bool,"inflight":int,"ready":bool}; HTTP 200 when ready, 503 while draining so LBs/deploy treat draining as not-ready.
  • graceful shutdown — main.go calls srv.SetDraining(true) before http.Server.Shutdown on SIGINT/SIGTERM, so /readyz flips immediately and in-flight requests finish within the existing 15s deadline.

State

Server gains two sync/atomic fields (httpInflight atomic.Int64, coordinatorDraining atomic.Bool) with SetDraining/IsDraining/Inflight + inc/dec helpers. All new logic lives in the new coordinator/api/drain.go; server.go changes are limited to struct fields + route registrations, per the repo's modularity rule.

Files changed

  • coordinator/api/drain.go (new) — state methods, drainGate, handleReadyz, handleAdminDrain
  • coordinator/api/drain_test.go (new) — tests
  • coordinator/api/server.go — sync/atomic import, 2 struct fields, /readyz + /v1/admin/drain routes, drain gate on the 4 inference routes
  • coordinator/cmd/coordinator/main.go — SetDraining(true) before Shutdown

Tests (real HTTP path via srv.Handler(), no mocks)

  • admin gate: 403 without bearer (and wrong bearer), 200 with Bearer test-key, flips IsDraining()→true; un-drain via body works
  • while draining: new POST /v1/chat/completions → 429 + positive Retry-After, inflight not leaked
  • /readyz: 200/{draining:false,ready:true} normally, 503/{draining:true,ready:false} after drain
  • inflight inc/dec returns to 0; SetDraining is deterministic; counter back to 0 after a completed request
  • regression: a non-draining inference request passes the gate (reaches auth → 401, not 429)

Verification

cd coordinator
gofmt -l .        # clean (no output)
go build ./...    # OK
go test ./api/... # ok  (full api package)
go test ./...     # ok  (all coordinator packages)

Not for merge/deploy in this PR — review only.


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

@vercel

vercel Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 21, 2026 1:20am
d-inference-console-ui-dev Ready Ready Preview Jun 21, 2026 1:20am
d-inference-landing Ready Ready Preview Jun 21, 2026 1:20am

Request Review

@github-actions

github-actions Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

This PR introduces a graceful drain phase (DAR-327 Phase 1) that is security-neutral overall — it does not weaken any mitigations and does not introduce new attack surface beyond one low-risk DoS prolongation.


Trust boundaries touched

  • TB-001 — Consumer → Coordinator API (shutdown behaviour, inflight request handling)
  • TB-002 — Coordinator → Provider WebSocket (drain signalling, indirectly via SetDraining)

Threat analysis

T-038 — Slow-header / DoS against HTTP server ℹ️ Neutral

The existing ReadHeaderTimeout=5s and MaxHeaderBytes=64 KB settings in main.go are not modified by this diff. The httpServer.Shutdown(shutdownCtx) call at line ~757 retains its hard 15-second deadline as the final backstop. No regression here.

T-032 — Solana wallet mnemonic / T-041 — Profile-signing identity ℹ️ Neutral

Neither PROFILE_SIGNING_P12_B64 nor the Solana mnemonic handling is touched. The startup/teardown path for those secrets is unchanged.

T-002 — Unbounded request body causes coordinator OOM ℹ️ Neutral (existing gap not worsened)

The drain grace window (EIGENINFERENCE_DRAIN_GRACE, default 10 minutes) means an authenticated consumer who opened a very large streaming request just before SIGTERM will be kept alive for up to 10 minutes while WaitForInflightZero polls. This is not a new attack (it requires an already-admitted, authenticated connection), but it does extend the blast radius of the existing SEC-006 unbounded-body gap: a malicious consumer could deliberately start a slow, large request to hold the coordinator alive at the edge of the grace window. This is a low-severity operational concern, not a meaningful escalation.


New attack surface not covered by an existing threat

Prolonged shutdown DoS via pre-drain long-lived streaming request
WaitForInflightZero at main.go lines ~743–749 polls until srv.Inflight() == 0 or the grace period expires. Because inference streaming responses have WriteTimeout=0 and no body cap (TB-001 known gap), an adversary who can time a request to arrive just before SetDraining(true) can hold the coordinator process alive for the full grace duration (up to 10 minutes by default) and delay a security-critical hot-restart or emergency rollback. The graceCancel() + 15-second Shutdown deadline ensures the process eventually exits, so this is bounded. Recommend documenting that EIGENINFERENCE_DRAIN_GRACE should be tuned conservatively (e.g. 2–3 minutes) in production and that an emergency override (e.g. SIGKILL) path exists in the runbook.


SEC-* open findings resolved

None — this PR does not resolve any open SEC-* findings.


Notes for reviewers

  • The TODO comment at lines ~731–734 (BroadcastGoingAway belongs after SetDraining) is a correct sequencing note and does not represent a security gap in the current diff; it is gating on Phase 3 (DAR-327 Phase 3: instant provider reconnect (going_away) #396).
  • The six uncovered files (capacity.go, consumer.go, drain.go, drain_test.go, server.go, types.go) are noted as not included in the diff; the new srv.SetDraining, srv.WaitForInflightZero, srv.Inflight, and api.DrainGraceFromEnv symbols surface here but their implementations are in those files. A follow-up review of drain.go and server.go should verify: (a) SetDraining is atomic/safe under concurrent requests, (b) WaitForInflightZero does not spin without backoff, and (c) the 429+Retry-After response emitted during drain does not leak internal state.

🔐 Threat model: docs/threat-model.yaml · Updates on each push to this PR

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1d8cf8672d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/api/drain.go Outdated
Comment on lines +76 to +80
if s.IsDraining() {
s.writeTokenRateLimited(w, "coordinator", "draining", coordinatorDrainRetryAfter)
return
}
s.incInflight()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Count requests before testing drain state

When /v1/admin/drain flips coordinatorDraining between this IsDraining() load and the following incInflight(), a request that already entered drainGate can proceed while /readyz concurrently reports draining:true and inflight:0. A deploy script or load balancer using that zero to terminate the process can still cancel this uncounted request, so the new drain is not race-free under concurrent traffic. Increment before the drain check (and decrement on rejected draining requests) or otherwise make the check/counter transition atomic.

Useful? React with 👍 / 👎.

Comment thread coordinator/api/server.go Outdated
// 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Run auth before the drain handler

When the operator uses the existing Privy admin token flow, this raw registration never populates auth.UserFromContext before handleAdminDrain calls isAdminAuthorized; only requireAuth/requirePrivyAuth do that. As a result scripts/admin.sh raw POST /v1/admin/drain with the stored Privy token gets 403 unless EIGENINFERENCE_ADMIN_KEY is also set, so the new drain control is unusable in the documented admin-token path. Wrap this route in auth or verify the Privy token inside the handler.

Useful? React with 👍 / 👎.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wait for in-flight requests on SIGTERM

When SIGTERM/SIGINT is the first drain signal, this sets drain mode and then immediately starts httpServer.Shutdown with the existing 15s deadline, so any valid inference stream that takes longer than 15 seconds is still canceled rather than waiting for Inflight()==0. The new signal-path drain therefore only works if an external script already called /v1/admin/drain; wait for the in-flight counter to drain, or use a separate drain grace, before starting the shutdown deadline.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8ea6ed28de

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/api/server.go
// 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Wire drain readiness into health checks

When the deploy/load-balancer path uses the repo's EigenCloud Caddy config, this new readiness signal is not the probed signal: coordinator/Caddyfile:44-49 health-checks the backend on /health, and the port-80 health handler at coordinator/Caddyfile:73-80 responds to /health directly. Since handleHealth still returns 200 during drain, setting coordinatorDraining will not mark the instance not-ready in that configured path, so traffic can continue to hit the old coordinator and receive drain 429s instead of being shifted; wire the configured checks/deploy script to /readyz or make the checked health path drain-aware.

Useful? React with 👍 / 👎.

Comment thread coordinator/api/server.go
Comment on lines +1600 to +1603
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)))))

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Stop advertising capacity while draining

When an upstream router uses the documented /v1/models/capacity feed to choose where to send work (coordinator/api/capacity.go:13-15 says it is for OpenRouter-style polling), this drain only gates the POST inference handlers, so the same coordinator still reports live model capacity while it will reject every dispatched inference request with 429. In that context the router can keep selecting the draining instance until it discovers the rejection after dispatch, defeating the zero-downtime drain; make the capacity/readiness signal return empty/not-ready while IsDraining() is true or require those routers to honor /readyz.

Useful? React with 👍 / 👎.

Gajesh2007 added a commit that referenced this pull request Jun 18, 2026
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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a04a9d1780

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/api/consumer.go Outdated
status := http.StatusOK
statusText := "ok"
if draining {
status = http.StatusServiceUnavailable

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Keep rollback endpoint reachable while draining

In the EigenCloud Caddy path I checked (coordinator/Caddyfile:44-49), Caddy actively health-checks its single upstream on /health with health_status 200 (Caddy docs define this as the expected healthy status, with mismatches marking the backend down). When this branch returns 503 during drain, Caddy can stop proxying all requests to the only backend, including the documented rollback POST /v1/admin/drain {"draining":false} and /readyz, so an aborted drain may be impossible to undo through the normal public URL after the next health check. Keep Caddy's backend liveness check returning 200 and expose drain on a separate LB readiness path, or otherwise leave an admin/ready path routable while drained.

Useful? React with 👍 / 👎.

@Gajesh2007

Copy link
Copy Markdown
Member Author

Integration note (cross-PR merge conflict). PRs #393 (Phase 1) and #396 (Phase 3) both edit the graceful-shutdown block in coordinator/cmd/coordinator/main.go, so whichever merges second will hit one conflict there. Everything else integrates cleanly — the api package merges with no conflict and #394 (Phase 2) is disjoint.

Canonical resolution (verified locally: combined go build, go vet, and go test ./api/ ./registry/... ./protocol/... ./cmd/... all green):

sentGoingAway := srv.BroadcastGoingAway()   // Phase 3 — broadcast first so providers skip backoff
logger.Info("broadcast going_away to providers", "count", sentGoingAway)

srv.SetDraining(true)                        // Phase 1 — /readyz+/health not-ready, capacity stops, 429 new reqs
cancel()
// ... Phase 1 drain-grace wait ...
if srv.WaitForInflightZero(graceCtx) { ... } else { ... }

shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 15*time.Second) // keep ONE decl
defer shutdownCancel()
httpServer.Shutdown(shutdownCtx)

Order: BroadcastGoingAway → SetDraining → WaitForInflightZero → Shutdown; drop Phase 3's duplicate shutdownCtx declaration (Phase 1's drain-grace block already declares it).

Gajesh2007 added a commit that referenced this pull request Jun 18, 2026
…iness 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.
@Gajesh2007

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: bf2f134621

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

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.
…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.
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.
…iness 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.
… correct /health liveness doc, gate-future-routes note, merge-order note

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 51cfc0f95b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread coordinator/api/drain.go Outdated
// 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Do not cut valid streams at the default drain grace

When SIGTERM arrives with an in-flight generation that lasts more than 120s, this default makes WaitForInflightZero time out and main immediately proceed to the 15s http.Server.Shutdown, so the request is still cut off even though the handler permits much longer work (inferenceTimeout is 600s and resets on each streaming chunk in coordinator/api/consumer.go:45-49). Fresh evidence: the new 120s default is still shorter than the coordinator’s own valid inference lifetime, so graceful drain only works if every deployment overrides the env var; make the default match the handler budget or wait for Inflight()==0 under an explicit operator deadline.

Useful? React with 👍 / 👎.

@blacksmith-sh

blacksmith-sh Bot commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

Found 1 test failure on Blacksmith runners:

Failure

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

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

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 3 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/api/drain.go:225-247 — 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
  • 🟡 [MEDIUM] coordinator/api/capacity.go:22-29 — 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
  • 🟡 [MEDIUM] coordinator/api/drain.go:79-99 — 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

Type_diligence — 1 finding(s)

  • 🔵 [INFO] coordinator/api/drain.go:186-188 — map[string]any used for JSON response in handleAdminDrain
    • Suggestion: Define a typed struct for the drain response instead of map[string]any{"draining": draining, "inflight": s.Inflight()}

Additive_complexity — 7 finding(s) (3 blocking)

  • 🟡 [MEDIUM] coordinator/api/drain.go:1-249 — 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.
  • 🔵 [INFO] coordinator/api/drain.go:32 — Hard-coded retry-after constant when existing writeTokenRateLimited already handles this
    • Suggestion: Remove coordinatorDrainRetryAfter constant and let writeTokenRateLimited use its existing retry logic
  • 🔵 [INFO] coordinator/api/drain.go:195 — DefaultDrainGrace duplicates inferenceTimeout concept
    • Suggestion: Reference existing timeout constants rather than defining a new 600s default
  • 🔵 [INFO] coordinator/api/capacity.go:11-17 — 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
  • 🟡 [MEDIUM] coordinator/api/server.go:1688-1701 — Drain gate wrapper applied to each route individually instead of middleware
    • Suggestion: Apply drainGate as middleware in the handler chain rather than wrapping each inference route individually
  • 🟡 [MEDIUM] coordinator/api/drain_test.go:1-501 — 501-line test file with extensive mocking when simpler integration tests would suffice
    • Suggestion: Reduce test complexity by focusing on key behaviors rather than exhaustive edge cases. Consider table-driven tests for similar scenarios.
  • 🔵 [INFO] coordinator/cmd/coordinator/main.go:699-732 — Shutdown logic now has two timeout contexts (grace + shutdown) when one would suffice
    • Suggestion: Combine grace period and shutdown timeout into a single context with appropriate deadline

11 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/api/drain.go
Comment on lines +225 to +247
// 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

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

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 thread coordinator/api/drain.go
Comment on lines +79 to +99
// 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)

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 thread coordinator/api/drain.go Resolved
Comment thread coordinator/api/drain.go
Comment on lines +1 to +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.
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)
}
}

// 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"`
}
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
}
}

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(),
})
}

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

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 thread coordinator/api/drain.go
// 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

Comment on lines +11 to +17
// 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"`
}

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 thread coordinator/api/server.go
Comment on lines 1688 to +1701
// 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).
//
// 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.

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] 🧩 Drain gate wrapper applied to each route individually instead of middleware

💡 Suggestion: Apply drainGate as middleware in the handler chain rather than wrapping each inference route individually

📊 Score: 3×4 = 12 · Category: misplaced responsibility

Comment on lines +1 to +501
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
// 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. 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 → 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 (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() {
t.Fatal("IsDraining() = true after a rejected admin call, want false")
}
}

// (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) {
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")
}
}

// (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) {
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)
}
}

// (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)

// 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: stays 200 (liveness) but reports draining:true for observability.
srv.SetDraining(true)
w = doReq(srv, http.MethodGet, "/health", "", "")
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)
}
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) {
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)
}
}

// (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)
}
}

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] 🧩 501-line test file with extensive mocking when simpler integration tests would suffice

💡 Suggestion: Reduce test complexity by focusing on key behaviors rather than exhaustive edge cases. Consider table-driven tests for similar scenarios.

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

Comment on lines +699 to 732
// 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)

// 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 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()
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)

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] 🧩 Shutdown logic now has two timeout contexts (grace + shutdown) when one would suffice

💡 Suggestion: Combine grace period and shutdown timeout into a single context with appropriate deadline

📊 Score: 2×3 = 6 · Category: duplicate logic

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Verdict: REQUEST_CHANGES

Security — 1 finding(s)

  • 🔵 [INFO] coordinator/api/drain.go:158-178 — 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.

Performance — 4 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/api/drain.go:78-99 — 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.
  • 🔵 [INFO] coordinator/api/drain.go:235-248 — 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.
  • 🔵 [INFO] coordinator/api/drain_test.go:400-450 — Test creates 64 concurrent goroutines without context cancellation or timeout
    • Suggestion: Add a test timeout context and use errgroup or similar to bound goroutine lifecycle and handle potential test hangs.
  • 🟡 [MEDIUM] coordinator/api/capacity.go:22-29 — 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.

Type_diligence — 1 finding(s)

  • 🔵 [INFO] coordinator/api/drain.go:186-188 — Using map[string]any 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" }

Additive_complexity — 6 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/api/drain.go:1-249 — 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.
  • 🔵 [INFO] coordinator/api/drain.go:195-249 — 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.
  • 🔵 [INFO] coordinator/api/capacity.go:11-18 — 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.
  • 🟡 [MEDIUM] coordinator/api/drain_test.go:1-501 — 501 lines of tests for relatively simple drain functionality
    • Suggestion: Consider if the core drain behavior could be tested in 100-150 lines. Some test cases (chunked body, concurrent hammering) may be testing edge cases that add more complexity than value.
  • 🔵 [INFO] coordinator/api/server.go:1688-1701 — Extensive middleware wrapping comments suggest complex layering
    • Suggestion: The comment about 'OUTERMOST wrapper' and future endpoint requirements suggests the middleware chain is becoming complex. Consider if drain logic could be handled at the router level instead of per-endpoint wrapping.
  • 🔵 [INFO] coordinator/cmd/coordinator/main.go:699-732 — Shutdown sequence has multiple timeouts and contexts for simple drain
    • Suggestion: Consider simplifying to: set drain flag, wait fixed time (e.g. 30s), then shutdown. The configurable grace period and separate contexts add complexity for uncertain benefit in most deployment scenarios.

12 finding(s) total, 4 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/api/drain.go
Comment on lines +158 to +178
draining := true
if r.Body != nil && r.ContentLength != 0 {
var payload struct {
Draining *bool `json:"draining"`
}
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
}
}

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

Comment thread coordinator/api/drain.go
Comment on lines +78 to +99
// 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)

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 thread coordinator/api/drain.go
Comment on lines +235 to +248
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
}
}
}

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 +400 to +450
// 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

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] ⚡ Test creates 64 concurrent goroutines without context cancellation or timeout

💡 Suggestion: Add a test timeout context and use errgroup or similar to bound goroutine lifecycle and handle potential test hangs.

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

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

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 thread coordinator/api/drain.go
Comment on lines +195 to +249
//
// 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
}
}
}
}

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 +11 to +18
// 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"`
}

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 +1 to +501
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
// 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. 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 → 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 (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() {
t.Fatal("IsDraining() = true after a rejected admin call, want false")
}
}

// (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) {
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")
}
}

// (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) {
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)
}
}

// (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)

// 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: stays 200 (liveness) but reports draining:true for observability.
srv.SetDraining(true)
w = doReq(srv, http.MethodGet, "/health", "", "")
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)
}
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) {
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)
}
}

// (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)
}
}

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] 🧩 501 lines of tests for relatively simple drain functionality

💡 Suggestion: Consider if the core drain behavior could be tested in 100-150 lines. Some test cases (chunked body, concurrent hammering) may be testing edge cases that add more complexity than value.

📊 Score: 3×3 = 9 · Category: over-abstraction

Comment thread coordinator/api/server.go
Comment on lines 1688 to +1701
// 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).
//
// 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.

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] 🧩 Extensive middleware wrapping comments suggest complex layering

💡 Suggestion: The comment about 'OUTERMOST wrapper' and future endpoint requirements suggests the middleware chain is becoming complex. Consider if drain logic could be handled at the router level instead of per-endpoint wrapping.

📊 Score: 2×3 = 6 · Category: misplaced responsibility

Comment on lines +699 to 732
// 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)

// 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 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()
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)

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] 🧩 Shutdown sequence has multiple timeouts and contexts for simple drain

💡 Suggestion: Consider simplifying to: set drain flag, wait fixed time (e.g. 30s), then shutdown. The configurable grace period and separate contexts add complexity for uncertain benefit in most deployment scenarios.

📊 Score: 2×2 = 4 · Category: over-configuration

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

Verdict: REQUEST_CHANGES

Security — 1 finding(s)

  • 🔵 [INFO] coordinator/api/drain.go:160-162 — 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

Performance — 3 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/api/drain.go:78-99 — 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
  • 🔵 [INFO] coordinator/api/drain.go:235-248 — 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
  • 🔵 [INFO] coordinator/api/drain.go:155-177 — 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

Type_diligence — 1 finding(s)

  • 🔵 [INFO] coordinator/api/drain.go:186-188 — 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" }

Additive_complexity — 6 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/api/drain.go:1-249 — 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.
  • 🔵 [INFO] coordinator/api/drain.go:200-249 — 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.
  • 🔵 [INFO] coordinator/api/capacity.go:11-18 — 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.
  • 🟡 [MEDIUM] coordinator/api/drain_test.go:1-501 — 501 lines of tests for relatively simple drain functionality
    • Suggestion: While thorough testing is good, 501 lines suggests the feature may be more complex than needed. Consider if the core functionality could be simpler, requiring fewer edge cases to test.
  • 🔵 [INFO] coordinator/api/server.go:1688-1701 — Long comment about future endpoints in routing code
    • Suggestion: The 8-line comment about future endpoints belongs in documentation, not inline code. Consider a simpler comment like '// drainGate must wrap all inference endpoints' and move details to docs.
  • 🔵 [INFO] coordinator/cmd/coordinator/main.go:723-756 — Complex shutdown sequence with multiple timeouts and contexts
    • Suggestion: The shutdown logic has grown complex with drain grace, shutdown context, and multiple phases. Consider if a simpler approach (e.g. single 30s timeout) would be sufficient for most use cases.

11 finding(s) total, 3 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/api/drain.go
Comment on lines +160 to +162
var payload struct {
Draining *bool `json:"draining"`
}

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

Comment thread coordinator/api/drain.go
Comment on lines +78 to +99
// 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)

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

Comment thread coordinator/api/drain.go
Comment on lines +235 to +248
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
}
}
}

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 thread coordinator/api/drain.go
Comment on lines +155 to +177
// 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"`
}
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
}

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 thread coordinator/api/drain.go
Comment on lines +186 to +188
"draining": draining,
"inflight": s.Inflight(),
})

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

Comment thread coordinator/api/drain.go
Comment on lines +200 to +249
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
}
}
}
}

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

Comment on lines +11 to +18
// 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"`
}

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

Comment on lines +1 to +501
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
// 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. 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 → 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 (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() {
t.Fatal("IsDraining() = true after a rejected admin call, want false")
}
}

// (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) {
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")
}
}

// (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) {
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)
}
}

// (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)

// 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: stays 200 (liveness) but reports draining:true for observability.
srv.SetDraining(true)
w = doReq(srv, http.MethodGet, "/health", "", "")
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)
}
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) {
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)
}
}

// (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)
}
}

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] 🧩 501 lines of tests for relatively simple drain functionality

💡 Suggestion: While thorough testing is good, 501 lines suggests the feature may be more complex than needed. Consider if the core functionality could be simpler, requiring fewer edge cases to test.

📊 Score: 3×3 = 9 · Category: over-abstraction

Comment thread coordinator/api/server.go
Comment on lines 1688 to +1701
// 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).
//
// 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.

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] 🧩 Long comment about future endpoints in routing code

💡 Suggestion: The 8-line comment about future endpoints belongs in documentation, not inline code. Consider a simpler comment like '// drainGate must wrap all inference endpoints' and move details to docs.

📊 Score: 2×3 = 6 · Category: misplaced responsibility

Comment on lines +723 to 756
// 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)

// 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 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()
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)

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 shutdown sequence with multiple timeouts and contexts

💡 Suggestion: The shutdown logic has grown complex with drain grace, shutdown context, and multiple phases. Consider if a simpler approach (e.g. single 30s timeout) would be sufficient for most use cases.

📊 Score: 2×2 = 4 · Category: over-configuration

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference-console-ui-dev — 4b04fb9f Deployed Jun 21, 2026 by vercel[bot]
Preview – d-inference — 4b04fb9f Deployed Jun 21, 2026 by vercel[bot]
Preview – d-inference-landing — 4b04fb9f Deployed Jun 21, 2026 by vercel[bot]
benchmarks — 4b04fb9f Deployed Jun 21, 2026 by Gajesh2007 via E2E Benchmarks #1317
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants